Snake Code in C++
Last Updated :
06 Sep, 2023
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++
const int width = 80;
const int height = 20;
int x, y;
int fruitCordX, fruitCordY;
int playerScore;
int snakeTailX[100], snakeTailY[100];
int snakeTailLen;
enum snakesDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
snakesDirection sDir;
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++
void GameRender(string playerName)
{
system ( "cls" );
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++) {
if (j == 0 || j == width)
cout << "|" ;
if (i == y && j == x)
cout << "O" ;
else if (i == fruitCordY && j == fruitCordX)
cout << "#" ;
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;
}
for ( int i = 0; i < width + 2; i++)
cout << "-" ;
cout << endl;
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++
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 ;
}
if (x >= width || x < 0 || y >= height || y < 0)
isGameOver = true ;
for ( int i = 0; i < snakeTailLen; i++) {
if (snakeTailX[i] == x && snakeTailY[i] == y)
isGameOver = true ;
}
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++
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++
void UserInput()
{
if (_kbhit()) {
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++
int main()
{
string playerName;
cout << "enter your name: " ;
cin >> playerName;
int dfc = SetDifficulty();
GameInit();
while (!isGameOver) {
GameRender(playerName);
UserInput();
UpdateGame();
Sleep(dfc);
}
return 0;
}
|
C++ Program to Implement Snake Game
C++
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
const int width = 80;
const int height = 20;
int x, y;
int fruitCordX, fruitCordY;
int playerScore;
int snakeTailX[100], snakeTailY[100];
int snakeTailLen;
enum snakesDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
snakesDirection sDir;
bool isGameOver;
void GameInit()
{
isGameOver = false ;
sDir = STOP;
x = width / 2;
y = height / 2;
fruitCordX = rand () % width;
fruitCordY = rand () % height;
playerScore = 0;
}
void GameRender(string playerName)
{
system ( "cls" );
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++) {
if (j == 0 || j == width)
cout << "|" ;
if (i == y && j == x)
cout << "O" ;
else if (i == fruitCordY && j == fruitCordX)
cout << "#" ;
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;
}
for ( int i = 0; i < width + 2; i++)
cout << "-" ;
cout << endl;
cout << playerName << "'s Score: " << playerScore
<< endl;
}
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 ;
}
if (x >= width || x < 0 || y >= height || y < 0)
isGameOver = true ;
for ( int i = 0; i < snakeTailLen; i++) {
if (snakeTailX[i] == x && snakeTailY[i] == y)
isGameOver = true ;
}
if (x == fruitCordX && y == fruitCordY) {
playerScore += 10;
fruitCordX = rand () % width;
fruitCordY = rand () % height;
snakeTailLen++;
}
}
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;
}
void UserInput()
{
if (_kbhit()) {
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 ;
}
}
}
int main()
{
string playerName;
cout << "enter your name: " ;
cin >> playerName;
int dfc = SetDifficulty();
GameInit();
while (!isGameOver) {
GameRender(playerName);
UserInput();
UpdateGame();
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
Share your thoughts in the comments
Please Login to comment...