用 C++ 打造你的第一个游戏:控制台贪吃蛇 → SDL2 图形渲染 → 完整小游戏框架。与 GESP C++ 等级考试大纲自然衔接。
本地环境(Windows 装 MinGW-w64 或 Visual Studio;Linux 装 g++):
# Windows (MinGW) / Linux
g++ --version # 确认版本 ≥ 8,建议 12+
# 编译并运行
g++ -O2 -std=c++17 game.cpp -o game
./game # Linux 上运行;Windows 上是 game.exe
不想装环境?可以直接用 scirco.cn 的在线代码编辑器(C++17 / g++ 12),把下面代码贴进去点运行:
#include <iostream>
#include <random>
int main() {
std::mt19937 rng(std::random_device{}());
int secret = rng() % 100 + 1, guess = 0, count = 0;
std::cout << "我想了一个 1~100 的数,猜猜看!\n";
while (std::cin >> guess) {
++count;
if (guess == secret) { std::cout << "答对!共猜 " << count << " 次\n"; break; }
std::cout << (guess < secret ? "小了" : "大了") << ",再猜:";
}
return 0;
}
50 75 88,程序会逐行读取。C++ 游戏循环与 Python 版结构一致:读输入 → 更新 → 渲染。用枚举表示游戏状态,是游戏开发最重要的设计模式之一:
enum class GameState { Menu, Playing, Paused, GameOver };
GameState state = GameState::Menu;
while (state != GameState::GameOver) {
switch (state) {
case GameState::Menu: /* 显示菜单,按键后 */ state = GameState::Playing; break;
case GameState::Playing: /* 处理输入 + 更新 + 渲染 */ break;
case GameState::Paused: /* 按键恢复 */ break;
case GameState::GameOver: break;
}
}
练习:给猜数字游戏加上 Menu / Playing / GameOver 三个状态,GameOver 时显示“再玩一次?(y/n)”。
完整可玩的终端贪吃蛇(跨平台键盘监听 + 游戏循环 + 双向队列)。Linux/macOS 与 Windows 分别用 termios 与 conio 实现按键:
#include <iostream>
#include <deque>
#include <random>
#include <chrono>
#include <thread>
using namespace std;
#ifdef _WIN32
#include <conio.h>
char read_key() { return _kbhit() ? _getch() : 0; }
#else
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
char read_key() {
termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
char c = 0;
if (read(STDIN_FILENO, &c, 1) < 1) c = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, flags);
return c;
}
#endif
const int W = 20, H = 15;
int main() {
deque<pair<int,int>> snake = {{W/2, H/2}};
int dx = 1, dy = 0, score = 0;
mt19937 rng(random_device{}());
pair<int,int> food = {rng() % W, rng() % H};
cout << "方向键/WASD 控制,Q 退出\n";
while (true) {
char c = read_key();
if (c == 'q' || c == 'Q') break;
if (c == 'a' || c == 75) { if (dx != 1) { dx = -1; dy = 0; } }
if (c == 'd' || c == 77) { if (dx != -1) { dx = 1; dy = 0; } }
if (c == 'w' || c == 72) { if (dy != 1) { dx = 0; dy = -1; } }
if (c == 's' || c == 80) { if (dy != -1) { dx = 0; dy = 1; } }
auto head = snake.front();
head.first = (head.first + dx + W) % W;
head.second = (head.second + dy + H) % H;
for (auto &s : snake)
if (s == head) { cout << "GAME OVER! score=" << score << "\n"; return 0; }
snake.push_front(head);
if (head == food) {
score += 10;
food = {rng() % W, rng() % H};
} else {
snake.pop_back();
}
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
bool isSnake = false;
for (auto &s : snake) if (s.first == x && s.second == y) isSnake = true;
if (isSnake) cout << (make_pair(x, y) == head ? 'O' : 'o');
else if (food.first == x && food.second == y) cout << '*';
else cout << '.';
}
cout << "\n";
}
cout << "score=" << score << "\n";
this_thread::sleep_for(chrono::milliseconds(150));
cout << "\033[2J\033[H"; // 清屏(Linux/macOS)
}
return 0;
}
SDL2 是工业级 2D 图形库(Steam 上大量独立游戏用它)。安装:
# Ubuntu/Debian
sudo apt install libsdl2-dev libsdl2-image-dev
# Windows:下载 SDL2-devel VC 版,把 include/lib 配进工程
g++ game.cpp -o game `sdl2-config --cflags --libs` -lSDL2_image
最小窗口与移动方块(和 Python pygame 版一一对应):
#include <SDL2/SDL.h>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *win = SDL_CreateWindow("SDL2 第一课", 100, 100, 640, 480, 0);
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect rect = {320, 240, 30, 30}; // x, y, w, h
bool running = true;
SDL_Event e;
while (running) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) running = false;
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_LEFT) rect.x -= 5;
if (e.key.keysym.sym == SDLK_RIGHT) rect.x += 5;
if (e.key.keysym.sym == SDLK_UP) rect.y -= 5;
if (e.key.keysym.sym == SDLK_DOWN) rect.y += 5;
}
}
SDL_SetRenderDrawColor(ren, 15, 23, 42, 255);
SDL_RenderClear(ren);
SDL_SetRenderDrawColor(ren, 59, 130, 246, 255);
SDL_RenderFillRect(ren, &rect);
SDL_RenderPresent(ren);
SDL_Delay(16); // 约 60 FPS
}
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
游戏里“会动的东西”统称实体(Entity)。用结构体 + vector 管理玩家、子弹、敌人,这就是最简单的 ECS 雏形:
struct Entity {
float x, y, vx, vy;
int w, h;
int hp;
};
std::vector<Entity> bullets, enemies;
// 每帧更新:移动所有实体
for (auto &b : bullets) { b.x += b.vx; b.y += b.vy; }
// 碰撞检测:AABB 矩形相交
bool hit(const Entity &a, const Entity &b) {
return a.x < b.x + b.w && a.x + a.w > b.x &&
a.y < b.y + b.h && a.y + a.h > b.y;
}
// 清理飞出屏幕或死亡的实体(erase-remove 惯用法)
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
[](const Entity &b) { return b.x > 800 || b.hp <= 0; }), bullets.end());
把它和上一课的 SDL 循环组合,你就能做出一个太空射击游戏:空格发射子弹、方向键移动、敌机定时生成。练习:① 加得分与生命;② 用 SDL_GetTicks() 做基于时间的移动(保证不同电脑速度一致);③ 加载 PNG 精灵图。
当代码超过 500 行,就该拆分文件:
game/
├── main.cpp # 入口:初始化 + 主循环
├── Game.h/.cpp # 游戏状态机、帧率控制
├── Entity.h/.cpp # 实体与碰撞
├── Render.h/.cpp # 渲染封装
└── Makefile # 或 CMakeLists.txt
vector、enum class、lambda、随机数,对应 GESP C++ 3~5 级考点;贪吃蛇的边界/状态判断对应 2 级。