#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <map>
#include <conio.h>
#include <utility>
using namespace std;
#define n 20
#define m 40
typedef pair<int, int> PII;
char g[n][m];
char s[n][m];
map<char,int> dir;
PII q[100];
int hh = 0,tt = -1;
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
PII head = {11,10},tail = {14,10};
int last_direction,score;
void gotoxy(short i,short j)
{
COORD position = {j,i};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);
}
void food()
{
int x = rand() % n,y = rand() % m;
bool flag = false;
for(int i = 0;i < tt - hh + 1;i ++)
if(q[i].first == x && q[i].second == y) flag = true;
if(x != 0 && y != 0 && x != n - 1 && y != n - 1 && g[x][y] != '#' && !flag)
{
gotoxy(x,y);
g[x][y] = '$';
printf("$");
}
else
{
food();
}
}
void init()
{
srand((unsigned) time(NULL));
for(int i = 11;i <= 14;i ++)
{
q[++ tt] = {i,10};
}
for(int i = 0;i < n;i ++)
{
for(int j = 0;j < m;j ++)
{
if(i == 0 || j == 0 || i == n - 1 || j == m - 1)
{
g[i][j] = '#';
}
}
}
for(int i = 0;i < n;i ++)
{
for(int j = 0;j < m;j ++)
{
printf("%c",g[i][j]);
}
printf("\n");
}
for(int i = 0;i < tt - hh + 1;i ++)
{
int x = q[i].first,y = q[i].second;
gotoxy(x,y);
printf("@");
}
food();
}
void draw_snake()
{
for(int i = 0;i < tt - hh + 1;i ++)
{
int x = q[i].first,y = q[i].second;
gotoxy(x,y);
printf("@");
}
}
int move_towards()
{
if(kbhit())
{
char in = getch();
if(in == 'w' || in == 's' || in == 'a' || in == 'd')
{
return dir[in];
}
}
else
{
return last_direction;
}
}
void run_snake()
{
while(1)
{
Sleep(500);
int pos_to_erase_x = q[tt].first,pos_to_erase_y = q[tt].second;
gotoxy(pos_to_erase_x,pos_to_erase_y);
printf(" ");
last_direction = move_towards();
int tail_x = q[tt].first,tail_y = q[tt].second;
for(int i = tt - hh + 1;i >= 1;i --) q[i].first = q[i - 1].first,q[i].second = q[i - 1].second;
q[hh] = {q[hh].first + dx[last_direction],q[hh].second + dy[last_direction]};
if(g[q[hh].first][q[hh].second] == '$')
{
score ++;
g[q[hh].first][q[hh].second] = ' ';
food();
q[++ tt] = {tail_x,tail_y};
}
bool flag = false;
for(int i = 1;i < tt - hh + 1;i ++)
{
if(q[hh].first == q[i].first && q[hh].second == q[i].second) flag = true;
}
if(g[q[hh].first][q[hh].second] == '#' || flag)
{
system("cls");
printf("Game Over.Your Score is : %d",score);
break;
}
draw_snake();
}
}
int main()
{
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
init();
dir['w'] = 0,dir['d'] = 1,dir['s'] = 2,dir['a'] = 3;
run_snake();
system("pause > nul");
return 0;
}