c语言用链表写游戏推箱子
时间: 2023-08-10 13:16:36 浏览: 47
好的,推箱子游戏是非常经典的益智游戏,使用链表可以方便地实现游戏中的地图和箱子的移动。以下是一个简单的推箱子游戏的链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAP_SIZE 10
typedef struct node {
int x;
int y;
struct node* next;
} Node;
Node* create_node(int x, int y) {
Node* node = (Node*)malloc(sizeof(Node));
node->x = x;
node->y = y;
node->next = NULL;
return node;
}
void free_list(Node* head) {
while (head != NULL) {
Node* node = head;
head = head->next;
free(node);
}
}
void print_map(Node* player, Node* boxes) {
int map[MAP_SIZE][MAP_SIZE] = {0};
// 在地图上标记玩家和箱子的位置
while (player != NULL) {
map[player->x][player->y] = 1;
player = player->next;
}
while (boxes != NULL) {
map[boxes->x][boxes->y] = 2;
boxes = boxes->next;
}
// 打印地图
for (int i = 0; i < MAP_SIZE; i++) {
for (int j = 0; j < MAP_SIZE; j++) {
if (map[i][j] == 1) {
printf("P ");
} else if (map[i][j] == 2) {
printf("B ");
} else {
printf("- ");
}
}
printf("\n");
}
}
int move(Node* player, Node* boxes, int dx, int dy) {
// 先判断玩家是否能移动
int px = player->x + dx;
int py = player->y + dy;
if (px < 0 || px >= MAP_SIZE || py < 0 || py >= MAP_SIZE) {
return 0;
}
// 判断玩家是否能移动到目标位置
Node* box = boxes;
while (box != NULL) {
if (box->x == px && box->y == py) {
int bx = box->x + dx;
int by = box->y + dy;
if (bx < 0 || bx >= MAP_SIZE || by < 0 || by >= MAP_SIZE) {
return 0;
}
Node* other_box = boxes;
while (other_box != NULL) {
if (other_box != box && other_box->x == bx && other_box->y == by) {
return 0;
}
other_box = other_box->next;
}
box->x = bx;
box->y = by;
break;
}
box = box->next;
}
player->x = px;
player->y = py;
return 1;
}
int main() {
Node* player = create_node(0, 0);
Node* boxes = create_node(2, 2);
boxes->next = create_node(3, 3);
boxes->next->next = create_node(4, 4);
while (1) {
print_map(player, boxes);
printf("请输入方向(上:w,下:s,左:a,右:d):");
char ch;
scanf("%c", &ch);
getchar(); // 读取换行符
int dx = 0, dy = 0;
switch (ch) {
case 'w': dx = -1; break;
case 's': dx = 1; break;
case 'a': dy = -1; break;
case 'd': dy = 1; break;
default: printf("无效的输入!\n"); continue;
}
if (move(player, boxes, dx, dy)) {
int win = 1;
Node* box = boxes;
while (box != NULL) {
if (box->x != MAP_SIZE - 1 || box->y != MAP_SIZE - 1) {
win = 0;
break;
}
box = box->next;
}
if (win) {
printf("恭喜你获胜!\n");
break;
}
} else {
printf("无法移动!\n");
}
}
free_list(player);
free_list(boxes);
return 0;
}
```
这个实现中,我们使用了两个链表,一个链表存储玩家的位置,另一个链表存储所有的箱子的位置。在游戏中,我们只需要不断接收玩家的输入,然后根据输入调用 `move` 函数来移动玩家和箱子。移动的过程中需要判断是否越界、是否有障碍等条件,如果满足条件则更新链表中的节点。最后判断是否获胜,如果所有的箱子都移动到了终点,则游戏胜利。