看板 Visual_Basic 關於我們 聯絡資訊
※ 引述《xtimer ()》之銘言: : Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click : x = x + 1 : Button1.Enabled = False : If x Mod 2 = 1 Then : Button1.Text = "O" : Else : Button1.Text = "X" : End If : End Sub : 分別為Button1~9 : 可是要怎麼判別 : 147 258 369 123 456 789 159 357的text相同 因為已經有Button1~Button9,我想可以宣告陣列 Dim a(8) as Button a(0) = Button1 a(1) = Button2 ... a(8) = Button9 每個ButtonX的Click動作,設定 o x 之後要做同樣的判斷動作, 要寫個函式讓9個ButtonX_Click都呼叫它,其中是 針對陣列 a 處理三縱行,三橫列,與交叉線 For i = 0 to 8 If a(i) \ 3 = 0 Then '第一列 ... ElseIf a(i) Mod 3 = 0 Then '第一行 ... ElseIf ... End If Next 不過這樣寫也蠻多的. 後來,覺得也許可以改成這樣,直接宣告八個陣列紀錄八條判斷線 Dim a(2) as Button '第一列 a(0) = Button1 a(1) = Button2 a(3) = Button3 Dim b(2) as Button '第二列 b(0) = Button4 b(1) = Button5 b(3) = Button6 ... Dim h(2) as Button '右上-左下斜線 h(0) = Button3 h(1) = Button5 h(2) = Button7 然後用一個函式,要接受以上八個陣列其中一種,能夠判斷答案 Function judge(ByVal a()) As Boolean Dim result As Boolean refult = (a(0).Text = a(1).Text And a(1).Text = a(2).Text) Return result End Function 在Button{1..9}_Click設定 ox 之後要寫 If judge(a) = True Then Console.WriteLine("獲勝方: " & a(0).Text) 'judge(a)判斷有沒有贏,a(0)就會紀錄其符號 '這部份看你要怎麼顯示答案,自己修改為自己的情況 ElseIf judge(b) = True Then ... End If 這八個判斷嫌太長,也可以將陣列 a 到 h 收在一個陣列中,就可以用迴圈處理. Dim t(7) As Button() t(0) = a t(1) = b ... t(7) = h For i = 0 To 7 If judge(t(i)) = True Then Label10.Text = "獲勝方" & t(i)(0).Text & ",遊戲結束" End If Next 判斷與結束遊戲部份,是九個按鈕共用的動作,可以抽出來寫成一個函式. 想睡時,沒辦法直接想出最有效率的程式或程式寫法,真抱歉. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.160.211.45 ※ 編輯: yauhh 來自: 218.160.211.45 (05/17 02:26)
xtimer:阿哩...看了兩個小時....還是看不懂= = 05/17 06:43
xtimer:好複雜~@@ 05/17 06:43
yauhh:哦? 我以為把一個按鈕物件指定給按鈕變數的思路很簡單... 05/17 11:06
yauhh:或許我該再檢討一下解說方式 05/17 11:07