|
#include <graphics.h>
#include<time.h> //包含随机数,时间函数
#include<bits/stdc++.h>
using namespace std;
int high=600,width=800,food_x,food_y,loait=0;
struct snake_body
{
int x;
int y;
};
struct snake
{
int v;
int len;
char dir;
snake_body body[100];
}she;
float ranx(int min,int max)
{
float h=rand()%(max-min)+min;
return h;
}
void food()
{
while(1)
{
int flag=0;
food_x=ranx(1,38);
food_y=ranx(1,29);
for(int i=0;i<she.len;i++)
{
if(she.body[i].x==food_x&&she.body[i].y==food_y)
{
flag=1;
}
}
if(flag==0)
{
break;
}
}
}
void startup()
{
srand(time(0));//随机种子函数
she.len = 4;
she.v = 50-(she.len-4)/5;
she.dir = 'd';
for(int i=0;i<4;i++)
{
she.body[i].x=20-i;
she.body[i].y=15;
}
initgraph(800, 600);
setcolor(BLACK);
setbkcolor(WHITE);
setfillcolor(GREEN);
setbkmode(TRANSPARENT); //设置文字背景色为透明(默认为有背景色)
}
void move()
{
for(int i=she.len;i>0;i--)
{
she.body[i].x=she.body[i-1].x;
she.body[i].y=she.body[i-1].y;
}
switch(she.dir)
{
case 'w':
she.body[0].y=she.body[0].y-1;
break;
case 's':
she.body[0].y=she.body[0].y+1;
break;
case 'a':
she.body[0].x=she.body[0].x-1;
break;
case 'd':
she.body[0].x=she.body[0].x+1;
break;
}
}
void food_eat()
{
for(int i=0;i<she.len;i++)
{
if(she.body[i].x==food_x&&she.body[i].y==food_y)
{
she.len++;
food();
}
}
}
void update()
{
if(kbhit())
{
she.dir=getch();
move();
}
loait++;
if(loait==she.v)
{
move();
loait=0;
}
}
void draw()
{
for(int i=0;i<she.len;i++)
{
setfillcolor(hsv2rgb(10*i%360, 1, 1));//设置填充颜色 参数(颜色,饱和度,明亮度)
bar(20*she.body[i].x,20*she.body[i].y,20*she.body[i].x+20,20*she.body[i].y+20);
}
setfillcolor(GREEN);
bar(20*food_x,20*food_y,20*food_x+20,20*food_y+20);
xyprintf(20,20,"分数:%d",she.len-4);
Sleep(10);
cleardevice();
}
bool gameover()
{
for(int i=1;i<=she.len;i++)
{
if(she.body[0].x==she.body[i].x&&she.body[0].y==she.body[i].y)
{
return true;
}
}
if((she.body[0].x>39||she.body[0].x<0)||(she.body[0].y>29||she.body[0].y<0))
{
return true;
}
return false;
}
int main()
{
startup();
food();
while(1)
{
draw();
update();
food_eat();
if(gameover())
{
break;
}
}
getch();
closegraph();
return 0;
} |
|