死宅番外——贪吃蛇

这两天码了个贪吃蛇我没用链表其实用链表效率应该更高一点。放代码了:
#include “pch.h”
#include<conio.h>
#include
#include<graphics.h>//要easyx
#include<time.h>
#include<Windows.h>
#include<mmsystem.h>//放音乐的
#pragma comment(lib,“winmm.lib”)//放音乐的
//using namespace std;
struct xx //蛇节点的坐标
{
int x, y;
};
struct snake
{
int n;//length
char d;//direction
xx p[490000];//position
}s;
int x2, y2;
void food()
{
srand((unsigned int)time(0));//生成一个随机种子 time0 :自1970-01-01 00:00:00 UTC)起经过的秒数
bool flag = false;
int i;
while (!flag)
{
x2 = (rand() % 978) / 10 * 10;
y2 = (rand() % 678) / 10 * 10;//在这个函数中进行了复杂的计算所以是伪随机数
for (i = 1; i <= s.n; i++)
if ((x2 + 10) / 2 == s.p[i].x && (y2 + 10) / 2 == s.p[i].y)break;
if (i == s.n + 1)flag = true;
}
}
void ns()//initial
{
s.d = ‘r’;
int l = 7;//蛇节点圆心的距离
s.n = 4;
for (int i = 1; i <= s.n; i++)
{
s.p[i].y = 350;
s.p[i].x = 300 - (l * 2 * (i - 1));
}
}
void draw()//把蛇画出来
{
cleardevice();//清屏
int r = 10;
for (int i = 1; i <= s.n; i++)
fillcircle(s.p[i].x, s.p[i].y, r);//画实心圆 圆心 半径
fillcircle(x2, y2,r/2);//画食物因为清屏清的整个屏幕
}
void move()//蛇的移动
{
if ((x2s.p[1].x )&& (y2 s.p[1].y)) { ++s.n; food(); }
//printf("%d %d ", x2, y2);
int dx = 0, dy = 0;
switch (s.d)
{
case ‘r’:
{
dx = 1;
break;
}
case ‘l’:
{
dx = -1;
break;
}
case ‘u’:
{
dy = -1;
break;
}
case ‘d’:
{
dy = 1;
break;
}
default:break;
}
for (int i = s.n; i > 1; i–)
{
s.p[i].x = s.p[i - 1].x;
s.p[i].y = s.p[i - 1].y;
}
s.p[1].x += (dx * 10);
s.p[1].y += (dy * 10);
if (s.p[1].x > 990) s.p[1].x = 10;
if (s.p[1].x < 10) s.p[1].x = 990;
if (s.p[1].y > 690) s.p[1].y = 10;
if (s.p[1].y < 10) s.p[1]. y= 690;
Sleep(100);//延迟100毫秒 或者说更新速度每100毫秒更新一次
}
void changedirection()//改变方向
{
char ch;
ch = getch();//需要conio.h 输入字符不需要enter
switch (ch)
{
case’w’:
if (s.d != ‘d’)s.d = ‘u’;
break;
case’s’:
if (s.d != ‘u’)s.d = ‘d’;
break;
case’d’:
if (s.d != ‘l’)s.d = ‘r’;
break;
case’a’:
if (s.d != ‘r’)s.d = ‘l’;
break;
default:break;
}
}
int main()
{
ns();
initgraph(1000, 700);//SHOWCONSOLE可以出来一个控制台来检测数据
food();
mciSendString(“open 1\1.mp3”, NULL, NULL, NULL);//要多字节字符集
mciSendString(“play 1\1.mp3”, NULL, NULL, NULL);
while (1)
{
while (1)
{
draw();
move();
if (kbhit())break;//是否按键盘了
}
changedirection();
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36323837/article/details/83042306