代码:
#include <iostream>
#include <conio.h>
#include <vector>
#include <windows.h>
#include <ctime>
using namespace std;
//设置范围
const int WIDTH = 20;
const int HEIGHT = 20;
const char EMPTY = ' ';
const char SNAKE = 'O';
const char FOOD = '*';
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
struct Position {
int x, y;
};
class SnakeGame {
public:
vector<Position> snake;
Position food;
Direction dir;
bool gameOver;
void SetupFood() {
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
// 确保食物不在蛇身上
for (const auto& pos : snake) {
if (pos.x == food.x && pos.y == food.y) {
SetupFood(); // 递归确保食物位置有效
break;
}
}
}
bool IsCollision(Position head) {
// 检查撞墙
if (head.x >= WIDTH || head.x < 0 || head.y >= HEIGHT || head.y < 0)
return true;
// 检查撞自己
for (size_t i = 1; i < snake.size(); i++) {
if (snake[i].x == head.x && snake[i].y == head.y)
return true;
}
return false;
}
public:
SnakeGame() : dir(STOP), gameOver(false) {
snake.push_back({WIDTH / 2, HEIGHT / 2}); // 初始化蛇头位置
SetupFood(); // 初始化食物位置
}
void ChangeDirection(Direction newDir) {
// 禁止反向移动
if ((dir == LEFT && newDir == RIGHT) || (dir == RIGHT && newDir == LEFT) ||
(dir == UP && newDir == DOWN) || (dir == DOWN && newDir == UP))
return;
dir = newDir;
}
void Move() {
Position head = snake[0];
Position newHead;
switch (dir) {
case LEFT: newHead = {head.x - 1, head.y}; break;
case RIGHT: newHead = {head.x + 1, head.y}; break;
case UP: newHead = {head.x, head.y - 1}; break;
case DOWN: newHead = {head.x, head.y + 1}; break;
default: return;
}
if (IsCollision(newHead)) {
gameOver = true;
return;
}
// 吃食物
if (newHead.x == food.x && newHead.y == food.y) {
SetupFood(); // 生成新食物
} else {
// 移动蛇身,去掉尾部
//snake.erase(snake.begin());
snake.pop_back();
}
// 添加新的头部
snake.insert(snake.begin(), newHead);
//snake.push_back(newHead);
}
void Draw() {
system("cls"); // 清屏
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
bool isSnake = false;
for (const auto& pos : snake) {
if (pos.x == j && pos.y == i) {
cout << SNAKE;
isSnake = true;
break;
}
}
if (!isSnake) {
if (i == food.y && j == food.x)
cout << FOOD;
else
cout << EMPTY;
}
// 每打印完一个字符后,如果不是最后一个字符,则打印空格
if (j < WIDTH - 1)
cout << " ";
}
cout << endl; // 每打印完一行后换行
}
}
};
int main() {
srand(time(0)); // 初始化随机数生成器
SnakeGame game;
while (!game.gameOver) {
if (_kbhit()) { // 检查是否有键盘输入
switch (_getch()) {
case 'A': game.ChangeDirection(LEFT); break;
case 'D': game.ChangeDirection(RIGHT); break;
case 'W': game.ChangeDirection(UP); break;
case 'S': game.ChangeDirection(DOWN); break;
}
}
game.Move(); // 移动蛇
game.Draw(); // 绘制游戏界面
Sleep(200); // 等待一段时间,减少CPU占用并"控制游戏速度"
}
cout << "Game Over!" << endl;
return 0;
}