Snake is a classic game that includes a growing line represented as a snake that can consume items, change direction, and grow in length. As the snake grows larger in length, the difficulty of the game grows. In this article, we will create a snake game using a C++ program.
Rules to Play Snake Game
- Donât hit a wall and donât bite your own tail.
- Crashing into a wall or your tail will end the game immediately.
- 10 points will be added to the player's score for eating the fruit (#).
- The player's total score is calculated based on the number of fruits the snake consumed.
- The length of the snake will be increased after eating the fruits.
- Use w, a, s, d to move the snake.
Steps to Write a Snake Game
By following these steps, you will be able to create a fully functional snake game in C++ which can be played in the console using the keyboard.
Step 1: Setting Up The Project
Create a new C++ source file (.cpp) in your desired directory.
Step 2: Including Necessary Libraries
We need 3 different libraries that are:
C++
#include <conio.h>
#include <iostream>
#include <windows.h>
Here,
- iostream: Standard Input and Output Library of C++..
- windows.h: Windows API Library.
- conio.h: Non-Standard Library that contains console commands.
Step 3: Defining Global Variables for the Game
We have to specify some global game variables that we need to be accessible to all the functions. These are:
C++
// height and width of the boundary
const int width = 80;
const int height = 20;
// Snake head coordinates of snake (x-axis, y-axis)
int x, y;
// Food coordinates
int fruitCordX, fruitCordY;
// variable to store the score of he player
int playerScore;
// Array to store the coordinates of snake tail (x-axis,
// y-axis)
int snakeTailX[100], snakeTailY[100];
// variable to store the length of the sanke's tail
int snakeTailLen;
// for storing snake's moving snakesDirection
enum snakesDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
// snakesDirection variable
snakesDirection sDir;
// boolean variable for checking game is over or not
bool isGameOver;
Step 4: Initializing the Game
Create a function named GameInit() of void type for initializing the game variables.
C++
void GameInit()
{
isGameOver = false;
sDir = STOP;
x = width / 2;
y = height / 2;
fruitCordX = rand() % width;
fruitCordY = rand() % height;
playerScore = 0;
}
Step 5: Creating Game Board cum Game Rendering Function
Create a function named GameRender() of void type for creating the game board and rendering the game whenever needed in the console.
C++
// Function for creating the game board & rendering
void GameRender(string playerName)
{
system("cls"); // Clear the console
// Creating top walls with '-'
for (int i = 0; i < width + 2; i++)
cout << "-";
cout << endl;
for (int i = 0; i < height; i++) {
for (int j = 0; j <= width; j++) {
// Creating side walls with '|'
if (j == 0 || j == width)
cout << "|";
// Creating snake's head with 'O'
if (i == y && j == x)
cout << "O";
// Creating the sanke's food with '#'
else if (i == fruitCordY && j == fruitCordX)
cout << "#";
// Creating snake's head with 'O'
else {
bool prTail = false;
for (int k = 0; k < snakeTailLen; k++) {
if (snakeTailX[k] == j
&& snakeTailY[k] == i) {
cout << "o";
prTail = true;
}
}
if (!prTail)
cout << " ";
}
}
cout << endl;
}
// Creating bottom walls with '-'
for (int i = 0; i < width + 2; i++)
cout << "-";
cout << endl;
// Display player's score
cout << playerName << "'s Score: " << playerScore
<< endl;
}
Step 6: Updating the Game State
Create a function named UpdateGame() of void type for updatig the game state after each move.
C++
// Function for updating the game state
void UpdateGame()
{
int prevX = snakeTailX[0];
int prevY = snakeTailY[0];
int prev2X, prev2Y;
snakeTailX[0] = x;
snakeTailY[0] = y;
for (int i = 1; i < snakeTailLen; i++) {
prev2X = snakeTailX[i];
prev2Y = snakeTailY[i];
snakeTailX[i] = prevX;
snakeTailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (sDir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
// Checks for snake's collision with the wall (|)
if (x >= width || x < 0 || y >= height || y < 0)
isGameOver = true;
// Checks for collision with the tail (o)
for (int i = 0; i < snakeTailLen; i++) {
if (snakeTailX[i] == x && snakeTailY[i] == y)
isGameOver = true;
}
// Checks for snake's collision with the food (#)
if (x == fruitCordX && y == fruitCordY) {
playerScore += 10;
fruitCordX = rand() % width;
fruitCordY = rand() % height;
snakeTailLen++;
}
}
Step 7: Setting the Game Difficulty
Create a function named SetDifficulty() of int type for setting up the game difficulty(returns a int variable 'dfc').
C++
// Function to set the game difficulty level
int SetDifficulty()
{
int dfc, choice;
cout << "\nSET DIFFICULTY\n1: Easy\n2: Medium\n3: hard "
"\nNOTE: if not chosen or pressed any other "
"key, the difficulty will be automatically set "
"to medium\nChoose difficulty level: ";
cin >> choice;
switch (choice) {
case '1':
dfc = 50;
break;
case '2':
dfc = 100;
break;
case '3':
dfc = 150;
break;
default:
dfc = 100;
}
return dfc;
}
Step 8: Handling User Input
Create a function named UserInput() of void type for getting the user input for playing the game.
C++
// Function to handle user UserInput
void UserInput()
{
// Checks if a key is pressed or not
if (_kbhit()) {
// Getting the pressed key
switch (_getch()) {
case 'a':
sDir = LEFT;
break;
case 'd':
sDir = RIGHT;
break;
case 'w':
sDir = UP;
break;
case 's':
sDir = DOWN;
break;
case 'x':
isGameOver = true;
break;
}
}
}
Note:
1._kbhit() function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch() or _getche() to get the keystroke.
2. getch()is a nonstandard function and is present in file which is mostly used by. It is not part of the C standard library or ISO C, nor is it defined by POSIX
Step 9: Creating Main Function
Create a loop in the main() function to continuously update the game state, render the game, and handle user input.
C++
// Main function / game looping function
int main()
{
string playerName;
cout << "enter your name: ";
cin >> playerName;
int dfc = SetDifficulty();
GameInit();
while (!isGameOver) {
GameRender(playerName);
UserInput();
UpdateGame();
// creating a delay for according to the chosen
// difficulty
Sleep(dfc);
}
return 0;
}
C++ Program to Implement Snake Game
C++
// required header file
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
// height and width of the boundary
const int width = 80;
const int height = 20;
// Snake head coordinates of snake (x-axis, y-axis)
int x, y;
// Food coordinates
int fruitCordX, fruitCordY;
// variable to store the score of he player
int playerScore;
// Array to store the coordinates of snake tail (x-axis,
// y-axis)
int snakeTailX[100], snakeTailY[100];
// variable to store the length of the sanke's tail
int snakeTailLen;
// for storing snake's moving snakesDirection
enum snakesDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
// snakesDirection variable
snakesDirection sDir;
// boolean variable for checking game is over or not
bool isGameOver;
// Function to initialize game variables
void GameInit()
{
isGameOver = false;
sDir = STOP;
x = width / 2;
y = height / 2;
fruitCordX = rand() % width;
fruitCordY = rand() % height;
playerScore = 0;
}
// Function for creating the game board & rendering
void GameRender(string playerName)
{
system("cls"); // Clear the console
// Creating top walls with '-'
for (int i = 0; i < width + 2; i++)
cout << "-";
cout << endl;
for (int i = 0; i < height; i++) {
for (int j = 0; j <= width; j++) {
// Creating side walls with '|'
if (j == 0 || j == width)
cout << "|";
// Creating snake's head with 'O'
if (i == y && j == x)
cout << "O";
// Creating the sanke's food with '#'
else if (i == fruitCordY && j == fruitCordX)
cout << "#";
// Creating snake's head with 'O'
else {
bool prTail = false;
for (int k = 0; k < snakeTailLen; k++) {
if (snakeTailX[k] == j
&& snakeTailY[k] == i) {
cout << "o";
prTail = true;
}
}
if (!prTail)
cout << " ";
}
}
cout << endl;
}
// Creating bottom walls with '-'
for (int i = 0; i < width + 2; i++)
cout << "-";
cout << endl;
// Display player's score
cout << playerName << "'s Score: " << playerScore
<< endl;
}
// Function for updating the game state
void UpdateGame()
{
int prevX = snakeTailX[0];
int prevY = snakeTailY[0];
int prev2X, prev2Y;
snakeTailX[0] = x;
snakeTailY[0] = y;
for (int i = 1; i < snakeTailLen; i++) {
prev2X = snakeTailX[i];
prev2Y = snakeTailY[i];
snakeTailX[i] = prevX;
snakeTailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (sDir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
// Checks for snake's collision with the wall (|)
if (x >= width || x < 0 || y >= height || y < 0)
isGameOver = true;
// Checks for collision with the tail (o)
for (int i = 0; i < snakeTailLen; i++) {
if (snakeTailX[i] == x && snakeTailY[i] == y)
isGameOver = true;
}
// Checks for snake's collision with the food (#)
if (x == fruitCordX && y == fruitCordY) {
playerScore += 10;
fruitCordX = rand() % width;
fruitCordY = rand() % height;
snakeTailLen++;
}
}
// Function to set the game difficulty level
int SetDifficulty()
{
int dfc, choice;
cout << "\nSET DIFFICULTY\n1: Easy\n2: Medium\n3: hard "
"\nNOTE: if not chosen or pressed any other "
"key, the difficulty will be automatically set "
"to medium\nChoose difficulty level: ";
cin >> choice;
switch (choice) {
case '1':
dfc = 50;
break;
case '2':
dfc = 100;
break;
case '3':
dfc = 150;
break;
default:
dfc = 100;
}
return dfc;
}
// Function to handle user UserInput
void UserInput()
{
// Checks if a key is pressed or not
if (_kbhit()) {
// Getting the pressed key
switch (_getch()) {
case 'a':
sDir = LEFT;
break;
case 'd':
sDir = RIGHT;
break;
case 'w':
sDir = UP;
break;
case 's':
sDir = DOWN;
break;
case 'x':
isGameOver = true;
break;
}
}
}
// Main function / game looping function
int main()
{
string playerName;
cout << "enter your name: ";
cin >> playerName;
int dfc = SetDifficulty();
GameInit();
while (!isGameOver) {
GameRender(playerName);
UserInput();
UpdateGame();
// creating a delay for according to the chosen
// difficulty
Sleep(dfc);
}
return 0;
}
Output/Game Screenshots
1. Entering the Player's Name and Choosing the Difficulty.

2. Initial State of the Game

3. Game Termination When Snake Collides with the Wall

4. Game Termination when Snake Collides with its Own Tail

Similar Reads
isless() in C/C++
In C++, isless() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions.isless() function used to check whether the 1st argument given to the function is less than the 2nd argument given to the function or not. Means if a is
2 min read
Snake and Ladder Game in C
Snake and Ladder game is a traditional game that involves two or more players and the winner is the guy who reaches the final square on the game board at the earliest. Components of the GameA square board with a series of numbered squares arranged in m x m grid.A dice to be rolled usually uses a six
5 min read
Naming Convention in C++
Naming a file or a variable is the first and the very basic step that a programmer takes to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way to read the code. In C++, naming conventions are the set of rules for choosing the valid name for
6 min read
goto Statement in C++
The goto statement in C++ is a control flow statement that provides for an unconditional jump to the same function's predefined label statement. In simple terms, the goto is a jump statement transfers the control flow of a program to a labeled statement within the scope of the same function, breakin
5 min read
Containers in C++ STL
Standard Template Library (STL) provides the built-in implementation of commonly used data structures known as containers. A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the data type
3 min read
cout in C++
In C++, cout is an object of the ostream class that is used to display output to the standard output device, usually the monitor. It is associated with the standard C output stream stdout. The insertion operator (<<) is used with cout to insert data into the output stream.Let's take a look at
2 min read
islessgreater() in C/C++
In C++, islessgreater() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions.islessgreater() function is used to check whether the 1st argument given to the function is less than or greater than the 2nd argument given to t
3 min read
find() in C++ STL
C++ find() is a built-in function used to find the first occurrence of an element in the given range. It works with any container that supports iterators, such as arrays, vectors, lists, and more. In this article, we will learn about find() function in C++.C++#include <bits/stdc++.h> using nam
2 min read
std::function in C++
The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases.Table of ContentWhat is std::function in C++?Example of std::functionMember Functions of s
5 min read
std::distance in C++
The std::distance() in C++ STL is a built-in function used to calculate the number of elements between two iterators. It is defined inside <iterator> header file. In this article, we will learn about the std::distance function in C++ with examples.Example:C++// C++ Program to illustrate the us
5 min read