Baroody's Game Development Site

A Website to help you program computer games

Step 4: Ending the Game

OK, so how are we going to end this game?  How does one win in Tic Tac Toe?  A player wins when he or she gets three in a row in one of the three rows, one of the three columns or one of the two diagonals.  So, let's see if we can write some code to check that.  Take a look at the following changes to our imgGrid_Click routine:

imgGrid_Click Sub Routine with updates 

The first new line checks a flag to make sure that the game has not already been won.  After that, the next new line runs a new routine called "CheckForWin."  We'll take a look at that in a minute.  The new code at the end of the imgGridClick routine changes the current player to 0 (no one) and places that into the player display label on the form if a win has occurred .  Pretty straight forward stuff.

OK, now, let's look at the new "CheckForWin" routine:

CheckForWin Sub Routine 

Essentially, this routine goes through the eight possibilities for a win...it checks to see if the three grid positions in the first row are the same, or the three in the second row, or the three in the third row.  It then checks the columns and finally, it checks the two diagonals.  If any of these have "three in a row," then the Boolean flag indicating that a win has occurred is set to "True" a message box telling who won is displayed and the current player is set to 0.

At this point, your Tic Tac Toe game should work.  Try it out!

If you're ready to add some options to this game, click here or select Step 5: Adding Options on the navigation bar.