# SnakeGame **Repository Path**: CyberSoviet/snake-game ## Basic Information - **Project Name**: SnakeGame - **Description**: Qt学习之仓库 - **Primary Language**: C++ - **License**: BSD-4-Clause - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-10-28 - **Last Updated**: 2026-10-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 项目 Qt6 Widgets 贪吃蛇。逻辑与界面分离,逻辑带单元测试。 ## 目录结构 - `src/game/` 纯逻辑(`Snake`、`Game`),只依赖 `Qt6::Core`,无界面。 - `src/ui/` 界面层:`MainWindow`(分数标签+布局)、`GameWidget`(绘制/定时器/键盘)。 - `tests/` QTest 单测(`tst_snake`、`tst_game`)。 - `resources/` `.qrc` 资源与图片(`apple.png` 食物)。 - `createFood.py` 用 Pillow 重新生成 `resources/apple.png`。 ## 构建 / 运行 系统同时装了 Qt5 和 Qt6,本项目用 Qt6。 cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON cmake --build build ./build/snake ## 测试 ctest --test-dir build --output-on-failure ctest --test-dir build -R tst_game --output-on-failure # 单个测试套件 ./build/tests/tst_game -functions # 列出用例 ./build/tests/tst_game hittingWallEndsGame # 单个用例 ## 关键约定与坑 - **资源必须开 AUTORCC**:`qt_standard_project_setup()` 只开启 MOC/UIC,**不含 RCC**。 缺 `set(CMAKE_AUTORCC ON)` 会把 `.qrc` 静默忽略,运行时 `QPixmap(":/apple.png")` 为 null。 改动 `.qrc`/加新文件后需重新 `cmake` 配置;若图加载失败,先查 `build/` 下有无 `qrc_*.cpp`。 - **分层**:`src/game/` 只允许依赖 `Qt6::Core`,GUI 只能留在 `src/ui/`,否则 `tests/` 无法无界面运行。 - **加规则进逻辑层**:移动/反向保护/碰撞/计分都在 `src/game/`,`GameWidget` 只管输入翻译、定时、绘制。 - `Game::setFood(QPoint)` 供测试注入确定食物;测试不要依赖随机食物。 - 提交前先跑 `ctest`。 拟定的 README.md # Snake 用 Qt6 Widgets 写的贪吃蛇小游戏。逻辑与界面分离,带单元测试。 ## 特性 - 方向键 / WASD 控制,空格暂停,结束后按 R 重开 - 吃食物变长加分,难度随分数递增 - 撞墙或撞到自己结束 - 食物图片经 Qt 资源系统(`.qrc`)打包进可执行文件 ## 依赖 - Qt6(Widgets、Test)、CMake ≥ 3.21、Ninja、支持 C++17 的编译器 - 可选:Python + Pillow(仅用于重新生成食物图片) ## 构建与运行 cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON cmake --build build ./build/snake ## 测试 ctest --test-dir build --output-on-failure ## 操作 - 移动:方向键 或 W / A / S / D - 暂停 / 继续:空格 - 重新开始:R(游戏结束后) ## 目录结构 src/game/ 逻辑(Snake、Game) src/ui/ 界面(MainWindow、GameWidget) tests/ QTest 单元测试 resources/ .qrc 与图片 ## 重新生成食物图片 python3 createFood.py # 从仓库根目录运行 拟定的 .gitignore 追加内容 .cache/