* 完善贪吃蛇by SOLO Coder

This commit is contained in:
2026-03-16 16:56:23 +08:00
parent 5f11909080
commit a2bbb5e91f
+337 -22
View File
@@ -1,13 +1,22 @@
#pragma once
#include "head.h"
constexpr Size MAP_SIZE = { 16,16 };
constexpr Size MAP_SIZE = { 24,24 };
constexpr Size MAP_NODE_SIZE = { 12,12 };
constexpr float MOVE_SPEED = 0.15f; // 移动速度(秒/步)
enum class MapNodeState {
PASS,
FOOD,
BODY
BODY,
WALL
};
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
};
class MapNode {
@@ -16,6 +25,14 @@ public:
_xy = xy;
}
const PointU& GetNodeXy() const {
return _xy;
}
void SetCoor(Coor* coor) {
_coor = coor;
}
void SetNodeState(MapNodeState s) {
_state = s;
switch (_state)
@@ -25,39 +42,66 @@ public:
break;
case MapNodeState::FOOD:
_spr = g_factory->CreateSpriteDefault(ColorDef::RED);
_spr->SetQuad(createQuad(Position{10.0f,10.0f}, false));
_spr->SetOrder(0.8);
_spr->AddCoor();
_spr->GetCoor()->SetPosition(toPosition(_xy * MAP_NODE_SIZE));
_spr->SetOrder(0.8f);
// 使用共享的Coor
_spr->SetCoor(_coor);
// 设置精灵的大小和位置
Position pos = toPosition(_xy * MAP_NODE_SIZE);
_spr->SetQuad(createQuad(pos, pos + Position{10.0f,10.0f}));
break;
case MapNodeState::BODY:
_spr = g_factory->CreateSpriteDefault(ColorDef::YELLOW);
_spr->SetQuad(createQuad(Position{ 10.0f,10.0f }, false));
_spr->SetOrder(0.8);
_spr->AddCoor();
_spr->GetCoor()->SetPosition(toPosition(_xy * MAP_NODE_SIZE));
_spr->SetOrder(0.8f);
// 使用共享的Coor
_spr->SetCoor(_coor);
// 设置精灵的大小和位置
Position posBody = toPosition(_xy * MAP_NODE_SIZE);
_spr->SetQuad(createQuad(posBody, posBody + Position{10.0f,10.0f}));
break;
case MapNodeState::WALL:
_spr = g_factory->CreateSpriteDefault(ColorDef::GRAY);
_spr->SetOrder(0.8f);
// 使用共享的Coor
_spr->SetCoor(_coor);
// 设置精灵的大小和位置
Position posWall = toPosition(_xy * MAP_NODE_SIZE);
_spr->SetQuad(createQuad(posWall, posWall + Position{10.0f,10.0f}));
break;
default:
break;
}
}
MapNodeState GetNodeState() const {
return _state;
}
void RenderNode() {
if (_spr)
{
_spr->Render();
}
}
private:
MapNodeState _state;
PointU _xy;
Coor* _coor; // 共享的Coor对象
gcSprite _spr;
};
class Map {
public:
Map() {
// 创建一个Coor对象,所有精灵的Coor都指向它
_coor = Coor::Create();
}
~Map() {
delete _coor;
}
void Reset() {
_vec.resize(MAP_SIZE[0] * MAP_SIZE[1]);
for (unsigned j = 0; j< MAP_SIZE[1]; ++j)
@@ -65,12 +109,25 @@ public:
for (unsigned i = 0; i < MAP_SIZE[0]; ++i)
{
unsigned idx = MAP_SIZE[0] * j + i;
_vec[idx].SetNodeState(MapNodeState::PASS);
// 先设置节点的坐标
_vec[idx].SetNodeXy({i,j});
// 设置共享的Coor对象
_vec[idx].SetCoor(_coor);
// 边界设置为墙壁
if (i == 0 || i == MAP_SIZE[0] - 1 || j == 0 || j == MAP_SIZE[1] - 1) {
_vec[idx].SetNodeState(MapNodeState::WALL);
} else {
_vec[idx].SetNodeState(MapNodeState::PASS);
}
}
}
}
void SetOffset(const Position& offset) {
// 只需要更新Coor的位置,所有精灵的位置会自动更新
_coor->SetPosition(offset);
}
void CreateFood(const PointU& xy) {
unsigned idx = MAP_SIZE[0] * xy[1] + xy[0];
if (idx >= _vec.size())
@@ -82,6 +139,21 @@ public:
_vec[idx].SetNodeState(MapNodeState::FOOD);
}
void SetNodeState(const PointU& xy, MapNodeState state) {
unsigned idx = MAP_SIZE[0] * xy[1] + xy[0];
if (idx < _vec.size()) {
_vec[idx].SetNodeState(state);
}
}
MapNodeState GetNodeState(const PointU& xy) const {
unsigned idx = MAP_SIZE[0] * xy[1] + xy[0];
if (idx < _vec.size()) {
return _vec[idx].GetNodeState();
}
return MapNodeState::PASS;
}
void RenderMap() {
for (size_t i = 0; i < _vec.size(); ++i)
{
@@ -91,6 +163,125 @@ public:
private:
std::vector<MapNode> _vec;
Coor* _coor; // 所有精灵共享的Coor
};
class Snake {
public:
Snake() {
// 初始位置
_body.push_back({ 8, 8 });
_body.push_back({ 7, 8 });
_body.push_back({ 6, 8 });
_dir = Direction::RIGHT;
_nextDir = Direction::RIGHT;
_moveTimer = 0.0f;
_grow = false;
}
void SetDirection(Direction dir) {
// 防止180度反向移动
if ((dir == Direction::UP && _dir == Direction::DOWN) ||
(dir == Direction::DOWN && _dir == Direction::UP) ||
(dir == Direction::LEFT && _dir == Direction::RIGHT) ||
(dir == Direction::RIGHT && _dir == Direction::LEFT)) {
return;
}
_nextDir = dir;
}
bool Update(float deltaTime, Map& map, int& score) {
_moveTimer += deltaTime;
if (_moveTimer < MOVE_SPEED) {
return true;
}
_moveTimer = 0.0f;
// 更新方向
_dir = _nextDir;
// 计算新头部位置
PointU head = _body.front();
switch (_dir) {
case Direction::UP:
head.y--;
break;
case Direction::DOWN:
head.y++;
break;
case Direction::LEFT:
head.x--;
break;
case Direction::RIGHT:
head.x++;
break;
}
// 边界检查
if (head.x >= MAP_SIZE[0] || head.y >= MAP_SIZE[1] || head.x < 0 || head.y < 0) {
return false; // 碰撞边界,游戏结束
}
// 墙壁碰撞检查
if (map.GetNodeState(head) == MapNodeState::WALL) {
return false; // 碰撞墙壁,游戏结束
}
// 自身碰撞检查
for (const auto& bodyPart : _body) {
if (bodyPart == head) {
return false; // 碰撞自身,游戏结束
}
}
// 检查是否吃到食物
if (map.GetNodeState(head) == MapNodeState::FOOD) {
_grow = true;
score += 10; // 增加分数
// 创建新食物
PointU foodPos;
do {
foodPos = {
Random::Uint(1, MAP_SIZE[0] - 2),
Random::Uint(1, MAP_SIZE[1] - 2)
};
} while (map.GetNodeState(foodPos) != MapNodeState::PASS);
map.CreateFood(foodPos);
} else {
// 移除尾部
if (!_grow) {
PointU tail = _body.back();
map.SetNodeState(tail, MapNodeState::PASS);
_body.pop_back();
} else {
_grow = false;
}
}
// 添加新头部
_body.insert(_body.begin(), head);
map.SetNodeState(head, MapNodeState::BODY);
return true;
}
void Render() {
// 渲染蛇身
for (const auto& bodyPart : _body) {
// 蛇身已经通过Map渲染,这里可以添加特殊效果
}
}
const std::vector<PointU>& GetBody() const {
return _body;
}
private:
std::vector<PointU> _body;
Direction _dir;
Direction _nextDir;
float _moveTimer;
bool _grow;
};
class Game{
@@ -98,32 +289,156 @@ class Game{
public:
Game() {
Random::SetSeed(0);
_sprBg = g_factory->CreateSpriteDefault(ColorDef::GREEN);
_sprBg = g_factory->CreateSpriteDefault(createColor(0x2c3e50ff)); // 深蓝色背景
_txtFps = g_factory->CreateTextDefault();
_txtScore = g_factory->CreateTextDefault();
_txtScore->SetFontSize(24);
_txtScore->SetString("Score: 0");
_txtControl = g_factory->CreateTextDefault();
_txtControl->SetFontSize(16);
_txtControl->SetString("WASD/方向键控制,R开始游戏");
_txtStart = g_factory->CreateTextDefault();
_txtStart->SetFontSize(36);
_txtStart->SetString("按R开始游戏");
_map.Reset();
_map.CreateFood({
Random::Uint(0, MAP_SIZE[0] - 1) ,
Random::Uint(0, MAP_SIZE[1] - 1)
});
_score = 0;
_gameOver = false;
_gameStarted = false;
}
void ResetGame() {
_map.Reset();
_snake = Snake();
_score = 0;
_txtScore->SetString("Score: 0");
// 初始化蛇身
for (const auto& bodyPart : _snake.GetBody()) {
_map.SetNodeState(bodyPart, MapNodeState::BODY);
}
// 创建初始食物
PointU foodPos;
do {
foodPos = {
Random::Uint(1, MAP_SIZE[0] - 2),
Random::Uint(1, MAP_SIZE[1] - 2)
};
} while (_map.GetNodeState(foodPos) != MapNodeState::PASS);
_map.CreateFood(foodPos);
_gameOver = false;
_gameStarted = true;
}
void Update() {
_sprBg->SetQuad(createQuad(g_system->GetWindowSize(), false));
_sprBg->SetOrder(0.9);
_sprBg->SetOrder(0.9f);
_sprBg->Render();
_txtFps->SetString(std::to_string(g_time->GetFPS()));
_txtFps->GetCoor()->SetPosition({ 200, 200 });
_txtFps->SetOrder(0.5);
// 计算地图偏移量,使地图居中显示
Size mapSize = MAP_SIZE * MAP_NODE_SIZE;
Size windowSize = g_system->GetWindowSize();
Position offset;
offset[0] = (windowSize[0] - mapSize[0]) / 2.0f;
offset[1] = (windowSize[1] - mapSize[1]) / 2.0f;
_map.SetOffset(offset);
_txtFps->SetString("FPS: " + std::to_string(g_time->GetFPS()));
_txtFps->GetCoor()->SetPosition({ 10, 10 });
_txtFps->SetOrder(0.5f);
_txtFps->Render();
_map.RenderMap();
// 放置Score到围墙左上角上方
_txtScore->SetString("Score: " + std::to_string(_score));
_txtScore->GetCoor()->SetPosition({ offset[0], offset[1] - 30.0f });
_txtScore->SetOrder(0.5f);
_txtScore->Render();
// 放置操作提示文本到围墙左下角
_txtControl->GetCoor()->SetPosition({ offset[0], offset[1] + mapSize[1] + 10.0f });
_txtControl->SetOrder(0.5f);
_txtControl->Render();
// 处理输入
HandleInput();
// 检查是否开始游戏
if (!_gameStarted) {
// 显示开始游戏提示
_txtStart->GetCoor()->SetPosition({ (windowSize[0] - 200.0f) / 2.0f, (windowSize[1] - 40.0f) / 2.0f });
_txtStart->SetOrder(0.4f);
_txtStart->Render();
if (g_input->KeyDown(KeyCode::R)) {
ResetGame();
}
} else {
// 更新游戏逻辑
if (!_gameOver) {
if (!_snake.Update(g_time->GetDelta(), _map, _score)) {
_gameOver = true;
// 显示游戏结束信息
_txtGameOver = g_factory->CreateTextDefault();
_txtGameOver->SetFontSize(36);
_txtGameOver->SetString("Game Over!");
_txtGameOver->SetOrder(0.4f);
_txtRestart = g_factory->CreateTextDefault();
_txtRestart->SetFontSize(24);
_txtRestart->SetString("Press R to restart");
_txtRestart->SetOrder(0.4f);
}
} else {
if (_txtGameOver) {
// 每次渲染时重新计算位置,确保在屏幕中间
_txtGameOver->GetCoor()->SetPosition({ (windowSize[0] - 150.0f) / 2.0f, (windowSize[1] - 40.0f) / 2.0f });
_txtGameOver->Render();
}
if (_txtRestart) {
// 每次渲染时重新计算位置,确保在屏幕中间
_txtRestart->GetCoor()->SetPosition({ (windowSize[0] - 180.0f) / 2.0f, (windowSize[1] + 20.0f) / 2.0f });
_txtRestart->Render();
}
if (g_input->KeyDown(KeyCode::R)) {
ResetGame();
// gcText是智能指针,不需要手动释放
// 只需要重置游戏状态,下次游戏结束时会重新创建
}
}
_map.RenderMap();
_snake.Render();
}
}
private:
void HandleInput() {
if (g_input->KeyDown(KeyCode::W) || g_input->KeyDown(KeyCode::UP)) {
_snake.SetDirection(Direction::UP);
} else if (g_input->KeyDown(KeyCode::S) || g_input->KeyDown(KeyCode::DOWN)) {
_snake.SetDirection(Direction::DOWN);
} else if (g_input->KeyDown(KeyCode::A) || g_input->KeyDown(KeyCode::LEFT)) {
_snake.SetDirection(Direction::LEFT);
} else if (g_input->KeyDown(KeyCode::D) || g_input->KeyDown(KeyCode::RIGHT)) {
_snake.SetDirection(Direction::RIGHT);
}
}
gcSprite _sprBg;
gcText _txtFps;
gcText _txtScore;
gcText _txtGameOver;
gcText _txtRestart;
gcText _txtControl;
gcText _txtStart;
Map _map;
Snake _snake;
int _score;
bool _gameOver;
bool _gameStarted;
};