Code:
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#include <User/Console.h>
#define UP 72
#define LEFT 75
#define RIGHT 77
#define DOWN 80
#define ESC 27
typedef struct
{
int x;
int y;
int exist;
}INFO;
typedef struct
{
int x;
int y;
}LOC;
void Clear(LOC* snake)
{
free(snake);
}
void Initialize(LOC snake[], int* size, INFO* food, int* direction)
{
int i;
srand((unsigned)time(NULL));
ResizeConsoleWindow(50,30);
ChangeConsoleTitle("Snake");
HideConsoleCursor();
*size = 3;
*direction = LEFT;
for (i=0;i<*size;i++)
{
snake[i].x = 40 + i;
snake[i].y = 10;
}
food->exist = 0;
}
void Input(int *input, LOC* snake)
{
int temp = *input;
if (kbhit())
*input = getch();
if (*input == 224)
{
*input = getch();
switch(*input)
{
case UP: if (temp == DOWN) *input = temp;
break;
case DOWN: if (temp == UP) *input = temp;
break;
case LEFT: if (temp == RIGHT) *input = temp;
break;
case RIGHT: if (temp == LEFT) *input = temp;
break;
}
}
else if (*input == ESC)
{
Clear(snake);
exit(0);
}
else *input = temp;
}
void Allocate(LOC* snake, int size)
{
snake = malloc(sizeof(LOC)*size);
if(snake == NULL)
{
printf("Allocating Error");
getch();
exit(1);
}
}
void Move(LOC snake[], int *size, int direction, INFO* food)
{
int i;
if ( (snake[0].x == food->x && snake[0].y == food->y) )
{
Allocate(snake,++(*size));
snake[*size-1].x = snake[*size-2].x;
snake[*size-1].y = snake[*size-2].y;
FilledCircle(food->x*8,food->y*12.33,4,BLACKRGB);
food->exist = 0;
}
if(food->exist)
FilledCircle(food->x*8,food->y*12.33,4,REDRGB);
Circle(snake[*size-1].x*8,snake[*size-1].y*12.33,5,BLACKRGB);
for (i=*size-1;i>0;i--)
{
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
Circle(snake[0].x*8,snake[0].y*12.33,5,YELLOWRGB);
switch (direction)
{
case UP: snake[0].y--;
break;
case DOWN: snake[0].y++;
break;
case LEFT: snake[0].x--;
break;
case RIGHT: snake[0].x++;
break;
}
Circle(snake[0].x*8,snake[0].y*12.33,5,GREENRGB);
}
void CreateFood(LOC snake[], int size, INFO* food)
{
int x, y, i;
RANDOM:
x = rand()%49+1; y = rand()%29+1;
for (i=0;i<size;i++)
if (snake[i].x == x && snake[i].y == y)
goto RANDOM;
food->x = x;
food->y = y;
food->exist = 1;
FilledCircle(food->x*8,food->y*12.33,4,REDRGB);
}
int Crash(LOC snake[], int size)
{
int i;
for (i=1;i<size;i++)
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y)
return 1;
if (snake[0].x == 0 || snake[0].y == 0 || snake[0].x == 51 || snake[0].y == 31)
return 1;
return 0;
}
void End(LOC* snake, int size)
{
Clear(snake);
ClearConsole();
gotoxy(10,10);
SetAttColor(LIGHTBLUE);
printf("Final Lenght: %d", size);
getch();
}
int main()
{
int size, direction;
LOC *snake = malloc(sizeof(LOC)*3);
INFO food;
Initialize(snake, &size, &food, &direction);
while(!Crash(snake, size))
{
Input (&direction, snake);
if (!food.exist)
CreateFood(snake, size, &food);
Move(snake, &size, direction, &food);
Sleep(((70-(size/3))>0)*(70-(size/3)));
}
End(snake, size);
return 0;
}
If you want to see it (Win only):