Skip to content

Case study: Connect Four

Difficulty: Beginner

Key concepts

  • delivery framework
  • column as a stack
  • game state as an enum
  • validate before changing state
  • direction vectors
  • win from the last move
  • verification trace
  • undo history
  • computer opponent
  • How the five steps of the delivery framework turn “design Connect Four” into tested C++, one step at a time, with each step labelled so you can see where you are.
  • Why a column is stored as a stack of discs, so that a disc can never float above an empty cell.
  • Why the state of the game is one enum whose values carry the winner (red_wins, yellow_wins), instead of a flag and a separate winner that could disagree.
  • Why every move is checked before anything changes, and in which order the checks run.
  • How to find a win by looking outwards from the last disc in four directions, counting both ways, and why that is enough.
  • How to check a design by hand with a verification trace: one move per line, with what changed.
  • How a change (a board of any size, undo, and a computer player) lands, and why none of it needs a design pattern yet.

This is the beginner study. It is small on purpose, so that every step of How to approach a case study can be shown in full without the problem getting in the way. It assumes that page and Finding classes, data members, and member functions. The five steps themselves are taught on the delivery framework page; here you watch them applied.

“We want a small Connect Four game for two people sitting at one computer. Each player drops a disc into a column, and the first to get four in a row wins. Can you design the part that runs the game?”

The request is short, which is normal. It names the game and leaves almost everything else open: how big the board is, what happens when someone picks a column that is full, whether a full board is a draw. Before any class exists, those gaps have to be filled.

Step 1 turns the vague request into a numbered list that everyone can check. It has four parts: questions, scope, requirements, and the checks that will become tests.

A clarifying question is one whose answer changes the design. Each question below is here because of what its answer changes.

Question Answer (from the team) What it changes
How big is the board? The usual one: 7 columns, 6 rows. Two constants in the board, for now. (A later change makes the size a choice.)
How many in a line wins, and in which directions? Four: across, up a column, or on either diagonal. Four directions to search, and a constant 4.
Who moves first? Red, then the players take turns. The game remembers whose turn it is, starting with Red.
How does a player choose a move? By typing a column number. Columns are numbered 0 to 6 from the left. A move is one int. The game gets a number and must cope with any number, including 7 or −1.
What happens if the column is full, or not there? Say why, and let the same player try again. A refused move changes nothing, and the refusal has a reason the screen can show.
What if someone tries to move after the game ended? Refuse it. “Game over” is a reason too, and it is checked first.
Can the game end with no winner? Yes, when the board is full and nobody has four. A draw is one of the ways a game ends.
Can a player take a move back? Not for now. No history in step 1. (A later change adds undo.)
Against the computer? Two people for now. No computer player in step 1. (A later change adds one.)
Does it need saving, a network, or a clock? No. One game, one computer, no time limit. Nothing is stored, nothing is sent, and there is no timer.

Two answers shape the design most. “Say why, and let the same player try again” means a bad move is an ordinary event, not a crash, and it must leave the game exactly as it was. “Four in a row, in any direction” means the win check is the one piece of real logic in the program, so it gets the most care and the most tests.

Confirmed (by the answers above):

  • A 7 by 6 board, two players, Red first, turns that alternate.
  • A disc falls to the lowest empty cell of its column.
  • A move into a full column, a column that does not exist, or a game that has ended is refused with a reason, and changes nothing.
  • Four or more in a line, in any of the four directions, wins.
  • A full board with no line is a draw.

Assumed (to confirm with the team; see Assumptions):

  • The game shows the board as plain text, with R for red, Y for yellow, and . for an empty cell. A real screen would draw it, but the rules do not care how.
  • If the very last cell makes a line, that is a win, not a draw. It is rare, but the rules must say something, and a win is what players expect.

Out of scope: a graphical screen, reading the keyboard (the program that uses the game does that), saving a game, playing over a network, time limits, and more than two players. Undo, a computer player, and other board sizes arrive later as a change, in Step 5.

Functional requirements (what the program must do; see functional requirement):

  • FR-1 Moves. Red moves first and the players then take turns. A move names a column, and the player’s disc falls to the lowest empty cell in it.
  • FR-2 Refused moves. A move is refused, with a reason, if the game has ended, if the column does not exist, or if the column is full. A refused move changes nothing, and the same player is still to move.
  • FR-3 Winning. A move that makes a line of four or more of the mover’s discs, across, up, or on either diagonal, wins, and the game ends.
  • FR-4 Drawing. A move that fills the board without making a line ends the game in a draw.
  • FR-5 Showing. Each move reports what happened in words, and the board can be shown as text.

Non-functional requirements (how well, or under what limits; see non-functional requirement):

  • NFR-1 Testable without a screen. The game takes column numbers and returns results. It reads no keyboard and prints nothing, so a test can play a whole game in a few lines.
  • NFR-2 A bug is loud. If code inside the program skips a check (not a player: the program), the board throws an exception rather than storing a disc where none can be.
  • NFR-3 One thread. One game is played by one thread. Nothing here is safe to share between threads. The code has no locks, and its comments do not mention threads, so this page is where the rule is stated.

A use case is one actor reaching one goal. Each has acceptance criteria: checkable statements that become tests. The tests in the example are named after these, so ac_2_2_a_full_column_is_refused checks AC-2.2.

UC-1 Make a move.

  • AC-1.1 Red moves first, and turns alternate.
  • AC-1.2 A disc falls to the lowest empty cell of its column.
  • AC-1.3 A move reports what happened, such as “Red drops into column 2.”
  • AC-1.4 The board is shown top row first, with the columns numbered underneath.

UC-2 Have a bad move refused.

  • AC-2.1 A column off the board (−1, 7, 100) is refused, and nothing changes.
  • AC-2.2 A full column is refused, and the same player tries again. A column with five discs still takes a sixth.
  • AC-2.3 After a win or a draw, every move is refused, and “game over” is the reason given, even for a column that does not exist.
  • AC-2.4 If code calls the board directly with a bad column or a full one, the board throws.

UC-3 Win.

  • AC-3.1 to AC-3.4 Four up a column, across a row, on a rising diagonal, and on a falling diagonal each win. A line of Yellow’s discs wins for Yellow just as a line of Red’s wins for Red.
  • AC-3.5 A disc dropped into the middle of a line completes it, and a line is found whichever of its discs is asked about.
  • AC-3.6 Lines that touch an edge or a corner count.
  • AC-3.7 Three in a line, a gap, a disc of the other colour, or a line that would only exist by wrapping past an edge, is not a win.
  • AC-3.8 A line longer than four wins. An empty cell has no line.

UC-4 Draw.

  • AC-4.1 A full board with no line is a draw.
  • AC-4.2 A move that fills the last cell and makes a line is a win, not a draw.

An invariant is a fact that must be true whenever no function is in the middle of running. Each one names the code that keeps it. See Invariants.

  • INV-1 No floating discs. In every column, the discs fill the cells from the bottom with no gap, and every cell above the top disc is empty. Kept by Board, which stores each column as a stack: the only way in is drop, which adds to the top.
  • INV-2 No column overflows. A column holds at most 6 discs. Kept by Board::drop, which throws for a full column, and by Game::check_move, which refuses the move before drop is called.
  • INV-3 The result cannot contradict itself. The game is in progress, won by Red, won by Yellow, or drawn: exactly one. Kept by the type: the winner is part of the Status value, so there is no second variable to disagree with it.
  • INV-4 A finished game never changes. Once the status is not in_progress, the board stays as it is. Kept by check_move, whose first check is “game over”.
  • INV-5 Turns alternate. Red has as many discs as Yellow, or one more. Kept by Game::play, which passes the turn only after an accepted move.

Step 2 of the framework: Entities and relationships

Section titled “Step 2 of the framework: Entities and relationships”

Step 2 finds the things in the problem and says who owns whom. Start from the nouns in the request and the answers: game, player, disc, column, row, cell, board, turn, move, line, winner, draw, reason. Then decide what each one becomes. Not every noun is a class; see Finding classes.

  • Board is a class. It knows where the discs are, and nothing else.
  • Column, row, and cell are positions on the board. A column becomes a stack of discs inside the board, and a row is a number. Neither needs a class of its own.
  • Disc is what a cell holds: an enum class Cell with empty, red, and yellow. A disc has no behaviour, so a class would add nothing.
  • Player is an enum class Player, Red or Yellow. The players are people at the keyboard; the program only needs to know whose turn it is.
  • Game is a class. It owns the board, the turn, and the result, and it decides whether a move is allowed.
  • Turn is a Player value inside the game. Winner and draw become values of one enum class Status.
  • Move is a column number passed to Game::play. Reason is an enum class Refusal, and the answer to a move is a small MoveResult struct.
  • Line is a length counted by the board. Nothing needs to keep a line after it is counted, so it is a number, not an object.
Entity sketch of step 1. Solid arrows: owns. Dashed arrows: uses or creates without owning
Text description of the diagram

Seven boxes. A dashed arrow from the program (main, or a test) to Game, labelled uses. Solid arrows from Game to Board (owns 1), to Player (owns the turn), and to Status (owns the result). A solid arrow from Board to Cell, labelled owns 7 columns, each a stack of 0 to 6. A dashed arrow from Game to MoveResult, labelled creates, for each move. A solid arrow from MoveResult to Refusal, labelled holds 1.

Diagram source (Mermaid)
flowchart LR
Caller["the program (main, or a test)"] -.->|"uses"| Game
Game -->|"owns 1"| Board
Game -->|"owns the turn"| Player
Game -->|"owns the result"| Status
Board -->|"owns 7 columns, each a stack of 0..6"| Cell
Game -.->|"creates, for each move"| MoveResult
MoveResult -->|"holds 1"| Refusal

