Project 3: Tic Tac Toe
Welcome to your third project!
How do computers play strategy games like checkers or chess? They don't act intuitively like we might, they look ahead instead. For every move they could make, they imagine every move their opponent might make after, and every reply they could make to that, as far as they can imagine with the time and compute they have, and then they pick the move that works out the best regardless of the other player's decisions. That idea is called minimax, and with it a program can play any two-player game where both players can see the whole board. Checkers, chess, Go, Connect Four, and Tic Tac Toe.
In this project you will start by writing a Tic Tac Toe board (maybe a more interesting one than you're used to!), then an agent that plays it with minimax, then a tournament that plays agents against each other. On a 3x3 board your agent will be unbeatable, but on a 5x5 board with walls it can't look all the way to the end, so you'll have to work within a time limit and use heuristics in addition to the look-ahead strategy to make decisions. The quality of those heuristics will ultimately be what makes one agent better than another, and at the end of the semester we will pit every agent in the class against each other to declare a final winner!
This project starts alongside the traits unit in lecture. An Agent is itself a trait, your Minimax is one type that implements it, and the tournament holds agents of different types in one Vec<Box<dyn Agent>> (so we'll finally get to see what Boxes are really useful for too!).
What is due when
- Checkpoint 1, Friday November 13. The board with your tests of it
- Checkpoint 2, Friday November 20.
Minimaxon the 3x3 board - The project, Friday December 4. The 5x5 game, round robin, and your writeup
- The tournament. We run it on the agent you submit on December 4, and the results come out in the last lecture
- Code review, in discussion the week of December 7
Checkpoint 1 is smaller, since it falls the week after the midterm. Checkpoint 2 is the heart of the project. Nothing in the last part needs anything from lecture past Nov 20, so you can manage your own time after that.
Meet your project repo
Your starting point is https://github.com/rust4ds/ds210-fa26-project-3.
Same as before: on GitHub, click Use this template, then Create a new repository. Name it ds210-fa26-project-3 and set it to Private. Then clone it.
src/board.rs checkpoint 1. The board: moves, apply and undo, score, game over
src/minimax.rs checkpoints 2 and 3. Your agent
src/tournament.rs checkpoint 3. The round robin
tests/my_tests.rs checkpoint 1. Your tests of the board
src/bin/arena.rs checkpoint 3. A playground for pitting heuristics against each other
src/agent.rs the Agent trait, and four agents to play against
src/game.rs plays one game between two agents, with a clock
src/layout.rs starting boards: 3x3, 5x5, bigger, with or without walls
src/player.rs X and O
src/main.rs the command line tool
tests/cp1.rs, cp2.rs, cp3.rs the checkpoint tests
README.md instructions to start, and where your writeup goes
You will only edit the first five files, plus the writeup in README.md. The others are ours. You should read them to make sense of them, since your code calls them, but leave them alone: when your agent enters the tournament it has to compile against our copy of everything else.
Like usual, all the spots where you have to write code are marked todo!, with a comment above it that sketches the steps.
Working on branches
Same workflow as Project 2: each checkpoint on its own branch, merged into main with a pull request when its tests pass.
git switch -c checkpoint-1
The Project 2 page has the full set of commands if you want them again.
Running your project
Everything runs from the top folder of your repo:
cargo run -- human random # play: you against a random agent, 3x3
cargo run -- human minimax # play: you against your agent
cargo run -- minimax greedy --board walls # watch your agent play against Greedy, 5x5 with walls
cargo run -- random first --board open # watch two agents on 5x5, no walls
cargo run -- tournament --board walls # watch everyone against everyone, on six fixed boards
cargo run -- minimax greedy --board open --size 7 --depth 3 # a bigger board
cargo run --bin arena # your heuristics against each other (checkpoint 3)
The agents are first, random, greedy, human, and minimax. All of first, random, and greedy are programmed for you, human lets you decide moves in real time, and minimax is yours to code up.
The boards are classic (3x3, the default), open (5x5), and walls (5x5 with five walls in random places). --size N makes the open and walls boards bigger, --depth N limits how far minimax looks ahead, and --limit SECONDS changes the time limit per turn. cargo run -- --help lists all of it.
On a fresh clone of the template repo none of these will run, since you first need to complete the todo!-marked code and make the board.
Open the repo's top folder in VS Code, with code . from inside it, so that rust-analyzer finds Cargo.toml and gives you types and errors as you type.
Running the tests
cargo test --test cp1 # the board
cargo test --test my_tests # your tests of the board
cargo test --test cp2 # Minimax on 3x3
cargo test --test cp3 # 5x5, the heuristic, and the round robin
cargo test # all the tests
Add part of a test's name to run only the tests that match it: cargo test --test cp1 undo.
When you first clone your repo, every test fails and you'll see a lot of warnings about things that are declared and never used. That's expected until you start writing your code.
If a test hangs, your search is probably looking too far ahead. A full minimax search of a 5x5 board never finishes. Press Ctrl-C and fix the bug, and try running one test at a time.
The rules of the game
You are probably familiar with the 3x3 game. X goes first, players alternate, three in a row wins, and if the board fills up it's a draw.
The 5x5 game is a little different. A great way to learn about it is by running it with the human option and playing against the computer.
- Some cells are walls, drawn
#. Nobody can play there, and you can't make a three-in-a-row through a wall. - Three in a row scores a point, and the game continues. It ends when the board is full, and whoever has more points wins. Four in a row is two runs of three, so it scores two
- In the code, the score is X's runs minus O's runs. Positive means X is ahead, negative means O is, zero is a tie. On the 3x3 board the game ends the moment the score is anything other than 0
That one number, X minus O, runs through the whole project. X wants it big, and O wants it small (negative).
Submitting
As before, each checkpoint and the final project has its own Gradescope assignment, which asks you to log into GitHub and point it at your repo. Pick the main branch (making sure all your work is on main).
Checkpoint 1: The board
Everything else in this project is built on the board, so we need to build that first.
What you are given
Open src/board.rs. The types at the top are written for you:
Cellis an enum representing one square. It is eitherEmpty,Wall,X, orO.Cell::mark(player)gives the mark a player makesPositionis(row, col), both counted from zero at the top left. The line that defines it,pub type Position = (usize, usize);, makesPositiona type alias, which is new: a second name for a type that already exists. Unlike a tuple struct, which you have seen, it makes no new type. A plain(1, 2)already is aPosition, and you take one apart the way you would any tuple, withlet (row, col) = position;. The alias is there so a function signature can sayPosition, where(usize, usize)would be less clearBoardhas three fields:cells, aVec<Vec<Cell>>so thatcells[row][col]is one square;to_move, whose turn it is; andhistory, aVec<Position>of every move made so far, in order
Some methods are written too. size() is the number of rows, which is also the number of columns. cell(row, col) reads one square. to_move() says whose turn it is. And Board::from_rows builds a board from text, which you will use constantly:
let board = Board::from_rows(&["XX.", ".O.", "..#"]);
X and O are marks, # is a wall, and anything else is empty. X is to move unless X already has more marks than O. The starting boards in src/layout.rs are built the same way.
What you are writing
Five methods, each marked todo!:
moves()returns every empty position, top to bottom and left to right. These are the legal movesapply_move(position)puts the current player's mark there, records the move inhistory, and makes it the other player's turn. If the cell isn't empty, it panics, with a message that includes the wordillegal.undo()takes back the last move: everythingapply_movedid, backwards. It panics withnothing to undoif there's nothing to take backscore()counts the runs of three. Every run of X's is plus one, every run of O's is minus oneis_over()says whether the game is finished: no moves left on any board, or three in a row on the 3x3 board
Notice what history is for. Minimax will try a move, look at what happens, then take it back and try the next one, thousands of times. apply_move pushes onto the end of history and undo pops off the end, so the last move in is the first one out. That shape should be familiar (it's a stack!) and we'll see it more deeply in lecture soon.
score() is the most involved method to write. Every three-in-a-row has a first cell, and from there it goes in one of four directions: right, down, down-right, or down-left. Left and up would wind up double-counting the same runs. So for every cell on the board, look in each of the four directions, skip any direction where the third cell would fall off the board, and check whether all three cells hold the same mark. Rows and columns are usize, so the down-left direction needs care: a usize can't go below zero, and asking it to panics.
Your tests
tests/my_tests.rs has one example test on score and room for yours. Write at least three more.
What makes a test worth writing? Think about how score could be broken. A score that forgets one of the four directions would pass a test on rows and columns. One that only checks the first three cells of a row passes on a 3x3 board and misses runs on a 5x5. One that stops at the first run it finds gets a four-in-a-row wrong. Build a position with Board::from_rows where exactly one of those mistakes would show, and assert the right answer. The tests we wrote in cp1.rs are the same idea, and reading them is a good way to see what yours could add.
We will run your tests against boards we broke on purpose, after the deadline. A test that catches the breaks earns credit!
Checklist
- Make your own private copy of the Project 3 repository with Use this template, then clone it
-
Put your name and your GitHub username on the two lines at the top of
README.md -
Make a
checkpoint-1branch -
The five board methods work, and
cargo test --test cp1is entirely green, twenty-six tests -
At least three tests of your own in
tests/my_tests.rs, and they pass -
cargo run -- human randomlets you play a game -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Remember you can run a subset of tests by name, so
cargo test --test cp1 movesruns only the tests ofmoves BoardhasPartialEq, so a test can compare two whole boards withassert_eq!. Theundotests do exactly that: apply, undo, and check the board is what it was- Each of the four directions in
scoreis a pair of steps: how much the row and the column change for each cell along the run. Right is(0, 1), down is(1, 0), down-right is(1, 1), and down-left is(1, -1). Put the four pairs in an array and loop over it, and the three cells of a run are(row, col),(row + step_row, col + step_col), and(row + 2 * step_row, col + 2 * step_col). That lets you write one loop instead of four - Two catches with the steps. They can be negative, so they can't be
usize: do the arithmetic inisize, check the result is on the board, and only then convert back withas usizeto index intocells(or check when you've hit zero before subtracting). And Rust won't add two tuples for you, so(row, col) + (step_row, step_col)doesn't compile; you'll need to add the two parts separately - Play a few games against
randomonce the board works. You'll noticehumanmoves aren't timed, and the board prints its row and column numbers so you can type a move as two numbers
Checkpoint 2: Minimax
How to think ahead
Here is a 3x3 position with X to move:
X | O | X
---+---+---
| O |
---+---+---
| |
X has four choices. Suppose X plays bottom left. Then O has three choices, and one of them, bottom middle, wins the game for O. So "bottom left" is a bad move for X, because of what O can do later.
Minimax expands on this lesson. Think of every position as a node in a tree, with the current board at the root and one child for every legal move. At the bottom of the tree are finished games, and a finished game has a score: the board's score(), positive if X won. Now we can give every unfinished node a score too, working upward. At a node where it's X's turn, X will pick the child with the biggest score, so that's the node's score. At a node where it's O's turn, O picks the smallest. If we continue backwards, the score that ends up at the root will be how the game ends if both players play perfectly.
X maximizes, O minimizes, hence the name "minimax". Both players are playing the same game with the same information, they just want the score to go opposite ways.
Two things to notice. 1) The algorithm is recursive, since the score of a node is a function of the scores of its children, and the base case is a finished game whose score is obvious. 2) The strategy never has "intuitions" about the game: it doesn't know that the center is a good square, or to try to trap the opponent between two bad moves. It's just simulating and accounting.
What you are given
src/agent.rs has the Agent trait:
pub trait Agent {
fn name(&self) -> String;
fn choose_move(&self, board: &Board, time_limit: Duration) -> Position;
}
An agent is anything that can look at a board and pick a move. The move has to be one of board.moves(), and it has to come back inside the time limit, or the game is forfeited. Four agents are written for you: FirstMove plays the first legal move it finds, Random picks one at random, Greedy tries every move and keeps the one that makes the score best right now, and Human asks you interactively. It may help to read Greedy, as it's similar to the loop you're about to write, without the recursion.
The trait has one more method, is_human, with a default that returns false. Human overrides it so that a person at the keyboard isn't on the clock. Leave it alone in your own agent. The tournament checks for it, and an entry that overrides it is out.
src/game.rs has play_game, which runs one game between two agents, times every move, and reports who won. It takes its two agents as &dyn Agent. This means play_game works for any two agents, of any two types, as long as they implement the trait. We'll come back to that in checkpoint 3.
src/minimax.rs has the Minimax struct, which is yours to write. It has three fields: max_depth (how far to look ahead), label (what it calls itself), and heuristic (the function it uses to guess at a position it didn't finish searching). Three constructors fill them in. Minimax::new() searches to the end of the game, Minimax::with_depth(d) stops after d moves and guesses, and Minimax::with_heuristic(d, name, f) lets you choose the guessing function too. Checkpoint 2 only asks you to write out Minimax::new().
What you are writing
Two functions in src/minimax.rs:
search(&self, board: &mut Board, depth: usize) -> i32is the recursion step. It returns the score the next player can get if they move optimally from this position:- If the game is over, that's just
board.score(). - If
depthis zero, the agent is left to make an assumption using(self.heuristic)(board), which by default returns the score at that point. (The first pair of parentheses picks out the function stored in the field; the second pair calls it. Without the first pair Rust looks for a method namedheuristic, and there isn't one.) - If
depthis positive, it looks at every available move, applies it, callssearchwith one less depth, undoes, and keeps the best (the biggest result if X is to move or the smallest if O is next)
- If the game is over, that's just
choose_movewrapssearchso that it remembers which move gave the best score, and returns that as the next move
A few things for you to work out:
- Whose turn is it?
board.to_move()always knows, at every level of the recursion. Remember that X maximizes and O minimizes, so compare scores accordingly. If you write the recursion assuming your agent is always X, it will play well as X and lose as O - Clone or undo?
choose_moveis given&Board, which is an immutable reference, so it can't change it. So you'll need to clone it once to get a board of your own. Inside the loop you have a choice: either clone the board again before each move, or (with it mutable) apply the move, search, and undo it. Either will work, though one of them is slower and uses more memory (do you know which?) - Starting depth.
choose_moveapplies one move itself before callingsearch, so that move is the first level of the search and the call isself.search(&mut board, self.max_depth - 1). The constructors won't allow you to start with a depth of zero, so this subtraction is always safe. (A depth of one looks at each legal move and nothing further, which withscore_onlyis exactly whatGreedydoes! TryMinimax::with_heuristic(1, "greedy again", score_only)in the arena later and see if you can tell them apart)
Testing it
Play it. cargo run -- human minimax and cargo run -- minimax human, so you're O in one and X in the other. You should never be able to beat it. If you do, that game is a bug report: write down the moves.
Then the tests. cargo test --test cp2 tactics sets up six positions by hand and checks the move your agent picks: take a win when there is one, block when there isn't, as X and as O. cargo test --test cp2 games plays full games against FirstMove and Greedy, both colors, and expects a win each time, then twenty games against Random each way and expects you never to lose. Last, it plays your agent against itself and expects a draw, which is what perfect 3x3 play looks like.
After the deadline we also play you against an agent that isn't in your repo. It uses minimax too, so it never loses either; the tests check that you don't.
Checklist
-
Make a
checkpoint-2branch frommain -
searchandchoose_movework, andcargo test --test cp2all pass -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- If a tactics test fails, the position is right there in the test, and you can build it in
main.rswithBoard::from_rowsand print what your agent does - A
gamestest that fails prints the final board. Look at where your agent was when it went wrong, then set that position up by hand - If
never_loses_to_randomfails once in a while and the others pass, you have a bug that only shows up on some move orders - Full search from an empty 3x3 board visits about half a million positions and should take well under a second. If it takes much longer, see if you can clone less and undo more
Checkpoint 3: The 5x5 game, and the tournament
Why the 3x3 agent can't play 5x5
Try it (and be ready to kill it):
cargo run -- minimax greedy --board open --depth 100
Nothing happens for a very long time. An empty 5x5 board has 25 legal moves, then 24 next moves, then 23, and the tree has about 25! leaves, which is a number with 26 digits. Checkpoint 1's score() on each would take... longer than the universe has been around. The depth limit is how every game-playing program handles this, in small projects like ours up to chess engines. You just get to look ahead a fixed number of moves, and at that point guess how the game will go instead of playing it out any further.
If we only look four moves ahead, the tree from an empty 5x5 board has 25x24x23x22 = 303,600 leaves, which takes about a quarter of a second. Five moves ahead is 21 times more, and it doesn't fit in the one-second limit, at least with the search as you've written it. So we'll be working with a 4-step look-ahead for most of the rest of the project.
The heuristic
With Minimax::with_depth(4), your search already stops at depth zero and calls the agent's heuristic. For new() and with_depth() that is the function my_heuristic in minimax.rs, which in the template just returns board.score(), which is the current net score (who is ahead right now). That's a decent guess, and you can try it against Greedy a few times:
cargo run -- minimax greedy --board walls
cargo run -- greedy minimax --board walls
It wins most of the time, and it also draws some and loses some, because it's not doing a great job of evaluating what might happen later in the game. Two X's in a row with an empty third cell count for nothing in this strategy, even though they're about to earn a point. Your job now is to make heuristic smarter. Keep it in the same units as score() (positive for X and negative for O), so the search can compare a guess with a real finished game, and think about what makes a position promising. Some ideas:
- Two in a row with the third cell empty, for either player
- Whether a cell is in many possible open lines (not blocked by walls) or few
- Whether it's early or late in the game. Potential matters more early, while points matter more late
The tests ask for a heuristic that never loses to Greedy on the six standard boards, as X and as O, and wins at least ten of those twelve games. The stencil's score() wins nine, draws two and loses one. One more test, heuristic_sees_more_than_score, gives your heuristic two positions that score() can't tell apart and asks which is better for X.
Measuring a heuristic
Beyond the tests, the measure of a heuristic is whether an agent using it beats an agent that doesn't. You can experiment with this: Minimax::with_heuristic(depth, name, function) builds an agent out of any function with the signature fn(&Board) -> i32, so you can pit two versions of your heuristics against each other in a tournament:
Box::new(Minimax::with_heuristic(4, "score only", score_only)),
Box::new(Minimax::with_heuristic(4, "open twos", open_twos)),
Passing a function by name, without calling it, is new. Parentheses are what call a function, so open_twos on its own is the function itself, handed over as a value for Minimax to store and call later. We'll see a lot more of this in the iterators lecture.
src/bin/arena.rs is set up to help you do this. It's a playground like the ones in Project 2: yours to edit, and not graded. It builds a Vec<Box<dyn Agent>> out of Greedy and four Minimax variants, two heuristics at two depths, and runs them through your round_robin on the six standard boards:
cargo run --bin arena
Add your versions, change the depths, swap in layout::sized(7). The writeup asks you to run this experiment with your own heuristic and report what you find.
Getting creative with the time limit
Every turn a player has one second to move. An agent that runs over forfeits the game, so a search that's too deep will always lose. Depth 4 fits comfortably, but depth 5 doesn't.
If you want to try for more depth, and in the tournament more depth is a real advantage, the trick is to skip the parts of the tree that can't change the answer, so the same second buys more depth. You can look up alpha-beta pruning, which is a well-documented algorithm, and try to implement it if you'd like. But it isn't required for the project.
Your agent can also see the time limit, so you could always search deeper when the board is nearly full and there are fewer moves to consider to make the best use of your one second, and search shallower when the board is empty. You're also not required to try that.
The round robin
This is the part that needs dyn. Open src/tournament.rs. Standing represents the results for one agent in the final results table. You need to fill in the round_robin function:
pub fn round_robin(agents: &[Box<dyn Agent>], boards: &[Board], time_limit: Duration) -> Vec<Standing>
Every agent plays every other agent, on every starting board, once as X and once as O. The standings come back sorted, most points first, three for a win and one for a draw.
Look at the type of agents. Remember from lecture why it can't be Vec<Agent>, or Vec<dyn Agent>: the agents are different types, and different sizes, so each one has to live on the heap behind a Box, and the Vec holds the boxes.
To hand an agent to play_game, which wants a &dyn Agent, write &*agents[i]: the * follows the pointer into the box, and the & borrows what's there (without the box).
cargo run -- tournament --board walls runs your round robin with FirstMove, Random, Greedy, and your Minimax on six fixed boards, and prints the table. Your agent should be at the top!
Entering the class tournament
Every agent submitted by the December 4 deadline is entered automatically. We take the src/minimax.rs from your Gradescope submission and play it against everyone else's, so there's nothing separate to hand in. Two things to set before you submit:
- Name your agent. This is what it will be called in the standings, so pick something you'd be happy to see at the top :-) Letters, digits, and underscores only, up to 20 characters. Write it on the Agent name line at the top of your
README.md, and set theAGENT_NAMEconstant at the top ofsrc/minimax.rsto the same thing. EveryMinimaxyou build takes itsname()from that constant - Pick your depth. Add a line to the top of your
README.md, right under the agent name, with the depth you want your agent to play at:**Tournament depth:** 4. More depth sees further, but your agent still has to move within the time limit. If the line is missing, we'll use 4
Three rules that make this work:
- Your
minimax.rsplays on ourboard.rs, so it can only call the board functions that came with the project. If it uses a helper you added to your ownboard.rs, move that helper intominimax.rs, or your agent won't compile and will have to sit out. - If you submit in the 48-hour late window, your agent has to sit out the tournament.
- And
is_humanhas to stay as it is (false).
The tournament runs in rounds, with the same one-second limit as your tests. Every entry plays every other on two of the standard boards, both colors, and the top half goes on. Those play again on four boards, and the top quarter goes on to a final round on all six standard boards plus six new boards with walls, so an agent that only learned the standard boards might not succeed. We'll share the results in the last lecture, round by round. Your rank doesn't affect your grade.
Checklist
-
Make a
checkpoint-3branch frommain -
my_heuristicsees more thanscore(), andMinimax::with_depth(4)never loses toGreedyon the standard boards and wins at least ten of the twelve games -
round_robinworks, andcargo test --test cp3is entirely green, eleven tests -
cargo run -- tournament --board wallsputs your agent at the top, andcargo run --bin arenahas your heuristic beatingscore_only -
Your agent name is on the Agent name line of
README.mdand inAGENT_NAME, your GitHub username is on its line, and you've added a Tournament depth line if you want something other than 4 - The writeup is done
-
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- The cp3 tests play six games each way against
Greedywith a one-second limit, and if a move runs over, the failure message says how slow your slowest move was. A lost game prints which board it was on, andlayout::walls_seeded(5, seed)with seeds 1 to 6 rebuilds the standard boards if you want to replay one - If
cargo test --test cp3hangs rather than failing, a test is running your agent with a depth it can't finish - To compare two heuristics, keep the old one as a second function and put both in the arena
standings.sort_by(...)with a closure orsort_by_keywill both help sort standings
The writeup
Your writeup goes in the README of your repo, under the headings that are already there. Leave the rest of that file alone.
Two to three sentences per question, unless it says otherwise. The answers have to be in your own words. You can use AI to help you understand a question, but not to write the answer, and the code review opens with your writeup, so be ready to say more about anything you wrote.
1. Clone or undo. In search, did you clone the board before each move, or apply the move and undo it? What does the other choice cost, in memory or in time?
2. One trait, many agents. FirstMove, Random, Greedy, and Minimax are four structs that each implement Agent. We could have written one Agent struct with a kind enum and a match inside choose_move. What would be harder about adding a classmate's agent to the tournament under that design? What would be easier?
3. Why Vec<Box<dyn Agent>>. In your own words: why won't Vec<Agent> compile, why won't Vec<dyn Agent>, and what does the Box fix?
4. How big is the tree. Run your agent against Greedy on open boards of size 5 and 7, at depths 2, 3 and 4, and note the slowest move time each game reports: cargo run -- minimax greedy --board open --size 7 --depth 3. Put the six times in a table. Then explain them: how many leaves does the search visit from an empty n by n board at depth d, and what happens to that count when n goes from 5 to 7 at the same depth, or d goes up by one? If heuristic looks at every cell in every direction, roughly how much work is one move, in big-O terms, as a function of n and d?
5. Your heuristic. What does it reward, and why did you think that would matter? Then the experiment: run the arena with score_only and your heuristic at two depths each, paste the standings, and explain them. Which mattered more, the heuristic or the depth? Did anything surprise you?
6. Process. What did you try first that you ended up changing, and why? Name a specific commit where you made that change. If you had another week, what would you do to improve your agent?
Your AI citation. Required. Which tools you used, for what parts of the project, and how. If you didn't use AI at all, say that; an empty section reads as a missing one. Course policy is in the syllabus.