Introduction: Simple Snake Game in C++
In this article, we’ll explore how to create a simple console-based Snake game in C++. We’ll cover the basics of game development, including managing the game state, handling user input, and updating the screen. By the end of this tutorial, you’ll have a fully functional Snake game that you can play directly in your console window.
Setup and Initialization:
Let’s start by setting up the basic components of our Snake game. We’ll define variables to keep track of the game state, the size of the game board, the position of the snake and the fruit, the player’s score, and the snake’s tail. We’ll also define an enumeration to represent the direction in which the snake is moving.
include<iostream>
include<conio.h>
include<window.h>
using namespace std;
bool gameOver;
const int width = 100;
const int height = 30;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
Initialization function:
We’ll create a function called Setup() to initialize the game state. This function will set the initial positions of the snake and the fruit, initialize the score and tail variables, and set the initial direction of the snake to STOP.
void Setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
Drawing function:
Next, we’ll create a function called Draw() to draw the game board and all its elements on the console screen. This function will loop through each cell of the game board, drawing the snake, the fruit, and the walls using ASCII characters. We’ll also use different colors to distinguish between the snake, the fruit, and the empty cells.
void Draw()
{
system(“cls”);
cout<<“Snake Game\n\n\n”;
cout<<“Press A for : Left\n Press D for : Right \n Press S for : Bottom \n Press W for : Up\n Press X for : Exit”;
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)
cout << "#";
if (i == y && j == x)
cout << "\x1b[32mO"; // Snake's head (green color)
else if (i == fruitY && j == fruitX)
cout << "\x1b[31mF"; // Fruit (red color)
else
{
bool print = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "\x1b[37mo"; // Snake's tail (white color)
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
cout << "Score:" << score << endl;
}
Input function: Simple Snake Game in C++
We’ll create a function called Input() to handle user input. This function will use the _kbhit() and _getch() functions from the conio.h library to detect key presses. Depending on the key pressed, the direction of the snake will be updated accordingly.
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case ‘a’:
dir = LEFT;
break;
case ‘d’:
dir = RIGHT;
break;
case ‘w’:
dir = UP;
break;
case ‘s’:
dir = DOWN;
break;
case ‘x’:
gameOver = true;
break;
}
}
}
Logic function: Simple Snake Game in C++
Finally, we’ll create a function called Logic() to update the game state based on the player’s input. This function will handle the movement of the snake, collision detection with the walls and the snake itself, and eating the fruit to increase the player’s score.
void Logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++)
{ prev2X = tailX[I];
prev2Y = tailY[I];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir)
{ case LEFT:
x–;
break;
case RIGHT:
x++;
break;
case UP:
y–;
break;
case DOWN: y++;
break;
default:
break;
}
if (x >= width) x = 0;
else if (x < 0) x = width – 1;
if (y >= height) y = 0;
else if (y < 0) y = height – 1;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
Main function:
Finally, we’ll create the main() function to initialize the game, run the game loop, and handle the game-over condition.
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(200);
}
system("pause");
return 0;
}
Conclusion:
In this article, we’ve learned how to create a simple Snake game in C++ using console graphics. We’ve covered the basics of game development, including setting up the game state, drawing the game board, handling user input, and updating the game logic. With this knowledge, you can further customize and enhance the game to add features such as levels.
Complete code: Simple Snake Game in C++
include<iostream>
include<conio.h>
include<window.h>
using namespace std;
bool gameOver;
const int width = 100;
const int height = 30;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
void Setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw()
{
system(“cls”);
cout<<“Snake Game\n\n\n”;
cout<<“Press A for : Left\n Press D for : Right \n Press S for : Bottom \n Press W for : Up\n Press X for : Exit”;
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)
cout << "#";
if (i == y && j == x)
cout << "\x1b[32mO"; // Snake's head (green color)
else if (i == fruitY && j == fruitX)
cout << "\x1b[31mF"; // Fruit (red color)
else
{
bool print = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "\x1b[37mo"; // Snake's tail (white color)
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
cout << "Score:" << score << endl;
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case ‘a’:
dir = LEFT;
break;
case ‘d’:
dir = RIGHT;
break;
case ‘w’:
dir = UP;
break;
case ‘s’:
dir = DOWN;
break;
case ‘x’:
gameOver = true;
break;
}
}
}
void Logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++)
{ prev2X = tailX[I];
prev2Y = tailY[I];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir)
{ case LEFT:
x–;
break;
case RIGHT:
x++;
break;
case UP:
y–;
break;
case DOWN: y++;
break;
default:
break;
}
if (x >= width) x = 0;
else if (x < 0) x = width – 1;
if (y >= height) y = 0;
else if (y < 0) y = height – 1;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(200);
}
system("pause");
return 0;
}
Output:Simple Snake Game in C++
![](https://allstudyhub.org/wp-content/uploads/2024/02/image-1024x726.png)