C++ Snake Game Code
C++ Snake Game Code
bool gameOver;
//Taking constant variables for arena width and height
const int width = 20;
const int height = 20;
//taking an array for the size of snake
int tailX[50], tailY[50];
int nTail;
//Variables for position of player and fruit
int x, y, FruitX, FruitY, score;
//Setting enumerators for fixed direction
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
void Settings()
{
//1
//Setting the game to start
//Setting gameover to false to start the game
gameOver = false;
//Setting direction to stop so snake will not be moving at the start of game
dir = STOP;
//Setting the location of snake at the centre of arena at the start of game
x = width / 2;
y = height / 2;
//using random operator to randomize our fruit in the map
FruitX = rand() % width;
FruitY = rand() % height;
//Setting score to zero
score = 0;
void Visual()
{
//Clearing the screen
system("cls");
//Drawing our arena in which snake can move
for (int i = 0; i < width + 2; i++)
if (!printtail)
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
{
cout << "#";
}
cout << endl;
//Adding total score at the bottom of arena
cout << "Score: " << score << endl;
void Input()
void logic()
//Adding a logic part for the tail to follow the next member
{
int prevX = tailX[0];
int prevY = tailY[0];
prevX = x;
prevY = y;
int prev2X, prev2Y;
for (int i = 0; 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 (y >= width)
y = 0;
else if (y < 0)
y = width - 1;
gameOver = true;
//Adding outputs if the game is over
system("cls");
cout << "***OOOPS....You have been hit***" << endl;
cout << "\n******GAME OVER******" << endl;
cout << "\nYour score is: " << score << endl;
cout << "\n\n*****GOOD LUCK*****\n " << endl;
}
int main()
{
//Main Funtion
Settings();
while (!gameOver)
{
Visual();
Input();
logic();
//Adding Sleep function to slow down the speed of snake
//and blinking of screen
Sleep(30);
}
return 0;
}