Sub ComputerPlay()
Dim RandomGenerator As New Random() Dim intRandom As Integer
Dim intCount As Integer = 0 Dim ctrl As Control
intRandom = RandomGenerator.Next(20, 100) While intCount < intRandom
For Each ctrl In Me.Controls
If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then If ctrl.Text = String.Empty Then
intCount += 1
If intCount = intRandom Then ctrl.Text = “O” ctrl.Enabled = False
Exit For End If
End If
End If Next
End While End Sub
When you clicked any square, the TicTacToe_Click procedure was called. Take a look at the Handles keyword in the declaration of the subroutine. The Click event from every button on the board has been added to the comma-delimited list. So when you clicked any square, this procedure handled the event.
The first step of the procedure disabled all squares, followed by a call to Application.DoEvents. The DoEvents method allowed all waiting events in the queue to complete. This was placed here to avoid the problems associated with clicking more than one button in a turn. If you removed these two lines of code, you could quickly click three squares in a row before the computer made one pick. Next, the button that was clicked, the sender, is marked with an X. After the square is marked, the board is checked for a winner. If no winner is found, the computer makes the next move. Again, the board is checked for a winner. If no winner is found, the player is asked to select again.
Private Sub TicTacToe_Click(ByVal sender As Object, ByVal e As _ System.EventArgs) Handles btn00.Click, btn20.Click, btn10.Click, _ btn01.Click, btn21.Click, btn11.Click, btn02.Click, btn22.Click, btn12.Click
CorrectEnabledState(False)
Application.DoEvents() ‘Allows the screen to refresh CType(sender, Button).Text = “X”
If IsGameOver() Then MsgBox(“Game Over”)
Else
lblMessages.Text = “Computer selecting ...” Application.DoEvents() ‘Allows the screen to refresh ComputerPlay()
If IsGameOver() Then MsgBox(“Game Over”)
Else
lblMessages.Text = “Select your next position ...” CorrectEnabledState()
End If End If
End Sub