班級:自控四甲 姓名:何禎隆 學號:49712075 老師:謝慶存 計算機程式及實習 題目:井字遊戲 班級:自控四甲 姓名:何禎隆 學號:49712075 老師:謝慶存
井字遊戲 相信大家小時候都有玩過類似井字遊戲的遊戲 他的遊戲規則很簡單在設計中的小框框點選一下就會出現符號,當同一種符號連接成一條線,時就獲勝了
表單設計解析 在表單設計中我利用到了幾個簡單地工具。 其中有Buutom ,在表單中井字形的九個格子都用此工具來展現。 其中在顯現出結果輸贏時則是利用label1著個工具來設計。
程式碼的撰寫 Public Class Form1 Dim btn(9) As Button 定義9個案紐,作井字方格 Dim oxFlag As Boolean 定義oxFlag來記錄目前輪到誰點取 Dim sco(9) As Integer 設定方格的存放值 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load btn(1) = Button1 將1-9的方格都設定為BTN陣列方便處理 btn(2) = Button2 btn(3) = Button3 btn(4) = Button4 btn(5) = Button5 btn(6) = Button6 btn(7) = Button7 btn(8) = Button8 btn(9) = Button9
Dim i As Integer 此頁為方塊的初始設定 For i = 1 To 9 With btn(i) .Height = btn(i).Width 設定方塊高寬和字型 .Left = ((i - 1) Mod 3) * btn(1).Width + 30 .Top = ((i - 1) \ 3) * btn(1).Height + 30 .Text = "" .Font = New System.Drawing.Font("Arial", 36) End With sco(i) = 0 Next oxFlag = True Label1.Text = "" Label1.Font = New System.Drawing.Font("新細明體", 20) Button10.Text = “重新開使”
Private Sub Button1_Click(ByVal sender As System Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click Dim no As Integer = Microsoft.VisualBasic.Right((CType(sender, Button).Name), 1) If oxFlag = True Then 將OXFLAG設定第一次按下時出現○ btn(no).Text = "○" sco(no) = 1 Else btn(no).Text = "╳" sco(no) = 2 End If oxFlag = Not oxFlag 以下是處理每次按下個井字方格時處理的動作 If sco(1) * sco(2) * sco(3) = 1 Then Label1.Text = "○贏!" If sco(4) * sco(5) * sco(6) = 1 Then Label1.Text = "○贏!" If sco(7) * sco(8) * sco(9) = 1 Then Label1.Text = "○贏!" If sco(1) * sco(4) * sco(7) = 1 Then Label1.Text = "○贏!" If sco(2) * sco(5) * sco(8) = 1 Then Label1.Text = "○贏!" If sco(3) * sco(6) * sco(9) = 1 Then Label1.Text = "○贏!"
If sco(1) * sco(5) * sco(9) = 1 Then Label1.Text = "○贏!" If Label1.Text <> “” Then 此處開始處理當一方得勝時讓按鈕無法再按下 Dim i As Integer For i = 1 To 9 btn(i).Enabled = False Next End If End Sub
Private Sub Button10_Click(ByVal sender As System Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click Dim i As Integer 以Button10_Click副程式處理按鈕重新的動作 For i = 1 To 9 With btn(i) .Enabled = True .Text = "" End With sco(i) = 0 Next Label1.Text = "" End Sub End Class
實際展示程式
參考文獻 學會寫程式Visual basic 2005 13-2頁