c语言推箱子代码
时间: 2023-08-12 12:22:14 浏览: 35
下面是一个简单的 C 语言推箱子游戏的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define ROW 10
#define COL 10
void draw_map(char map[][COL], int row, int col); // 绘制地图
void move_box(char map[][COL], int row, int col, int x, int y, int dx, int dy); // 移动箱子
int main() {
char map[ROW][COL] = {
"##########",
"# #",
"# #",
"# #",
"# #",
"# #",
"# O #",
"# #",
"# #",
"##########",
};
int row = ROW, col = COL; // 地图的行和列
int x = 6, y = 6; // 箱子的初始位置
int dx = 0, dy = 0; // 箱子的移动方向
while (1) {
system("cls"); // 清屏
draw_map(map, row, col); // 绘制地图
if (map[x][y] == 'X') { // 判断是否胜利
printf("Congratulations! You win!\n");
break;
}
char ch = getch(); // 获取输入
switch (ch) {
case 'w': // 上
dx = -1;
dy = 0;
break;
case 's': // 下
dx = 1;
dy = 0;
break;
case 'a': // 左
dx = 0;
dy = -1;
break;
case 'd': // 右
dx = 0;
dy = 1;
break;
default:
break;
}
if (map[x+dx][y+dy] != '#') { // 判断是否可以移动
move_box(map, row, col, x, y, dx, dy);
x += dx;
y += dy;
}
}
return 0;
}
// 绘制地图
void draw_map(char map[][COL], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
// 移动箱子
void move_box(char map[][COL], int row, int col, int x, int y, int dx, int dy) {
if (map[x+dx][y+dy] == ' ') { // 移动到空格
map[x+dx][y+dy] = 'X';
map[x][y] = 'O';
} else if (map[x+dx][y+dy] == 'O' && map[x+dx+dx][y+dy+dy] != '#') { // 移动到箱子上
map[x+dx+dx][y+dy+dy] = 'X';
map[x+dx][y+dy] = 'O';
map[x][y] = ' ';
}
}
```
这个程序实现了一个简单的推箱子游戏,玩家可以通过 w、s、a、d 四个方向键来移动箱子,当箱子移动到终点时,游戏结束,输出胜利信息。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)