#include<iostream>
#include<easyx.h>
#include<vector>
#include<conio.h>
#include<ctime>
using namespace std;
/*精灵类*/
class Sprite
{
public:
Sprite() { };
Sprite(int x, int y) :m_x(x), m_y(y), m_color(BLUE) { };
virtual void draw() //绘制精灵
{
setfillcolor(m_color); //设置填充颜色
fillrectangle(m_x, m_y, m_x + 10, m_y + 10); //绘制矩形
}
void moveBy(int dx, int dy) //移动
{
m_x += dx;
m_y += dy;
//if(m_x = 0)
}
//碰撞检测
bool collosion(const Sprite& other)
{
return m_x == other.m_x && m_y == other.m_y;
}
protected:
int m_x;
int m_y;
COLORREF m_color;
};
/*蛇类*/
class Snake : public Sprite
{
public:
Snake() :Snake(0,0)
{ }
Snake(int x, int y) :Sprite(x, y), dir(VK_RIGHT)
{
nodes.push_back(Sprite(30, 0));
nodes.push_back(Sprite(20, 0));
nodes.push_back(Sprite(10, 0));
} //初始化三节蛇
void draw()override
{
for (int i = 0; i < nodes.size(); i++)
{
nodes[i].draw();
}
}
//蛇的身体移动
void bodyMove()
{
for (size_t i = nodes.size() - 1; i > 0; i--) //身体跟着蛇头移动
{
nodes[i] = nodes[i - 1];
}
//移动蛇头
switch (dir)
{
case VK_UP:
nodes[0].moveBy(0, -10);
break;
case VK_DOWN:
nodes[0].moveBy(0, 10);
break;
case VK_LEFT:
nodes[0].moveBy(-10, 0);
break;
case VK_RIGHT:
nodes[0].moveBy(10, 0);
break;
}
}
bool collision(const Sprite& other)
{
return nodes[0].collosion(other);
}
//蛇增加一节
void incrment()
{
nodes.push_back(Sprite());
}
private:
vector<Sprite> nodes; //蛇的所有节点
public:
int dir; //蛇的方向
};
/*食物类*/
class Food :public Sprite
{
public:
Food() :Sprite(0, 0)
{
changePos();
}
void draw()override
{
setfillcolor(RED);
solidellipse(m_x, m_y, m_x + 10, m_y + 10);
}
//改变食物的坐标
void changePos()
{
m_x = rand() % 64 * 10;
m_y = rand() % 48 * 10;
}
};
/*游戏场景*/
class GameScence
{
public:
GameScence()
{
};
void run()
{
BeginBatchDraw(); //双缓冲绘图
cleardevice();
snake.draw();
food.draw();
EndBatchDraw();
snake.bodyMove(); //移动蛇,改变蛇的坐标
snakeEatFood();
//获取信息
ExMessage msg = { 0 };
while (peekmessage(&msg, EX_KEY))
{
onMsg(msg);
}
}
//响应消息:鼠标信息 键盘信息
void onMsg(const ExMessage& msg)
{
if (msg.message == WM_KEYDOWN)
{
switch (msg.vkcode)
{
case VK_UP:
if (snake.dir != VK_DOWN)
snake.dir = msg.vkcode;
break;
case VK_DOWN:
if (snake.dir != VK_UP)
snake.dir = msg.vkcode;
break;
case VK_LEFT:
if (snake.dir != VK_RIGHT)
snake.dir = msg.vkcode;
break;
case VK_RIGHT:
if (snake.dir != VK_LEFT)
snake.dir = msg.vkcode;
break;
}
}
}
//判断蛇能否吃到食物
void snakeEatFood()
{
if (snake.collision(food)) //如果蛇和食物产生了碰撞
{
//蛇的节数增加
snake.incrment();
//食物重新产生在其他位置
food.changePos();
}
}
private:
Snake snake;
Food food;
};
int main()
{
initgraph(640, 480, EX_SHOWCONSOLE); //创建一个图形窗口
srand(time(nullptr)); //设置随机数种子
GameScence scence;
while (true)
{
scence.run();
Sleep(100);
}
getchar(); //防止闪退
return 0;
}
【贪吃蛇模板】怎么让蛇从左边出去了但是又从右边回来呢?
最新推荐文章于 2024-11-15 16:06:58 发布