Baroody's Game Development Site

A Website to help you program computer games

Step 3: Code to Play!

Now, how should this game work?  If it is a player's turn, then they should be able to click in a space on the grid and have their symbol ("X" or "O") show up there, right?  Remember, whenever we want something to happen when we click the mouse button, we need the "Cick" event for that object.  So, let's see how that will look.  In the form, double click on imgGrid(0).  This will bring you to the code and will create a sub routine like that shown below.

Private Sub imgGrid_Click(Index As Integer)

End Sub

This is slightly different than most of sub routines you've seen before...do you see the "Index As Integer" in the parentheses?  There's never been anything in those parentheses before, has there?  This was created automatically since the image on which we clicked is part of a control array.  When the user clicks on one of the images in the array, this sub routine is run, but something else very important is going on...we know which one of the images in the array was clicked.  How do we know?  Because the variable "Index" stores the index number of the array position that was clicked!  So, if the player clicked on the middle space in the grid, this routine will be run and the "Index" variable will have a value of 4.  If the player clicked on the top left space on the grid, then the "Index" variable will have a value of 0.  Get the idea?

This is really useful information for us to have.  Now, when Player 1 clicks on one of the positions in the image control array, we can put a "1" in the associated position of the parallel integer array.  Because of the way we coded our UpdateDisplay routine, it will take care of putting the correct image in the correct position.  Let's see what the code should look like:

imgGrid_Click Sub Routine 

The first "If" condition is a little complex.  First we check to make sure that the grid position clicked is empty (if it's not, then we don't want to do anything).  Then we check to make sure that the current player is either Player 1 or Player 2.  When would it be anything different?  Hold on to that thought for a bit...  Assuming that all of these conditions hold true, we update the integer array for the position clicked with the current player number.  Finally, we change the current player to the other person (in other words, if the current player is player1, we change it to player2 and vice versa).

Try running your program now...you should be able to play the game, but it won't end...let's work on that next!

If your code is working like you think it should and you're ready to end the game, click here or select Step 4: End the Game in the navigation bar.