program snake2;   

#define SIZEPOS 20 

global

int xpos[SIZEPOS];
int ypos[SIZEPOS];

int xold[SIZEPOS];
int yold[SIZEPOS];

score = 0;
sspeed = 5;
bits;
direction;
i; 
dead;

begin
	SET_MODE(320,240,8); 
	LOAD_FPG("snake.fpg");
	for(i = 1;i<SIZEPOS;i++)
		xold[i] = 100+3*i;
		yold[i] = 100+3*i;
	end;
	head();
	apple();
	score();
end;

process score()
private
int highscore = 0;

begin
load("snake.sco",highscore);
	while(1==1) 
			delete_text(0);
			write(0,10,20,0,"YOUR SCORE " + score);
			write(0,10,30,0,"HIGH SCORE " + highscore);
			if(dead)
				write(0,10,10,0,"GAME OVER");
				write(0,10,40,0,"press A to play again");
				if(score>highscore)
					save("snake.sco",score);
					load("snake.sco",highscore);
				end;
			end;
 
			frame;
	end;
end; 


process restart()
begin
	LET_ME_ALONE ();
	score();
	while(dead)
		if(key(_control)) 
			for(i = 1;i<SIZEPOS;i++)
				xold[i] = 100+3*i;
				yold[i] = 100+3*i;
			end;
				direction = 0; 
				dead = false;
				apple();
				head();
				score = 0;
		end;
		frame;
	end;	
end;


process head()
begin
	x = 10;
	y = 10;
	graph = 1;
	while(!dead)
			if (key(_up) && direction != 3)
				y-=sspeed;
				direction = 1;
			elseif (key(_down) && direction !=1)
				y+=sspeed;
				direction = 3;
			elseif (key(_left)&& direction !=2)
				x-=sspeed;
				direction = 4;
			elseif (key(_right) && direction !=4)
				x+=sspeed;
				direction = 2;
			elseif (direction == 1)
				y-=sspeed;
			elseif (direction == 3)
				y+=sspeed;
			elseif (direction == 4)
				x-=sspeed;
			elseif (direction == 2)
				x+=sspeed;
			end;	
	    
	    if(direction>0)
	    
				for(bits = 1;bits<SIZEPOS;bits++)
					tail(bits);
				end;
				
				for(bits = 0; bits < SIZEPOS; bits++)
					xold[bits] = xpos[bits];
					yold[bits] = ypos[bits]; 
				end;
					 
				
				xpos[0] = x;
				ypos[0] = y; 
			end;
		
		if(x>320 || y >240 || x<0 || y<0)
			dead = true;
			restart();
		end;
		frame;
	end;
end;

process apple()
begin
	graph = 2;
	x = rand(10,320);
	y = rand(10,230);
	loop
		if(collision(type head))
			score++;
			obstacle();
			x = rand(10,320);
			y = rand(10,230);
		end;
		
		if(collision(type obstacle))
			x = rand(10,320);
			y = rand(10,230); 
		end;
		
		frame;
	end;
end;
	
process tail(abits)
begin
	graph = 1;
	x = xpos[abits] = xold[abits-1];
	y = ypos[abits] = yold[abits-1];
	if(collision(type head))
		dead = true; 
		restart();
	end;
frame;	
end;

process obstacle()
begin
	graph = rand(3,6);
	x = rand(10,320);
	y = rand(10,230);
	while(!dead)
		if(collision(type head))
			dead = true;
			restart();
		end; 
		frame;
	end;
end;
			
		