figure: tinker

This computer, built of Tinker-Toy parts, plays tic-tac-toe.

Simply Scheme: Introducing Computer Science ch 10: Example: Tic-Tac-Toe


Simply Scheme: Introducing Computer Science 2/e Copyright (C) 1999 MIT

Chapter 10

Example: Tic-Tac-Toe

cover photo
Brian Harvey
University of California, Berkeley
Matthew Wright
University of California, Santa Barbara

Download PDF version
Back to Table of Contents
BACK chapter thread NEXT
MIT Press web page for Simply Scheme

Now that you've learned about higher-order functions, we're going to look at a large example that uses them extensively. Using the techniques you've learned so far, we're going to write a program that plays perfect tic-tac-toe.

You can load our program into Scheme by typing

(load "ttt.scm")

(See Appendix A if this doesn't work for you.)

A Warning

Programs don't always come out right the first time. One of our goals in this chapter is to show you how a program is developed, so we're presenting early versions of procedures. These include some mistakes that we made, and also some after-the-fact simplifications to make our explanations easier. If you type in these early versions, they won't work. We will show you how we corrected these "bugs" and also will present a complete, correct version at the end of the chapter.

To indicate the unfinished versions of procedures, we'll use comments like "first version" or "not really part of game."

Technical Terms in Tic-Tac-Toe

We'll number the squares of the board this way:

 
123
456
789
 

We'll call a partially filled-in board a "position."

 
o
xo
xx
 

To the computer, the same position will be represented by the word __o_xox_x. The nine letters of the word correspond to squares one through nine of the board. (We're thinking ahead to the possibility of using item to extract the nth square of a given position.)

Thinking about the Program Structure

Our top-level procedure, ttt, will return the computer's next move given the current position. It takes two arguments: the current position and whether the computer is playing X or O. If the computer is O and the board looks like the one above, then we'd invoke ttt like this:

(ttt '__o_xox_x 'o)

Here is a sample game:

> (ttt '____x____ 'o)                   ; Human goes first in square 5
1                                       ; Computer moves in square 1
> (ttt 'o__xx____ 'o)                   ; Human moves in square 4
6                                       ; Computer blocks in square 6
> (ttt 'o_xxxo___ 'o)                   ; Human moves in square 3
7                                       ; Computer blocks again
> (ttt 'o_xxxoox_ 'o)
2

This is not a complete game program! Later, when we talk about input and output, you'll see how to write an interactive program that displays the board pictorially, asks the player where to move, and so on. For now, we'll just write the strategy procedure that chooses the next move. As a paying customer, you wouldn't be satisfied with this partial program, but from the programmer's point of view, this is the more interesting part.

Let's plan the computer's strategy in English before we start writing a computer program. How do you play tic-tac-toe? You have several strategy rules in your head, some of which are more urgent than others. For example, if you can win on this move, then you just do it without thinking about anything else. But if there isn't anything that immediate, you consider less urgent questions, such as how this move might affect what happens two moves later.

So we'll represent this set of rules by a giant cond expression:

(define (ttt position me)                    ;; first version
  (cond ((i-can-win?)
         (choose-winning-move))
        ((opponent-can-win?)
         (block-opponent-win))
        ((i-can-win-next-time?)
         (prepare-win))
        (else (whatever))))

We're imagining many helper procedures. I-can-win? will look at the board and tell if the computer has an immediate winning move. If so, choose-winning-move will find that particular move. Opponent-can-win? returns true if the human player has an immediate winning move. Block-opponent-win will return a move that prevents the computer's opponent from winning, and so on.

We didn't actually start by writing this definition of ttt. The particular names of helper procedures are just guesses, because we haven't yet planned the tic-tac-toe strategy in detail. But we did know that this would be the overall structure of our program. This big picture doesn't automatically tell us what to do next; different programmers might fill in the details differently. But it's a framework to keep in mind during the rest of the job.

Our first practical step was to think about the data structures in our program. A data structure is a way of organizing several pieces of information into a big chunk. For example, a sentence is a data structure that combines several words in a sequence (that is, in left-to-right order).

In the first, handwavy version of ttt, the strategy procedures like i-can-win? are called with no arguments, but of course we knew they would need some information about the board position. We began by thinking about how to represent that information within the program.

The First Step: Triples

A person looking at a tic-tac-toe board looks at the rows, columns, and diagonals. The question "do I have a winning move?" is equivalent to the question "are there three squares in a line such that two of them are mine and the last one is blank?" In fact, nothing else matters about the game besides these potential winning combinations.

There are eight potential winning combinations: three rows, three columns, and two diagonals. Consider the combination containing the three squares 1, 5, and 9. If it contains both an x and an o then nobody can win with this combination and there's nothing to think about. But if it contains two xs and a free square, we're very interested in the combination. What we want to know in particular is which square is free, since we want to move in that square to win or block.

More generally, the only squares whose numbers we care about are the ones we might want to move into, namely, the free ones. So the only interesting information about a square is whether it has an x or an o, and if not, what its number is.

The information that 1, 5, 9 is a potential winning combination and the information that square 1 contains an x, square 5 is empty, and square 9 contains another x can be combined into the single word x5x. Looking at this word we can see immediately that there are two xs in this "triple" and that the free square is square 5. So when we want to know about a three-square combination, we will turn it into a triple of that form.

Here's a sample board position:

 
xo
x
o
 

and here is a sentence of all of its triples:

(1xo 4x6 o89 14o xx8 o69 1x9 oxo)

Take a minute to convince yourself that this sentence really does tell you everything you need to know about the corresponding board position. Once our strategy procedure finds the triples for a board position, it's never going to look at the original position again.

This technique of converting data from one form to another so that it can be manipulated more easily is an important idea in computer science. There are really three representations of the same thing. There's this picture:

 
xo
x
o
 

as well as the word _xo_x_o__ and the sentence (1xo 4x6 o89 14o xx8 o69 1x9 oxo). All three of these formats have the same information but are convenient in different ways. The pictorial form is convenient because it makes sense to the person who's playing tic-tac-toe. Unfortunately, you can't type that picture into a computer, so we need a different format, the word _xo_x_o__, which contains the contents of the nine squares in the picture, but without the lines separating the squares and without the two-dimensional shape.

The third format, the sentence, is quite inconvenient for human beings. You'd never want to think about a tic-tac-toe board that way yourself, because the sentence doesn't have the visual simplicity that lets you take in a tic-tac-toe position at a glance. But the sentence of triples is the most convenient representation for our program. Ttt will have to answer questions like "can x win on the next move?" To do that, it will have to consider an equivalent but more detailed question: "For each of the eight possible winning combinations, can x complete that combination on the next move?" It doesn't really matter whether a combination is a row or a column; what does matter is that each of the eight combinations be readily available for inspection by the program. The sentence-of-triples representation obscures part of the available information (which combination is where) to emphasize another part (making the eight combinations explicit, instead of implicit in the nine boxes of the diagram).

The representation of fractions as "mixed numerals," such as 21/3, and as "improper fractions," such as 7/3, is a non-programming example of this idea about multiple representations. A mixed numeral makes it easier for a person to tell how big the number is, but an improper fraction makes arithmetic easier.

Finding the Triples

We said that we would combine the current board position with the numbers of the squares in the eight potential winning combinations in order to compute the things we're calling triples. That was our first task in writing the program.

Our program will start with this sentence of all the winning combinations:

(123 456 789 147 258 369 159 357)

and a position word such as _xo_x_o__; it will return a sentence of triples such as

(1xo 4x6 o89 14o xx8 o69 1x9 oxo)

All that's necessary is to replace some of the numbers with xs and os. This kind of word-by-word translation in a sentence is a good job for every.

(define (find-triples position)              ;; first version
  (every substitute-triple '(123 456 789 147 258 369 159 357)))

We've made up a name substitute-triple for a procedure we haven't written yet. This is perfectly OK, as long as we write it before we try to invoke find-triples. The substitute-triple function will take three digits, such as 258, and return a triple, such as 2x8:

(define (substitute-triple combination)      ;; first version
  (every substitute-letter combination))

This procedure uses every to call substitute-letter on all three letters.

There's a small problem, though. Every always returns a sentence, and we want our triple to be a word. For example, we want to turn the potential winning combination 258 into the word 2x8, but every would return the sentence (2 x 8). So here's our next version of substitute-triple:

(define (substitute-triple combination)      ;; second version
  (accumulate word (every substitute-letter combination)))

Substitute-letter knows that letter number 3 of the word that represents the board corresponds to the contents of square 3 of the board. This means that it can just call item with the given square number and the board to find out what's in that square. If it's empty, we return the square number itself; otherwise we return the contents of the square.

(define (substitute-letter square)           ;; first version
  (if (equal? '_ (item square position)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module ranger.__main__</title>
</head><body bgcolor="#f0f0f8">

<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="ranger.html"><font color="#ffffff">ranger</font></a>.__main__</strong></big></big></font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/hut/ranger/ranger/__main__.py">/home/hut/ranger/ranger/__main__.py</a></font></td></tr></table>
    <p><tt>#&nbsp;coding=utf-8<br>
#<br>
#&nbsp;Copyright&nbsp;(C)&nbsp;2009,&nbsp;2010&nbsp;&nbsp;Roman&nbsp;Zimbelmann&nbsp;&lt;romanz@lavabit.com&gt;<br>
#<br>
#&nbsp;This&nbsp;program&nbsp;is&nbsp;free&nbsp;software:&nbsp;you&nbsp;can&nbsp;redistribute&nbsp;it&nbsp;and/or&nbsp;modify<br>
#&nbsp;it&nbsp;under&nbsp;the&nbsp;terms&nbsp;of&nbsp;the&nbsp;GNU&nbsp;General&nbsp;Public&nbsp;License&nbsp;as&nbsp;published&nbsp;by<br>
#&nbsp;the&nbsp;Free&nbsp;Software&nbsp;Foundation,&nbsp;either&nbsp;version&nbsp;3&nbsp;of&nbsp;the&nbsp;License,&nbsp;or<br>
#&nbsp;(at&nbsp;your&nbsp;option)&nbsp;any&nbsp;later&nbsp;version.<br>
#<br>
#&nbsp;This&nbsp;program&nbsp;is&nbsp;distributed&nbsp;in&nbsp;the&nbsp;hope&nbsp;that&nbsp;it&nbsp;will&nbsp;be&nbsp;useful,<br>
#&nbsp;but&nbsp;WITHOUT&nbsp;ANY&nbsp;WARRANTY;&nbsp;without&nbsp;even&nbsp;the&nbsp;implied&nbsp;warranty&nbsp;of<br>
#&nbsp;MERCHANTABILITY&nbsp;or&nbsp;FITNESS&nbsp;FOR&nbsp;A&nbsp;PARTICULAR&nbsp;PURPOSE.&nbsp;&nbsp;See&nbsp;the<br>
#&nbsp;GNU&nbsp;General&nbsp;Public&nbsp;License&nbsp;for&nbsp;more&nbsp;details.<br>
#<br>
#&nbsp;You&nbsp;should&nbsp;have&nbsp;received&nbsp;a&nbsp;copy&nbsp;of&nbsp;the&nbsp;GNU&nbsp;General&nbsp;Public&nbsp;License<br>
#&nbsp;along&nbsp;with&nbsp;this&nbsp;program.&nbsp;&nbsp;If&nbsp;not,&nbsp;see&nbsp;&lt;<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>&gt;.</tt></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
    
<tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="os.html">os</a><br>
</td><td width="25%" valign=top><a href="sys.html">sys</a><br>
</td><td width="25%" valign=top></td><td width="25%" valign=top></td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
    
<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl><dt><a name="-main"><strong>main</strong></a>()</dt><dd><tt>initialize&nbsp;objects&nbsp;and&nbsp;run&nbsp;the&nbsp;filemanager</tt></dd></dl>
 <dl><dt><a name="-parse_arguments"><strong>parse_arguments</strong></a>()</dt><dd><tt>Parse&nbsp;the&nbsp;program&nbsp;arguments</tt></dd></dl>
</td></tr></table>
</body></html>
e) (best-move (keep (lambda (triple) (my-single? triple me)) triples) triples me)) (define (best-move my-triples all-triples me) (if (empty? my-triples) #f (best-square (first my-triples) all-triples me) )) (define (best-square my-triple triples me) (best-square-helper (pivots triples (opponent me)) (keep number? my-triple))) (define (best-square-helper opponent-pivots pair) (if (member? (first pair) opponent-pivots) (first pair) (last pair))) (define (best-free-square triples) (first-choice (accumulate word triples) '(5 1 3 7 9 2 4 6 8))) (define (first-choice possibilities preferences) (first (keep (lambda (square) (member? square possibilities)) preferences)))

Exercises

10.1  The ttt procedure assumes that nobody has won the game yet. What happens if you invoke ttt with a board position in which some player has already won? Try to figure it out by looking through the program before you run it.

A complete tic-tac-toe program would need to stop when one of the two players wins. Write a predicate already-won? that takes a board position and a letter (x or o) as its arguments and returns #t if that player has already won.

10.2  The program also doesn't notice when the game has ended in a tie, that is, when all nine squares are already filled. What happens now if you ask it to move in this situation?

Write a procedure tie-game? that returns #t in this case.

10.3  A real human playing tic-tac-toe would look at a board like this:

 
oxo
oxx
xo
 

and notice that it's a tie, rather than moving in square 9. Modify tie-game? from Exercise 10.2 to notice this situation and return #t.

(Can you improve the program's ability to recognize ties even further? What about boards with two free squares?)

10.4  Here are some possible changes to the rules of tic-tac-toe:

    What if you could win a game by having three squares forming an L shape in a corner, such as squares 1, 2, and 4?
    What if the diagonals didn't win?
    What if you could win by having four squares in a corner, such as 1, 2, 4, and 5?

Answer the following questions for each of these modifications separately: What would happen if we tried to implement the change merely by changing the quoted sentence of potential winning combinations in find-triples? Would the program successfully follow the rules as modified?

10.5  Modify ttt to play chess.


[1] A kludge is a programming trick that doesn't follow the rules but works anyway somehow. It doesn't rhyme with "sludge"; it's more like "clue" followed by "j" as in "Jim."

[2] Brian thinks this is a kludge, but Matt thinks it's brilliant and elegant.

[3] Matt thinks this is a kludge, but Brian thinks it's brilliant and elegant.

(back to Table of Contents)

BACK chapter thread NEXT

Brian Harvey, bh@cs.berkeley.edu