Step 7Programming Tic Tac Toe
Let's first break down the tic tac toe game into its various steps, in the two player mode:
Step 1: Player A picks an unfilled cell by touching an intersection.
Step 2: The LED for that cell lights up with the colour A.
Step 3: Check to see if Player A has won.
Step 4: Player B picks an unfilled cell.
Step 5: The LED for that cell lights up with colour B.
Step 6: Check to see if Player B has won.
Step 7: Repeat 1-6 until there's a win condition, or if all the cells are filled.
Reading the cells:
The program loops between reading the grid and displaying the LED matrix. As long as the grid sensor does not register a non-zero value, this loop will continue. When an intersection is pressed, the Pressed variable stores the position of the pressed cell.
Checking if the cell is unfilled:
When a position reading is obtained (variable Pressed), it is compared against the current cell status (stored in the variable GridOnOff) using a bitwise addition. If the Pressed cell is unfilled, then proceed to light up the LED, otherwise return to reading the cells.
Toggling the colours:
A boolean variable, Turn, is used to record whose turn it is. The LED colour chosen when a cell is picked is determined by this variable, which alternates each time a cell is chosen.
Checking for a win condition:
There are only 8 possible win conditions, and these are stored as word variables in an array (winArray). Two bitwise additions are used to compare a player's filled cell positions to the win conditions. If there's a match, then the program displays a win routine, after which it starts a new game.
Checking for a draw condition:
When nine turns have been recorded and there is still no win condition, then the game is a draw. The LEDs are then faded out and a new game is started.
Switching to one player mode:
If the switch is in the on position, the program goes into one player mode, with the human player starting first. At the end of the human player's turn, the program simply picks a random cell. Obviously, this isn't the smartest strategy!
tictactoe.pde8 KB| « Previous Step | Download PDFView All Steps | Next Step » |
4
comments
|
Add Comment
|
origamiwolf (author)
says:
origamiwolf (author)
says:
![]() |
Add Comment
|












































