Kovan's Tic-Tac-Toe


Screen shot of what it looks like:

(you need 9 label controls set font size to something big, and make them all the same size).



Form variables.

Private playerLastPlayed As Integer = 0 'initially no one went

Which will hold the value of the last player that went.

When each label is clicked, this function will get called.

Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click, Label2.Click, Label3.Click, Label4.Click, Label5.Click, Label6.Click, Label7.Click, Label8.Click, Label9.Click
labelClicked(sender)
End Sub

Private
Sub labelClicked(ByVal lbl As Label)
If RadioButton1.Checked Then
If playerLastPlayed = 1 Then
MessageBox.Show("its not your turn")
Return
End If
lbl.Text = "X"
playerLastPlayed = 1
'player one played
Else
If playerLastPlayed = 2 Then
MessageBox.Show("its not your turn")
Return
End If
lbl.Text = "O"
playerLastPlayed = 2
'player two played
End If

'disable so its no longer clickable (make that square used)
lbl.Enabled = False
checkForWinner(1)
checkForWinner(2)
End Sub

Now we must check to see if there is a winner.

Private Sub checkForWinner(ByVal playerNumber As Integer)
Dim chr As String = ""
Select Case playerNumber
Case 1
chr = "X"
Case 2
chr = "O"
End Select

'check for column 1,2,3
'check for column 4,5,6
'check for column 7,8,9

'check for column 1,4,7
'check for column 2,5,8
'check for column 3,6,9

'check for column 1,5,9
'check for column 3,5,7

If (Label1.Text = chr And Label2.Text = chr And Label3.Text = chr) Then
Or
(Label4.Text = chr And Label5.Text = chr And Label6.Text = chr) _
Or (Label7.Text = chr And Label8.Text = chr And Label9.Text = chr) _
Or (Label1.Text = chr And Label4.Text = chr And Label7.Text = chr) _
Or (Label2.Text = chr And Label5.Text = chr And Label8.Text = chr) _
Or (Label3.Text = chr And Label6.Text = chr And Label9.Text = chr) _
Or (Label1.Text = chr And Label5.Text = chr And Label9.Text = chr) _
Or (Label3.Text = chr And Label5.Text = chr And Label7.Text = chr) Then

'we found a winner
If playerNumber = 1 Then
MessageBox.Show("player one WON")
reset()
ElseIf playerNumber = 2 Then
MessageBox.Show("player two WON")
reset()
End If
End If
End
Sub

Now lets see the reset function.

Private Sub reset()
'remove the x, o
For Each lbl As Control In Me.Controls
If lbl.GetType Is GetType(Label) Then
lbl.Text = ""
End If
Next
'reset last player played.
playerLastPlayed = 0
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
reset()
End Sub


Similar Articles