|
本帖最后由 code016 于 2017-1-1 17:41 编辑
[mw_shl_code=c,true]#include <stdio.h>
#include <windows.h>
char a[20][21],fx='s',ax,ay;
int x[10000],y[10000],head,tail,eat=0;
void init()
{
int i,j;
for(i=0;i<=19;i++)
{
for(j=0;j<=19;j++)
{
a[j]='.';
}
a[20]='\0';
}
return ;
}
void fill()
{
int i,tx,ty;
for(i=tail;i<=head;i++)
{
tx=x;ty=y;
a[tx][ty]='@';
}
return;
}
void ppp()
{
int i;
system("cls");
for(i=0;i<=19;i++)
printf("%s\n",a);
return ;
}
void addfood()
{
int f,i;
srand(time(NULL));
while(1>0)
{
ax=rand()%20;ay=rand()%20;
f=0;
for(i=tail;i<=head;i++)
{
if(x==ax && y==ay)
{
f=1;
}
}
if(f==0)break;
}
return ;
}
int main()
{
int tx,ty;
char ch;
x[0]=0;y[0]=1;
x[1]=1;y[1]=1;
x[2]=2;y[2]=1;
tail=0;head=2;
addfood();
while(1>0)
{
init();//清空游乐场
fill();//向游乐场中填充该蛇身
a[ax][ay]='$';//向游乐场中投入食物
ppp();//打印
if(kbhit()==1)//键盘是否会被按下
{
ch=getch();
if((ch=='w' || ch=='s') && (fx=='a' || fx=='d'))
fx=ch;
if((ch=='a' || ch=='d') && (fx=='w' || fx=='s'))
fx=ch;
}
if(fx=='s')
{
tx=x[head]+1; ty=y[head];
}
if(fx=='w')
{
tx=x[head]-1; ty=y[head];
}
if(fx=='a')
{
tx=x[head];ty=y[head]-1;
}
if(fx=='d')
{
tx=x[head];ty=y[head]+1;
}
if(tx==20)tx=0;
if(tx==-1)tx=19;
if(ty==20)ty=0;
if(ty==-1)ty=19;
head++;
x[head]=tx;y[head]=ty;
if(tx==ax && ty==ay)
addfood();
else
tail++;
Sleep(100);
}
return 0;
}[/mw_shl_code]
如果你想玩“贪吃蛇”,可以试一试这段代码
|
|