c语言推箱子源代码程序运行及结果
时间: 2023-07-15 11:10:09 浏览: 88
推箱子源代码及程序(C语言)
5星 · 资源好评率100%
下面是一个简单的 C 语言推箱子游戏的源代码,可以在 Linux 或 Windows 操作系统上编译运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define ROWS 10
#define COLS 10
char map[ROWS][COLS] = {
"##########",
"# #",
"# O #",
"# #",
"# #",
"# X #",
"# #",
"# #",
"# #",
"##########"
};
int player_x = 2;
int player_y = 2;
void draw_map()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (i == player_y && j == player_x) {
printf("P");
} else {
printf("%c", map[i][j]);
}
}
printf("\n");
}
}
int main()
{
char ch;
while (1) {
system("cls");
draw_map();
ch = getch();
switch (ch) {
case 'w':
if (map[player_y - 1][player_x] == ' ') {
player_y--;
} else if (map[player_y - 1][player_x] == 'X' && map[player_y - 2][player_x] == ' ') {
map[player_y - 1][player_x] = ' ';
map[player_y - 2][player_x] = 'X';
player_y--;
}
break;
case 's':
if (map[player_y + 1][player_x] == ' ') {
player_y++;
} else if (map[player_y + 1][player_x] == 'X' && map[player_y + 2][player_x] == ' ') {
map[player_y + 1][player_x] = ' ';
map[player_y + 2][player_x] = 'X';
player_y++;
}
break;
case 'a':
if (map[player_y][player_x - 1] == ' ') {
player_x--;
} else if (map[player_y][player_x - 1] == 'X' && map[player_y][player_x - 2] == ' ') {
map[player_y][player_x - 1] = ' ';
map[player_y][player_x - 2] = 'X';
player_x--;
}
break;
case 'd':
if (map[player_y][player_x + 1] == ' ') {
player_x++;
} else if (map[player_y][player_x + 1] == 'X' && map[player_y][player_x + 2] == ' ') {
map[player_y][player_x + 1] = ' ';
map[player_y][player_x + 2] = 'X';
player_x++;
}
break;
case 'q':
exit(0);
}
}
return 0;
}
```
运行结果:
```
##########
# #
# O #
# #
# #
# X #
# #
# #
# #
##########
```
玩家用 WASD 来控制箱子的移动,Q 键退出游戏。
阅读全文