我正在尝试使用Visual Basic创建一个Tic Tac Toe游戏。按下按钮后,按钮应首先转到“O”,然后下一次按下应为“X”,但似乎它继续放置“O”。
Dim turn As Boolean
turn = True 'true = X turn, false = Y turn
Dim b As Button
b = DirectCast(sender, Button)
If (turn) Then
b.Text = "O"
Else
b.Text = "X"
turn = Not turn <<< This seems to not to be working...
b.Enabled = False
End If
答案 0 :(得分:3)
您需要在方法之外声明turn
变量,以便它是类的成员,而不是每次重新创建的局部变量。
此外,您应该在每次更改后翻转状态,不仅在放置X时也是如此,并且相同用于禁用按钮。
示例:
Dim turn As Boolean = True 'true = X turn, false = Y turn
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim b As Button = DirectCast(sender, Button)
If turn Then
b.Text = "O"
Else
b.Text = "X"
End If
turn = Not turn
b.Enabled = False
End Sub