使用Devc++写的一个简单版贪吃蛇程序,不过,在未配置之前,是不包含图形库的,所以需要自己配置新的环境
-------------------------------------------------------------------分割线----------------------------------------------------------------------------------
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<time.h>
#include<windows.h>
main()
{
int x[200]={200,210,220},y[200]={60,60,60},i,n=3,d=3,key;
int food_x,food_y,flag=0,score=0;
char str[100];
initwindow(640,480);
setcolor(RED);
outtextxy(50,30,"greedysnake1.0");
outtextxy(400,30,"score:");//初始化分数显示
itoa(score,str,10);
outtextxy(450,30,str);
rectangle(50,50,500,400);
setcolor(WHITE);//画初始蛇
for(i=0;i<n;i++)
rectangle(x[i],y[i],x[i]+10,y[i]+10);
while(1)
{
if(flag==0)//发食物
{
srand((unsigned)time(NULL));
food_x=rand()%400+50;
food_y=rand()%300+50;
while(food_x%10!=0) food_x++;
while(food_y%10!=0) food_y++;
flag=1;
rectangle(food_x,food_y,food_x+10,food_y+10);
}
if(food_x==x[0]&&food_y==y[0])//吃食物
{
setcolor(BLACK);
rectangle(food_x,food_y,food_x+10,food_y+10);
n++;
flag=0;
score+=100;
itoa(score,str,10);//整数分数转换为字符串
setcolor(WHITE);//显示分数
outtextxy(450,30,str);
}
Sleep(200);//擦蛇
setcolor(BLACK);
for(i=0;i<n;i++)
rectangle(x[i],y[i],x[i]+10,y[i]+10);
for(i=n-1;i>=1;i--)//移动
{
x[i]=x[i-1];
y[i]=y[i-1];
}
if(kbhit()!=0)//如果有按键发生,则执行语句体
{
key=getch();
switch(key)
{
case‘w‘:d=1;break;
case‘s‘:d=2;break;
case‘a‘:d=3;break;
case‘d‘:d=4;break;
case‘p‘:getch();
}
}
switch(d)//控制蛇头的方向
{
case 1:y[0]-=10;break;
case 2:y[0]+=10;break;
case 3:x[0]-=10;break;
case 4:x[0]+=10;break;
}
setcolor(WHITE);//画蛇
for(i=0;i<n;i++)
rectangle(x[i],y[i],x[i]+10,y[i]+10);
if(x[0]<=50&&x[0]>=0||x[0]<=640&&x[0]>=500||y[0]<=50&&y[0]>=0||y[0]<=480&&y[0]>=400)//撞墙死
{
break;
}
}
closegraph();
}