Snake Game

How could I make the tail of the snake to grow?

#include <iostream>
#include <string>
#include <stdlib.h>
#include <conio.h>

using namespace std;

bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitx, fruity, score;
int tailX[100], tailY[100];
int nTail;
enum eDirecton {STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirecton 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");
system("color F0");

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";

else if ( i == fruity && j == fruitx)
cout << "@";

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;
}


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 'e':
system("cls");
cout << "********************"<< endl << "Score:"<< score << endl<< "********************";
gameOver = true;
break;
}
}
}

void logic()
{
int preX = tailX[0];
int preY = tailY[0];
int pre2X, pre2Y;
tailX[0] = x;
tailY[0] = y;

for (int i = 1; i < nTail; i++)
{
pre2X = tailX[i];
pre2Y = tailY[i];
tailX[i] = pre2X;
tailY[i] = pre2Y;
preX = pre2X;
preY = pre2Y;
}
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 || y > height || y < 0)
gameOver = true;
if ( x == fruitx && y == fruity)
{
score += 10;
fruitx = rand() % width;
fruity = rand() % height;
nTail++;
}
}

int main()
{
setup();
while(!gameOver)
{
draw();
input();
logic();
}

return 0;
}
Last edited on
Please indent your code and put it between code brackets, which is the button that looks like this [<>] in the format section before you submit. Hit the edit button and you can set that up now.


I would suggest that instead of having a separate array for tail[x] and tail[y], make it a 2d boolean array tail[x][y], and make sure that it gets more priority over board drawing in the draw function.
Last edited on
Topic archived. No new replies allowed.