Ownership here is as simple as it gets, and it is still worth saying out loud. The Game holds its Board by value: the board is built when the game is built and destroyed with it, and nothing else can hold it. The board holds its discs by value too. There are no pointers, no new, and no shared objects, so there is nothing that can be left dangling. The program that plays the game owns the Game, and reads the board through a const Board& that is valid as long as the game is.

Step 3 decides, for each class, what it must remember (its data members) and what it must do (its member functions), and justifies each from the requirements. The design below is step 1 of the example, the complete answer to FR-1 to FR-5. The change comes in Step 5.

Requirement What must be remembered Where As
FR-1 a disc falls to the lowest empty cell the discs in each column, bottom first Board std::array<std::vector<Cell>, 7> stacks_
FR-1 Red first, then turns alternate whose turn it is Game Player to_move_ = Player::red
FR-2 refuse moves after the end; FR-3, FR-4 the result whether the game is over, and how it ended Game Status status_ = Status::in_progress
FR-1 7 by 6; FR-3 four wins the size and the line length Board, Game constants: Board::columns, Board::rows, Game::connect

Notice what is not in the table. There is no count of discs (the size of each stack is the count), no “last move” (the game uses it at once and forgets it), and no “winner” variable (the status says it). Every value that can be worked out from another one is worked out, not stored, so it cannot get out of step.

Need Member function Class
Is this column on the board? (FR-2) bool has_column(int column) const Board
Is this column full? (FR-2) bool column_full(int column) const Board
Is the whole board full? (FR-4) bool full() const Board
What is in this cell? (FR-5, tests) Cell at(int column, int row) const Board
Put a disc in a column, and say where it landed (FR-1) int drop(int column, Cell disc) Board
How long is the line through this disc? (FR-3) int longest_line_through(int column, int row) const Board
May the player to move play here, and if not, why? (FR-2) Refusal check_move(int column) const Game
Play a move (FR-1 to FR-5) MoveResult play(int column) Game
Who is to move, how is it going, what is on the board? to_move(), status(), board(), all const Game

The split follows one question: is this about where the discs are, or about the rules? The board answers geometry: which cells exist, which are full, how long a line is. The game answers rules: whose turn it is, whether a move is allowed, and whether a line of that length wins. That is why longest_line_through returns a length and not “won or not”: the board does not know that four wins. The same board would serve a game where three wins, which is exactly what the change in Step 5 needs.

A class outline is one box per class, listing its data members (-) and member functions (+) as C++ declarations, as described in Finding classes. Data members are private unless the outline says otherwise.

enum class Cell

what one cell holds

Values

  • empty
  • red
  • yellow

enum class Player

red always moves first

Values

  • red
  • yellow

enum class Status

the winner is part of the value

Values

  • in_progress
  • red_wins
  • yellow_wins
  • draw

enum class Refusal

why a move was refused

Values

  • none the move is allowed
  • game_over
  • no_such_column
  • column_full

struct MoveResult

what play() returns; public members

Data members

  • Refusal refusal = Refusal::none;
  • std::string message; in words, for the person playing

Member functions

  • bool accepted() const; refusal == Refusal::none
The small value types of step 1

class Board

where the discs are; knows nothing about turns or winning

Data members

  • std::array<std::vector<Cell>, 7> stacks_; owned; column c is stacks_[c], bottom disc first

Member functions

  • bool has_column(int column) const;
  • bool column_full(int column) const; the column must exist
  • bool full() const;
  • Cell at(int column, int row) const; throws std::out_of_range off the board
  • int drop(int column, Cell disc); returns the row; throws for a bad or full column
  • int longest_line_through(int column, int row) const; 0 for an empty cell

class Game

the rules; owns the board; not thread-safe

Data members

  • Board board_; owned, by value
  • Player to_move_ = Player::red;
  • Status status_ = Status::in_progress;

Member functions

  • Refusal check_move(int column) const; changes nothing
  • MoveResult play(int column); a refused move changes nothing
  • Status status() const;
  • Player to_move() const;
  • const Board& board() const; read-only view, valid while the game lives
The board and the game in step 1, with the owner of each member

The code on this page comes from the example’s files, so it cannot drift from what was compiled and tested. Here are the small types first.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.hpp
// What one cell of the board holds. A cell above the top disc of its column
// is empty.
enum class Cell { empty, red, yellow };

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// The two players. Red always moves first.
enum class Player { red, yellow };
// The other player: red gives yellow, yellow gives red.
[[nodiscard]] Player other(Player player);
// The disc a player drops: Cell::red for red, Cell::yellow for yellow.
[[nodiscard]] Cell disc_of(Player player);
// "Red" or "Yellow".
[[nodiscard]] std::string to_string(Player player);

An enum class is a type with a fixed list of named values. Unlike a plain enum or an int, its values do not turn into numbers by themselves, so Cell::red cannot be passed where a Player is expected by mistake. That is why there are two enums that look alike: a Cell can be empty, a Player cannot. disc_of is the one place that turns a player into the disc they drop.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// Where the game is. The winner is part of the value (red_wins or
// yellow_wins), so there is no separate "winner" field that could disagree
// with it, such as a draw that also has a winner.
enum class Status { in_progress, red_wins, yellow_wins, draw };
// "in progress", "Red wins", "Yellow wins", or "draw".
[[nodiscard]] std::string to_string(Status status);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// Why a move was refused. none means the move is allowed.
enum class Refusal { none, game_over, no_such_column, column_full };
// "none", "game over", "no such column", or "column full".
[[nodiscard]] std::string to_string(Refusal refusal);
// What play() returns. refusal says, for a program, what happened; message
// says it in words for the person playing.
struct MoveResult {
Refusal refusal = Refusal::none;
std::string message;
[[nodiscard]] bool accepted() const { return refusal == Refusal::none; }
};

MoveResult answers two readers at once. A program (or a test) reads refusal, which it can compare; a person reads message. A refused move is not an exception, because a player picking a full column is an ordinary thing that happens many times a game, and the caller must always handle it. Exceptions are kept for bugs (NFR-2).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.hpp
// A board 7 columns wide and 6 rows high. Columns are numbered 0 to 6 from
// the left and rows 0 to 5 from the bottom, so (column 0, row 0) is the
// bottom-left cell.
//
// Each column is stored as a stack of the discs in it, bottom disc first.
// A disc always falls to the lowest free cell, so a column never has a gap:
// dropping a disc is a push_back, and the height of a column is the size of
// its stack.
class Board {
public:
static constexpr int columns = 7;
static constexpr int rows = 6;
// True if column is one of 0 to 6.
[[nodiscard]] bool has_column(int column) const;
// True if the column already holds 6 discs. The column must exist.
[[nodiscard]] bool column_full(int column) const;
// True if every column is full, so no move is left.
[[nodiscard]] bool full() const;
// What is at (column, row): a disc, or Cell::empty above the top disc.
// Throws std::out_of_range for a cell outside the board.
[[nodiscard]] Cell at(int column, int row) const;
// Puts disc on top of column and returns the row it landed in.
// Throws std::out_of_range if the column does not exist, and
// std::logic_error if the column is full or disc is Cell::empty.
// Game checks a move before calling this, so a throw here means a bug in
// the caller, not a bad move by a player.
int drop(int column, Cell disc);
// The length of the longest straight line of same-colour discs that
// passes through (column, row), in any of the four directions
// (across, up, and the two diagonals). 0 if that cell is empty.
[[nodiscard]] int longest_line_through(int column, int row) const;
private:
[[nodiscard]] bool inside(int column, int row) const;
[[nodiscard]] int count_from(int column, int row, int column_step, int row_step) const;
[[nodiscard]] const std::vector<Cell>& stack(int column) const;
// stacks_[c] holds the discs in column c, bottom first. Every stack
// starts empty.
std::array<std::vector<Cell>, columns> stacks_;
};
How this code works: Why a column is a stack

A board looks like a grid, so the first idea is a grid: 6 rows of 7 cells, Cell cells[6][7]. That works, but then “drop a disc into column 3” has to search column 3 from the bottom for the first empty cell, and nothing stops a bug from writing a disc into row 5 of an empty column, floating in the air.

Storing each column as a stack of the discs in it, bottom first, makes both problems go away:

  1. Dropping is adding to the top. drop is a push_back, and the row the disc landed in is the size of the stack minus one. There is no search.
  2. A gap cannot be stored. A std::vector has no holes, so the only cells that can hold a disc are rows 0 up to the height of the column. INV-1 (no floating discs) is kept by the shape of the data, not by care.
  3. “Full” is a size. A column is full when its stack holds 6 discs.
  4. Reading a cell still works. at(column, row) returns the disc if row is below the height of the stack, and Cell::empty if it is above.

Here is column 0 of the step 1 demo after its six discs, as the stack holds it and as the board shows it:

Row stacks_[0][row] Shown as
5 Cell::yellow Y
4 Cell::red R
3 Cell::yellow Y
2 Cell::red R
1 Cell::yellow Y
0 Cell::red R

stacks_[0].size() is 6, so column_full(0) is true, and at(1, 0) is Cell::empty because stacks_[1] is still empty.

The std::array holds exactly 7 stacks, one per column, and each std::vector starts empty. Both live inside the Board object, so the board can be copied, compared as text, and destroyed with no extra code: this is the rule of zero in practice.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// One game of Connect Four on a 7 by 6 board; four in a line wins.
class Game {
public:
// A line this long, or longer, wins.
static constexpr int connect = 4;
// Checks a move for the player whose turn it is, without changing
// anything. Returns the first reason that applies, in this order: the
// game is already over, the column does not exist, the column is full.
// Returns Refusal::none if the move is allowed.
[[nodiscard]] Refusal check_move(int column) const;
// The player whose turn it is drops a disc into column. A refused move
// changes nothing and the same player is still to move. An accepted move
// places the disc, then the game is won, drawn, or still in progress,
// and the turn passes to the other player.
MoveResult play(int column);
[[nodiscard]] Status status() const { return status_; }
// Whose turn it is. Only meaningful while the game is in progress.
[[nodiscard]] Player to_move() const { return to_move_; }
[[nodiscard]] const Board& board() const { return board_; }
private:
Board board_;
Player to_move_ = Player::red;
Status status_ = Status::in_progress;
};

