Learn C · lesson 56 of 60 · about 11 minutes
Project: Noughts and Crosses
Read a noughts and crosses board and work out who has won.
What you'll learn
- Store a game board as a 2D char array
- Check rows, columns and diagonals
- Split the checks into small functions
A game for the night shift
Like the guessing game that locks the admin menu, the report ends with a game for whoever is on the night shift: noughts and crosses against the server. The board is typed as 3 lines of 3 squares, and reading it is already written for you, with board_ok set to false if any square isn't X, O or .. Your part is the referee: a wins function that checks every line for one player, and a result that says X wins, O wins, Draw for a full board, or No winner yet: 4 squares left.
The plan
A board is 3 rows of 3 characters: X, O or . for an empty square. The program will:
1. Read the board into char board[3][3]
2. Check whether a player fills any row, any column or either diagonal
3. Print X wins, O wins or No winner
Checking the rows
#include <stdio.h>
int wins_row(char b[][3], char p) {
for (int r = 0; r < 3; r++) {
if (b[r][0] == p && b[r][1] == p && b[r][2] == p) return 1;
}
return 0;
}
int main(void) {
char b[3][3] = {{'X', 'O', '.'}, {'X', 'X', 'X'}, {'O', '.', 'O'}};
printf("%d %d\n", wins_row(b, 'X'), wins_row(b, 'O'));
return 0;
}Output
1 0Columns and diagonals
Columns use the same idea with the indexes swapped: b[0][c], b[1][c], b[2][c]. The two diagonals are b[0][0], b[1][1], b[2][2] and b[0][2], b[1][1], b[2][0]. A wins function can call all the checks.
Reading a board
#include <stdio.h>
int main(void) {
char b[3][3];
const char *lines[3] = {"XO.", ".X.", "O.X"};
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++) b[r][c] = lines[r][c];
int diag = b[0][0] == 'X' && b[1][1] == 'X' && b[2][2] == 'X';
printf("Diagonal: %d\n", diag);
return 0;
}Output
Diagonal: 1A draw or a game still going
When neither player has a line, the empty squares decide: none left is a draw, and otherwise the game isn't over. empty += board[r][c] == '.' counts them, because a comparison in C gives 1 when it's true and 0 when it isn't. The report reads the board with fgets, a whole line at a time, so the newline at the end of each row never reaches a square.
Tip
When reading the board with scanf, " %c" (with a space first) skips the newlines between rows, so each %c gets a real square.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.