贪吃蛇C语言游戏代码
//开始编写游戏需要的类
#include //EasyX_惊蛰版(绘图库)
#include
#include
#include
#define UP1
#define DOWN2
#define LEFT3
#define RIGHT4
//格子类,定义一个格子的属性及行为
class Cell
{
public:
friend class GameArea; //设置友元函数
void setxy(short x, short y) //设置格子左上角坐标
{
m_x = x, m_y = y;
}
void setfull(short full) //设置格子属性,0为空,1为障碍,2为食物
{
m_full = full;
}
void display(COLORREF color) //设置格子颜色并显示
{
m_color = color;
setfillstyle(m_color);
bar(m_x, m_y, m_x+7, m_y+7);
}
void LaserDisplay() //显示镭射状态的格子
{
IMAGE image(10,10);
SetWorkingImage(&image);
DWORD* pMem = GetImageBuffer(&image);
for(int i = 0; i < 10 * 10; i++)
pMem[i] = BGR(RGB(0, 0, i * 256 / (10*10) ));
SetWorkingImage(NULL);
putimage(m_x,m_y,&image);
}
short ReturnFull() //返回格子状态
{
return m_full;
}
Cell() //构造函数
{
m_x = 0,m_y = 0,m_full = 0;
m_color = BLACK;
}
private:
short m_x;//格子的左上角X坐标
short m_y;//格子的左上角Y坐标
short m_full;//0为空,1为阻挡,2为食物
COLORREF m_color;//格子颜色
};
//游戏区类,编写有关游戏区的一些操作
class GameArea //游戏区域
{
public:
Cell m_game[60][60];//定义游戏区域(由360个格子组成)
friend void MessageDispose();//设置友元函数
bool CreatFood()//产生随机食物
{
srand(time(NULL));//初始化随机数种子
m_random1 = rand()%58+1;//随机生成一个0 - 58的整数
m_random2 = rand()%58+1;//随机一个0 - 58的整数
if(m_game[m_random2][m_random2].m_full == 0)//检查生成的食物坐标是否在障碍上
{
m_game[m_random1][m_random2].display(GREEN);
m_game[m_random1][m_random2].m_full = 2;
return true;
}
//如果随机的食物正好出现在蛇身上,则进入下面的循环寻找可以生成食物的地方
for(m_random1 = 1;m_random1 < 59;m_random1++)
{
for(m_random2 = 1;m_random2 < 59;m_random2++)
{
if(m_game[m_random2][m_random2].m_full == 0)
{
m_game[m_random1][m_rand