#include <iostream>
#include <conio.h>
#include <Windows.h>
usingnamespace std;
bool gameOver;
constint width =20;
constint height = 20;
int x,y, fruitX, fruitY, score;
int tailX[100], tailY[100]; //this variable will keep track of where the tail is at on the map.
int ntail; //this variable will tell the length of the tail.
enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN}; //this enum is help the snake move.
eDirection dir; //and this variable is to hold the direction of the snake.
void setup()
{
gameOver = false;
dir = STOP;
x = width / 2; //those two functions is so the snake head will be centered on the map
y = height / 2;
fruitX = rand() % width; //and those two variable is so the fruit will appear all over the map.
fruitY = rand() % height;
score = 0;
}
void draw()
{
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)
cout << "#";
if (i == y && j ==x)
cout << "O";
elseif (j == fruitX && i == fruitY)
cout << "F";
else
{
bool print = false;
for (int k = 0; k < ntail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "o";
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()) //this will handle the controls.
{
switch (_getch())
{
case'a':
dir = LEFT;
break;
case'd':
dir = RIGHT;
break;
case's':
dir = DOWN;
break;
case'w':
dir = UP;
break;
case'x':
gameOver = true;
break;
}
}
}
void logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x; //those two functions are telling the tail to follow the head.
tailY[0] = y;
for (int i = 1; i < ntail; i++) //this for loop is telling what happens when the snake eat the fruit.
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) //this actual makes the snake move when you run the program.
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x >= width) x = 0; elseif (x < 0) x = width - 1;
if (y >= height) y = 0; elseif (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(15);
}
return 0;
}
I am also new to c++ but maybe you could do this. You will have to make a new function to clear the "board" or modify the draw function, but if you want to ask the player to play again thats how i would do it.