The Game holds three things and offers two actions. check_move only looks; play changes things. Keeping the check separate means the program can ask “may I play here?” without playing, which the computer player in Step 5 relies on.

The Status of a game in step 1, and the moves that change it
Text description of the diagram

Four states. A new game starts in in progress, with an empty board and Red to move. In in progress, an accepted move that makes no line of four and does not fill the board stays in in progress, and so does a refused move (no such column, or column full). A move by Red that makes a line of four or more goes to Red wins; a move by Yellow that does goes to Yellow wins. A move that fills the board without a line goes to draw. In Red wins, Yellow wins, and draw, every move is refused as game over, and the state does not change. There is no way out of the three end states in step 1.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> in_progress : Game built, empty board, Red to move
in_progress --> in_progress : accepted move, no line of 4, board not full
in_progress --> in_progress : refused move (no such column, column full)
in_progress --> red_wins : Red's move makes a line of 4 or more
in_progress --> yellow_wins : Yellow's move makes a line of 4 or more
in_progress --> draw : a move fills the board with no line
red_wins --> red_wins : any move, refused as game over
yellow_wins --> yellow_wins : any move, refused as game over
draw --> draw : any move, refused as game over

The three end states have no way out. That is INV-4, and the diagram makes it easy to see: the only arrows that leave an end state come back to it. In Step 5, undo adds the first arrow out.

Step 4 writes the code for the important functions, checks the edge cases, and then traces a real game through the code by hand. There are three functions worth real attention: checking a move, playing it, and finding a line.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.cpp
// Game over is checked first: once the game has ended, no move is allowed,
// whatever the column. has_column is checked before column_full, because
// column_full may only be asked about a column that exists.
Refusal Game::check_move(int column) const {
if (status_ != Status::in_progress) return Refusal::game_over;
if (!board_.has_column(column)) return Refusal::no_such_column;
if (board_.column_full(column)) return Refusal::column_full;
return Refusal::none;
}

check_move asks three questions, and the order matters:

  1. Is the game over? First, because once the game has ended, no move is allowed whatever the column. If this came later, a finished game asked about column 9 would answer “no such column”, which is true but not the reason the move is refused (AC-2.3).
  2. Does the column exist? Second, because the next question may only be asked about a real column: column_full(9) would look for a stack that does not exist, and throws.
  3. Is the column full? Last.

Each if returns as soon as it finds a reason, so later questions are never asked once one has failed. This is often called an early return, and it keeps the function flat: one line per rule, in the order the rules apply.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.cpp
MoveResult Game::play(int column) {
// 1. Validate before changing anything. A refused move returns here, so
// the board, the turn, and the status are exactly as they were.
const Refusal refusal = check_move(column);
if (refusal == Refusal::game_over) return {refusal, "The game is over."};
if (refusal == Refusal::no_such_column) {
return {refusal, "There is no column " + std::to_string(column) + ". Choose 0 to 6."};
}
if (refusal == Refusal::column_full) {
return {refusal, "Column " + std::to_string(column) + " is full."};
}
// 2. The move is allowed: place the disc.
const Player mover = to_move_;
const int row = board_.drop(column, disc_of(mover));
std::string message = to_string(mover) + " drops into column " + std::to_string(column) + ".";
// 3. Decide the new status. Only the disc just placed can have made a
// new line, so we look from it alone. A win is checked before a draw:
// filling the last cell with a winning disc is a win.
if (board_.longest_line_through(column, row) >= connect) {
status_ = mover == Player::red ? Status::red_wins : Status::yellow_wins;
message += " " + to_string(mover) + " wins.";
} else if (board_.full()) {
status_ = Status::draw;
message += " The board is full: a draw.";
}
// 4. Pass the turn. After the game ends this no longer matters, because
// check_move refuses every move.
to_move_ = other(mover);
return {Refusal::none, message};
}
How this code works: Game::play in four steps

The function is numbered in its comments, and the numbers are the design:

  1. Validate before changing anything. check_move runs first, and each refusal returns at once with a reason and a message. Nothing has been touched yet, so a refused move leaves the board, the turn, and the status exactly as they were (FR-2). The same player is still to move, because to_move_ was never changed.
  2. Place the disc. Only now, with every check passed, does board_.drop run. It returns the row the disc landed in, which step 3 needs. mover is a copy of to_move_ taken before anything changes, so the rest of the function talks about the player who moved, even after the turn passes.
  3. Decide the new status. longest_line_through(column, row) looks at lines through the new disc only. A length of connect (4) or more is a win for mover. Only if that fails does it ask board_.full(), for a draw. Otherwise the status stays in_progress.
  4. Pass the turn. to_move_ = other(mover). After a win this does not matter, because check_move refuses every later move.

Here is one call, Red’s winning move in the step 1 demo, play(5):

Step What runs Result
1 check_move(5) Refusal::none: in progress, column 5 exists, empty
2 board_.drop(5, Cell::red) row 0
3 board_.longest_line_through(5, 0) 4, which is at least connect: status_ = Status::red_wins
4 to_move_ = other(Player::red) Player::yellow
out returned MoveResult {Refusal::none, "Red drops into column 5. Red wins."}

This is the one piece of real logic in the program. It is in two parts: counting in one direction, and putting four directions together.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.cpp
// Counts the same-colour discs next to (column, row) in one direction,
// not counting (column, row) itself. Each step moves column_step columns
// and row_step rows; for example (1, 0) walks right and (-1, -1) walks down
// and to the left. The walk stops at the edge of the board, at an empty
// cell, or at a disc of the other colour.
int Board::count_from(int column, int row, int column_step, int row_step) const {
const Cell colour = at(column, row);
int count = 0;
int c = column + column_step;
int r = row + row_step;
// inside is checked first, so at() is never asked about a cell off the
// board.
while (inside(c, r) && at(c, r) == colour) {
++count;
c += column_step;
r += row_step;
}
return count;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.cpp
// A line through the newest disc must contain that disc, so we only need to
// look outwards from it, not search the whole board. A line can run in four
// directions. For each one we count both ways from the disc: a move can
// complete a line at its end (R R R + R) or in its middle (R R + R R).
int Board::longest_line_through(int column, int row) const {
if (at(column, row) == Cell::empty) return 0;
// One step in each direction, as (columns, rows). The opposite
// directions (left, down, and so on) are covered by negating the step,
// so four are enough.
struct Direction {
int column_step;
int row_step;
};
static constexpr std::array<Direction, 4> directions{{
{1, 0}, // across
{0, 1}, // up and down
{1, 1}, // diagonal rising to the right
{1, -1}, // diagonal falling to the right
}};
int longest = 0;
for (const Direction& d : directions) {
// The disc itself, plus the run on each side of it.
const int length = 1 + count_from(column, row, d.column_step, d.row_step) +
count_from(column, row, -d.column_step, -d.row_step);
longest = std::max(longest, length);
}
return longest;
}

A direction vector is a pair of numbers: how many columns and how many rows one step moves. (1, 0) is one column right; (0, 1) is one row up; (1, 1) is up and right; (1, -1) is down and right. Its opposite is the same pair with both signs flipped: (-1, 0) is left. A straight line on the board runs in one of only four ways: across, up, or along one of the two diagonals. So four vectors, each walked forwards and backwards, cover every line through a cell.

How this code works: A win completed in the middle of a line

In the step 1 demo, Red has discs at columns 3, 4, and 6 of the bottom row, with a gap at 5, and yellow discs on top of each. Red drops into column 5, which lands in row 0. The row looks like this, with the new disc in brackets: . . . R R [R] R.

longest_line_through(5, 0) tries each direction, counting forwards with the vector and backwards with its opposite:

Direction Forwards: cells looked at Count Backwards: cells looked at Count Length = 1 + both
(1, 0) across (6, 0) red; (7, 0) off the board 1 (4, 0) red; (3, 0) red; (2, 0) empty 2 4
(0, 1) up (5, 1) empty 0 (5, −1) off the board 0 1
(1, 1) rising (6, 1) yellow 0 (4, −1) off the board 0 1
(1, -1) falling (6, −1) off the board 0 (4, 1) yellow 0 1

The longest is 4, so play makes it a win. Two things to notice:

  1. Counting only forwards would miss it. From (5, 0), looking right finds one disc. The line is mostly to the left. A move can complete a line at its end (R R R ., then R into the empty cell) or in its middle (R R . R, then R into the gap), and only counting both ways handles both.
  2. Every walk stops early. At the edge of the board, at an empty cell, or at the other colour. inside is tested before at, so at is never asked about a cell like (7, 0), which would throw.

The demo’s trace program, run against the example, printed a longest line of 4 for that disc, and of 1 or 2 for every earlier move.

Why looking only from the last disc is enough. Before the move, the game was in progress, so the board had no line of four: if it had, the game would already have ended. The move changed exactly one cell. So any line of four on the board now must pass through that one cell, and longest_line_through looks at every line through it. Nothing else on the board can have changed, so nothing else needs to be looked at. Each walk passes at most 3 discs of its colour (a fourth would have been a line of four before this move), and then reads at most one more cell, the one that stops it. So, with four to win, at most 4 directions times 2 ways times 4 cells, 32 cells around the new disc, are read, however big the board is.

play checks for a win first and for a full board second. The order matters only once per game at most, on the move that fills the last cell, and that is exactly the kind of case that is easy to get wrong.

Rule Where it lives
A disc falls to the lowest empty cell; no gaps Board: each column is a stack; drop is push_back
A column holds at most 6 discs Board::drop throws; Game::check_move refuses first
Which moves are allowed, and the reason if not Game::check_move, in that order
A refused move changes nothing Game::play, which checks before it changes
Whose turn it is, and that turns alternate Game::play, step 4
How long a line through a disc is Board::longest_line_through and count_from
How long a line must be to win Game::connect, compared in Game::play
A win on the last cell is a win the order of the if in Game::play, step 3
What a result can be enum class Status

A verification trace plays a short game through the code by hand, one line per call, and writes down what changed. It is the quickest way to find out whether a design works before trusting the tests. Here is the second half of the step 1 demo. Column 0 is already full (six discs, alternating, Red at the bottom), and Red is to move.

Move Who play(...) check_move result Lands in row Longest line through it Status after To move after
7 Red 0 column_full none none in progress Red
8 Red 7 no_such_column none none in progress Red
9 Red 3 none 0 1 in progress Yellow
10 Yellow 3 none 1 1 in progress Red
11 Red 4 none 0 2 in progress Yellow
12 Yellow 4 none 1 2 in progress Red
13 Red 6 none 0 1 in progress Yellow
14 Yellow 6 none 1 1 in progress Red
15 Red 5 none 0 4 Red wins Yellow
16 Yellow 1 game_over none none Red wins Yellow

Every value in this table was printed by a small trace program run against the step 1 files, and it matches the demo’s output below. Read it against the rules:

  • Moves 7 and 8 are refused, and the turn does not pass: Red is still to move (FR-2).
  • Move 11 is the first with a line longer than 1: Red’s discs at 3 and 4 on row 0. Move 12 gives Yellow the same, one row up.
  • Move 13 at column 6 makes a line of only 1, because column 5 is still empty: the gap breaks it (AC-3.7).
  • Move 15 fills the gap and makes 4: a win in the middle of a line (AC-3.5).
  • Move 16 is refused as game over, even though column 1 is empty (AC-2.3). The turn had passed to Yellow after the win, which is why Yellow is the one refused; it no longer matters.

The example has two steps, each a complete program with its own tests and demo:

  • Step 1 is the design above.
  • Step 2 is the change in Step 5: a board of any size, undo, and a computer player.

Inside step 1, the order is worth copying. The board came first, with drop and at and their tests, then count_from and longest_line_through with tests that draw positions directly (every direction, both ends, the middle, edges, and near misses). Only then came the Game, its refusals, and whole games played move by move. Each piece was tested before the next one used it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
Game game;
// Six discs fill column 0, alternating red and yellow, so no line.
for (int i = 0; i < 6; ++i) play(game, 0);
std::cout << "\n" << to_text(game.board()) << "\n";
play(game, 0); // refused: column 0 is full; still red's turn
play(game, 7); // refused: there is no column 7
// Red builds 3, 4 and 6 on the bottom row; yellow stacks on top of them.
for (const int column : {3, 3, 4, 4, 6, 6}) play(game, column);
play(game, 5); // red fills the gap at 5: four across, columns 3 to 6
play(game, 1); // refused: the game is over
std::cout << "\n" << to_text(game.board()) << "\n";
std::cout << "Status: " << to_string(game.status()) << "\n";
return 0;
}
Expected output
Red drops into column 0.
Yellow drops into column 0.
Red drops into column 0.
Yellow drops into column 0.
Red drops into column 0.
Yellow drops into column 0.
Y . . . . . .
R . . . . . .
Y . . . . . .
R . . . . . .
Y . . . . . .
R . . . . . .
0 1 2 3 4 5 6
Refused (column full): Column 0 is full.
Refused (no such column): There is no column 7. Choose 0 to 6.
Red drops into column 3.
Yellow drops into column 3.
Red drops into column 4.
Yellow drops into column 4.
Red drops into column 6.
Yellow drops into column 6.
Red drops into column 5. Red wins.
Refused (game over): The game is over.
Y . . . . . .
R . . . . . .
Y . . . . . .
R . . . . . .
Y . . Y Y . Y
R . . R R R R
0 1 2 3 4 5 6
Status: Red wins

