Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
The whole game
Read it, run it, change a line and run it again.
Loading editor…
The parts of the implementation page in one file. It shows a draw, a refused move, a win and a step back. Try `Game(5)`, a move after the end, or a replay from a list of squares.
The same in Java
import java.util.*;enum Mark { X, O; Mark other() { return this == X ? O : X; }}enum Status { PLAYING, X_WON, O_WON, DRAW }record Move(int row, int col, Mark mark) {}/** Outside, taken, not your turn, or the game is over. */final class IllegalMove extends RuntimeException { IllegalMove(String why) { super(why); }}/** The squares, and nothing else: no turns, no winners. */final class Board { private final Mark[][] cells; // null is empty private int empty; Board(int size) { cells = new Mark[size][size]; empty = size * size; } int size() { return cells.length; } Mark at(int row, int col) { return cells[row][col]; } boolean holds(int row, int col) { return row >= 0 && row < size() && col >= 0 && col < size(); } void put(Move move) { if (cells[move.row()][move.col()] != null) throw new IllegalMove("taken"); cells[move.row()][move.col()] = move.mark(); empty--; } void clear(Move move) { cells[move.row()][move.col()] = null; empty++; } boolean full() { return empty == 0; }}/** For each line: how many marks of each kind are on it. */final class LineCounts { private final int size; private final int[][] count; // [mark][line] LineCounts(int size) { this.size = size; this.count = new int[Mark.values().length][2 * size + 2]; } private int[] lines(Move m) { int[] found = new int[4]; int n = 0; found[n++] = m.row(); // rows come first found[n++] = size + m.col(); // then columns if (m.row() == m.col()) found[n++] = 2 * size; if (m.row() + m.col() == size - 1) found[n++] = 2 * size + 1; return Arrays.copyOf(found, n); } /** Count the move. True if it completes a line. */ boolean add(Move move) { boolean won = false; for (int line : lines(move)) if (++count[move.mark().ordinal()][line] == size) won = true; return won; } void remove(Move move) { for (int line : lines(move)) count[move.mark().ordinal()][line]--; }}final class Game { private final Board board; private final LineCounts lines; private final Deque<Move> moves = new ArrayDeque<>(); private Mark turn; private Status status = Status.PLAYING; Game(int size, Mark first) { board = new Board(size); lines = new LineCounts(size); turn = first; } Mark turn() { return turn; } Status status() { return status; } Status play(Mark mark, int row, int col) { if (status != Status.PLAYING) throw new IllegalMove("the game is over"); if (mark != turn) throw new IllegalMove("not your turn"); if (!board.holds(row, col)) throw new IllegalMove("outside"); Move move = new Move(row, col, mark); board.put(move); // throws if the square is taken moves.push(move); if (lines.add(move)) status = mark == Mark.X ? Status.X_WON : Status.O_WON; else if (board.full()) status = Status.DRAW; else turn = mark.other(); return status; } Move undo() { if (moves.isEmpty()) throw new IllegalMove("nothing to undo"); Move move = moves.pop(); board.clear(move); lines.remove(move); turn = move.mark(); // it is their turn again status = Status.PLAYING; return move; } List<int[]> legal() { List<int[]> free = new ArrayList<>(); if (status != Status.PLAYING) return free; for (int r = 0; r < board.size(); r++) for (int c = 0; c < board.size(); c++) if (board.at(r, c) == null) free.add(new int[] {r, c}); return free; } /** The board as text, for screens and tests. */ List<String> rows() { List<String> out = new ArrayList<>(); for (int r = 0; r < board.size(); r++) { StringBuilder row = new StringBuilder(); for (int c = 0; c < board.size(); c++) row.append(board.at(r, c) == null ? "." : board.at(r, c).name()); out.add(row.toString()); } return out; }}public class Main { public static void main(String[] args) { Game game = new Game(3, Mark.X); int[][] squares = {{1, 1}, {0, 1}, {0, 0}, {0, 2}, {2, 2}}; for (int[] s : squares) game.play(game.turn(), s[0], s[1]); System.out.println(game.rows() + " " + game.status()); // [XOO, .X., ..X] X_WON game.undo(); System.out.println(game.status() + " " + game.turn() + " " + game.legal().size()); // PLAYING X 5 }}The same in C++
#include <array>#include <iostream>#include <optional>#include <stdexcept>#include <string>#include <utility>#include <vector>enum class Mark { X, O };constexpr Mark other(Mark m) { return m == Mark::X ? Mark::O : Mark::X; }enum class Status { Playing, XWon, OWon, Draw };struct Move { int row, col; Mark mark;};struct IllegalMove : std::logic_error { // outside, taken, not your turn, or over using std::logic_error::logic_error;};// The squares, and nothing else: no turns, no winners.class Board {public: explicit Board(int size) : size_(size), cells_(size * size), empty_(size * size) {} int size() const { return size_; } std::optional<Mark> at(int row, int col) const { return cells_[row * size_ + col]; } bool holds(int row, int col) const { return row >= 0 && row < size_ && col >= 0 && col < size_; } bool full() const { return empty_ == 0; } void put(const Move& m) { auto& cell = cells_[m.row * size_ + m.col]; if (cell) throw IllegalMove("taken"); cell = m.mark; --empty_; } void clear(const Move& m) { cells_[m.row * size_ + m.col].reset(); ++empty_; }private: int size_; std::vector<std::optional<Mark>> cells_; // row after row int empty_;};// For each line: how many marks of each kind are on it.class LineCounts {public: explicit LineCounts(int size) : size_(size) { for (auto& c : count_) c.assign(2 * size + 2, 0); } // Count the move. True if it completes a line. bool add(const Move& m) { bool won = false; for (int line : lines(m)) if (++count_[static_cast<int>(m.mark)][line] == size_) won = true; return won; } void remove(const Move& m) { for (int line : lines(m)) --count_[static_cast<int>(m.mark)][line]; }private: std::vector<int> lines(const Move& m) const { std::vector<int> found{m.row, size_ + m.col}; // rows first, then columns if (m.row == m.col) found.push_back(2 * size_); if (m.row + m.col == size_ - 1) found.push_back(2 * size_ + 1); return found; } int size_; std::array<std::vector<int>, 2> count_; // [mark][line]};class Game {public: explicit Game(int size = 3, Mark first = Mark::X) : board_(size), lines_(size), turn_(first) {} Mark turn() const { return turn_; } Status status() const { return status_; } Status play(Mark mark, int row, int col) { if (status_ != Status::Playing) throw IllegalMove("the game is over"); if (mark != turn_) throw IllegalMove("not your turn"); if (!board_.holds(row, col)) throw IllegalMove("outside"); Move move{row, col, mark}; board_.put(move); // throws if the square is taken moves_.push_back(move); if (lines_.add(move)) status_ = mark == Mark::X ? Status::XWon : Status::OWon; else if (board_.full()) status_ = Status::Draw; else turn_ = other(mark); return status_; } Move undo() { if (moves_.empty()) throw IllegalMove("nothing to undo"); Move move = moves_.back(); moves_.pop_back(); board_.clear(move); lines_.remove(move); turn_ = move.mark; // it is their turn again status_ = Status::Playing; return move; } std::vector<std::pair<int, int>> legal() const { std::vector<std::pair<int, int>> free; if (status_ != Status::Playing) return free; for (int r = 0; r < board_.size(); ++r) for (int c = 0; c < board_.size(); ++c) if (!board_.at(r, c)) free.emplace_back(r, c); return free; } // The board as text, for screens and tests. std::string text() const { std::string out; for (int r = 0; r < board_.size(); ++r) { for (int c = 0; c < board_.size(); ++c) { auto m = board_.at(r, c); out += !m ? '.' : *m == Mark::X ? 'X' : 'O'; } out += '\n'; } return out; }private: Board board_; LineCounts lines_; std::vector<Move> moves_; Mark turn_; Status status_ = Status::Playing;};int main() { Game game; for (auto [r, c] : {std::pair{1, 1}, {0, 1}, {0, 0}, {0, 2}, {2, 2}}) game.play(game.turn(), r, c); std::cout << game.text() << (game.status() == Status::XWon ? "X won\n" : "?\n"); game.undo(); std::cout << (game.turn() == Mark::X) << ' ' << game.legal().size() << '\n'; // 1 5}The same in TypeScript
type Mark = "X" | "O";const other = (mark: Mark): Mark => (mark === "X" ? "O" : "X");type Status = "playing" | "X won" | "O won" | "draw";interface Move { readonly row: number; readonly col: number; readonly mark: Mark }/** Outside, taken, not your turn, or the game is over. */class IllegalMove extends Error {}/** The squares, and nothing else: no turns, no winners. */class Board { readonly size: number; readonly #cells: (Mark | null)[][]; #empty: number; constructor(size: number) { this.size = size; this.#cells = Array.from({ length: size }, () => Array<Mark | null>(size).fill(null)); this.#empty = size * size; } at(row: number, col: number): Mark | null { return this.#cells[row][col]; } holds(row: number, col: number): boolean { return [row, col].every((n) => Number.isInteger(n) && n >= 0 && n < this.size); } put(move: Move): void { if (this.#cells[move.row][move.col] !== null) throw new IllegalMove("taken"); this.#cells[move.row][move.col] = move.mark; this.#empty--; } clear(move: Move): void { this.#cells[move.row][move.col] = null; this.#empty++; } get full(): boolean { return this.#empty === 0; }}/** For each line: how many marks of each kind are on it. */class LineCounts { readonly #size: number; readonly #count = new Map<string, number>(); constructor(size: number) { this.#size = size; } #lines({ row, col, mark }: Move): string[] { const lines = [`${mark} row ${row}`, `${mark} col ${col}`]; if (row === col) lines.push(`${mark} down`); if (row + col === this.#size - 1) lines.push(`${mark} up`); return lines; } /** Count the move. True if it completes a line. */ add(move: Move): boolean { let won = false; for (const line of this.#lines(move)) { const n = (this.#count.get(line) ?? 0) + 1; this.#count.set(line, n); won ||= n === this.#size; } return won; } remove(move: Move): void { for (const line of this.#lines(move)) this.#count.set(line, this.#count.get(line)! - 1); }}class Game { readonly #board: Board; readonly #lines: LineCounts; readonly #moves: Move[] = []; #turn: Mark; #status: Status = "playing"; constructor(size = 3, first: Mark = "X") { this.#board = new Board(size); this.#lines = new LineCounts(size); this.#turn = first; } get turn(): Mark { return this.#turn; } get status(): Status { return this.#status; } play(mark: Mark, row: number, col: number): Status { if (this.#status !== "playing") throw new IllegalMove("the game is over"); if (mark !== this.#turn) throw new IllegalMove("not your turn"); if (!this.#board.holds(row, col)) throw new IllegalMove("outside"); const move: Move = { row, col, mark }; this.#board.put(move); // throws if the square is taken this.#moves.push(move); if (this.#lines.add(move)) this.#status = `${mark} won`; else if (this.#board.full) this.#status = "draw"; else this.#turn = other(mark); return this.#status; } undo(): Move { const move = this.#moves.pop(); if (!move) throw new IllegalMove("nothing to undo"); this.#board.clear(move); this.#lines.remove(move); this.#turn = move.mark; // it is their turn again this.#status = "playing"; return move; } legal(): [number, number][] { if (this.#status !== "playing") return []; const n = [...Array(this.#board.size).keys()]; return n.flatMap((r) => n.filter((c) => this.#board.at(r, c) === null).map((c): [number, number] => [r, c])); } /** The board as text, for screens and tests. */ rows(): string[] { const n = [...Array(this.#board.size).keys()]; return n.map((r) => n.map((c) => this.#board.at(r, c) ?? ".").join("")); }}const game = new Game();for (const [r, c] of [[1, 1], [0, 1], [0, 0], [0, 2], [2, 2]]) game.play(game.turn, r, c);console.log(game.rows(), game.status); // [ 'XOO', '.X.', '..X' ] X wongame.undo();console.log(game.status, game.turn, game.legal().length); // playing X 5