请用C语言写一个推箱子小游戏
时间: 2023-12-25 12:04:21 浏览: 177
以下是一个简单的推箱子小游戏的 C 语言实现:
```c
#include <stdio.h>
#include <conio.h>
#define MAX_ROW 20
#define MAX_COL 20
int map[MAX_ROW][MAX_COL] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
}; // 地图
int player_row = 1;
int player_col = 1; // 玩家位置
int box_row = 3;
int box_col = 3; // 箱子位置
void draw_map();
void move_player(int dx, int dy);
int main()
{
char ch;
draw_map(); // 绘制地图
while (1)
{
ch = getch();
switch (ch)
{
case 'w': move_player(-1, 0); break;
case 's': move_player(1, 0); break;
case 'a': move_player(0, -1); break;
case 'd': move_player(0, 1); break;
default: break;
}
draw_map(); // 绘制地图
}
return 0;
}
void draw_map()
{
int i, j;
system("cls"); // 清屏
for (i = 0; i < MAX_ROW; i++)
{
for (j = 0; j < MAX_COL; j++)
{
if (i == player_row && j == player_col)
{
printf("P");
}
else if (i == box_row && j == box_col)
{
printf("B");
}
else if (map[i][j] == 1)
{
printf("#");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
void move_player(int dx, int dy)
{
int new_player_row = player_row + dx;
int new_player_col = player_col + dy;
if (map[new_player_row][new_player_col] == 0)
{
player_row = new_player_row;
player_col = new_player_col;
if (player_row == box_row && player_col == box_col)
{
int new_box_row = box_row + dx;
int new_box_col = box_col + dy;
if (map[new_box_row][new_box_col] == 0)
{
box_row = new_box_row;
box_col = new_box_col;
}
}
}
}
```
使用说明:
- `WASD` 键控制玩家移动;
- 玩家为 `P`,箱子为 `B`,墙为 `#`;
- 玩家碰到箱子时会推动箱子。
这只是一个简单的示例,如果要实现更多功能,例如游戏结束判断、多个箱子、关卡设计等,还需要进一步完善。
阅读全文