c语言小程序 贪吃蛇,C语言实现的简易贪吃蛇小游戏

#include 

#include 

#include 

#include 

#include 

#include 

typedef struct SnakeGame{ int x;int y;struct SnakeGame *next

;}snake;

snake *front, *rear;

char map[20][42];//give the map//

void ini();

int Move();

void insert(int x,int y);

void clean();

void print();

int main()

{

int res;

res=1;

ini();

while(res!=0)

{

Move();//when this function ends,game over//

res=0;

}

printf("GAME OVER!!!\n");

return 0;

}

void ini()//print the map ,food and snake//

{

int i,j,a,b;

front=rear=NULL;

for(i=0;i<20;i++)

{

for(j=0;j<42;j++)

{

if(i==0||i==19||j==0||j==41)

map[i][j]='*';

else

map[i][j]=' ';

}

}

for(i=2;i<6;i++)

map[2][i]='x';

map[2][i]='H';

a= rand()%19+1;

b= rand()%41+1;

map[a][b] = '$';

}

void insert(int x,int y)//insert the new head after every step//

{

snake *p;

p=(snake*)malloc(sizeof(snake));

p->x=x;//the coordine of the body ,head and food//

p->y=y;

if(rear==NULL)

rear=front=p;

else

{

p->next=front;

front=p;

}

}

void clean()//if not eat food,clean the old rear//

{

snake *q;

q=front;

while(q->next!=rear)

q=q->next;

free(rear);

rear=q;

}

void gotoxy(int x,int y)//just find this online //

{ HANDLE hOutput;

COORD loc;

loc.X=x;

loc.Y=y;

hOutput = GetStdHandle(STD_OUTPUT_HANDLE);

SetConsoleCursorPosition(hOutput, loc);

}

void print()//print the picture in time//

{

int i,j;

gotoxy(0,0);

for(i=0;i<20;i++)

{

for(j=0;j<42;j++)

{

printf("%c",map[i][j]);

if(j>0&&j%41==0)

printf("\n");

}

}

}

int Move()//to tell how to move //

{

char key='d';

int a,b,rx,ry;

int i;

rear = front = NULL;

for(i=2;i<7;i++)

insert(2,i);

print();

while(1)

{

Sleep(200);

if(kbhit())

key=getch();

switch(key)//the way to go in four directions//

{

case'a':{

ry = (front->y)-1;

rx = front->x;

break;

}

case'd':{

ry=(front->y)+1;

rx = front->x;

break;

}

case'w':{

ry=front->y;

rx=(front->x)-1;

break;

}

case's':{

ry=front->y;

rx=(front->x)+1;

break;

}

default:break;

}

map[front->x][front->y] = 'x';//replace the old head and insert the new head//

insert(rx,ry);

if(map[front->x][front->y]=='*' ||map[front->x][front->y]=='x') //judge the death//

return 0;

else

{

if(map[front->x][front->y]!='$')//judge the food//

{

map[rear->x][rear->y] = ' ';

clean();

}

else

{

a= rand()%19+1;

b= rand()%41+1;

while(map[a][b] != ' ')

{

a= rand()%19+1;

b= rand()%41+1;

}

map[a][b] = '$';

}

map[front->x][front->y]='H';

print();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值