QML实现贪吃蛇 项目地址https://github.com/xcj-fighting/snake-qml打包的可执行程序地址https://github.com/xcj-fighting/snake-qml/releases/tag/v1.0.0基于 Qt 6.4 与 QML 实现的经典贪吃蛇小游戏使用 StackView 管理页面纯 QML 完成游戏逻辑支持难度选择、暂停、失败、通关与最高分持久化。一、界面展示二、项目结构snake-qml/ ├── main.cpp # 程序入口 ├── CMakeLists.txt # CMake 构建配置 ├── Main.qml # 主窗口 StackView 页面导航 ├── TitlePage.qml # 首页 ├── DifficultyPage.qml # 难度选择页 ├── GamePage.qml # 游戏主界面核心逻辑 ├── PauseDialog.qml # 暂停弹窗 ├── GameOverDialog.qml # 失败弹窗 ├── VictoryDialog.qml # 通关弹窗 └── README.md各 QML 文件在CMakeLists.txt中通过qt_add_qml_module注册qt_add_qml_module(appsnake-qml URI snake-qml VERSION 1.0 QML_FILES Main.qml TitlePage.qml DifficultyPage.qml GamePage.qml GameOverDialog.qml PauseDialog.qml VictoryDialog.qml )三、页面导航设计3.1 StackView 管理页面栈Main.qml使用StackView实现页面切换StackView { id: stackId anchors.fill: parent initialItem: homePage } Component { id: homePage TitlePage { onEnterDiffcultyPage: stackId.push(diffPage) } } Component { id: diffPage DifficultyPage { onBackRequested: stackId.pop() onDiffcultySelected: (speed) stackId.push(gamePage, { tickInterval: speed }) } } Component { id: gamePage GamePage { onBackToTitlePage: stackId.pop(null) } }四、游戏核心逻辑4.1 数据模型数据类型说明snake[{x, y}, ...]从蛇头到蛇尾的格子坐标food{x, y}食物坐标direction{dx, dy}当前移动方向nextDirection{dx, dy}下一帧待应用方向按键缓冲4.2 主循环Timer 驱动 tick()Timer { id: gameTimer interval: tickInterval repeat: true onTriggered: tick() }每隔tickInterval毫秒执行一次tick()完成「移动一步」的全部逻辑。4.3 每步 tick() 流程1. direction nextDirection 2. 计算新蛇头坐标 3. 撞墙→ gameOver() 4. 是否会吃到食物 5. 撞自身没吃到时不检查尾巴 6. 更新 snake 数组 7. 吃到食物 → 加分 spawnFood() 8. 蛇占满全图→ gameWin()4.4 渲染Repeater 画蛇Repeater { model: snake delegate: Rectangle { readonly property bool isHead: index 0 x: modelData.x * gameArea.cellSize 1 y: modelData.y * gameArea.cellSize 1 width: gameArea.cellSize - 2 height: gameArea.cellSize - 2 color: isHead ? #238b45 : #41ab5d } }snake数组一变Repeater自动更新方块位置。食物同理用一个Rectangle绑定food.x / food.y即可。五、最高分持久化使用 Qt 的Settings保存历史最高分Settings { id: scoreSettingId category: Score property int maxScore: 0 }在gameOver()和gameWin()中更新if (score scoreSettingId.maxScore) scoreSettingId.maxScore score标签建议CSDNQt6QMLQt Quick贪吃蛇CMakeQML教程小游戏版权声明本文为 snake-qml 项目实践记录欢迎转载请注明出处。