Read the output against the rules:

  • Column 0 fills with six discs, alternating, and no line: four of one colour up a column needs four in a row, and these alternate.
  • Two refusals follow, a full column and a column that does not exist, each with its reason. Red is still to move after both.
  • “Red drops into column 5. Red wins.” is the move in the middle of the line, traced above.
  • The last refusal is “game over”, and the final board is unchanged by it.

The tests are named after the acceptance criteria, and run against the real Board and Game; there is nothing to fake, because the game talks to nothing outside itself. Two helpers keep them short. play_all plays a string of column digits:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Plays each column in `columns` ("0101" plays 0, 1, 0, 1), checking that
// every move is accepted.
void play_all(Game& game, const std::string& columns) {
for (const char digit : columns) {
const MoveResult result = game.play(digit - '0'); // '3' - '0' is 3
LLD_CHECK(result.accepted());
}
}

The second helper, board_from, builds a board from a picture drawn like the demo’s output, so a test of the win check can set up any position directly, without finding a game that reaches it.

The refusal tests check the reason, the message, and that nothing changed: the board as text and whose turn it is are compared before and after.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_2_1_a_column_off_the_board_is_refused) {
Game game;
for (const int column : {-1, 7, 100}) {
LLD_CHECK_EQ(game.check_move(column), Refusal::no_such_column);
const MoveResult result = game.play(column);
LLD_CHECK_EQ(result.refusal, Refusal::no_such_column);
LLD_CHECK(!result.accepted());
}
LLD_CHECK_EQ(game.play(7).message, std::string("There is no column 7. Choose 0 to 6."));
// Nothing changed: still red's turn on an empty board.
LLD_CHECK_EQ(game.to_move(), Player::red);
LLD_CHECK_EQ(to_text(game.board()), to_text(Board{}));
// The edges themselves are allowed.
LLD_CHECK_EQ(game.check_move(0), Refusal::none);
LLD_CHECK_EQ(game.check_move(6), Refusal::none);
}
LLD_TEST(ac_2_2_a_full_column_is_refused) {
Game game;
play_all(game, "000000"); // six discs, alternating colours: no line
LLD_CHECK(game.board().column_full(0));
LLD_CHECK_EQ(game.check_move(0), Refusal::column_full);
const std::string before = to_text(game.board());
const MoveResult result = game.play(0);
LLD_CHECK_EQ(result.refusal, Refusal::column_full);
LLD_CHECK_EQ(result.message, std::string("Column 0 is full."));
LLD_CHECK_EQ(to_text(game.board()), before);
LLD_CHECK_EQ(game.to_move(), Player::red); // the same player tries again
LLD_CHECK(game.play(1).accepted());
}
LLD_TEST(ac_2_2_a_column_with_five_discs_still_takes_one_more) {
Game game;
play_all(game, "00000");
LLD_CHECK(!game.board().column_full(0));
LLD_CHECK_EQ(game.check_move(0), Refusal::none);
}
LLD_TEST(ac_2_3_no_move_is_accepted_after_a_win) {
Game game;
play_all(game, "0101010"); // red: four up column 0
LLD_CHECK_EQ(game.status(), Status::red_wins);
const std::string before = to_text(game.board());
for (const int column : {1, 2, 6}) {
const MoveResult result = game.play(column);
LLD_CHECK_EQ(result.refusal, Refusal::game_over);
LLD_CHECK_EQ(result.message, std::string("The game is over."));
}
LLD_CHECK_EQ(to_text(game.board()), before);
LLD_CHECK_EQ(game.status(), Status::red_wins);
}
LLD_TEST(ac_2_3_game_over_is_the_first_reason_given) {
Game game;
play_all(game, "0101010");
// Off the board and a full column would also be refused, but the game
// being over is the reason reported.
LLD_CHECK_EQ(game.check_move(9), Refusal::game_over);
LLD_CHECK_EQ(game.check_move(-1), Refusal::game_over);
}
LLD_TEST(ac_2_3_no_move_is_accepted_after_a_draw) {
Game game;
play_all(game, "416210144241363310466123232265505465550030");
LLD_CHECK_EQ(game.status(), Status::draw);
LLD_CHECK_EQ(game.play(0).refusal, Refusal::game_over);
}
LLD_TEST(ac_2_4_the_board_throws_if_a_caller_skips_the_check) {
Board board;
LLD_CHECK_THROWS(board.drop(7, Cell::red), std::out_of_range);
LLD_CHECK_THROWS(board.drop(-1, Cell::red), std::out_of_range);
LLD_CHECK_THROWS(board.drop(0, Cell::empty), std::logic_error);
for (int i = 0; i < Board::rows; ++i) board.drop(0, i % 2 == 0 ? Cell::red : Cell::yellow);
LLD_CHECK_THROWS(board.drop(0, Cell::red), std::logic_error);
LLD_CHECK_THROWS(static_cast<void>(board.at(0, 6)), std::out_of_range);
LLD_CHECK_THROWS(static_cast<void>(board.at(7, 0)), std::out_of_range);
}

The win tests come in two kinds. Game-level tests play real moves, like this one for a disc in the middle of a line:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_3_5_a_disc_in_the_middle_of_a_line_completes_it) {
Game game;
play_all(game, "001133"); // red has 0, 1 and 3 on the bottom row
LLD_CHECK_EQ(game.status(), Status::in_progress);
play_all(game, "2"); // the gap is filled: R R R R
LLD_CHECK_EQ(game.status(), Status::red_wins);
}

Board-level tests draw positions with board_from and ask longest_line_through about each disc of a line, at the low end, in the middle, and at the high end, in all four directions, at the edges and corners, and for near misses: three in a row, a gap, the other colour, and a line that would only exist if the board wrapped from one row to the next. Step 1 has 27 tests in all.

