Skip to content
Tutorials Center
My learning

Topics

Lesson 178 of 201 ยท Projects

Project: Tic-Tac-Toe

Build Tic-Tac-Toe in Java step by step - a 2D array board, enums for players, moves from input, win and draw detection, and a computer opponent you can beat.

Tic-Tac-Toe is small enough to finish in an afternoon and rich enough to teach real design. The board is a grid, which means 2D arrays. The players are a fixed set of values, which means enums. Every move must be validated, every turn must check for a winner, and the moment you add a computer opponent you're writing a tiny piece of artificial intelligence.

In this project you'll build the game in six stages: a board that prints itself, a two-player game loop reading moves from the Input box, win and draw detection, a rule-based computer opponent, a complete human-versus-computer game, and finally a computer that can't be beaten, using recursion. Every stage is a complete, runnable program, and the moves you type in the Input box are played in order.

You'll use 2D arrays, enums, classes with encapsulation, exceptions, loops, switch and, in the last stage, recursion.

The board and its numbering

Players pick a square by number, laid out like a phone keypad:

TEXT
 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9

Inside the program, the board is a 3 ร— 3 array indexed by row and column, both starting at 0. Converting a square number to array indexes is simple arithmetic: square n sits in row (n - 1) / 3 and column (n - 1) % 3. Square 6, for example, is row 5 / 3 = 1, column 5 % 3 = 2. Integer division and the remainder operator, from Arithmetic Operators, do all the work.

Stage 1: a board that knows its rules

Start with the two core types. Player is an enum with two constants, X and O, and a method that returns the other player. Board wraps the 2D array and is the only code allowed to touch it.

Java Stage 1: the board, placing marks and printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The empty board prints the square numbers, so players can see which number to type. Once a square is taken, its mark replaces the number.

The design decisions:

  • Player is an enum, not a char or a String. With char, nothing stops a typo like 'x' or '0' (zero) from sneaking in, and the compiler can't help. An enum has exactly two possible values, so invalid players can't exist. It can also carry behavior: opponent() lives where it belongs, on the player. See Enums.
  • An empty square is null. A new Player[3][3] array starts filled with null, so "empty" comes for free. null is risky when it leaks, which is why only Board ever sees the array: outside code asks isFree(5) and never touches a null itself. An alternative is a third enum constant such as EMPTY; that works too, but then EMPTY would also be a "player", which is odd.
  • The array is private final. final means cells always refers to the same array; private means only Board can change what's inside. Every placement goes through place, so every placement is validated. This is encapsulation protecting the game's rules.
  • Squares are checked before they're used. place checks the range first, then whether the square is free. In the opposite order, isFree(10) would compute row 3 and crash with an ArrayIndexOutOfBoundsException instead of a clear message.
  • print builds each row in a StringBuilder and prints it once, with | only between cells and the divider only between rows. The c < 2 and r < 2 checks are how you avoid trailing separators in any grid or list output.

Stage 2: taking turns

Now the game loop. Moves come from the Input box, one per line. Players alternate, and an invalid move (not a number, out of range, or taken) gets a message and the same player tries again with the next line. There's no win check yet, so the game runs until the board is full or the moves run out.

Java Stage 2: a two-player game loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The input contains three bad moves on purpose: 5 again (taken), ten and 0. Each one is rejected, and X, whose turn it is, simply tries the next line until 9 works. The game then continues until the Input box runs out of moves. Nobody happens to have three in a row here, but the program couldn't tell if someone had: it would keep asking for moves after a win. That's exactly what Stage 3 adds.

How the loop is built:

  • turn holds the current player, and turn = turn.opponent() switches players only after a valid move. The continue inside the catch jumps back to the top of the loop without switching, so the same player moves again. Putting the switch at the very end of the loop body is what makes that work; see break and continue.
  • Invalid input becomes an IllegalArgumentException. parsePosition translates NumberFormatException (which is itself a subclass of IllegalArgumentException) into a clearer message, and place throws the same type for range and taken-square problems. So a single catch handles every kind of bad move.
  • Running out of input is handled. in.hasNextLine() is checked before every read. Without it, nextLine() would throw a NoSuchElementException when the Input box runs dry. In an interactive console the program would simply wait for the user; here, the input is finite, so the program must say what happened.
  • Each move is echoed (X plays 5), because input from the Input box doesn't appear in the output by itself. A transcript you can follow is half of debugging a game.

Stage 3: wins and draws

A game ends when a player has three marks in a row, column or diagonal, or when the board is full with no winner (a draw). The result of checking is one of four states, so it's another enum: Status.

Java Stage 3: detecting wins and draws

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The four demo boards show each status, and then a full game ends in a draw. Change the Input box to 5, 1, 9, 3, 2, 4, 8 and X wins down the middle column after seven moves; the loop stops by itself, ignoring any moves left over.

