贪吃蛇c语言代码
时间: 2023-07-30 15:05:14 浏览: 125
以下是一个简单的贪吃蛇 C 语言代码:
```c
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<windows.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int width=20,height=20;
int x,y,fruitx,fruity,score,gameover,flag;
int tailx[100],taily[100],counttail=0;
void setup()
{
gameover=0;
x=width/2;
y=height/2;
label1:
fruitx=rand()%20;
if(fruitx==0)
goto label1;
label2:
fruity=rand()%20;
if(fruity==0)
goto label2;
score=0;
}
void draw()
{
system("cls");
int i,j,k;
for(i=0;i<width;i++)
{
for(j=0;j<height;j++)
{
if(i==0||i==height-1||j==0||j==width-1)
{
printf("*");
}
else
{
if(i==x&&j==y)
printf("O");
else if(i==fruitx&&j==fruity)
printf("F");
else
{
int ch=0;
for(k=0;k<counttail;k++)
{
if(i==tailx[k]&&j==taily[k])
{
printf("o");
ch=1;
}
}
if(ch==0)
printf(" ");
}
}
}
printf("\n");
}
printf("SCORE=%d",score);
}
void input()
{
if(kbhit())
{
switch(getch())
{
case UP:
flag=1;
break;
case DOWN:
flag=2;
break;
case LEFT:
flag=3;
break;
case RIGHT:
flag=4;
break;
case 27:
gameover=1;
break;
}
}
}
void logic()
{
int i;
int prevx=tailx[0];
int prevy=taily[0];
int prev2x,prev2y;
tailx[0]=x;
taily[0]=y;
for(i=1;i<counttail;i++)
{
prev2x=tailx[i];
prev2y=taily[i];
tailx[i]=prevx;
taily[i]=prevy;
prevx=prev2x;
prevy=prev2y;
}
switch(flag)
{
case 1:
x--;
break;
case 2:
x++;
break;
case 3:
y--;
break;
case 4:
y++;
break;
default:
break;
}
if(x<0||x>width||y<0||y>height)
gameover=1;
for(i=0;i<counttail;i++)
{
if(x==tailx[i]&&y==taily[i])
gameover=1;
}
if(x==fruitx&&y==fruity)
{
label3:
fruitx=rand()%20;
if(fruitx==0)
goto label3;
label4:
fruity=rand()%20;
if(fruity==0)
goto label4;
score+=10;
counttail++;
}
}
int main()
{
int m,n;
char c;
label5:
setup();
while(!gameover)
{
draw();
input();
logic();
for(m=0;m<1000;m++)
{
for(n=0;n<10000;n++)
{
}
}
}
printf("\nPress Y to play again and any other key to exit:");
scanf("%c",&c);
if(c=='Y'||c=='y')
goto label5;
return 0;
}
```
这是一个简单的控制台游戏,可以通过上下左右键控制蛇的移动,吃到水果得分并增加蛇的长度,碰到边界或自己的身体即为游戏结束。
阅读全文