Checking the tests. A test suite is only useful if it fails when the code is wrong. One way to check that is with mutations: small deliberate bugs, such as a wrong comparison or a missing direction, applied one at a time to a scratch copy of the code. In a run of 19 such mutations of step 1, built with AddressSanitizer and UndefinedBehaviorSanitizer so that a read past the end of a column also counts as a failure, every one made at least one test fail.

Step 5 asks: when the requirements change, how much of the design has to change with them? A good design lets most changes land in one place. Here is the change, and what it touched.

“People want to play on other sizes, so let them choose the width, the height, and how many in a line win. They also want to take a move back. And add a computer player, nothing clever, so one person can play alone.”

Three clarifying questions, with the answers this page assumes:

Question Answer assumed here
Which sizes? Any at all? From 4 to 10 each way. This is the example’s own choice, not a rule of the game.
How many back? Can a win be taken back? Any number, one at a time, back to the empty board. A win or a draw can be undone.
How good must the computer be? Simple and predictable: the same position always gives the same move.

So there are three new functional requirements:

  • FR-6 Chosen rules. A game is made with a width and a height, each from 4 to 10, and a line length from 3 to the shorter side. Anything else is refused when the game is made.
  • FR-7 Undo. The last accepted move can be taken back, repeatedly, down to an empty board. Undo after a win or a draw reopens the game.
  • FR-8 Computer player. A function picks a legal column for the player to move, by a fixed rule.

UC-5 Choose the rules. A game is made with chosen Rules.

  • AC-5.1 Sizes within the limits are accepted.
  • AC-5.2 A width or height below 4 or above 10 is refused with std::invalid_argument, including zero and negative sizes.
  • AC-5.3 A line length below 3, or longer than the board’s width or height, is refused. A length equal to the shorter side is allowed.
  • AC-5.4 Columns are checked against the chosen width.
  • AC-5.5 A column is full at the chosen height.
  • AC-5.6 The chosen line length decides a win.
  • AC-5.7 A small board can end in a draw.
  • AC-5.8 A small board prints at its own size.

UC-6 Take a move back.

  • AC-6.1 Undo with no moves does nothing and says so.
  • AC-6.2 Undo takes off the last disc and gives the turn back to the player who dropped it.
  • AC-6.3 Undo after a win, or after a draw, reopens the game.
  • AC-6.4 Undoing every move returns to the starting position.
  • AC-6.5 The history records each accepted move, in order; refused moves are not recorded.
  • AC-6.6 After undo, a different move can be played.
  • AC-6.7 The board refuses to lift a disc from an empty column.

UC-7 Let the computer move.

  • AC-7.1 With nothing to win or block, the computer plays the playable column nearest the centre, trying columns from the centre out.
  • AC-7.2 If it can win now, it does, even before blocking, and even far from the centre.
  • AC-7.3 If the opponent could win next move, it plays there to block, as either colour.
  • AC-7.4 It always chooses a legal move, the same move each time for the same position, changes nothing, and has no move when the game is over.
  • AC-7.5 would_win ignores whose turn it is, changes nothing, and is false for a full column.

Two invariants change. INV-2 now reads “a column holds at most rows discs”. INV-4 becomes “a finished game changes only by undo”: undo is the first way out of an end state.

Change Where it landed What did not change
Sizes Board stores its own width and height; Rules; Game’s constructor count_from, longest_line_through, check_move, play’s order
Line length Rules::connect, compared in play and would_win the board, which still returns only a length
Undo Move, Game::history_, Game::undo, Board::lift the rules for accepting a move
Computer new files, computer.hpp and computer.cpp, with two free functions Game, apart from the read-only would_win

The line check needed no change at all. It always worked from the size of the board and returned a length rather than “a win”, so a new size and a new length simply passed through it. That is the payoff of the small decisions in Step 3.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// The size of the board and the length of a winning line. There are no
// default values: every game states all three, and the compiler's
// missing-field warning (an error in this project's build) catches a
// forgotten one in Rules{7, 6}.
struct Rules {
int columns;
int rows;
int connect; // a line this long, or longer, wins
};
// The usual game: 7 columns, 6 rows, four in a line.
inline constexpr Rules classic{7, 6, 4};

Rules is an aggregate: a plain struct with public members and no constructor, made by listing its values in braces, as in Rules{7, 6, 4}. Its members deliberately have no default values. Here is why. Suppose someone writes Rules{7, 6}, meaning a 7 by 6 board, and forgets the line length. With a default, this would quietly mean “connect whatever the default is”. Without one, C++ fills the missing member with zero, and the compiler can warn about a member left out. This project builds with warnings as errors, so the mistake stops the build. Compiling c4::Game g{c4::Rules{7, 6}}; against step 2 gave, with g++ 11.4:

error: missing initializer for member ‘c4::Rules::connect’ [-Werror=missing-field-initializers]

and with clang++ 14:

error: missing field 'connect' initializer [-Werror,-Wmissing-field-initializers]

The warning covers a member left out of a list that names some members. Rules{}, with nothing at all, gave no warning: every member is zero. That case is caught one step later, when the game is made. In a run, Game{Rules{}} threw with the message “columns must be from 4 to 10, not 0”. classic gives the usual game a name, so most code writes Game{classic} and never spells out the numbers.

The limits are checked where the values are used:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.cpp
// The size is checked before any column is made. A bad size throws, and
// a constructor that throws leaves no Board behind, so a Board that exists
// always has a size within the limits.
Board::Board(int columns, int rows) : columns_(columns), rows_(rows) {
if (columns < min_size || columns > max_size) {
throw std::invalid_argument("columns must be from 4 to 10, not " + std::to_string(columns));
}
if (rows < min_size || rows > max_size) {
throw std::invalid_argument("rows must be from 4 to 10, not " + std::to_string(rows));
}
// One empty stack per column. static_cast: the vector's size type is an
// unsigned std::size_t, and columns is known here to be at least 4.
stacks_.resize(static_cast<std::size_t>(columns));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.cpp
// rules_ and board_ are built in the order they are declared in the class.
// Board's constructor checks the size and throws if it is wrong; the body
// then checks the line length against that board.
Game::Game(Rules rules) : rules_(rules), board_(rules.columns, rules.rows) {
const int longest_fit = std::min(rules.columns, rules.rows);
if (rules.connect < min_connect || rules.connect > longest_fit) {
throw std::invalid_argument("connect must be from 3 to " + std::to_string(longest_fit) +
", not " + std::to_string(rules.connect));
}
}

The board checks its own size, because a board of any other size would be broken whoever made it. The game checks the line length against that board, because only the game knows what a line length means. Both throw from the constructor, so a Game that exists always has rules that make sense. There is no half-made game to check later.

Why these numbers? A line of 6 cannot fit up a board 5 rows high, or on any of its diagonals. It could still fit across, if the board is wide enough, so a longer line is not impossible; but then lines would count in some directions and not in others. The example chooses that a winning line must fit in every direction, so connect can be no longer than the shorter side. A line of 2 or less would be won almost at once, so the example asks for at least 3. The size limits, 4 to 10, are the example’s own choice: up to 10 columns, every column number under the printed board is one digit, so the picture lines up; the same limits are used for rows to keep the rule simple; and 4 to 10 is wide enough for the usual variants of the game. Another program could pick other limits; what matters is that the limits are stated, checked in one place, and tested at each edge (Rules{3, 6, 3} and Rules{11, 6, 4} are refused).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_5_2_a_size_outside_the_limits_is_refused) {
LLD_CHECK_THROWS(Game(Rules{3, 6, 3}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{11, 6, 4}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{7, 3, 3}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{7, 11, 4}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{0, 0, 0}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{-7, 6, 4}), std::invalid_argument);
LLD_CHECK_THROWS(Board(4, 3), std::invalid_argument);
LLD_CHECK_THROWS(Board(3, 4), std::invalid_argument);
}
LLD_TEST(ac_5_3_the_line_length_must_be_at_least_three_and_fit_the_board) {
LLD_CHECK_THROWS(Game(Rules{7, 6, 2}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{7, 6, 0}), std::invalid_argument);
LLD_CHECK_THROWS(Game(Rules{7, 6, 7}), std::invalid_argument); // taller than 6 rows
LLD_CHECK_THROWS(Game(Rules{5, 8, 6}), std::invalid_argument); // wider than 5 columns
const Game longest{Rules{7, 6, 6}}; // as long as the shorter side: allowed
LLD_CHECK_EQ(longest.rules().connect, 6);
}

Undo needs to know which move to take back. The game keeps a history: a std::vector of every accepted move, oldest first.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.hpp
// One accepted move, as kept in the history: who dropped a disc, and into
// which column. The row is not stored: undoing the move always takes the
// top disc off that column, wherever it is.
struct Move {
Player player;
int column;
};

