用C++编写一个推箱子小游戏
以下是一个简单的推箱子小游戏的C++代码示例:
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 10;
const int height = 10;
int playerX, playerY;
int targetX, targetY;
int boxX, boxY;
char map[height][width] = {
{'#','#','#','#','#','#','#','#','#','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#','#','#','#','#','#','#'}
};
void drawMap() {
system("cls");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << map[i][j] << ' ';
}
cout << endl;
}
}
void movePlayer(char direction) {
int nextX = playerX;
int nextY = playerY;
switch (direction) {
case 'w':
nextY--;
break;
case 's':
nextY++;
break;
case 'a':
nextX--;
break;
case 'd':
nextX++;
break;
}
if (map[nextY][nextX] == ' ') {
playerX = nextX;
playerY = nextY;
}
else if (map[nextY][nextX] == '$') {
int nextBoxX = boxX;
int nextBoxY = boxY;
switch (direction) {
case 'w':
nextBoxY--;
break;
case 's':
nextBoxY++;
break;
case 'a':
nextBoxX--;
break;
case 'd':
nextBoxX++;
break;
}
if (map[nextBoxY][nextBoxX] == ' ') {
map[boxY][boxX] = ' ';
boxX = nextBoxX;
boxY = nextBoxY;
playerX = nextX;
playerY = nextY;
}
}
if (playerX == targetX && playerY == targetY && map[boxY][boxX] == '$') {
map[targetY][targetX] = '*';
}
else {
map[targetY][targetX] = '.';
}
map[boxY][boxX] = '$';
map[playerY][playerX] = '@';
}
bool checkWin() {
return map[targetY][targetX] == '*';
}
int main() {
playerX = 1;
playerY = 1;
targetX = 8;
targetY = 8;
boxX = 4;
boxY = 4;
while (true) {
drawMap();
if (checkWin()) {
cout << "You win!" << endl;
break;
}
char input = _getch();
movePlayer(input);
}
return 0;
}
这个代码示例使用了一个简单的字符地图来表示游戏场景,玩家通过输入"w", "s", "a", "d"来控制人物移动,目标是将箱子推到指定位置。玩家通过控制台输入来进行游戏操作,当箱子被推到指定位置时,游戏结束,输出"You win!"
原文地址: http://www.cveoy.top/t/topic/hCoZ 著作权归作者所有。请勿转载和采集!