A maze game I wrote in C with ncurses for an Operating Systems assignment. It generates a map with depth-first search and lets you play through it.
Introduction#
During my school subject of Operating Systems we had to write a simple program
demonstrating the usage for the ncurses library. I chose to
write a Maze generator and it turned out to be a really great challenge and
fun project.
The game should generate a random maze and allow the player to navigate through it using the arrow keys. The goal is for the user to reach the finish point.
Libraries and Constants#
The very first thing we need to do is to include the necessary libraries and define the constants required for the game:
// Libraries
#include <stdio.h> // We need standard I/O!
#include <ncurses.h> // 🪄 magic for our text UI! 🪄
#include <time.h> // We need to have a random(ish) seed for our map generation!
#include <stdlib.h> // We use `malloc()` and such.
// Constants
#define WALL_CHAR '#' // The character to show as a wall.
#define EMPTY_CHAR ' ' // The character to show as an empty space.
#define PLAYER_CHAR '@' // The character to show a player.
#define GOAL_CHAR 'G' // The character to show at the finish point!
#define DIRECTION_UP 0 // The int ID for up direction.
#define DIRECTION_LEFT 1 // The int ID for left direction.
#define DIRECTION_RIGHT 2 // The int ID for right direction.
#define DIRECTION_DOWN 3 // The int ID for down direction.
#define EXIT_OPTION_LOWER 'q' // Lowercase letter for exiting the game.
#define EXIT_OPTION_UPPER 'Q' // Uppercase letter for quitting the game.
In the libraries section, we include ncurses.h in order to use the ncurses
library and manipulate more efficiently our terminal interface. We also have
time.h over there because we’ll have to initialize the random seed for our
map using functions from that library.
The constants defined are for defining the characters we use to display the map, the direction ID’s and the letter that quits the game.
Enumerations and Structures#
We define an enumeration CellContent for the cell’s content and a structure
Cell to represent the maze cells:
enum CellContent {
Wall,
Empty,
Player,
Goal
};
typedef struct Cell{
int row, // Y coordinate.
column; // X coordinate.
enum CellContent content;
} Cell;
Each cell has to be in one of the following states: Wall, Empty, Player or
Goal. We are going to be working with cartesian coordinates for the map so
we store the row and column for each Cell.
Function Prototypes#
By declaring our prototypes at the top of the file we can use the functions in
our main() code without having to implement the function there (it doesn’t
even need to be in the same file!).
With just the signatures we’re able to grasp what the print_map, depth_first_search
and get_available_directions do:
void print_map(WINDOW *maze_window, int rows, int cols, Cell **map);
void depth_first_search(int current_row, int current_col, int rows, int cols, Cell **map);
void get_available_directions(int current_row, int current_col, int rows, int cols, Cell **map, int available_directions[4]);
However, if you’d like, you can jump into the implementation section where you can find the details of what (and why) each function does what it does.
Main Function#
The main function does a bunch of stuff:
- Initializes the
ncurses’screen. - Allocates memory for the maze.
- Generates a random maze using Depth-First Search.
- Handles the player’s input to move through the maze.
Many other things happen under the hood, but they’re mostly ramifications of those ones. Take a look:
int main(void)
{
WINDOW *maze_window; // ncurses Window.
int rows, // The amount of rows in the screen.
cols, // The amount of columns in the screen.
current_row, // The current row for iterations.
current_col, // The current column for iterations.
maze_window_rows, // The amount of rows in the maze window.
maze_window_cols; // The amount of columns in the maze window.
int player_row = 1, // The current row of the player.
player_col = 1, // The current column of the player.
goal_row, // The row for the goal.
goal_col, // The column for the goal.
key_pressed; // The ID of the key pressed by the user.
Cell **map; // The map is a matrix of Cells.
int quit = 0;
// Initialize the random seed.
srand(time(NULL));
// Initialize the screen.
initscr();
// Get the maximum amount of rows and columns for the current screen.
getmaxyx(stdscr, rows, cols);
// Calculate the amount of rows and columns available (margin).
maze_window_rows = rows - 3;
maze_window_cols = cols - 2;
// Keep a wall border and put both start and goal on odd coordinates.
if (maze_window_rows % 2 == 0) maze_window_rows--;
if (maze_window_cols % 2 == 0) maze_window_cols--;
if (maze_window_rows < 5 || maze_window_cols < 5)
{
endwin();
fprintf(stderr, "Terminal is too small.\n");
return 1;
}
map = calloc((size_t)maze_window_rows, sizeof *map);
if (map == NULL)
{
endwin();
return 1;
}
for (current_row = 0; current_row < maze_window_rows; current_row++)
{
map[current_row] = malloc((size_t)maze_window_cols * sizeof *map[current_row]);
if (map[current_row] == NULL)
{
for (int r = 0; r < current_row; r++) free(map[r]);
free(map);
endwin();
return 1;
}
for (current_col = 0; current_col < maze_window_cols; current_col++)
{
map[current_row][current_col] = (Cell){current_row, current_col, Wall};
}
}
// Clear the screen.
clear();
// Deactivate the "echo" function of the prompt.
noecho();
// Eliminate the breaks.
cbreak();
// Create the window.
maze_window = newwin(maze_window_rows, maze_window_cols, 2, 1);
if (maze_window == NULL)
{
for (current_row = 0; current_row < maze_window_rows; current_row++) free(map[current_row]);
free(map);
endwin();
return 1;
}
// Associate the keypad to the window.
keypad(maze_window, TRUE);
// Print simple information.
mvprintw(0, 0, "Dynamic Maze using ncurses.h - ESCOM Operating Systems");
mvprintw(1, 0, "Use the arrow keys to move through the window, reach the goal '%c' to win or press '%c' to exit.", GOAL_CHAR, EXIT_OPTION_LOWER);
// Refresh the screen to show the changes.
refresh();
// We randomly generate the maze by using a custom DFS function which will
// go through the map and _carve_ its path through it.
depth_first_search(1, 1, maze_window_rows, maze_window_cols, map);
// Set the player in the map.
map[player_row][player_col].content = Player;
// Odd dimensions make the last inner cell a reachable DFS cell.
goal_row = maze_window_rows - 2;
goal_col = maze_window_cols - 2;
map[goal_row][goal_col].content = Goal;
// Print the initial map.
print_map(maze_window, maze_window_rows, maze_window_cols, map);
// While the player doesn't reach the goal...
while (!quit && (player_row != goal_row || player_col != goal_col))
{
// Get the key pressed by the user.
key_pressed = wgetch(maze_window);
// Erase the user from it's current position.
map[player_row][player_col].content = Empty;
// Act based on the key entered.
switch (key_pressed)
{
case KEY_UP:
if (player_row > 1 && map[player_row - 1][player_col].content != Wall)
{
player_row -= 1;
}
break;
case KEY_DOWN:
if (player_row < (maze_window_rows - 1) && map[player_row + 1][player_col].content != Wall)
{
player_row += 1;
}
break;
case KEY_LEFT:
if (player_col > 1 && map[player_row][player_col - 1].content != Wall)
{
player_col -= 1;
}
break;
case KEY_RIGHT:
if (player_col < (maze_window_cols - 1) && map[player_row][player_col + 1].content != Wall)
{
player_col += 1;
}
break;
case EXIT_OPTION_UPPER:
case EXIT_OPTION_LOWER:
quit = 1;
break;
}
// Set the position of the player in the map.
map[player_row][player_col].content = Player;
// Print the map.
print_map(maze_window, maze_window_rows, maze_window_cols, map);
}
// If the user won or lost, end the window.
delwin(maze_window);
endwin();
// Free the memory allocated to each row within the map.
for (current_row = 0; current_row < maze_window_rows; current_row++)
{
free(map[current_row]);
}
// Now free the map itself.
free(map);
// Print a simple message.
printf(quit ? "Goodbye!\n" : "Congratulations! You reached the goal!\n");
// End the execution.
return 0;
}
Helper Functions#
Remember the functions’ prototypes we declared earlier? It’s time to look at the implementation. Each function is written with simplicity in mind, however you may have to look into the main function section to trace where everything gets called.
Printing the map#
The print_map function does what its name says, maybe the only peculiarities
regarding this implementation is that we need to map our current map into the
size of the maze_window, other than that is read-and-display.
void print_map(WINDOW *maze_window, int rows, int cols, Cell **map)
{
int row, col;
// We iterate through each row.
for (row = 0; row < rows; row++)
{
// We iterate throgh each column in each row.
for (col = 0; col < cols; col++)
{
// Switch the content of the Cell.
switch (map[row][col].content)
{
case Wall:
mvwaddch(maze_window, row, col, WALL_CHAR);
break;
case Empty:
mvwaddch(maze_window, row, col, EMPTY_CHAR);
break;
case Player:
mvwaddch(maze_window, row, col, PLAYER_CHAR);
break;
case Goal:
mvwaddch(maze_window, row, col, GOAL_CHAR);
break;
default:
mvwaddch(maze_window, row, col, '?');
}
}
}
// We have to refresh the window to show our changes in the screen.
wrefresh(maze_window);
}
Depth-First Search (DFS)#
We use a modified version of the well-known Depth-First Search algorithm (known
also as DFS) to get a random maze generated when the game
starts. If you see our main program we initialize the map by
filling it in with the Wall enumeration value. Our DFS will try to carve into
the map the valid pathways for the player to navigate. Let’s see the definition:
void depth_first_search(int current_row, int current_col, int rows, int cols, Cell **map)
{
int available_directions[4] = {0, 0, 0, 0}, // Array for storing the available directions for each cell.
direction; // The selected direction.
do
{
// Set the current location as Empty.
map[current_row][current_col].content = Empty;
// Get the UPDATED and available directions for the current Cell.
get_available_directions(current_row, current_col, rows, cols, map, available_directions);
// Check for the base case for our recursion: no available directions.
if (!available_directions[DIRECTION_UP] && !available_directions[DIRECTION_DOWN] && !available_directions[DIRECTION_LEFT] && !available_directions[DIRECTION_RIGHT])
{
// Bye bye!
return;
}
// Get a random, avilable, direction.
do
{
// Random value between 0 and 4 (0-3).
direction = rand() % 4;
} while(available_directions[direction] == 0); // While the random direction is a not available direction.
// We move to the next Cell based on the direction.
switch(direction)
{
case DIRECTION_UP:
// Carve the wall with a space to walk through.
map[current_row - 1][current_col].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row - 2, current_col, rows, cols, map);
break;
case DIRECTION_LEFT:
// Carve the wall with a space to walk through.
map[current_row][current_col - 1].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row, current_col - 2, rows, cols, map);
break;
case DIRECTION_RIGHT:
// Carve the wall with a space to walk through.
map[current_row][current_col + 1].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row, current_col + 2, rows, cols, map);
break;
case DIRECTION_DOWN:
// Carve the wall with a space to walk through.
map[current_row + 1][current_col].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row + 2, current_col, rows, cols, map);
break;
}
} while (available_directions[DIRECTION_UP] || available_directions[DIRECTION_DOWN] || available_directions[DIRECTION_LEFT] || available_directions[DIRECTION_RIGHT]);
}
So what we are doing here is:
- Set the current position as empty.
- Get the
available_directionsfor our currentCell. - Check for the base case of recursion: no directions available.
- Select pseudo-randomly1 a
direction. - Carve an
Emptyspace between our currentCelland our destination. - Repeat from 1 until there are no available directions.
Get available directions#
Each Cell can have four available directions (ideally): DIRECTION_UP,
DIRECTION_DOWN, DIRECTION_RIGHT and DIRECTION_LEFT. A direction is available
if, 2 blocks from our Cell, in the direction we’re testing, the Cell is
a Wall.
// Get the available directions for a cell.
void get_available_directions(int current_row, int current_col, int rows, int cols, Cell **map, int available_directions[4])
{
// DIRECTION_UP
if ((current_row - 2) >= 1 && map[current_row - 2][current_col].content == Wall)
{
available_directions[DIRECTION_UP] = 1;
}
else
{
available_directions[DIRECTION_UP] = 0;
}
// DIRECTION_DOWN
if ((current_row + 2) <= (rows - 2) && map[current_row + 2][current_col].content == Wall)
{
available_directions[DIRECTION_DOWN] = 1;
}
else
{
available_directions[DIRECTION_DOWN] = 0;
}
// DIRECTION_RIGHT
if ((current_col + 2) <= (cols - 2) && map[current_row][current_col + 2].content == Wall)
{
available_directions[DIRECTION_RIGHT] = 1;
}
else
{
available_directions[DIRECTION_RIGHT] = 0;
}
// DIRECTION_LEFT
if ((current_col - 2) >= 1 && map[current_row][current_col - 2].content == Wall)
{
available_directions[DIRECTION_LEFT] = 1;
}
else
{
available_directions[DIRECTION_LEFT] = 0;
}
}
Compilation#
In order to compile this program we need to have the ncurses library installed,
for this you can follow the online instructions for your specific operating
system.
If you’re on macOS and using Homebrew, you just need to run the following
command:brew install libncurses
Once installed the compilation flag required for linking our project is: -lncurses.
The final command looks like this:
$ gcc -o MazeGame.out -lncurses MazeGame.c
Execution#
Showtime! Here are some screen captures of the mazes generated by the game:



