#include <iostream>
#include <vector>
#include <conio.h> // 用于_getch()
#include <windows.h> // 用于Sleep()
#include <cstdlib> // 用于rand()和srand()
#include <ctime> // 用于time()
// 游戏区域大小
const int WIDTH = 20;
const int HEIGHT = 20;
// 方向枚举
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
// 蛇的节点结构
struct Point {
int x, y;
Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
};
// 游戏类
class SnakeGame {
private:
bool gameOver;
Point food;
std::vector<Point> snake;
Direction dir;
int score;
// 生成随机食物位置
void generateFood() {
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
// 确保食物不会生成在蛇身上
for (size_t i = 0; i < snake.size(); ++i) {
if (food.x == snake[i].x && food.y == snake[i].y) {
generateFood();
return;
}
}
}
public:
SnakeGame() : gameOver(false), dir(STOP), score(0) {
// 初始化蛇身,长度为3
snake.push_back(Point(WIDTH/2, HEIGHT/2));
snake.push_back(Point(WIDTH/2+1, HEIGHT/2));
snake.push_back(Point(WIDTH/2+2, HEIGHT/2));
generateFood();
}
// 绘制游戏界面
void draw() {
system("cls"); // 清屏
// 绘制上边界
for (int i = 0; i < WIDTH+2; ++i)
std::cout << "#";
std::cout << std::endl;
for (int y = 0; y < HEIGHT; ++y) {
for (int x = 0; x < WIDTH; ++x) {
// 绘制左边界
if (x == 0) std::cout << "#";
// 绘制蛇头
if (x == snake[0].x && y == snake[0].y)
std::cout << "O";
// 绘制蛇身
else {
bool isBody = false;
for (size_t i = 1; i < snake.size(); ++i) {
if (x == snake[i].x && y == snake[i].y) {
std::cout << "o";
isBody = true;
break;
}
}
// 绘制食物
if (!isBody) {
if (x == food.x && y == food.y)
std::cout << "F";
else
std::cout << " ";
}
}
// 绘制右边界
if (x == WIDTH-1) std::cout << "#";
}
std::cout << std::endl;
}
// 绘制下边界
for (int i = 0; i < WIDTH+2; ++i)
std::cout << "#";
std::cout << std::endl;
std::cout << "Score: " << score << std::endl;
}
// 处理输入
void input() {
if (_kbhit()) {
switch (_getch()) {
case 'a': dir = LEFT; break;
case 'd': dir = RIGHT; break;
case 'w': dir = UP; break;
case 's': dir = DOWN; break;
case 'x': gameOver = true; break;
}
}
}
// 更新游戏逻辑
void logic() {
// 保存蛇尾位置
Point prev = snake.back();
Point prev2;
// 移动蛇身
for (size_t i = snake.size()-1; i > 0; --i) {
snake[i] = snake[i-1];
}
// 移动蛇头
switch (dir) {
case LEFT: snake[0].x--; break;
case RIGHT: snake[0].x++; break;
case UP: snake[0].y--; break;
case DOWN: snake[0].y++; break;
default: break;
}
// 检查是否吃到食物
if (snake[0].x == food.x && snake[0].y == food.y) {
score += 10;
// 蛇身增长
snake.push_back(prev);
generateFood();
}
// 检查撞墙
if (snake[0].x >= WIDTH || snake[0].x < 0 || snake[0].y >= HEIGHT || snake[0].y < 0)
gameOver = true;
// 检查撞到自己
for (size_t i = 1; i < snake.size(); ++i) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y)
gameOver = true;
}
}
bool isGameOver() const { return gameOver; }
};
int main() {
// 设置随机种子
srand(static_cast<unsigned>(time(0)));
SnakeGame game;
while (!game.isGameOver()) {
game.draw();
game.input();
game.logic();
Sleep(100); // 控制游戏速度
}
std::cout << "Game Over! Final Score: " << std::endl;
system("pause");
return 0;
}