VB Tutor Logo VB2022 VB2019 VB6 VB Sample Code About Us
VB Tutor Logo

Tic Tac Toe Game

Learn to create a classic game with Visual Basic


Introduction

Tic Tac Toe is a popular game that you can play at any time and anywhere as long as you have a piece of paper and a pen, or you could draw it on sand or any surface. Now, you can create a VB version that allows users to play the game virtually.

First of all, you need to draw the interface with four straight lines, then insert nine image controls and make them an array, Image1(0) to Image1(8). Secondly, insert two pictures, one is a circle and the other one is a cross to represent player 1 and player2.

The Interface

Tic Tac Toe Interface

To check whether a position is empty or not, we use two arrays, cross(8) and ball(8) (We use ball instead of circle because circle is an internal function of VB) and set them as Boolean. If cross(n)=false and ball(n)=false, that means position n is not occupied by a cross or a ball, where n is any integer between 0 and 8.

In addition, you need to insert eight straight lines that would cross out three crosses or three circles if they are aligned in a straight line side by side, as shown in the diagram. You need to make these lines invisible at start-up and make one of the lines appear whenever the above condition is fulfilled.

Play Tic Tac Toe

Tic Tac Toe

Player X's turn

Implementation Code

Here's the Visual Basic code for implementing the Tic Tac Toe game logic:

TicTacToe.vb Visual Basic
Dim cross(8) As Boolean
Dim ball(8) As Boolean
Dim m As Integer
Dim player As Integer

Sub check_status()
    If ball(0) = True And ball(1) = True And ball(2) = True Then
        Line10.Visible = True
    End If
    ' Additional win condition checks...
End Sub

Sub check_position()
    For m = 0 To 8
        If Image1(m).Picture = Image2.Picture Then
            ball(m) = True
        Else
            ball(m) = False
        End If
        ' Check for cross positions...
    Next
End Sub

Private Sub Image1_Click(Index As Integer)
    check_position
    If player = 1 And cross(Index) = False And ball(Index) = False Then
        Image1(Index).Picture = Image2.Picture
    End If
    ' Player 2 logic...
    check_position
    check_status
End Sub

Private Sub mnuNew_Click()
    For m = 0 To 8
        Image1(m).Picture = LoadPicture("")
    Next
    ' Reset all lines visibility...
End Sub

Code Explanation

The implementation uses two arrays to track positions: cross() for X marks and ball() for O marks. The check_status() subroutine verifies all possible winning combinations by checking if three consecutive positions are occupied by the same player.

The check_position() subroutine updates the arrays based on the current state of the game board. The Image1_Click event handles player moves, while mnuNew_Click resets the game to its initial state.