And now here’s a GIF of me winning a game:

Final Code#
The final code for this simple project is:
// Libraries
#include <stdio.h> // We need standard I/O!
#include <ncurses.h> // 🪄 magic for our text UI! 🪄
#include <time.h> // We need to have a random(ish) seed for our map generation!
#include <stdlib.h> // We use `malloc()` and such.
// Constants
#define WALL_CHAR '#' // The character to show as a wall.
#define EMPTY_CHAR ' ' // The character to show as an empty space.
#define PLAYER_CHAR '@' // The character to show a player.
#define GOAL_CHAR 'G' // The character to show at the finish point!
#define DIRECTION_UP 0 // The int ID for up direction.
#define DIRECTION_LEFT 1 // The int ID for left direction.
#define DIRECTION_RIGHT 2 // The int ID for right direction.
#define DIRECTION_DOWN 3 // The int ID for down direction.
#define EXIT_OPTION_LOWER 'q' // Lowercase letter for exiting the game.
#define EXIT_OPTION_UPPER 'Q' // Uppercase letter for quitting the game.
enum CellContent {
Wall,
Empty,
Player,
Goal
};
typedef struct Cell{
int row, // Y coordinate.
column; // X coordinate.
enum CellContent content;
} Cell;
void print_map(WINDOW *maze_window, int rows, int cols, Cell **map);
void depth_first_search(int current_row, int current_col, int rows, int cols, Cell **map);
void get_available_directions(int current_row, int current_col, int rows, int cols, Cell **map, int available_directions[4]);
int main(void)
{
WINDOW *maze_window; // ncurses Window.
int rows, // The amount of rows in the screen.
cols, // The amount of columns in the screen.
current_row, // The current row for iterations.
current_col, // The current column for iterations.
maze_window_rows, // The amount of rows in the maze window.
maze_window_cols; // The amount of columns in the maze window.
int player_row = 1, // The current row of the player.
player_col = 1, // The current column of the player.
goal_row, // The row for the goal.
goal_col, // The column for the goal.
key_pressed; // The ID of the key pressed by the user.
Cell **map; // The map is a matrix of Cells.
int quit = 0;
// Initialize the random seed.
srand(time(NULL));
// Initialize the screen.
initscr();
// Get the maximum amount of rows and columns for the current screen.
getmaxyx(stdscr, rows, cols);
// Calculate the amount of rows and columns available (margin).
maze_window_rows = rows - 3;
maze_window_cols = cols - 2;
// Keep a wall border and put both start and goal on odd coordinates.
if (maze_window_rows % 2 == 0) maze_window_rows--;
if (maze_window_cols % 2 == 0) maze_window_cols--;
if (maze_window_rows < 5 || maze_window_cols < 5)
{
endwin();
fprintf(stderr, "Terminal is too small.\n");
return 1;
}
map = calloc((size_t)maze_window_rows, sizeof *map);
if (map == NULL)
{
endwin();
return 1;
}
for (current_row = 0; current_row < maze_window_rows; current_row++)
{
map[current_row] = malloc((size_t)maze_window_cols * sizeof *map[current_row]);
if (map[current_row] == NULL)
{
for (int r = 0; r < current_row; r++) free(map[r]);
free(map);
endwin();
return 1;
}
for (current_col = 0; current_col < maze_window_cols; current_col++)
{
map[current_row][current_col] = (Cell){current_row, current_col, Wall};
}
}
// Clear the screen.
clear();
// Deactivate the "echo" function of the prompt.
noecho();
// Eliminate the breaks.
cbreak();
// Create the window.
maze_window = newwin(maze_window_rows, maze_window_cols, 2, 1);
if (maze_window == NULL)
{
for (current_row = 0; current_row < maze_window_rows; current_row++) free(map[current_row]);
free(map);
endwin();
return 1;
}
// Associate the keypad to the window.
keypad(maze_window, TRUE);
// Print simple information.
mvprintw(0, 0, "Dynamic Maze using ncurses.h - ESCOM Operating Systems");
mvprintw(1, 0, "Use the arrow keys to move through the window, reach the goal '%c' to win or press '%c' to exit.", GOAL_CHAR, EXIT_OPTION_LOWER);
// Refresh the screen to show the changes.
refresh();
// We randomly generate the maze by using a custom DFS function which will
// go through the map and _carve_ its path through it.
depth_first_search(1, 1, maze_window_rows, maze_window_cols, map);
// Set the player in the map.
map[player_row][player_col].content = Player;
// Odd dimensions make the last inner cell a reachable DFS cell.
goal_row = maze_window_rows - 2;
goal_col = maze_window_cols - 2;
map[goal_row][goal_col].content = Goal;
// Print the initial map.
print_map(maze_window, maze_window_rows, maze_window_cols, map);
// While the player doesn't reach the goal...
while (!quit && (player_row != goal_row || player_col != goal_col))
{
// Get the key pressed by the user.
key_pressed = wgetch(maze_window);
// Erase the user from it's current position.
map[player_row][player_col].content = Empty;
// Act based on the key entered.
switch (key_pressed)
{
case KEY_UP:
if (player_row > 1 && map[player_row - 1][player_col].content != Wall)
{
player_row -= 1;
}
break;
case KEY_DOWN:
if (player_row < (maze_window_rows - 1) && map[player_row + 1][player_col].content != Wall)
{
player_row += 1;
}
break;
case KEY_LEFT:
if (player_col > 1 && map[player_row][player_col - 1].content != Wall)
{
player_col -= 1;
}
break;
case KEY_RIGHT:
if (player_col < (maze_window_cols - 1) && map[player_row][player_col + 1].content != Wall)
{
player_col += 1;
}
break;
case EXIT_OPTION_UPPER:
case EXIT_OPTION_LOWER:
quit = 1;
break;
}
// Set the position of the player in the map.
map[player_row][player_col].content = Player;
// Print the map.
print_map(maze_window, maze_window_rows, maze_window_cols, map);
}
// If the user won or lost, end the window.
delwin(maze_window);
endwin();
// Free the memory allocated to each row within the map.
for (current_row = 0; current_row < maze_window_rows; current_row++)
{
free(map[current_row]);
}
// Now free the map itself.
free(map);
// Print a simple message.
printf(quit ? "Goodbye!\n" : "Congratulations! You reached the goal!\n");
// End the execution.
return 0;
}
void print_map(WINDOW *maze_window, int rows, int cols, Cell **map)
{
int row, col;
// We iterate through each row.
for (row = 0; row < rows; row++)
{
// We iterate throgh each column in each row.
for (col = 0; col < cols; col++)
{
// Switch the content of the Cell.
switch (map[row][col].content)
{
case Wall:
mvwaddch(maze_window, row, col, WALL_CHAR);
break;
case Empty:
mvwaddch(maze_window, row, col, EMPTY_CHAR);
break;
case Player:
mvwaddch(maze_window, row, col, PLAYER_CHAR);
break;
case Goal:
mvwaddch(maze_window, row, col, GOAL_CHAR);
break;
default:
mvwaddch(maze_window, row, col, '?');
}
}
}
// We have to refresh the window to show our changes in the screen.
wrefresh(maze_window);
}
void depth_first_search(int current_row, int current_col, int rows, int cols, Cell **map)
{
int available_directions[4] = {0, 0, 0, 0}, // Array for storing the available directions for each cell.
direction; // The selected direction.
do
{
// Set the current location as Empty.
map[current_row][current_col].content = Empty;
// Get the UPDATED and available directions for the current Cell.
get_available_directions(current_row, current_col, rows, cols, map, available_directions);
// Check for the base case for our recursion: no available directions.
if (!available_directions[DIRECTION_UP] && !available_directions[DIRECTION_DOWN] && !available_directions[DIRECTION_LEFT] && !available_directions[DIRECTION_RIGHT])
{
// Bye bye!
return;
}
// Get a random, avilable, direction.
do
{
// Random value between 0 and 4 (0-3).
direction = rand() % 4;
} while(available_directions[direction] == 0); // While the random direction is a not available direction.
// We move to the next Cell based on the direction.
switch(direction)
{
case DIRECTION_UP:
// Carve the wall with a space to walk through.
map[current_row - 1][current_col].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row - 2, current_col, rows, cols, map);
break;
case DIRECTION_LEFT:
// Carve the wall with a space to walk through.
map[current_row][current_col - 1].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row, current_col - 2, rows, cols, map);
break;
case DIRECTION_RIGHT:
// Carve the wall with a space to walk through.
map[current_row][current_col + 1].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row, current_col + 2, rows, cols, map);
break;
case DIRECTION_DOWN:
// Carve the wall with a space to walk through.
map[current_row + 1][current_col].content = Empty;
// Move recursively to the next Cell.
depth_first_search(current_row + 2, current_col, rows, cols, map);
break;
}
} while (available_directions[DIRECTION_UP] || available_directions[DIRECTION_DOWN] || available_directions[DIRECTION_LEFT] || available_directions[DIRECTION_RIGHT]);
}
// Get the available directions for a cell.
void get_available_directions(int current_row, int current_col, int rows, int cols, Cell **map, int available_directions[4])
{
// DIRECTION_UP
if ((current_row - 2) >= 1 && map[current_row - 2][current_col].content == Wall)
{
available_directions[DIRECTION_UP] = 1;
}
else
{
available_directions[DIRECTION_UP] = 0;
}
// DIRECTION_DOWN
if ((current_row + 2) <= (rows - 2) && map[current_row + 2][current_col].content == Wall)
{
available_directions[DIRECTION_DOWN] = 1;
}
else
{
available_directions[DIRECTION_DOWN] = 0;
}
// DIRECTION_RIGHT
if ((current_col + 2) <= (cols - 2) && map[current_row][current_col + 2].content == Wall)
{
available_directions[DIRECTION_RIGHT] = 1;
}
else
{
available_directions[DIRECTION_RIGHT] = 0;
}
// DIRECTION_LEFT
if ((current_col - 2) >= 1 && map[current_row][current_col - 2].content == Wall)
{
available_directions[DIRECTION_LEFT] = 1;
}
else
{
available_directions[DIRECTION_LEFT] = 0;
}
}
If you’re interested in reading my class project from which all of this is based on, you can visit the GitHub Repository for it:
Footnotes
-
As you can imagine, generating real random numbers is a bit of a hassle in computer science. We must assume the output of
rand()to be a pseudo-random value. If you have more questions about it you can read its documentation at: https://en.cppreference.com/w/c/numeric/random/rand ↩