play adds one Move after it drops the disc, and only then, so a refused move is never in the history. Undo reads it back:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.cpp
// This is the Command idea kept as small as it can be: a record of each
// move, and a way to reverse it. Every move is the same kind of action,
// "drop a disc into a column", and its reverse is always "take the top disc
// off that column". So one plain struct and one function are enough. Command
// objects with their own execute and undo functions would pay off only if
// there were many kinds of action, each reversed in its own way.
bool Game::undo() {
if (history_.empty()) return false;
const Move last = history_.back();
history_.pop_back();
board_.lift(last.column);
to_move_ = last.player; // the player who made that move moves again
// Moves are only accepted while the game is in progress, so the game was
// in progress just before `last`, whatever `last` did to it.
status_ = Status::in_progress;
return true;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

board.cpp
void Board::lift(int column) {
if (!has_column(column)) throw std::out_of_range("no such column");
if (column_empty(column)) throw std::logic_error("column is empty");
stacks_[static_cast<std::size_t>(column)].pop_back();
}
How this code works: Undo after the win in the step 2 demo

In the step 2 demo, Red has just won with a disc in column 5 of a board 6 wide and 5 high. The history holds seven moves:

# Player Column
1 Red 2
2 Yellow 2
3 Red 3
4 Yellow 2
5 Red 4
6 Yellow 1
7 Red 5

The status is “Red wins”. Then undo() runs:

  1. The history is not empty, so it goes on.
  2. last is a copy of move 7, {Player::red, 5}. It is copied before pop_back, because pop_back destroys the element, and a reference to it would then refer to nothing.
  3. pop_back removes move 7. Six moves remain.
  4. board_.lift(5) takes the top disc off column 5. Column 5 held one disc, so it is now empty.
  5. to_move_ = last.player: Red is to move again.
  6. status_ = Status::in_progress. Why is that always right? A move is only accepted while the game is in progress. So just before move 7, the game was in progress, whatever move 7 did to it.

The demo prints “Status: in progress, Red to move, 6 moves in the history”, and the bottom row goes from . Y R R R R back to . Y R R R .. Undo is exact because the move’s row never needs storing: the disc that move 7 dropped is always the top disc of its column, since every later disc has already been taken back.

The Command idea, kept small. In the Command pattern, each action is an object that knows how to do itself and how to undo itself, and an undo list holds those objects. That is the right tool when there are many kinds of action, each reversed in its own way: a text editor’s typing, deleting, and formatting. Here there is exactly one kind of action, “drop a disc into a column”, and its reverse is always “take the top disc off that column”. So the idea of Command is used, a list of records of what was done, without its machinery: Move is a plain struct of two values, and one function, undo, reverses any of them. A class hierarchy with a virtual undo would add code and give nothing back.

A Command class would earn its place if the game grew different actions to undo, such as “pop out a disc from the bottom” (a known variant of the game) next to “drop a disc”. Then each action would carry its own reverse. Another way to undo is to save a copy of the whole board before each move (the Memento idea), which is simpler to get right for complicated changes but stores far more. Here two small values per move, a player and a column, are enough.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_6_1_undo_with_no_moves_does_nothing) {
Game game{classic};
LLD_CHECK(!game.undo());
LLD_CHECK_EQ(game.to_move(), Player::red);
LLD_CHECK_EQ(game.status(), Status::in_progress);
LLD_CHECK(game.history().empty());
}
LLD_TEST(ac_6_2_undo_takes_off_the_last_disc_and_gives_the_turn_back) {
Game game{classic};
play_all(game, "33");
LLD_CHECK(game.undo());
LLD_CHECK_EQ(game.board().at(3, 1), Cell::empty); // yellow's disc is gone
LLD_CHECK_EQ(game.board().at(3, 0), Cell::red); // red's is still there
LLD_CHECK_EQ(game.to_move(), Player::yellow); // yellow moves again
LLD_CHECK_EQ(game.history().size(), std::size_t{1});
}
LLD_TEST(ac_6_3_undo_after_a_win_reopens_the_game) {
Game game{classic};
play_all(game, "0101010");
LLD_CHECK_EQ(game.status(), Status::red_wins);
LLD_CHECK(game.undo());
LLD_CHECK_EQ(game.status(), Status::in_progress);
LLD_CHECK_EQ(game.to_move(), Player::red);
LLD_CHECK_EQ(game.board().at(0, 3), Cell::empty);
LLD_CHECK_EQ(game.board().longest_line_through(0, 2), 3);
// Moves are accepted again: red plays elsewhere, and yellow then makes
// four up column 1.
LLD_CHECK(game.play(6).accepted());
LLD_CHECK(game.play(1).accepted()); // yellow: four up column 1
LLD_CHECK_EQ(game.status(), Status::yellow_wins);
}
LLD_TEST(ac_6_3_undo_after_a_draw_reopens_the_game) {
Game game{classic};
play_all(game, "416210144241363310466123232265505465550030");
LLD_CHECK_EQ(game.status(), Status::draw);
LLD_CHECK(game.undo());
LLD_CHECK_EQ(game.status(), Status::in_progress);
LLD_CHECK(!game.board().full());
LLD_CHECK_EQ(game.to_move(), Player::yellow);
LLD_CHECK_EQ(game.check_move(0), Refusal::none); // the last cell is free again
LLD_CHECK_EQ(game.check_move(1), Refusal::column_full);
}
LLD_TEST(ac_6_4_undoing_every_move_returns_to_the_start) {
Game game{classic};
const std::string moves = "3324455610";
play_all(game, moves);
for (std::size_t i = 0; i < moves.size(); ++i) LLD_CHECK(game.undo());
LLD_CHECK(!game.undo());
LLD_CHECK_EQ(to_text(game.board()), to_text(Board{7, 6}));
LLD_CHECK_EQ(game.to_move(), Player::red);
LLD_CHECK(game.history().empty());
}
LLD_TEST(ac_6_5_the_history_records_each_accepted_move_in_order) {
Game game{classic};
play_all(game, "36");
static_cast<void>(game.play(9)); // refused: not recorded
play_all(game, "000000"); // fills column 0
static_cast<void>(game.play(0)); // refused: full, not recorded
LLD_CHECK_EQ(game.history().size(), std::size_t{8});
LLD_CHECK_EQ(game.history()[0].column, 3);
LLD_CHECK_EQ(game.history()[0].player, Player::red);
LLD_CHECK_EQ(game.history()[1].column, 6);
LLD_CHECK_EQ(game.history()[1].player, Player::yellow);
LLD_CHECK_EQ(game.history().back().column, 0);
LLD_CHECK_EQ(game.history().back().player, Player::yellow);
}
LLD_TEST(ac_6_6_after_undo_a_different_move_can_be_played) {
Game game{classic};
play_all(game, "33");
LLD_CHECK(game.undo());
play_all(game, "4"); // yellow plays 4 instead of 3
LLD_CHECK_EQ(game.board().at(4, 0), Cell::yellow);
LLD_CHECK_EQ(game.board().at(3, 1), Cell::empty);
LLD_CHECK_EQ(game.history().back().column, 4);
LLD_CHECK_EQ(game.to_move(), Player::red);
}
LLD_TEST(ac_6_7_the_board_refuses_to_lift_from_an_empty_column) {
Board board{7, 6};
LLD_CHECK_THROWS(board.lift(0), std::logic_error);
LLD_CHECK_THROWS(board.lift(7), std::out_of_range);
board.drop(2, Cell::red);
board.lift(2);
LLD_CHECK(board.column_empty(2));
}

The state diagram for step 2 gains the arrows that undo adds:

The Status of a game in step 2: undo is the way back out of an end state
Text description of the diagram

The same four states as in step 1. A new game starts in in progress, from valid rules, with an empty board and Red to move. In in progress, an accepted move that makes no line and leaves space, a refused move, or an undo all stay in in progress. A move that makes a line of the chosen length or more goes to Red wins or Yellow wins, for the player who made it. A move that fills the board without a line goes to draw. From each of the three end states, a move is refused as game over and the state does not change, and undo goes back to in progress.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> in_progress : Game built from valid Rules, empty board, Red to move
in_progress --> in_progress : accepted move with no line and space left, refused move, or undo
in_progress --> red_wins : Red's move makes a line of connect or more
in_progress --> yellow_wins : Yellow's move makes a line of connect or more
in_progress --> draw : a move fills the board with no line
red_wins --> in_progress : undo
yellow_wins --> in_progress : undo
draw --> in_progress : undo
red_wins --> red_wins : any move, refused as game over
yellow_wins --> yellow_wins : any move, refused as game over
draw --> draw : any move, refused as game over

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

computer.hpp
// Picks a column for the player whose turn it is, by a fixed rule:
// 1. if a move wins now, play it;
// 2. else, if the opponent could win next move in some column, block it
// by playing there;
// 3. else, play the playable column nearest the centre.
// In every step, columns are tried in centre_first order, so the answer is
// always the same for the same position: no randomness, no seed.
// Returns std::nullopt if the game is over, since there is no move to make.
//
// The rule looks only one move ahead. It cannot see a double threat coming
// (two cells that each win, when it can block only one), and it does not
// notice that its own move may let the opponent win in the cell just above.
[[nodiscard]] std::optional<int> choose_column(const Game& game);
// Every column of a board `columns` wide, nearest the centre first. When
// two columns are equally near (an even width), the left one comes first.
// For 7 columns: 3 2 4 1 5 0 6. For 6 columns: 2 3 1 4 0 5.
[[nodiscard]] std::vector<int> centre_first(int columns);

The computer is a free function: a function that is not a member of any class. It reads the Game through a const reference, so it can look but not change anything, and returns a column, or std::nullopt (“no value”) when the game is over. It keeps nothing between moves, so there is no object to make or own. If the program later had to choose between kinds of player at run time, a human, an easy computer, and a harder one, a small interface with one choose_column function would be the next step, as the header comment says. Until then, an interface would have one implementation and no user; see YAGNI.

To look one move ahead, the computer needs to ask “would this move win?” without making it:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

game.cpp
// Tries the move on a copy of the board, so the real board is not touched
// and this function can be const. A board is a few small vectors, so the
// copy is cheap.
bool Game::would_win(int column, Player player) const {
if (!board_.has_column(column) || board_.column_full(column)) return false;
Board trial = board_;
const int row = trial.drop(column, disc_of(player));
return trial.longest_line_through(column, row) >= rules_.connect;
}

Board trial = board_; makes a copy of the board. The trial disc goes into the copy, the copy is asked about the line, and the copy is destroyed at the end of the function. The real board is never touched, so would_win can be const, which the compiler checks. The copy is cheap: a few small vectors of at most 10 cells each. would_win takes the player as an argument and ignores whose turn it is, which is what lets the computer ask about its opponent’s next move.

Columns are tried from the centre out:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

