我正在使用Windows窗体编写一个井字游戏。我有一个用于比赛场地的“桌子”和图标按钮。我使用了一个模块,我想处理每个按钮,而不是为每个按钮写出代码。
代码:
Private Sub Btn_Box6_Click(sender As Object, e As EventArgs) Handles Btn_Box6.Click
ChangeTxt()
End Sub
( 其中一个按钮点击条件的示例 )
Sub ChangeTxt()
If Form1.Active_PlayerTxt.Text = "X" Then
PlayerOne = True
ElseIf Form1.Active_PlayerTxt.Text = "O" Then
PlayerTwo = True
Else
MsgBox("Please enter X or O to decide the player!")
End If
If PlayerOne = True Then
Form1.Btn_Box1.Text = "X"
ElseIf PlayerTwo = True Then
Form1.Btn_Box1.Text = "O"
Else
MsgBox("Please enter X or O to decide the player!")
End If
Form1.Active_PlayerTxt.Text = ""
PlayerOne = False
PlayerTwo = False
End Sub
所以基本上你可以看到,这当前只改变了btn_box1,但我想让它在点击它们时改变每个单独的按钮(btn_box2)而不是仅仅改变btn_box1。有一个简单的方法吗?
答案 0 :(得分:0)
这是一个非常简单的做tic-tac-toe游戏的方法:
您可以这样做:
' Create an enum to represent the current player.
Public Enum CurrentPlayer
X
O
End Enum
' Create an "instance" of the enum.
Public cPlayer As CurrentPlayer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Lets say the first player is X.
cPlayer = CurrentPlayer.X
' Reset the text of the buttons.
' You can do this using the properties of the buttons in the designer.
For Each btn As Button In Me.Controls
btn.Text = ""
Next
End Sub
' Occures when the first button is clicked.
Private Sub ButtonClicked(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click
' Calls the funciton and passing the current button (byref).
CheckText(sender)
End Sub
' Passing an argument byref does not create a copy
' of the argument, but sends the "real" one.
Public Sub CheckText(ByRef btn As Button)
' First check if the current button is "free".
If btn.Text = "" Then
' Change the text of the button according to the current player.
Select Case cPlayer
Case CurrentPlayer.X
btn.Text = "x"
cPlayer = CurrentPlayer.O
Case CurrentPlayer.O
btn.Text = "O"
' Changes the current player.
cPlayer = CurrentPlayer.X
End Select
Else
MsgBox("This button is already used!")
End If
End Sub
我让你做一个寻找胜利者的功能:)
希望它有所帮助。