#include <stdio.h>
#include <ctime>
#include <conio2.h>
#include <cstdlib>

#define MAXX 120 
#define MAXY 30
 

void show (int x, int y, int dir, int len, int sx, int sy){
	for (int i=0; i<len; i++){
		switch (dir){
			case 1:     
				gotoxy(x,(y-i-1)%MAXY+1); //DOWN
				break;
		    case 2:
			    gotoxy(((x+i+MAXX-1)%MAXX+1),y); //LEFT
				break;
		    case 3:
			    gotoxy(x,(y+i+MAXY-1)%MAXY+1); //UP
				break;    
			case 4:     
				gotoxy(((x-i-1)%MAXX+1),y); //RIGHT
				break;
		}               
		if(i==0){    
			textcolor(YELLOW);    
			textbackground(LIGHTRED);    
			printf("A");    
		}else{
		    textbackground(LIGHTBLUE);
			printf(" ");     
		}      
	}
	switch (dir){
		case 1:
			gotoxy(x,y%MAXY-1);
			break;
		case 2:
			gotoxy(x%MAXX+1,y);
			break;
		case 3:
			gotoxy(x,y%MAXY+1);
			break;
		case 4:
			gotoxy(x%MAXX-1,y);
			break;
	}
	textattr((YELLOW<<4) + BLACK);
	gotoxy(sx, sy);
	printf("0");
}
void control(int *dir){
	char key;
	if (kbhit){
		key = getch();
		switch(key){
			case 'w':
				*dir = 3;
				break;
			case 'a':
				*dir = 2;
				break;
			case 's':
				*dir = 1;
				break;
			case 'd':
				*dir = 4;
				break;
			case 'p':
				exit(0);
				break;
			default:
				gotoxy(MAXX/2,MAXY/2);
				printf("USE ONLY LOWERCASE W/A/S/D");
		}
	}
}
void move(int dir, int *x, int *y){
	switch(dir){
		case 1:
			*y+=1;
			if(*y==MAXY+1){
				*y=0;
			}
			break;
		case 2:
			*x-=1;
			if(*x==0){
				*x=MAXX
			}
			break;
		case 3:
			*y-=1;
			if(*y==0){
				*y=MAXY;
			}
			break;
		case 4:
			*x+=1;
			if(*x==MAXX+1){
				*x=0;
			}
			break;
	}
}
void gen_stone(int *x, int*y, int *flag){
	if(*flag==0){
		*x = rand()%MAXX;
		*y = rand()%MAXY;
		*flag = 1;
	}
} 
void eat(int x, int y, int *len, int sx, int sy, int *sflag){ 
	if(x==sx && y==sy){
		*len+=1;
		*sflag = 0;
	}
}
 
int main(){   
	int x=20, y=20, dir=1, len=1;
	int sx, sy, sflag=0;
	
	srand(time(NULL));
	while(1){
		textbackground(BLACK);
		clrscr();
		gen_stone(&sx, &sy, &sflag);
		control(&dir);
		move(dir, &x, &y);
		eat(x,y,&len,sx,sy,&sflag); 
		show (x,y,dir,len,sx,sy);
		_sleep(500);
	}
	return 0;
}