用了几天业余时间,写了个C语言的小游戏,贪吃蛇,用到了easyx库
运行效果图:
/
// 程序名称:贪吃蛇
// 编译环境 Visual Studio2019,EasyX
// 作者:千剑堂主<82497232@qq.com> <QQ:82497232>
// 最后修改:2020-9-12
#include <conio.h>
//#include <easyx.h>
#include<graphics.h>
#include <time.h>
#define W_LENGTH 1200
#define W_WIDTH 800
#define SNAKEWIDTH 20
#define SNAKESIZE 10
#define FOODSIZE 20
#define LEVELSPEED 10
#define SLEEPTIME 120
int s_direction;//蛇前进的方向
int button = 0;
int current_score;//当前分数
int highest_score;//最高分
void GameStart();
void GameProcess();
void GameOver();
int initsnake();
void addbody();
void drawsnake();
void drawfood();
void drawscore();
void movesnake();
void getkey();
void select();
void initfood(int);
int collidetest();
struct point
{
int x;
int y;
};
struct block
{
struct point top;
struct point bottom;
};
// 蛇的属性
struct Snake
{
struct block body;
COLORREF color;
struct Snake* next;
} snake;
// 食物的属性
struct Food
{
struct point position; // 坐标
int grade; // 分数
IMAGE img; // 食物图案
} food;
enum LEVEL
{
level1,
level2,
level3,
level4,
level5
};// 难度
enum position
{
up,
down,
left,
right,
other
}; // 蛇的方向
enum iscollide
{
dead,
eatfood,
none
};
int main()
{
initgraph(W_LENGTH, W_WIDTH);
GameStart();
_getch();
GameProcess();
}
void GameStart()//显示游戏开始画面
{
IMAGE img,imgbutton;
loadimage(&img, _T("rc\\start.png"), W_LENGTH, W_WIDTH, false);
loadimage(&imgbutton, _T("rc\\startbutton.png"), 200, 80, false);
putimage(0, 0, &img);
putimage((W_LENGTH - 110)/2, W_WIDTH / 2 + 100, 200, 80, &imgbutton, 0,0, SRCCOPY);
highest_score = current_score = 0;
}
void GameProcess()//游戏处理过程
{
int cr = none; //碰撞状态,初始为没有事
int c_level = level1; //初始化游戏难度
int sleeptime = SLEEPTIME; //蛇前进的速度
int mod = 0;
IMAGE imgs,imgd;
button = current_score = 0;
srand((unsigned)time(NULL));
s_direction = initsnake(); //初始化蛇,和蛇初始运动方向
initfood(level1); //初始化第一个食物
BeginBatchDraw();
cleardevice();
loadimage(&imgs, _T("rc\\bg.jpg"), W_LENGTH, W_WIDTH, false);//显示背景图案
imgd = imgs; //因为绘图的原因,备份绘图的背景图案,防止闪烁,留影
putimage(0, 0, &imgd);
FlushBatchDraw();
SetWorkingImage(&imgd);
drawsnake(); //画蛇
drawfood(); //画食物
SetWorkingImage();
putimage(0, 0, &imgd);
while (cr != dead)
{
Sleep(sleeptime); //暂停一下,开始绘图
if (_kbhit()) //无阻塞检测键盘输入状态
getkey(); //检测键盘输入键是否为方向键
cr = collidetest(); //碰撞检测,根据键盘输入的方向键检测下一步前进方向事件
switch (cr)
{
case dead: //撞到墙或自身
cr = dead;
break;
case eatfood: //吃到食物
current_score += food.grade; //累加计分
if (current_score > 50) //根据当前累加分数区分游戏难度
{
c_level = level2;
sleeptime -= c_level * 10;
}
else if (current_score > 1000)
{
c_level = level3;
sleeptime -= c_level * 10;
}
else if (current_score > 2500)
{
c_level = level4;
sleeptime -= c_level * 2;
}
else if