当然可以!下面是一个简单的命令行版贪吃蛇游戏的C++实现。它使用了标准库和一些基本的控制台操作,适合在Windows和类Unix系统的终端中运行。
代码说明
- 使用
<conio.h>的_kbhit()和_getch()实现非阻塞键盘输入(Windows)。
- 使用简单的二维数组表示地图。
- 蛇用一个
std::deque存储身体坐标。
- 食物随机生成。
- 游戏通过不断刷新控制台实现动画效果。
代码示例
#include <iostream>
#include <conio.h> // Windows下非阻塞输入
#include <windows.h> // Sleep函数
#include <deque>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 15;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
struct Point {
int x, y;
bool operator==(const Point& p) const {
return x == p.x && y == p.y;
}
};
class SnakeGame {
private:
bool gameOver;
Direction dir;
Point food;
deque<Point> snake; // 蛇身体,头在末尾
int score;
public:
SnakeGame() {
gameOver = false;
dir = STOP;
score = 0;
// 初始化蛇在中间
snake.push_back({WIDTH / 2, HEIGHT / 2});
placeFood();
}
void placeFood() {
while (true) {
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
bool onSnake = false;
for (auto& s : snake) {
if (s == food) {
onSnake = true;
break;
}
}
if (!onSnake) break;
}
}
void draw() {
system("cls"); // Windows清屏,Linux用 system("clear");
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << "\n";
for (int y = 0; y < HEIGHT; y++) {
cout << "#";
for (int x = 0; x < WIDTH; x++) {
Point pt = {x, y};
if (pt == snake.back()) cout << "O"; // 蛇头
else if (pt == food) cout << "F"; // 食物
else {
bool printed = false;
for (auto it = snake.begin(); it != snake.end() - 1; ++it) {
if (*it == pt) {
cout << "o"; // 蛇身
printed = true;
break;
}
}
if (!printed) cout << " ";
}
}
cout << "#\n";
}
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << "\nScore: " << score << "\n";
}
void input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
case 'A':
if (dir != RIGHT) dir = LEFT;
break;
case 'd':
case 'D':
if (dir != LEFT) dir = RIGHT;
break;
case 'w':
case 'W':
if (dir != DOWN) dir = UP;
break;
case 's':
case 'S':
if (dir != UP) dir = DOWN;
break;
case 'x':
case 'X':
gameOver = true;
break;
}
}
}
void logic() {
if (dir == STOP) return;
Point head = snake.back();
Point newHead = head;
switch (dir) {
case LEFT: newHead.x--; break;
case RIGHT: newHead.x++; break;
case UP: newHead.y--; break;
case DOWN: newHead.y++; break;
default: break;
}
// 碰壁检测
if (newHead.x < 0 || newHead.x >= WIDTH || newHead.y < 0 || newHead.y >= HEIGHT) {
gameOver = true;
return;
}
// 碰到自己
for (auto& s : snake) {
if (s == newHead) {
gameOver = true;
return;
}
}
snake.push_back(newHead);
// 吃到食物
if (newHead == food) {
score += 10;
placeFood();
} else {
snake.pop_front(); // 移除尾巴
}
}
void run() {
while (!gameOver) {
draw();
input();
logic();
Sleep(100); // 100ms刷新一次
}
cout << "Game Over! Final Score: " << score << "\n";
}
};
int main() {
srand(time(0));
SnakeGame game;
game.run();
return 0;
}
编译运行
操作说明
如果你需要Linux版本或者更复杂的版本(带菜单、难度等),也可以告诉我!