We're going to go through the program structure bottom-up, which means that you'll build helper blocks before you build ttt
itself. But keep the goal in mind.
A good way to approach building a program: Design top-down, implement bottom-up.
Remember on the last page, when we asked ourselves several questions about the game? Let's think about answering those, and how we could design the program to fit our goals.
Question 1: What constitutes a good move?
Before you continue, discuss with a neighbor what you think the most important rules for a good move are in tic-tac-toe.
We thought of a couple that are pretty important: (1) if we can win on this move, make that move! (2) if the opponent can win on the next move, block that move! (3) otherwise, prioritize the middle, then corners, then edges.
Thinking about the first two rules, we'll probably need to check if we ever have two in a row and the opponent isn't in the third spot. That is, if we see two X's and no O's in a row, then we know where to move to win! Think about what condition we'd need to look for to block opponent wins.
Question 2: What do I want my tic-tac-toe block to accomplish?
We know that we should input the current board and the player to find a move for. We also know that we want the output to be an indication of where we should move on the board. There are only nine spots on the board, what if we just numbered them 1 through 9? Then, our ttt
block could simply output a number that corresponds to the spot where we should move!
This brings us to another important question: What should our representation of the board look like? Our board needs to store 9 pieces of information, mainly where X and O have been played. What if we made our board a simple 9 item list, and put X's and O's on it where the players move? How should we represent the blank spaces? Well, we just determined that our ttt
block should report a number representing the space where a player should move. If the empty spaces are simply their space number, it could make things easier for us!
Question 3: How do you win tic-tac-toe?
You win by getting "three in a row". A tic-tac-toe board is 3x3.
How many ways can you win tic-tac-toe? It's not 9 — think about it.