computer.cpp
std::vector<int> centre_first(int columns) {
std::vector<int> order;
for (int column = 0; column < columns; ++column) order.push_back(column);
// How far a column is from the centre, doubled so that it stays a whole
// number: on 6 columns the centre is at 2.5, and column 2 is 0.5 away,
// which doubled is |2 * 2 - 5| = 1.
// [columns] copies the board width into the lambda, so it can use it.
auto distance = [columns](int column) { return std::abs(2 * column - (columns - 1)); };
// Sort by distance. stable_sort keeps columns that are equally near in
// the order they were in, left to right, so ties go to the left one.
// The lambda answers "should a come before b?"; [&distance] lets it
// call the distance lambda above.
std::stable_sort(order.begin(), order.end(),
[&distance](int a, int b) { return distance(a) < distance(b); });
return order;
}
How this code works: centre_first for 7 and for 6 columns

The distance of column c from the centre is |2c − (columns − 1)|: twice the real distance, so that it is always a whole number.

Column 0 1 2 3 4 5 6
Distance, 7 columns 6 4 2 0 2 4 6
Distance, 6 columns 5 3 1 1 3 5

Sorting by distance gives 3 2 4 1 5 0 6 for 7 columns. Columns 2 and 4 are equally near, and std::stable_sort keeps equal values in the order they started in, which was left to right, so 2 comes before 4. For 6 columns it gives 2 3 1 4 0 5. A plain std::sort makes no such promise, and could put 4 before 2 on one compiler and not on another. The test ac_7_1_columns_are_tried_from_the_centre_out checks both orders, and those for 4 and 5 columns.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

computer.cpp
std::optional<int> choose_column(const Game& game) {
if (game.status() != Status::in_progress) return std::nullopt;
const Player me = game.to_move();
const Player opponent = other(me);
const std::vector<int> order = centre_first(game.board().columns());
// 1. A move that wins now.
for (const int column : order) {
if (game.would_win(column, me)) return column;
}
// 2. A cell where the opponent would win next move: take it first.
// would_win ignores whose turn it is, which is what lets us ask
// about the opponent's move here.
for (const int column : order) {
if (game.would_win(column, opponent)) return column;
}
// 3. Otherwise the playable column nearest the centre. A column in the
// middle is part of more possible lines than one at the edge. While
// the game is in progress the board is not full, so some column is
// always playable and the loop returns.
for (const int column : order) {
if (game.check_move(column) == Refusal::none) return column;
}
return std::nullopt; // not reached while the game is in progress
}

The rule in three lines: win now if you can; else block the cell where the opponent would win next; else play nearest the centre. Win comes before block, because winning ends the game, so there is no “next move” for the opponent to win with.

How this code works: The computer's choices in the step 2 demo

The board is 6 columns by 5 rows, connect 4. Red is played by the demo; the computer answers for Yellow. The order of columns is 2 3 1 4 0 5.

Red plays Can Yellow win now? Could Red win next, and where? Step that decides Computer plays
2 no no 3: centre first 2
3 no no: Red has two in a row 3: column 2 is still playable 2
4 no yes, at 1 and at 5: Red has 2, 3, 4 on row 0 2: block the first threat in order, column 1 1
5 game over no move

On the third answer, Red has three in a row with both ends open. That is a double threat: two cells, either of which wins. The computer can block only one. It tries column 1 before column 5, because 1 is nearer the centre, so it plays 1, and Red wins at 5. This matches the demo’s output: “Computer chooses column 1”, then “Red drops into column 5. Red wins.”

After the undo, the computer moves for Red. Trying 2 3 1 4 0 5, the first column where Red would win is 5, so it chooses 5 and wins.

What the computer cannot do. The rule looks at one move only, and it is honest to say what that misses:

  1. A double threat beats it, as the demo shows: once there are two cells that each win, it can block only one of them.

  2. It can hand the opponent a win in the cell above. In a run of the game 32302211 (columns, Red first), Red is to move with this board, and nobody can win at once:

    . . . . . . .
    . . . . . . .
    . . . . . . .
    . . Y . . . .
    . Y R R . . .
    Y R Y R . . .
    0 1 2 3 4 5 6

    Nothing to win and nothing to block, so the computer plays the centre, column 3, which lands in row 2. That fills the cell under (3, 3), and Yellow drops into column 3 and wins on the rising diagonal (0, 0), (1, 1), (2, 2), (3, 3). The Exercise fixes this one case.

  3. It does not plan. A real game-playing program searches many moves ahead (the usual method is called minimax) and scores positions. That is a different, much bigger design, and out of scope here.

The rule is still useful: it never misses a win in one, never ignores a single threat, always plays a legal move, and is completely predictable, so it can be tested with exact expected moves.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_7_2_winning_comes_before_blocking) {
Game game{classic};
// Red has three up column 0, yellow three up column 1. Red to move:
// blocking column 1 would be wrong, because column 0 wins at once.
play_all(game, "010101");
LLD_CHECK(choose_column(game) == std::optional<int>{0});
play_all(game, "0");
LLD_CHECK_EQ(game.status(), Status::red_wins);
}
LLD_TEST(ac_7_2_the_computer_wins_far_from_the_centre) {
Game game{classic};
play_all(game, "101020"); // yellow: three up column 0
play_all(game, "6"); // red does not block, so yellow can win at 0
LLD_CHECK_EQ(game.to_move(), Player::yellow);
LLD_CHECK(choose_column(game) == std::optional<int>{0});
}
LLD_TEST(ac_7_3_a_threat_up_a_column_is_blocked) {
Game game{classic};
play_all(game, "06061"); // yellow: two up column 6
play_all(game, "6"); // yellow: three up column 6
// Red to move, cannot win, yellow wins next at 6 unless red plays there.
LLD_CHECK_EQ(game.to_move(), Player::red);
LLD_CHECK(choose_column(game) == std::optional<int>{6});
}
LLD_TEST(ac_7_3_a_threat_across_is_blocked_at_the_end_nearer_the_centre) {
Game game{classic};
play_all(game, "511223"); // yellow: row 0 at 1, 2, 3; both ends open
LLD_CHECK_EQ(game.to_move(), Player::red);
// Yellow would win at 0 or at 4. The computer blocks 4, nearer the centre.
LLD_CHECK(choose_column(game) == std::optional<int>{4});
// The rule sees one threat at a time: yellow still wins at 0.
play_all(game, "40");
LLD_CHECK_EQ(game.status(), Status::yellow_wins);
}

The last of these tests the limit, not just the rule: Yellow has three across with both ends open, the computer blocks at 4, and Yellow still wins at 0. A test that records a known weakness keeps it from being forgotten, and tells the next person exactly what “better” would have to change.

struct Rules

no default values; public members

Data members

  • int columns;
  • int rows;
  • int connect; a line this long, or longer, wins

struct Move

one accepted move; public members

Data members

  • Player player;
  • int column; the row is not needed: undo lifts the top disc

class Board

now any size from 4 to 10 each way

Data members

  • int columns_;
  • int rows_;
  • std::vector<std::vector<Cell>> stacks_; owned; one stack per column

Member functions

  • Board(int columns, int rows); throws std::invalid_argument outside the limits
  • int columns() const;
  • int rows() const;
  • void lift(int column); takes the top disc off; throws if there is none

class Game

still owns the board, by value; not thread-safe

Data members

  • Rules rules_;
  • std::vector<Move> history_; owned; oldest first

Member functions

  • explicit Game(Rules rules); throws std::invalid_argument for bad rules
  • bool undo(); false, and nothing changes, if there is no move
  • bool would_win(int column, Player player) const; tries the move on a copy
  • const std::vector<Move>& history() const;

namespace c4

free functions in computer.hpp

Functions

  • std::optional<int> choose_column(const Game& game); nullopt if the game is over
  • std::vector<int> centre_first(int columns);
What step 2 adds or changes; members not shown are as in step 1

Game still owns everything by value, so copying a Game copies the board and the history, and the class needs no destructor or copy functions of its own. The computer owns nothing at all.

Step 2 keeps every step 1 test, now run on Game{classic}, and adds the tests above for each new acceptance criterion: 57 tests in all. The same play_all helper drives whole games, so most new tests are two or three lines of moves followed by checks.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
// Rules are checked when the game is made: a line of 6 cannot fit up a
// board 5 rows high.
try {
const Game impossible{Rules{6, 5, 6}};
} catch (const std::invalid_argument& error) {
std::cout << "Rules{6, 5, 6} refused: " << error.what() << "\n\n";
}
Game game{Rules{6, 5, 4}};
// Red's moves; after each one the computer answers for yellow. After
// red's win, computer_move finds no move and prints nothing.
for (const int column : {2, 3, 4, 5}) {
play(game, column);
computer_move(game);
}
std::cout << "\n" << to_text(game.board()) << "\n";
std::cout << "Status: " << to_string(game.status()) << "\n\n";
// Undo red's winning move: the disc comes off and the game reopens.
if (game.undo()) std::cout << "Undo: the last move is taken back.\n";
std::cout << "Status: " << to_string(game.status()) << ", " << to_string(game.to_move())
<< " to move, " << game.history().size() << " moves in the history\n";
std::cout << "\n" << to_text(game.board()) << "\n";
// Now the computer plays red's move: it finds the win at once.
computer_move(game);
std::cout << "Status: " << to_string(game.status()) << "\n";
return 0;
}
Expected output
Rules{6, 5, 6} refused: connect must be from 3 to 5, not 6
Red drops into column 2.
Computer chooses column 2. Yellow drops into column 2.
Red drops into column 3.
Computer chooses column 2. Yellow drops into column 2.
Red drops into column 4.
Computer chooses column 1. Yellow drops into column 1.
Red drops into column 5. Red wins.
. . . . . .
. . . . . .
. . Y . . .
. . Y . . .
. Y R R R R
0 1 2 3 4 5
Status: Red wins
Undo: the last move is taken back.
Status: in progress, Red to move, 6 moves in the history
. . . . . .
. . . . . .
. . Y . . .
. . Y . . .
. Y R R R .
0 1 2 3 4 5
Computer chooses column 5. Red drops into column 5. Red wins.
Status: Red wins

