Programming Tic-Tac-Toe In Visual Basic.NET

Written By: Kevin Jordan

- 10 Feb 2006 -
















Description: We'll start by using the visual editor to set up our interface and take it all the way into programming the artificial intelligence of the computer opponent.

  1. Creating the User Interface
  2. Starting a Game and Making a Menu
  3. Programming the Game Logic
  4. An Intelligent Opponent

Create the Project

Create a new Visual Basic.NET project. I used the Windows Application template and called it "scratchProjects – Tic Tac Toe"

To make things easier for me I renamed Form1.vb to frmTicTacToe.vb by right clicking the file in the solutions explorer. I then selected the form and changed the text to "Tic-Tac-Toe" and the name to "frmTicTacToe".

Click Here To View A Screenshot

Building the Main Menu

I then went to the handy dandy toolbox and dragged over a MainMenu object. I decided to add two headings: "Options", which would have all the features of the game, and "About" which would have an all people to see a little information on the program. Under Options I added New Game, Difficulty, and Quit. And then I added the three difficulty settings: Easy, Medium, and Hard.

To make my code easier to understand, I gave each of these design elements a more descriptive name. The Options heading was originally called MenuItem1, so it was renamed "menuOptions". I repeated this process for all of the recently created menus.

Building the Grid

Tic Tac Toe Grid Layout

Instead of making images for the X's and O's, I decided to keep things simple and use the letter X and O. To create the grid I used 9 labels laid out in a 3x3 square. To create the first label I used the Toolbox and dragged it out to 8x8 using the dots as my reference measurement. I then changed the following settings:

        BackColor: White
        BorderStyle: FixedSingle
        Cursor: Hand
        Font: Tahoma, 36pt, style=bold
        Text: X
        TextAlign: MiddleCenter
        Name: lblGrid00

After everything was set, I dragged the label over to the top-left corner and then made 8 copies of it arranged in a 3x3 grid. I then renamed each label to correspond to the grid.

        lblGrid00       lblGrid01       lblGrid02
        lblGrid10       lblGrid11       lblGrid12
        lblGrid20       lblGrid21       lblGrid22

Since that's all that I'm putting in the windows I got rid of the negative space by dragging the window frame until only the grid could fit. Here's what the initial build looks like.

Looks pretty good, but it didn't do much. Like all programs, we need more than just eye candy.

Next >>