c语言推箱子游戏
时间: 2023-07-09 13:19:02 浏览: 60
推箱子游戏是一种经典的益智游戏,以下是一个简单的C语言推箱子游戏示例。注意,这个示例只实现了最基本的功能,没有进行美化和优化。
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define WIDTH 10
#define HEIGHT 10
char map[HEIGHT][WIDTH] = {
"##########",
"# #",
"# o * #",
"# #",
"# ######",
"# #",
"#### * #",
"# o #",
"# #",
"##########"
}; // 地图
int playerX, playerY; // 玩家位置
int boxX, boxY; // 箱子位置
// 打印地图
void printMap() {
system("cls"); // 清屏
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
// 移动玩家
void movePlayer(int dx, int dy) {
if (map[playerY + dy][playerX + dx] == ' ') {
map[playerY][playerX] = ' ';
playerX += dx;
playerY += dy;
map[playerY][playerX] = 'o';
} else if (map[playerY + dy][playerX + dx] == '*') {
if (map[boxY + dy][boxX + dx] == ' ') {
map[playerY][playerX] = ' ';
playerX += dx;
playerY += dy;
map[playerY][playerX] = 'o';
map[boxY][boxX] = ' ';
boxX += dx;
boxY += dy;
map[boxY][boxX] = '*';
}
}
}
int main() {
// 初始化位置
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (map[i][j] == 'o') {
playerX = j;
playerY = i;
} else if (map[i][j] == '*') {
boxX = j;
boxY = i;
}
}
}
printMap(); // 打印地图
while (true) {
char input = getchar();
switch (input) {
case 'w':
movePlayer(0, -1);
break;
case 's':
movePlayer(0, 1);
break;
case 'a':
movePlayer(-1, 0);
break;
case 'd':
movePlayer(1, 0);
break;
default:
break;
}
printMap(); // 打印地图
// 判断是否成功通关
if (map[boxY][boxX] == '#' && map[boxY - 1][boxX] == '#' && map[boxY][boxX - 1] == '#' && map[boxY - 1][boxX - 1] == '#') {
printf("恭喜你通关了!\n");
break;
}
}
return 0;
}
```
该游戏使用二维字符数组作为地图,玩家用字母“o”表示,箱子用符号“*”表示,墙用符号“#”表示,空白地方用空格表示。玩家可以通过键盘输入w、s、a、d四个方向键来移动,玩家只能推着箱子移动,不能拉着箱子移动。当箱子被推到目标位置时,通关成功。