用c语言设计一个简单的推箱子游戏
时间: 2024-02-13 16:00:41 浏览: 88
好的,推箱子游戏可以分为游戏界面、地图、角色、箱子、目标点等几个部分。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define ROW 10
#define COL 10
int map[ROW][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},
};
typedef struct {
int x;
int y;
} Position;
Position player = {1, 1};
Position box = {4, 4};
Position target = {8, 8};
void drawMap();
void movePlayer();
void moveBox();
int main() {
int isWin = 0;
drawMap();
while (!isWin) {
movePlayer();
moveBox();
drawMap();
if (player.x == target.x && player.y == target.y) {
isWin = 1;
printf("You Win!\n");
}
}
return 0;
}
void drawMap() {
system("cls");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (i == player.x && j == player.y) {
printf("P");
} else if (i == box.x && j == box.y) {
printf("B");
} else if (i == target.x && j == target.y) {
printf("T");
} else if (map[i][j] == 1) {
printf("#");
} else {
printf(" ");
}
}
printf("\n");
}
}
void movePlayer() {
char input;
input = getch();
switch (input) {
case 'w':
if (map[player.x-1][player.y] != 1) {
player.x--;
}
break;
case 's':
if (map[player.x+1][player.y] != 1) {
player.x++;
}
break;
case 'a':
if (map[player.x][player.y-1] != 1) {
player.y--;
}
break;
case 'd':
if (map[player.x][player.y+1] != 1) {
player.y++;
}
break;
default:
break;
}
}
void moveBox() {
if (player.x == box.x && player.y == box.y) {
char input;
input = getch();
switch (input) {
case 'w':
if (map[box.x-1][box.y] != 1 && player.x-1 >= 0 && box.x-1 >= 0) {
player.x--;
box.x--;
}
break;
case 's':
if (map[box.x+1][box.y] != 1 && player.x+1 < ROW && box.x+1 < ROW) {
player.x++;
box.x++;
}
break;
case 'a':
if (map[box.x][box.y-1] != 1 && player.y-1 >= 0 && box.y-1 >= 0) {
player.y--;
box.y--;
}
break;
case 'd':
if (map[box.x][box.y+1] != 1 && player.y+1 < COL && box.y+1 < COL) {
player.y++;
box.y++;
}
break;
default:
break;
}
}
}
```
在这个游戏中,地图由一个二维数组表示,0表示空地,1表示墙,P表示玩家,B表示箱子,T表示目标点。玩家可以通过键盘输入控制移动,当玩家和箱子在同一个位置时,可以通过再次输入控制箱子的移动。当玩家到达目标点时,游戏胜利。
阅读全文