Can the Computer Win on this Move?

Let's call the current board our position; it's the current position of the game. Converting a position into a list of triples will pay off as we start writing strategy rules. The overall structure of ttt will be (don't try to build this in Snap! yet; just read it)

super-simplified ttt structure

But that's an oversimplified picture just so you understand the important parts before we add the bookkeeping. Each of the reporters and predicates shown above (except the last, all-else-fails rule) will need two inputs: the list of triples and the computer's letter (X or O). So here's a more realistic picture:

ttt with inputs to helpers

This is the clearest way to express the process that ttt must follow to try several "if this then do that" rules in sequence. It's a bit inefficient, though, because the computation to answer the blue yes-or-no questions above is basically to look for an answer to the green which-square question below it, and then report true if a square is found. So we end up doing those computations twice. Instead, we'll combine the yes-or-no computation and the which-square computation by writing rule procedures that report a square number if one is found, or false if not. Then the code in ttt for each rule becomes

fragment of ttt for one rule using temp variable


Okay, time to move from planning to doing. The next goal is to build a winning square block. It'll take a list of triples and an X-or-O, and look for a square in which that player can move to win immediately. What does that mean in terms the program can understand? (We asked you to think about this a few screens ago.) Our answer is, "look for a winning combination in which our letter appears twice and the other letter doesn't appear at all." So we seem to need two helpers: one that reports how many times a letter appears in a triple, and one that reports "the other letter."

Start by writing a reporter called opponent that just takes an X or O as its input, and reports the other letter.

Now make a helper block called appearances that takes a word and a list as inputs, and returns the number of times the first one appears in the second. Hint: Use a higher order function.

Write the appearances block as defined above. Definitely use the given hint; this block can be really short!

Now write a winning square block that uses a higher order function to select those triples in which our letter appears twice and the opponent's letter doesn't appear at all, and then if any such triples are found, report the number of the vacant square in the first such triple; if not, report false.

Write the winning square block as defined above.