帮我用C语言写一个推箱子游戏
时间: 2023-12-29 15:16:17 浏览: 33
好的,以下是一个简单的推箱子游戏的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define WIDTH 10
#define HEIGHT 10
char map[HEIGHT][WIDTH] = {
"##########",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"##########"
};
int player_x = 1;
int player_y = 1;
int box_x = 3;
int box_y = 3;
void draw_map() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
printf("%s\n", map[i]);
}
}
void move_player(int dx, int dy) {
int new_x = player_x + dx;
int new_y = player_y + dy;
if (map[new_y][new_x] == ' ') {
player_x = new_x;
player_y = new_y;
} else if (map[new_y][new_x] == '$') {
int new_box_x = box_x + dx;
int new_box_y = box_y + dy;
if (map[new_box_y][new_box_x] == ' ') {
player_x = new_x;
player_y = new_y;
box_x = new_box_x;
box_y = new_box_y;
}
}
}
int main() {
while (1) {
draw_map();
int c = getch();
if (c == 'w') {
move_player(0, -1);
} else if (c == 'a') {
move_player(-1, 0);
} else if (c == 's') {
move_player(0, 1);
} else if (c == 'd') {
move_player(1, 0);
}
if (box_x == 8 && box_y == 8) {
printf("Congratulations, you win!\n");
break;
}
}
return 0;
}
```
这个实现中,我们使用了一个二维字符数组来表示地图,其中 "#" 表示墙," " 表示空地,"$" 表示箱子。使用两个变量来表示玩家的位置和箱子的位置,每次移动时判断目标位置是否为空地或者有箱子可以移动,然后更新玩家和箱子的位置。使用 getch() 函数来读取用户输入的方向键。当箱子到达终点位置时,游戏结束。