#include<stdio.h>
#include<windows.h>
#include<time.h>
#include<conio.h>
#defineframe_height20//definemapsize
#defineframe_width40
#defineUP'w'//defineoperatekey
#defineDOWN's'
#defineLEFT'a'
#defineRIGHT'd'
inti,j,k;
charch=UP;//initialdirection
intgrow=0;//flag:ifsnakegrow
structFood{
intx;
inty;
}food;
structSnake{
intx[50];
inty[50];
intlen;
intspeed;
}snake;//snake[0]ishead
voidinit_map(void);
voidupdate_food(void);
voidmove_snake(void);
intis_alive(void);
voidget_speed(void);
voidgotoxy(intx,inty);
intmain()
{
init_map();//初始化地圖
while(1)
{
update_food();//是否產(chǎn)生食物
get_speed();//獲取速度
move_snake();//移動蛇身
Sleep(snake.speed);//移動速度
if(!(is_alive()))//蛇的死活(撞墻或自食)
break;
}
printf("GameOver!");
getch();
return0;
}
//initialize
voidinit_map(void)
{
//initialfood
srand(time(NULL));
food.x=rand()%(frame_height-2)+1;
food.y=rand()%(frame_width-2)+1;
gotoxy(food.x,food.y);
printf("!");
//initialsnake
snake.x[0]=frame_height/2;
snake.y[0]=frame_width/2;
gotoxy(snake.x[0],snake.y[0]);
printf("@");
snake.len=3;
snake.speed=200;
for(k=1;k<snake.len;k++)
{
snake.x[k]=snake.x[k-1]+1;
snake.y[k]=snake.y[k-1];
gotoxy(snake.x[k],snake.y[k]);
printf("@");
}
//initialbar
for(j=0;j<frame_width;j++)
{
gotoxy(0,j);
printf("#");
gotoxy(frame_height-1,j);
printf("#");
}
for(i=1;i<frame_height-1;i++)
{
gotoxy(i,0);
printf("#");
gotoxy(i,frame_width-1);
printf("#");
}
}
//generatefood
voidupdate_food()
{
if(snake.x[0]==food.x&&snake.y[0]==food.y)
{
srand(time(NULL));
food.x=rand()%(frame_height-2)+1;
food.y=rand()%(frame_width-2)+1;
gotoxy(food.x,food.y);
printf("!");
snake.len++;
grow=1;
}
}
//movesnake
voidmove_snake()
{
if(kbhit())
ch=getch();
if(!grow)
{
gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);
printf("");
}
for(k=snake.len-1;k>0;k--)
{
snake.x[k]=snake.x[k-1];
snake.y[k]=snake.y[k-1];
}
switch(ch)
{
caseUP:snake.x[0]--;break;
caseDOWN:snake.x[0]++;break;
caseLEFT:snake.y[0]--;break;
caseRIGHT:snake.y[0]++;break;
default:break;
}
gotoxy(snake.x[0],snake.y[0]);
printf("@");
grow=0;
gotoxy(frame_height,0);
}
//isalive
intis_alive(void)
{
if(snake.x[0]==0||snake.x[0]==frame_height-1||snake.y[0]==frame_width-1||snake.y[0]==0)
return0;
for(k=1;k<snake.len;k++)
if(snake.x[k]==snake.x[0]&&snake.y[k]==snake.y[0])
return0;
return1;
}
//speedup
voidget_speed(void)
{
if(snake.len<=6)snake.speed=200;
elseif(snake.len<=10)snake.speed=100;
elseif(snake.len<=20)snake.speed=50;
elseif(snake.len<=30)snake.speed=30;
elsesnake.speed=20;
}
//movecursor
voidgotoxy(intx,inty)
{
HANDLEhout;
COORDcor;
hout=GetStdHandle(STD_OUTPUT_HANDLE);
cor.X=y;
cor.Y=x;
SetConsoleCursorPosition(hout,cor);
}