How the checking works:

  • There are exactly 8 ways to win: 3 rows, 3 columns and 2 diagonals. The loop checks row i and column i together in one pass, then the two diagonals. In row i the row index is fixed and the column changes; in column i it's the other way around. Writing out cells[i][0], cells[i][1], cells[i][2] versus cells[0][i], cells[1][i], cells[2][i] makes that symmetry visible.
  • sameMark returns the winner or null. The a != null check matters: three empty squares are also "the same", and without it an empty row would count as a win for nobody, which would crash in winFor.
  • A win is checked before a draw. If the last move fills the board and completes a line, it's a win, not a draw. Checking freePositions().isEmpty() only after all lines get this right.
  • Status.message() uses an exhaustive switch expression over the enum. If you add a new status later, the compiler rejects the switch until you handle it; see switch.
  • Board.of("XXXOO....") builds a position from a string, nine characters read left to right, top to bottom. It exists purely to make test positions quick to write, and Player.valueOf("X") turns the character into the enum constant. Factory methods like this make code that's hard to set up easy to test. It's also where you can see that i / 3 and i % 3 map a 0-based index to row and column.

The loop condition changed from "while squares are free" to while (board.status() == Status.PLAYING), which covers both endings at once.

Stage 4: a computer opponent

A computer player needs a strategy: a rule for choosing a move. A remarkably decent one fits in five steps, tried in order:

  1. Win: if a move completes my line, play it.
  2. Block: if the opponent could complete a line next turn, take that square.
  3. Center: take square 5 if it's free; it's part of four winning lines, more than any other square.
  4. Corner: take a free corner (each is part of three lines).
  5. Side: take whatever is left.

Steps 1 and 2 are the same question asked for different players: "is there a square that wins for this player?" The easy way to answer it is to try each free square on a copy of the board and ask the copy for its status. That reuses status() instead of writing a second, separate line-checking algorithm.

Java Stage 4: a rule-based computer player

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each puzzle gets the move its rule predicts. The last one has a single free square, and the computer finds it whatever rule produced it.

Design notes:

  • Trying moves on a copy keeps the real board untouched. copy() creates a new Board and clones each row. Copying a 2D array needs a loop like this: cells.clone() alone would copy only the outer array, so both boards would share the same row arrays, and a "trial" move would appear on the real board too. That's the shallow-versus-deep copy problem from Copying Objects, and it's one of the most common bugs in grid games.
  • OptionalInt says "maybe a square". winningMove either finds a square or doesn't. Returning -1 for "none" would work but invites someone to place a mark on square -1. Optional and its primitive cousin OptionalInt make absence part of the type.
  • The strategy lives in its own class. Computer knows how to choose moves; Board knows the rules; neither knows about input or output. That separation pays off in the next two stages, where we use the computer in a real game and then swap in a smarter strategy without touching Board.
  • Priorities are data. CORNERS and SIDES are arrays, so changing the preference order is an edit to a constant, not to the logic.

Stage 5: playing against the computer

Time to put it together: you play X and move first, the computer plays O. Your moves come from the Input box. The preset moves try a classic trap, so watch what happens.

Java Stage 5: human versus computer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You win in four moves. Here's what happened: you took corner 1, the computer took the center, and you took the opposite corner 9. Following its rules, the computer then took corner 3. That threatens 3-5-7, so you blocked at 7, and now you have two open lines at once: 1-4-7 and 7-8-9. The computer can block only one of them: it takes 4, and your 8 completes the bottom row. A position with two threats is called a fork, and our five-rule strategy has no rule against walking into one. (The correct reply to opposite corners is a side square, which forces you to block instead.)

Change the Input box to try other games. Start with 5 and you'll find the computer much harder to beat; play randomly and it will usually win.

The game loop is Stage 3's loop with one branch per kind of player. The turn == human check decides whether the next move comes from the Input box or from Computer.chooseMove. Because both branches end by printing the board and switching turn, the rest of the loop doesn't care who moved. You could make the computer play itself by removing the human branch, or let it move first by starting with turn = Player.O.

Stage 6: a computer that never loses

Rules like "take the center, then a corner" are how people play. A computer can do something people can't: look at every possible future of the game and choose the move with the best guaranteed outcome. Tic-Tac-Toe is small enough for that: from an empty board there are only about 255,000 possible games, which Java explores in a fraction of a second.

The algorithm is called minimax. Score a finished game from the computer's point of view: a win is positive, a loss negative, a draw 0. On the computer's turn, it picks the move with the highest score; on the opponent's turn, it assumes the opponent picks the move with the lowest score, the one that's worst for the computer. Each of those scores is computed the same way, recursively, until the game ends. Here it is, replacing the rule-based chooseMove; Board and the game loop are unchanged, and the Input box has the same opening moves as Stage 5.

