用c++帮我编一个我的世界小游戏
以下是一个简单的C++代码,用于实现一个简单的我的世界小游戏:
#include <iostream>
#include <vector>
using namespace std;
const int SIZE = 10;
class World {
private:
vector<vector<char>> grid;
int playerX, playerY;
public:
World() : grid(SIZE, vector<char>(SIZE, ' ')), playerX(0), playerY(0) {}
void display() {
cout << "┏";
for (int i = 0; i < SIZE; i++) {
cout << "━";
}
cout << "┓" << endl;
for (int i = 0; i < SIZE; i++) {
cout << "┃";
for (int j = 0; j < SIZE; j++) {
if (i == playerY && j == playerX) {
cout << "P";
} else {
cout << grid[i][j];
}
}
cout << "┃" << endl;
}
cout << "┗";
for (int i = 0; i < SIZE; i++) {
cout << "━";
}
cout << "┛" << endl;
}
void movePlayer(char direction) {
int newX = playerX;
int newY = playerY;
if (direction == 'W' && playerY > 0) {
newY = playerY - 1;
} else if (direction == 'S' && playerY < SIZE - 1) {
newY = playerY + 1;
} else if (direction == 'A' && playerX > 0) {
newX = playerX - 1;
} else if (direction == 'D' && playerX < SIZE - 1) {
newX = playerX + 1;
}
if (newX != playerX || newY != playerY) {
playerX = newX;
playerY = newY;
}
}
void placeBlock(int x, int y, char block) {
if (x >= 0 && x < SIZE && y >= 0 && y < SIZE) {
grid[y][x] = block;
}
}
};
int main() {
World world;
world.placeBlock(2, 2, '#');
world.placeBlock(5, 5, '#');
world.placeBlock(8, 8, '#');
char input;
while (true) {
world.display();
cout << "请输入移动方向 (W/A/S/D):";
cin >> input;
world.movePlayer(toupper(input));
cout << endl;
}
return 0;
}
这个小游戏使用二维数组来表示游戏世界的网格,每个单元格可以是空白或者一个方块。玩家可以通过输入W/A/S/D来移动,游戏会根据玩家的输入移动玩家的位置,并显示更新后的游戏世界。
玩家的位置显示为字母P,方块显示为#。你可以根据需要修改placeBlock函数来添加更多的方块。
请注意,这只是一个简单的示例代码,可能需要根据你的具体需求进行修改和扩展
原文地址: http://www.cveoy.top/t/topic/iogS 著作权归作者所有。请勿转载和采集!