PyToe: A Tic-Tac-Toe Game Widget
Finally, a bit of fun to close out this chapter. Our last example, PyToe, implements an
artificially intelligent tic-tac-toe (sometimes called “naughts and crosses”) game-
playing program in Python. Most readers are probably familiar with this simple game,
so I won’t dwell on its details. In short, players take turns marking board positions, in
an attempt to occupy an entire row, column, or diagonal. The first player to fill such a
pattern wins.
In PyToe, board positions are marked with mouse clicks, and one of the players is a
Python program. The game board itself is displayed with a simple tkinter GUI; by
default, PyToe builds a 3 × 3 game board (the standard tic-tac-toe setup), but it can be
configured to build and play an arbitrary N × N game.
When it comes time for the computer to select a move, artificial intelligence (AI) algo-
rithms are used to score potential moves and search a tree of candidate moves and
countermoves. This is a fairly simple problem as gaming programs go, and the heuristics
used to pick moves are not perfect. Still, PyToe is usually smart enough to spot wins a
few moves in advance of the user.
Running PyToe
PyToe’s GUI is implemented as a frame of expandable packed labels, with mouse-click
bindings on the labels to catch user moves. The label’s text is configured with the
player’s mark after each move, computer or user. The GuiMaker class we coded earlier
in the prior chapter (Example 10-3) is also reused here again to add a simple menu bar
at the top (but no toolbar is drawn at the bottom, because PyToe leaves its format
descriptor empty). By default, the user’s mark is “X” and PyToe’s is “O.” Fig-
ure 11-25 shows PyToe run from PyGadgets with its status pop-up dialog, on the verge
of beating me one of two ways.
Figure 11-26 shows PyToe’s help pop-up dialog, which lists its command-line config-
uration options. You can specify colors and font sizes for board labels, the player who
moves first, the mark of the user (“X” or “O”), the board size (to override the 3 × 3
default), and the move selection strategy for the computer (e.g., “Minimax” performs
a move tree search to spot wins and losses, and “Expert1” and “Expert2” use static
scoring heuristics functions).
The AI gaming techniques used in PyToe are CPU intensive, and some computer move
selection schemes take longer than others, but their speed varies mostly with the speed
of your computer. Move selection delays are fractions of a second long on my machine
for a 3 × 3 game board, for all “-mode” move-selection strategy options.
Figure 11-27 shows an alternative PyToe configuration (shown running its top-level
script directly with no arguments), just after it beat me. Despite the scenes captured
for this book, under some move selection options, I do still win once in a while. In
762 | Chapter 11: Complete GUI Programs