Project #10: Tic Tac Toe

TIC TAC TOE
Ability Level: Beginner
Estimated Time: 1 hour 30 minutes
Objectives:
  • Understand control arrays and how they differ from individual controls
  • Understand IF statements using arrays
  • Use Boolean variables as flags
Materials and Resources:
  • Visual Basic Software
Overview: Create a version of Tic Tac Toe that allows two players to play against each other. The game should report winners, losers, and draws. The program must not allow illegal moves or additional moves after a game has been won.
Instructions:
  1. On a new form, create a label box.
  2. Set the label box Tag property to 0.
  3. Copy the label box and paste eight new copies on the form. Answer Yes when Visual Basic asks if you want to create a control array.
  4. Add two buttons. one for exiting the program and one for clearing the board. Give each button an appropriate caption.
  5. In the label click subroutine, write program code to verify the box is available. Hint: An available box has a tag value of zero.
  6. If an open box is clicked on, display an X or O, depending on which player made the move.
  7. Set the label tag to a new value to indicate which player (1 or 2) moved into that box.
  8. After each move, check to see if there is a winner or a drawn game. Report that the game is over if there is a winner or a draw. If there is a winner, no additional moves should be allowed.
  9. If the clear game button is pressed, reset all the tags to zero and the label captions to blank.
  10. If the exit game is pressed, shut down the game.
Hints:
  • Assuming the label box control array is named Label1 and the boxes in the array are arranged from 0 in the top left to 8 in the bottom right corners, the following IF statement will identify a win across the top of the board.
         IF Label1(0).Tag <> 0 and Label1(0).Tag = Label1(1).Tag _
         and Label1(1).Tag = Label1(2).Tag then
         Winner = True
  • This will set the Boolean variable Winner to True if the top three boxes have the same non zero value. The value of Winner should have been set to False before the checks for a winner are made. Once all eight possible winning combinations are checked, the program can take appropriate action if Winner is True.
  • The value of a Player flag indicates which player to report as the winner and must be switched after each move.
  • Checking the tags in all nine label boxes can identify a draw. If all the tags are non zero the game is a draw.
  • A completed game form may look like the following:



PROJECT EXTRAS
  • Use the Beep statement to notify users when they click on an occupied box.
  • Display a count of the number of draws and the number of times each player wins a game.
  • Have the game board clear automatically once the game is over.
Project courtesy of MainFunction.com
Edited by: M. Levy 1/02/2001