Read the output against the requirements:

  • The first line is FR-6: Rules{6, 5, 6} is refused when the game is made, because a line of 6 does not fit up 5 rows.
  • The game is on a board 6 wide and 5 high, and the computer’s three answers are the ones in the walkthrough: centre, centre, then a block that cannot cover both ends.
  • The undo reopens a won game: in progress, Red to move, six moves.
  • The last line is the computer, now playing for Red, finding the win at once.

Connect Four is a common first design question, because it is small enough to finish and has one real piece of logic. A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask about the size, who plays, what a bad move does, whether there is a screen, and whether undo is needed. “Is the board always 7 by 6, and is it two people at one keyboard?”
5 min Sketch Board and Game, the four enums, and who owns what. State the invariants. “The board knows where discs are. The game knows whose turn it is and whether anyone has won.”
10–15 min Write drop, longest_line_through, check_move, and play, in that order. “Only the last disc can have made a new line, so I count outwards from it, both ways.”
10 min Trace a short game, including a refused move and a win in the middle of a line. Name the tests. “A refused move changes nothing: the checks all come before the drop.”
About 5 min Take a change: other sizes, undo, or a computer player. “Undo is a list of moves and one function; I would add a Command class only for many actions.”

What is usually expected at each level

Level Usually expected
Junior A board and a game; dropping into the lowest cell; turns; a win check in all four directions, including both diagonals; refused moves; a draw; a few tests.
Mid-level All of the above, plus: checking only from the last disc, both ways; a status enum rather than flags; validating before changing; win before draw; configurable sizes checked at construction; undo.
Senior All of the above, plus: a clear split of what the board and the game each own; the reasoning for why one-move checks are enough; when Command or an interface would earn its place; the computer’s limits stated and tested; how the design would change for a network game.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

How this code works: Interview questions, with short answers
  1. Why not keep the board as a 7 by 6 grid of cells? A grid works too. Column stacks make “no floating discs” (INV-1) impossible to break, and make drop one push_back. With a grid, drop has to search for the lowest empty cell, and every function that writes a cell could create a gap.
  2. How do you know a win check from the last disc is enough? The game was in progress before the move, so there was no line. The move changed one cell, so any new line passes through it. Counting both ways in four directions covers every line through a cell.
  3. What happens on a move into column 9? check_move returns no_such_column, play returns that refusal with a message, and nothing changes. If code skipped the check and called Board::drop directly, it would throw: a bug in the program is loud (NFR-2).
  4. Why does play return a result rather than throw? A bad move by a player is expected, not exceptional, and the caller should show it and ask again. Exceptions are kept for code that breaks the rules.
  5. Why an enum class for the status? One value cannot contradict itself. Flags for “over”, “draw”, and “winner” can.
  6. How would you add undo? Keep a history of moves; undo pops one, lifts the top disc of its column, gives the turn back, and sets the status to in progress. A Command class only if there are many kinds of action to undo.
  7. Is it thread-safe? No, and the design says so (NFR-3). One game belongs to one thread. A server running many games would give each game to one thread at a time, or put a lock around each game, rather than make the board itself thread-safe.
  8. How would a stronger computer work? It would look several moves ahead, scoring positions, using a search such as minimax. The current interface, a function from a Game to a column, would not change.
  • One thread, one process. A Game is not safe to share between threads, and nothing is saved: closing the program ends the game.
  • No user interface. The game takes column numbers and returns text. A real program needs a screen, input that is not a number, and a way to start a new game.
  • No saving or loading. The history of moves would make this easy (a game is its list of columns), but it is not written.
  • No network play. Two players on two machines would need a server that owns the game, checks whose connection is allowed to move, and copes with a player who disconnects.
  • The computer is weak. It sees one move ahead, loses to a double threat, and can open the cell above its own disc, as shown above.
  • Sizes are capped at 10. The limit is the example’s choice. The logic would work on larger boards, but the printed board puts one character per cell under one label per column, and the tests’ play_all helper reads one digit per move, so both stop at 10 columns (0 to 9).
  • Undo has no limit and no redo. The history grows with the game, which is at most 100 moves on the largest board, so this is not a problem here. Redo would need a second list of undone moves, cleared on every new move.
Requirement Design element Code Tests Status
FR-1 moves Board column stacks, drop; Game::to_move_ step 1 board.*, game.* ac_1_1_…, ac_1_2_… Tested
FR-2 refused moves check_move, Refusal, MoveResult step 1 game.cpp ac_2_1_… to ac_2_3_… Tested
FR-3 winning count_from, longest_line_through, play step 3 step 1 board.cpp, game.cpp ac_3_1_… to ac_3_8_…, ac_4_2_… Tested
FR-4 drawing Board::full, win checked first step 1 game.cpp ac_4_1_…, ac_4_2_…, ac_2_3_… after a draw Tested
FR-5 showing MoveResult::message, to_text step 1 game.cpp, board.cpp ac_1_3_…, ac_1_4_… Tested
NFR-1 testable no input or output inside Board or Game step 1 headers every test Tested
NFR-2 a bug is loud Board::drop and at throw step 1 board.cpp ac_2_4_… Tested
NFR-3 one thread no locks; stated on this page none none: a statement, not a behaviour Stated
FR-6 chosen rules Rules, Board and Game constructors step 2 game.*, board.* ac_5_1_… to ac_5_8_… Tested
FR-7 undo Move, history_, Game::undo, Board::lift step 2 game.*, board.cpp ac_6_1_… to ac_6_7_… Tested
FR-8 computer player choose_column, centre_first, Game::would_win step 2 computer.*, game.cpp ac_7_1_… to ac_7_5_… Tested

Exercise: Stop handing over the cell above

The computer in step 2 sometimes plays a column that lets the opponent win by dropping a disc straight on top, as in the game 32302211 shown above. Change choose_column so that, when it has nothing to win or block, it avoids such a column if it can. Start from step 2.

  1. How can the computer find out whether a move opens the cell above, without changing the real game?
  2. Where in choose_column does the new check go, and what should happen if every playable column opens a win?
  3. Write it, and a test using the game 32302211.
  4. Does this fix the double threat in the step 2 demo? Why or why not?
Show the explained answer
  1. Try the move on a copy of the game. A Game holds everything by value, so Game trial = game; is a full, separate copy. Play the column on the copy; it is then the opponent’s turn on the copy, and would_win(column, trial.to_move()) asks whether the opponent would win in the same column, which is the cell just above.

  2. Between step 2 (block) and step 3 (centre). Winning and blocking still come first: a win ends the game, and a block that opens the cell above is still better than losing at once. Then try the centre order, skipping columns that open a win. If every playable column does, play the nearest the centre anyway: some move must be made.

  3. The code:

    IllustrativeA fragment for explanation; not compiled on its own.

    // True if playing column now would let the opponent win by dropping a
    // disc on top of it, in the cell just above.
    bool opens_cell_above(const Game& game, int column) {
    Game trial = game; // a copy: the real game is not touched
    if (!trial.play(column).accepted()) return false;
    // After the move it is the opponent's turn. Steps 1 and 2 already
    // returned if this move wins, so trial is still in progress or drawn;
    // a drawn board is full, and would_win is false for a full column.
    return trial.would_win(column, trial.to_move());
    }
    // In choose_column, step 3 becomes two loops:
    // 3a. The playable column nearest the centre that does not hand the
    // opponent a win in the cell just above it.
    for (const int column : order) {
    if (game.check_move(column) == Refusal::none && !opens_cell_above(game, column)) {
    return column;
    }
    }
    // 3b. Every playable column gives one away: take the nearest the centre.
    for (const int column : order) {
    if (game.check_move(column) == Refusal::none) return column;
    }

    And the test:

    LLD_TEST(exercise_the_computer_does_not_open_the_cell_above) {
    Game game{classic};
    play_all(game, "32302211"); // yellow: (0,0) (1,1) (2,2); (3,3) would win
    const std::optional<int> column = choose_column(game);
    LLD_CHECK(column == std::optional<int>{2}); // not 3, the centre
    LLD_CHECK(game.play(*column).accepted());
    }

    Column 3 is skipped because it opens (3, 3). Column 2 is next in the centre order, and Red’s disc lands at (2, 3), which opens nothing.

  4. No. In the demo, when the computer moves, Red already has two open ends, and no single move can block both. The new check only looks at the cell above the computer’s own move. Stopping a double threat means blocking a move earlier, when Red has two in a row with space on both sides, and that needs looking two or more moves ahead. The step 2 demo’s output is the same with this change.

This answer was checked in a scratch copy of step 2; it is not part of the example in the repository. With these changes, the new test (a slightly longer form of the one above) passed along with the other 57 step 2 tests, under GCC, Clang, and GCC with AddressSanitizer and UndefinedBehaviorSanitizer, and the demo printed the same output as before.

  • Follow the framework even on a small problem: requirements, then entities, then classes, then code, then the change. Each step here was short, and each one decided something the next step used.
  • Store data in the shape of the rules. A column is a stack, so a floating disc cannot exist.
  • Look only where something can have changed. A new line must pass through the last disc, so count outwards from it, both ways, in four directions.
  • Check everything, then change. A refused move needs no clean-up when nothing was touched.
  • One enum for the result, with the winner inside it, cannot contradict itself. Check a win before a draw.
  • Rules without defaults let the compiler catch a forgotten value, and a constructor that checks them means a game that exists is valid.
  • Undo is a record of moves and one reverse function. That is the Command idea without its machinery; add a Command class when there are many kinds of action.
  • Say what a simple design cannot do, show it, and test it. The computer’s one-move rule loses to a double threat, and the page and the tests both say so.