【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;
}
运行结果: