推箱子c语言程序代码200行
时间: 2023-07-02 11:03:35 浏览: 61
以下是一个简单的推箱子游戏的 C 语言程序,共计约200行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define ROWS 10
#define COLS 10
int map[ROWS][COLS] = {
{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 playerRow, playerCol;
void printMap() {
system("cls");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (i == playerRow && j == playerCol) {
printf("P");
} else if (map[i][j] == 1) {
printf("#");
} else if (map[i][j] == 2) {
printf("$");
} else {
printf(" ");
}
}
printf("\n");
}
}
void movePlayer(int row, int col) {
int newRow = playerRow + row;
int newCol = playerCol + col;
if (map[newRow][newCol] == 0) {
playerRow = newRow;
playerCol = newCol;
} else if (map[newRow][newCol] == 2) {
int newBoxRow = newRow + row;
int newBoxCol = newCol + col;
if (map[newBoxRow][newBoxCol] == 0) {
map[newRow][newCol] = 0;
map[newBoxRow][newBoxCol] = 2;
playerRow = newRow;
playerCol = newCol;
}
}
}
int main() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (map[i][j] == 0) {
playerRow = i;
playerCol = j;
}
}
}
while (1) {
printMap();
char input = getch();
switch (input) {
case 'w':
movePlayer(-1, 0);
break;
case 's':
movePlayer(1, 0);
break;
case 'a':
movePlayer(0, -1);
break;
case 'd':
movePlayer(0, 1);
break;
}
}
return 0;
}
```
该程序使用了一个10x10的二维数组表示地图,其中1表示墙,0表示空地,2表示箱子。程序通过循环遍历地图数组来查找玩家初始位置,并在每次移动时根据玩家输入的方向移动玩家和箱子。在控制台中输出当前地图的状态,以实现游戏界面。
阅读全文