Java Stage 6: an unbeatable opponent with minimax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same opening as Stage 5 goes very differently. After corners 1 and 9, minimax doesn't take corner 3; it plays side square 2, threatening the middle column (2-5-8). You're forced to block at 8, the computer blocks your bottom row at 7, and from there every threat is answered until the game ends in a draw. Try to beat it: you can't. Put 1, 9, 7 in the Input box (the Stage 5 trap) and the computer punishes the mistake by winning at 8.

How minimax works, piece by piece:

  • The base case is a finished game. score first asks the board for its status. A win for the computer scores 10 - depth, a loss depth - 10, a draw 0. Every recursive method needs a case that stops the recursion, and here it's the end of the game, which always comes within nine moves. See Recursion.
  • The recursive case tries every move. For each free square, it places the current player's mark on a copy and scores the resulting position with the other player to move, one level deeper. On the computer's turn it keeps the maximum; on the opponent's turn, the minimum. That alternation is the "mini" and "max" in minimax.
  • Depth makes it eager. Subtracting the depth means a win in two moves scores higher than a win in four, and a loss in four scores higher than a loss in two. Without it, the computer would see all wins as equal and might dawdle, or give up early in a lost position instead of making you work for it.
  • Copies keep the search honest. Each trial move happens on a fresh copy, so exploring one future can't leak into another. The correct deep copy() from Stage 4 is now essential; with a shallow copy, the search would corrupt its own board within the first few moves.
  • The counter shows the cost. examined counts how many positions were scored for each decision. The first reply looks at thousands of positions; later ones far fewer, because each move shrinks the tree of possible futures. Bigger games like chess have far too many positions to search completely, which is why chess programs stop at a certain depth and estimate the score, and prune branches that can't matter (a technique called alpha-beta pruning).

Because both strategies are just "a method that takes a board and a player and returns a square", swapping one for the other changed one line in the game loop. If you formalize that with an interface, interface Strategy { int chooseMove(Board board, Player me); }, the game could pick a difficulty level at startup. That's the strategy pattern from Structural and Behavioral Design Patterns.

Ideas to extend it

  • Difficulty levels. Introduce the Strategy interface, implement RuleBased and Perfect, and add an Easy strategy that picks a random free square (with a fixed seed for repeatable runs; see Random Numbers). Read the level from the first line of input.
  • Fix the rule-based player. Add a rule between "block" and "center" that detects forks: if the opponent has two opposite corners and I have the center, play a side.
  • Who goes first? Let the first input line be first or second, and let the computer open the game.
  • Best of five. Play several games in a row from one Input box, alternating who starts, and keep a score table with an EnumMap<Status, Integer>.
  • Bigger boards. Generalize to an N ร— N board where you need K in a row. The status method needs loops instead of fixed indexes, and minimax becomes too slow without depth limits or alpha-beta pruning.
  • Memoization. Many move orders lead to the same position. Cache each position's score in a HashMap<String, Integer> keyed by a string like "XO.X....O" and watch the examined counter drop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which row and column does square 8 map to with row = (n - 1) / 3 and column = (n - 1) % 3?

    (8 - 1) / 3 is 7 / 3 = 2 with integer division, and 7 % 3 is 1. Square 8 is the middle of the bottom row.
  2. 2. Why does Board.copy() clone each row instead of just calling cells.clone()?

    A 2D array is an array of row arrays. Cloning the outer array copies the references to the rows, not the rows themselves, which is a shallow copy.
  3. 3. In Stage 2, a player types ten. What happens next?

    parsePosition throws an IllegalArgumentException, the catch prints a message and continue jumps back to the loop's start before turn is switched.
  4. 4. Why does sameMark check a != null?

    Comparing null with == is safe, but three nulls are "the same", and without the check an empty row would be reported as a line won by null.
  5. 5. In minimax, why is a win scored as 10 - depth instead of a flat 10?

    Subtracting the depth makes nearer wins worth more, and adding it to losses makes distant losses less bad, so the computer finishes quickly and resists for as long as possible.

Summary

  • A 3 ร— 3 Player[][] array holds the board; (n - 1) / 3 and (n - 1) % 3 convert square numbers to row and column.
  • Enums model the fixed sets in the game: Player (with opponent()) and Status (with an exhaustive switch). Invalid players and states can't exist.
  • Board encapsulates the array and validates every move; a single IllegalArgumentException type covers non-numbers, out-of-range squares and taken squares, and the loop retries without switching turns.
  • Win detection checks 3 rows, 3 columns and 2 diagonals, ignoring empty lines, and checks wins before draws.
  • A rule-based computer (win, block, center, corner, side) tries moves on deep copies of the board; it plays well but can be beaten with a fork.
  • Minimax searches every possible future recursively and never loses; strategies that share a method shape can be swapped, which is the strategy pattern.

Next: Project: Employee Management System.