Introduction
Tic-Tac-Toe is small enough to finish in an afternoon but has real game logic: a board, turns, invalid moves and win conditions. It is an ideal first exercise in modelling state with a 2D array.
Problem statement
Objectives
- Represent game state in a 2D char array
- Convert between cell numbers and row/column indexes
- Check all eight winning lines with helper functions
- Loop over turns and games
Features
- Numbered board display
- Validation of out-of-range and occupied cells
- Win detection on rows, columns and diagonals; draw detection
- Score kept across repeated games
Concepts demonstrated
- 2D arrays
- Functions
- Game loop
- Pointers to array elements
System architecture
board[3][3] holds '1'–'9' for empty cells or 'X'/'O'. play runs one game: draw, read a cell, convert with (cell−1)/3 and (cell−1)%3, validate, place, test wins(player), then switch players. wins checks three rows, three columns and two diagonals with the line helper. main repeats games and keeps the score.
Folder structure
Complete source code
Makefile
What each file does
- src/main.c
- Board reset and drawing, win checking, the turn loop in
play, and the score loop inmain. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
5 1 9 5 3 2 7 4 6 8 y 1 4 2 5 3 n
Testing
- Compare with
tests/expected-output.txt: game 1 includes an occupied-cell attempt and ends with X completing the middle column; game 2 ends with X winning on the top row. - Play a full draw and confirm “It's a draw.” after 9 moves.
Common errors
Moves land in the wrong cell
Row = (cell − 1) / 3 and column = (cell − 1) % 3 — don't forget the −1.
A win isn't detected on a diagonal
Both diagonals, (0,0)(1,1)(2,2) and (0,2)(1,1)(2,0), must be checked.
Possible improvements
- Add a single-player mode with a simple AI that blocks wins
- Let players enter names
- Highlight the winning line
Additional challenges
- 1Implement an unbeatable computer opponent using the minimax algorithm.
- 2Generalise to an N×N board with K in a row to win.
- 3Save scores to a file between runs.
Built and tested it yourself? Mark it to update your dashboard.