#include \n#include <conio.h>\n\nusing namespace std;\n\nconst int WIDTH = 10;\nconst int HEIGHT = 10;\nconst char PLAYER = 'P';\nconst char ENEMY = 'E';\nconst char EMPTY = ' ';\n\nstruct Position {\n int x;\n int y;\n};\n\nclass Game {\nprivate:\n char grid[WIDTH][HEIGHT];\n Position playerPos;\n Position enemyPos;\n bool gameOver;\npublic:\n Game() {\n // 初始化游戏地图\n for (int i = 0; i < WIDTH; i++) {\n for (int j = 0; j < HEIGHT; j++) {\n grid[i][j] = EMPTY;\n }\n }\n \n // 初始化玩家和敌人的位置\n playerPos.x = 0;\n playerPos.y = 0;\n enemyPos.x = WIDTH - 1;\n enemyPos.y = HEIGHT - 1;\n \n // 在地图上放置玩家和敌人\n grid[playerPos.x][playerPos.y] = PLAYER;\n grid[enemyPos.x][enemyPos.y] = ENEMY;\n \n gameOver = false;\n }\n \n void printGrid() {\n system("cls");\n \n for (int i = 0; i < WIDTH; i++) {\n for (int j = 0; j < HEIGHT; j++) {\n cout << grid[i][j] << " ";\n }\n cout << endl;\n }\n }\n \n void update() {\n char input = _getch();\n \n // 根据用户输入更新玩家的位置\n switch (input) {\n case 'w':\n if (playerPos.y > 0) {\n grid[playerPos.x][playerPos.y] = EMPTY;\n playerPos.y--;\n grid[playerPos.x][playerPos.y] = PLAYER;\n }\n break;\n case 'a':\n if (playerPos.x > 0) {\n grid[playerPos.x][playerPos.y] = EMPTY;\n playerPos.x--;\n grid[playerPos.x][playerPos.y] = PLAYER;\n }\n break;\n case 's':\n if (playerPos.y < HEIGHT - 1) {\n grid[playerPos.x][playerPos.y] = EMPTY;\n playerPos.y++;\n grid[playerPos.x][playerPos.y] = PLAYER;\n }\n break;\n case 'd':\n if (playerPos.x < WIDTH - 1) {\n grid[playerPos.x][playerPos.y] = EMPTY;\n playerPos.x++;\n grid[playerPos.x][playerPos.y] = PLAYER;\n }\n break;\n case ' ':\n // 玩家攻击敌人\n if (playerPos.x == enemyPos.x && playerPos.y == enemyPos.y) {\n grid[enemyPos.x][enemyPos.y] = EMPTY;\n gameOver = true;\n }\n break;\n }\n }\n \n bool isGameOver() {\n return gameOver;\n }\n};\n\nint main() {\n Game game;\n \n while (!game.isGameOver()) {\n game.printGrid();\n game.update();\n }\n \n cout << "游戏结束!" << endl;\n \n return 0;\n}

C++ WASD 和空格键控制的人机游戏代码示例

原文地址: https://www.cveoy.top/t/topic/pCD0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录