200行代码写一个简易的C++小黑窗贪吃蛇游戏
发布人:shili8
发布时间:2025-02-01 06:28
阅读次数:0
**贪吃蛇游戏实现**
=====================### **游戏规则**
* 游戏背景是一个简单的黑白窗口,玩家控制一个方向向上的蛇。
* 蛇可以移动、吃食物并增长长度。
* 当蛇撞到墙壁或自身时,游戏结束。
### **代码实现**
#### **头文件和类定义**
cpp// snake_game.h#ifndef SNAKE_GAME_H#define SNAKE_GAME_H#include <iostream>
#include <vector>
class SnakeGame {
public:
SnakeGame();
~SnakeGame();
void run();
private:
int width_;
int height_;
std::vector<std::pair<int, int>> snake_;
std::pair<int, int> food_;
};
#endif // SNAKE_GAME_H#### **类实现**
cpp// snake_game.cpp#include "snake_game.h"
SnakeGame::SnakeGame() : width_(20), height_(10) {
// 初始化游戏窗口大小}
SnakeGame::~SnakeGame() {}
void SnakeGame::run() {
// 游戏主循环 while (true) {
// 清屏 std::cout << "033[2J033[H";
// 绘制蛇和食物 for (int i =0; i < height_; ++i) {
for (int j =0; j < width_; ++j) {
bool isSnake = false;
for (auto& pos : snake_) {
if (pos.first == j && pos.second == i) {
std::cout << "*";
isSnake = true;
break;
}
}
if (!isSnake) {
if (food_.first == j && food_.second == i) {
std::cout << "F";
} else {
std::cout << " ";
}
}
}
std::cout << "
";
}
// 获取用户输入 int dir =0;
std::cin >> dir;
// 更新蛇位置 switch (dir) {
case1: // 上 snake_.push_back({snake_[snake_.size() -1].first, snake_[snake_.size() -1].second -1});
break;
case2: // 右 snake_.push_back({snake_[snake_.size() -1].first +1, snake_[snake_.size() -1].second});
break;
case3: // 下 snake_.push_back({snake_[snake_.size() -1].first, snake_[snake_.size() -1].second +1});
break;
case4: // 左 snake_.push_back({snake_[snake_.size() -1].first -1, snake_[snake_.size() -1].second});
break;
}
// 判断是否吃到食物 if (snake_[snake_.size() -1] == food_) {
// 吃到食物,生成新食物 food_ = {rand() % width_, rand() % height_};
} else {
// 不吃到食物,移除蛇尾部 snake_.erase(snake_.begin());
}
// 判断是否撞墙或自身 if (snake_[snake_.size() -1].first < 0 || snake_[snake_.size() -1].first >= width_ ||
snake_[snake_.size() -1].second < 0 || snake_[snake_.size() -1].second >= height_) {
// 撞墙,游戏结束 std::cout << "Game Over!
";
return;
}
for (int i = snake_.size() -2; i >=0; --i) {
if (snake_[i] == snake_[snake_.size() -1]) {
// 撞自身,游戏结束 std::cout << "Game Over!
";
return;
}
}
// 等待下一帧 std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
#### **main函数**
cpp// main.cpp#include "snake_game.h"
int main() {
SnakeGame game;
game.run();
return0;
}
### **游戏运行**
1. 编译代码:`g++ -std=c++11 snake_game.cpp main.cpp -o snake_game`
2. 运行游戏:`./snake_game`
### **注意事项**
* 游戏窗口大小可以通过修改 `width_` 和 `height_` 变量来调整。
* 食物的生成位置是随机的,可以通过修改 `food_` 变量来改变。
* 当蛇撞到墙壁或自身时,游戏会自动结束。
### **贡献**
感谢您阅读本文档!如果您有任何问题或建议,请在下面的评论区留言。

