用c/c++ 编程实现一个推箱子
时间: 2024-05-04 16:22:20 浏览: 129
推箱子是一个经典的游戏,可以用C/C++编程语言来实现。下面是一个简单的推箱子的实现代码。
```
#include <iostream>
#include <vector>
using namespace std;
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
};
class BoxGame {
private:
int m, n;
vector<vector<char>> board;
Point player;
vector<Point> boxes;
public:
BoxGame(int m, int n, vector<vector<char>>& board) : m(m), n(n), board(board) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'P') {
player = Point(i, j);
} else if (board[i][j] == 'B') {
boxes.push_back(Point(i, j));
}
}
}
}
void move(char direction) {
int dx = 0, dy = 0;
if (direction == 'U') {
dx = -1;
} else if (direction == 'D') {
dx = 1;
} else if (direction == 'L') {
dy = -1;
} else if (direction == 'R') {
dy = 1;
}
Point new_player(player.x + dx, player.y + dy);
if (new_player.x < 0 || new_player.x >= m || new_player.y < 0 || new_player.y >= n || board[new_player.x][new_player.y] == '#') {
return;
}
bool can_move = true;
for (int i = 0; i < boxes.size(); i++) {
if (boxes[i].x == new_player.x && boxes[i].y == new_player.y) {
Point new_box(boxes[i].x + dx, boxes[i].y + dy);
if (new_box.x < 0 || new_box.x >= m || new_box.y < 0 || new_box.y >= n || board[new_box.x][new_box.y] == '#' || (new_box.x == player.x && new_box.y == player.y)) {
can_move = false;
break;
}
boxes[i] = new_box;
break;
}
}
if (can_move) {
player = new_player;
}
print_board();
if (is_win()) {
cout << "You win!" << endl;
}
}
bool is_win() {
for (int i = 0; i < boxes.size(); i++) {
if (board[boxes[i].x][boxes[i].y] != 'G') {
return false;
}
}
return true;
}
void print_board() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (player.x == i && player.y == j) {
cout << 'P';
} else {
bool is_box = false;
for (int k = 0; k < boxes.size(); k++) {
if (boxes[k].x == i && boxes[k].y == j) {
cout << 'B';
is_box = true;
break;
}
}
if (!is_box) {
cout << board[i][j];
}
}
}
cout << endl;
}
cout << endl;
}
};
int main() {
vector<vector<char>> board{
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', 'P', '#', '#', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', '#', '#', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', 'B', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
BoxGame game(10, 10, board);
game.print_board();
while (true) {
char direction;
cout << "Enter move (U/D/L/R): ";
cin >> direction;
game.move(direction);
}
return 0;
}
```
这个实现采用了面向对象的思想,将游戏板面、玩家、箱子等都封装到了一个BoxGame类中。move方法用于移动玩家,is_win方法用于判断是否胜利,print_board方法用于打印游戏板面。在主函数中,先构造一个游戏对象,然后循环读入玩家的移动指令,并调用move方法移动玩家。
阅读全文