推箱子游戏是一款经典的益智小游戏,玩家需要控制主角角色将几个木箱按照要求推到指定位置。在控制台终端中,可以使用字符来表示不同的游戏元素,例如 '#' 表示墙壁, ' ' 表示空地, '$' 表示木箱, '@' 表示主角角色, '+' 表示完成任务的目标位置。
实现步骤如下:
#include < stdio.h >
#include < conio.h >
#include < windows.h >
//定义常量和全局变量
const int WIDTH = 11;
const int HEIGHT = 10;
const char WALL = '#';
const char EMPTY = ' ';
const char BOX = '$';
const char TARGET = '+';
const char PLAYER = '@';
int playerX, playerY, score;
char board[HEIGHT][WIDTH];
//初始化游戏界面
void InitGame() {
//设置游戏界面的边框和各个元素的位置
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
board[i][j] = WALL;
}
else {
board[i][j] = EMPTY;
}
}
}
//设置木箱和目标位置
board[2][2] = BOX;
board[4][5] = BOX;
board[6][8] = BOX;
board[2][8] = TARGET;
board[4][2] = TARGET;
board[6][5] = TARGET;
//设置主角角色位置
playerX = 7;
playerY = 5;
board[playerX][playerY] = PLAYER;
}
//绘制游戏画面
void DrawGame() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
printf("%c", board[i][j]);
}
printf("\\n");
}
printf("Score: %d\\n", score);
}
//更新游戏状态
void UpdateGame(int dx, int dy) {
int nextX = playerX + dx;
int nextY = playerY + dy;
//判断主角角色是否可以移动
if (board[nextX][nextY] == EMPTY || board[nextX][nextY] == TARGET) {
board[playerX][playerY] = EMPTY;
playerX = nextX;
playerY = nextY;
board[playerX][playerY] = PLAYER;
}
else if (board[nextX][nextY] == BOX && (board[nextX + dx][nextY + dy] == EMPTY || board[nextX + dx][nextY + dy] == TARGET)) {
//判断主角角色是否可以推动木箱
board[playerX][playerY] = EMPTY;
playerX = nextX;
playerY = nextY;
board[playerX][playerY] = PLAYER;
board[nextX + dx][nextY + dy] = BOX;
board[nextX][nextY] = EMPTY;
}
//判断是否完成任务
if (board[2][8] == BOX && board[4][2] == BOX && board[6][5] == BOX) {
score += 100;
printf("Congratulations! You win!\\n");
Sleep(2000);
exit(0);
}
}
//控制主角角色移动
void Control() {
char c = getch();
switch (c) {