当前位置: 首页 > news >正文

【C++/控制台】迷宫游戏

操作方式

  • 使用方向键(↑ ↓ ← →)控制移动

字符:墙壁:#,玩家:P(起点),出口:E

程序实现

#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;const int HEIGHT = 10;
const int WIDTH = 10;// 迷宫地图:'#'=墙 ' '=路 'P'=玩家 'E'=出口
char maze[HEIGHT][WIDTH] = {{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},{'#', 'P', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},{'#', '#', '#', ' ', '#', ' ', '#', '#', ' ', '#'},{'#', ' ', '#', ' ', ' ', ' ', '#', ' ', ' ', '#'},{'#', ' ', '#', '#', '#', ' ', '#', ' ', '#', '#'},{'#', ' ', ' ', ' ', '#', ' ', '#', ' ', ' ', '#'},{'#', '#', '#', ' ', '#', ' ', '#', ' ', '#', '#'},{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'E', '#'},{'#', ' ', '#', '#', '#', '#', '#', '#', '#', '#'},{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};int playerX = 1;
int playerY = 1;void hideCursor() {HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);CONSOLE_CURSOR_INFO cursorInfo;GetConsoleCursorInfo(hOut, &cursorInfo);cursorInfo.bVisible = false; // 隐藏光标SetConsoleCursorInfo(hOut, &cursorInfo);
}void clearScreen() {HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD coord;coord.X = 0;coord.Y = 0;SetConsoleCursorPosition(hOut, coord);
}void drawMaze() {for (int y = 0; y < HEIGHT; y++) {for (int x = 0; x < WIDTH; x++) {if (x == playerX && y == playerY) {cout << 'P'; // 绘制玩家} else {cout << maze[y][x];}}cout << endl;}clearScreen();
}bool isValidMove(int x, int y) {// 检查边界和墙壁if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)return false;return maze[y][x] != '#';
}int main() {hideCursor();bool gameOver = false;while (!gameOver) {drawMaze();// 获取键盘输入int input = _getch();if (input == 224) {// 方向键的第一字节int direction = _getch(); // 获取具体方向int newX = playerX;int newY = playerY;switch (direction) {case 72:newY--;break; // 上case 80:newY++;break; // 下case 75:newX--;break; // 左case 77:newX++;break; // 右}// 验证移动合法性if (isValidMove(newX, newY)) {playerX = newX;playerY = newY;// 检查是否到达出口if (maze[playerY][playerX] == 'E') {gameOver = true;drawMaze();cout << "\n恭喜!你逃出迷宫了!" << endl;Sleep(2000);}}}else if (input == 'q' || input == 'Q') {// 退出游戏gameOver = true;}}return 0;
}

运行结果

相关文章:

  • SQL每日一练
  • CloudWeGo-Netpoll:高性能NIO网络库浅析
  • python web 开发-Flask-Login使用详解
  • AtCoder AT_abc407_c [ABC407C] Security 2
  • 开发者工具箱-鸿蒙设备信息功能开发实践
  • 神经算子与FNO技术详解
  • 浅析Spring AOP 代理的生成机制
  • 实现Web网站冷启动的全面指南
  • [软件测试_4] 沟通技巧 | 测试用例 | 设计方法
  • 基于cornerstone3D的dicom影像浏览器 第二十二章 mpr + vr
  • 基于AI生成测试用例的处理过程
  • TestHubo V1.0.8版本发布,支持按模块树筛选用例,让查询更便捷
  • A-Teacher: Asymmetric Network for 3D Semi-Supervised Object Detection
  • c/c++的opencv像素级操作二值化
  • 【RAG文档切割】从基础拆分到语义分块实战指南
  • 【动态规划】P12223 [蓝桥杯 2023 国 Java B] 非对称二叉树|普及+
  • 使用ps为图片添加水印
  • Gitlab-Runner安装
  • 【人工智能】AI的炼金术:大模型训练的秘密配方
  • curl常用指令
  • 网页制作与网站建设英文翻译/媒体资源
  • 高校档案网站建设的目的是什么意思/神秘网站
  • 网站建设基本知识代码/品牌全网推广
  • 免费外贸自建网站/渠道网官网
  • 什么网站有教做衣服视频的/信息流广告模板
  • 个人网站备案材料填写/关键词搜索站长工具