|
楼主 |
发表于 2019-2-25 14:32:31
|
显示全部楼层
这是源码
#include <stdio.h>
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define UP 'w' //上下左右
#define DOWN 's'
#define LEFT 'a'
#define RIGHT 'd'
struct snake{
int x;
int y;
};
struct snake snake[676],tail;
int length=2;
int foodx,foody;
void huichekongge()
{
while(1)//按回车或空格进入游戏
{
char c = getch();
if(c==32||c==13)
{
break;
}
}
cleardevice();//清除屏幕内容
}
void kaishijiemian()
{
initgraph(640,480);
char wz1[] = "贪吃蛇";
char wz2[] = "按回车或空格进入游戏";
outtextxy(240,120,wz1);
outtextxy(180,360,wz2);
huichekongge();
}
/**************************************/
void biankuang() //游戏界面
{
char shiwu[] = "■";
for(int x1=10;x1<400;x1=x1+15)
outtextxy(x1,10,shiwu);
for(int x2=10;x2<400;x2=x2+15)
outtextxy(x2,400,shiwu);
for(int y1=10;y1<400;y1=y1+15)
outtextxy(10,y1,shiwu);
for(int y2=10;y2<401;y2=y2+15)
outtextxy(400,y2,shiwu);
/* fillrectangle(10,10,400,20);
bar(10,10,300,20);
fillrectangle(10,10,20,400);
bar(10,10,300,20);
fillrectangle(390,10,400,400);
bar(10,10,300,20);
fillrectangle(10,390,400,400);
bar(10,10,300,20);*/
}
void wenzi()
{
char wz1[] = "游戏得分:";
char wz2[] = "游戏时间:";
outtextxy(450,200,wz1);
outtextxy(450,300,wz2);
}
void youxijiemian() //游戏界面
{
biankuang();
wenzi();
}
/****************************************/
int death_determine()
{
if(snake[0].x==10||snake[0].x==400||snake[0].y==10||snake[0].y==400)
return 0;
for(int i=1;i<length;i++)
{
if(snake[0].x==snake[i].x && snake[0].y==snake[i].y)
{
return 0;
}
}
return 1;
}
void random() //随机食物
{
int a1,b1,a2,b2,rand();
void srand (unsigned int);
srand(time(NULL));
char shiwu[] = "■";
food:a1 = 25+rand()%361;
b1 = (a1-10)%15;
a1 = a1-b1;
a2 = 25+rand()%361;
b2 = (a2-10)%15;
a2 = a2-b2;
for(int i=0;i<length;i++)
{
if(a1==snake[i].x && a2==snake[i].y)
goto food;
}
outtextxy(a1,a2,shiwu);
foodx = a1;
foody = a2;
}
void move_snake()//移动蛇
{
snake[0].x = 205;
snake[0].y = 205;
snake[1].x = 205;
snake[1].y = 220;
char kong[] = " ";
char tou[] = "□";
char wei[] = "■";
outtextxy(snake[0].x,snake[0].y,tou);
outtextxy(snake[1].x,snake[1].y,wei);
char ch;
while(death_determine())
{
if(kbhit())
{
ch=getch();
}
if(ch=='w'||ch=='s'||ch=='a'||ch=='d')
{
tail.x=snake[length-1].x; //存放蛇尾
tail.y=snake[length-1].y;
int k=length-1;
for(k;k>0;k--)
{
outtextxy(snake[k].x,snake[k].y,kong);
}
for(k;k>0;k--)
{
snake[k].x=snake[k-1].x;
snake[k].y=snake[k-1].y;
outtextxy(snake[k].x,snake[k].y,wei);
}
outtextxy(snake[0].x,snake[0].y,tou);
switch(ch)
{
case UP: snake[0].y -= 15;Sleep(200);break;
case DOWN: snake[0].y += 15;Sleep(200);break;
case LEFT: snake[0].x -= 15;Sleep(200);break;
case RIGHT: snake[0].x += 15;Sleep(200);break;
default: break;
}
if(snake[0].x==foodx && snake[0].y==foody)
{
length++;
outtextxy(tail.x,tail.y,wei);
snake[length-1].x=tail.x; //重新定义最后一块
snake[length-1].y=tail.y;
random();
}
}
}
}
void main()
{
initgraph(640,480);
//kaishijiemian();
youxijiemian();
random();
move_snake();
huichekongge();
cleardevice();
} |
|