Easyx用c语言制作的贪吃蛇无法吃食物
用的Vs2022和最新版的easyx
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
#define weith 900
#define heigth 640
#define MAX 500
enum keys
{
DOWN,
UP,
LEFT,
RIGHT,
};
struct snake
{
int speek;//蛇的速度
int dar;//蛇的方向
int num;//蛇的长度
POINT snake[MAX];
}a;
struct Food
{
int size;//颜色
int color;//颜色
int x;//坐标
int y;
bool flag;//判断食物是否被吃掉
}food;
//初始化
void start() {
srand(GetTickCount());
initgraph(weith, heigth);
a.num = 3;
a.speek = 10;
a.dar = RIGHT;
//初始化蛇的坐标
for (int i = 0; i < a.num; i++) {
a.snake[i].x = (10 + 10 * a.num)-10 * i;
a.snake[i].y = 10;
}
food.x = rand() % (weith / 10) * 10;
food.y = rand() % (heigth / 10) * 10;
food.size = rand() % 8 + 8;
food.color = rand() % 256;
food.flag = 1;
}
void set_color() {
BeginBatchDraw();
setbkcolor(BLUE);
cleardevice();
setfillcolor(YELLOW);
for (int i = 0; i < a.num; i++) {
solidcircle(a.snake[i].x, a.snake[i].y, 5);//绘制蛇
}
if (food.flag == 1) {//蛇头的坐标是否与食物的坐标重叠
solidcircle(food.x, food.y, food.size);//绘制食物
}
EndBatchDraw();//双缓冲
}
void Set_key() {
if (_kbhit()) {//获取键盘的信息
switch (_getch())
{
case 'W':
case 'w':
case 72:
if (a.dar != DOWN) {//使蛇不能瞬间向相反的方向运动
a.dar = UP;
}
break;
case 'S':
case 's':
case 80:
if (a.dar != UP) {
a.dar = DOWN;
}
break;
case 'A':
case 'a':
case 75:
if (a.dar != RIGHT) {
a.dar = LEFT;
}
break;
case 'D':
case 'd':
case 77:
if (a.dar != LEFT) {
a.dar = RIGHT;
}
break;
}
}
}
void Move_Circle() {
for (int i = a.num - 1; i > 0; i--) {//让蛇的身体能够跟随蛇头运动
a.snake[i].x = a.snake[i - 1].x;
a.snake[i].y = a.snake[i - 1].y;
}
switch (a.dar) {
case UP:
a.snake[0].y -= a.speek;//让蛇头向键盘输入的方向运动
break;
case DOWN:
a.snake[0].y += a.speek;
break;
case LEFT:
a.snake[0].x -= a.speek;
break;
case RIGHT:
a.snake[0].x += a.speek;
break;
}
}
void Eat_FOOD() {//判断蛇头的位置是否与食物相撞
if (a.snake[0].x >= (food.x - food.size) && a.snake[0].x <= (food.x + food.size) &&
a.snake[0].y >= (food.y + food.size) && a.snake[0].y <= (food.y - food.size)) {
food.flag = 0;//让这个食物消失
a.num++;//增加蛇的长度
}
}
int main() {
start();
while (1) {
set_color();
Set_key();
Move_Circle();
Eat_FOOD();
Sleep(50);
}
system("pause");
return 0;
}