用c语言制作一个推箱子游戏
时间: 2023-06-13 16:03:47 浏览: 110
好的,下面是一个简单的推箱子游戏的 C 语言代码。请注意,这只是一个基础框架,您可以根据自己的需求进行更改和完善。
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#define MAX_SIZE 10
int map[MAX_SIZE][MAX_SIZE] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 2, 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_x = 1, player_y = 1; //玩家初始位置
int box_num = 1; //箱子数
int box_x[10] = {2}, box_y[10] = {2}; //箱子初始位置
void drawMap() //绘制地图
{
system("cls"); //清屏
for (int i = 0; i < MAX_SIZE; i++)
{
for (int j = 0; j < MAX_SIZE; j++)
{
if (map[i][j] == 1) //墙壁
printf("#");
else if (i == player_x && j == player_y) //玩家
printf("P");
else //空地或箱子
{
int flag = 0;
for (int k = 0; k < box_num; k++)
{
if (box_x[k] == i && box_y[k] == j)
{
printf("B");
flag = 1;
break;
}
}
if (!flag)
printf(" ");
}
}
printf("\n");
}
}
void move(int x, int y) //移动函数
{
int next_x = player_x + x;
int next_y = player_y + y;
if (map[next_x][next_y] == 0) //下一步为空地
{
player_x = next_x;
player_y = next_y;
}
else if (map[next_x][next_y] == 2) //下一步为箱子
{
int next_box_x = next_x + x;
int next_box_y = next_y + y;
for (int i = 0; i < box_num; i++)
{
if (box_x[i] == next_x && box_y[i] == next_y)
{
if (map[next_box_x][next_box_y] == 0) //箱子可以移动
{
box_x[i] = next_box_x;
box_y[i] = next_box_y;
player_x = next_x;
player_y = next_y;
}
break;
}
}
}
}
int checkWin() //检查是否胜利
{
for (int i = 0; i < box_num; i++)
{
if (map[box_x[i]][box_y[i]] != 3)
return 0;
}
return 1;
}
int main()
{
while (1)
{
drawMap(); //绘制地图
if (checkWin()) //检查是否胜利
{
printf("You win!\n");
break;
}
int key = getch(); //获取键盘输入
switch (key)
{
case 'w':
move(-1, 0);
break;
case 's':
move(1, 0);
break;
case 'a':
move(0, -1);
break;
case 'd':
move(0, 1);
break;
case 27: //ESC键退出游戏
exit(0);
break;
}
}
return 0;
}
```
这是一个基础的推箱子游戏,您可以根据实际需求进行修改和完善,例如增加关卡、难度、动画等元素。
阅读全文