|
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.)
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."
We'll number the squares of the board this way:
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
We'll call a partially filled-in board a "position."
o | ||
x | o | |
x | x |
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.)
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.
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 x
s 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 x
s 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:
x | o | |
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:
x | o | |
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.
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 x
s and
o
s. 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)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)))<!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> <br> <font color="#ffffff" face="helvetica, arial"> <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># coding=utf-8<br> #<br> # Copyright (C) 2009, 2010 Roman Zimbelmann <romanz@lavabit.com><br> #<br> # This program is free software: you can redistribute it and/or modify<br> # it under the terms of the GNU General Public License as published by<br> # the Free Software Foundation, either version 3 of the License, or<br> # (at your option) any later version.<br> #<br> # This program is distributed in the hope that it will be useful,<br> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br> # GNU General Public License for more details.<br> #<br> # You should have received a copy of the GNU General Public License<br> # along with this program. If not, see <<a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>>.</tt></p> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#aa55cc"> <td colspan=3 valign=bottom> <br> <font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr> <tr><td bgcolor="#aa55cc"><tt> </tt></td><td> </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> <br> <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr> <tr><td bgcolor="#eeaa77"><tt> </tt></td><td> </td> <td width="100%"><dl><dt><a name="-main"><strong>main</strong></a>()</dt><dd><tt>initialize objects and run the filemanager</tt></dd></dl> <dl><dt><a name="-parse_arguments"><strong>parse_arguments</strong></a>()</dt><dd><tt>Parse the program arguments</tt></dd></dl> </td></tr></table> </body></html>
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:
o | x | o |
o | x | x |
x | o |
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.
[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.
Brian Harvey,
bh@cs.berkeley.edu