C++#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
// 方块类型枚举
enum BlockType {
AIR = 0,
GRASS = 1,
DIRT = 2,
STONE = 3,
WATER = 4
};
// 世界类
class World {
private:
vector<vector<vector<int>>> blocks;
int worldSize;
int worldHeight;
public:
World(int size = 32, int height = 16) : worldSize(size), worldHeight(height) {
blocks.resize(worldSize, vector<vector<int>>(worldSize, vector<int>(worldHeight, AIR)));
generateWorld();
}
void generateWorld() {
srand(time(0));
// 生成基础地形
for (int x = 0; x < worldSize; x++) {
for (int z = 0; z < worldSize; z++) {
int surfaceHeight = worldHeight / 2 + rand() % 4 - 2;
for (int y = 0; y < worldHeight; y++) {
if (y == 0) {
blocks[x][z][y] = STONE; // 基岩层
} else if (y < surfaceHeight - 3) {
blocks[x][z][y] = STONE; // 石头层
} else if (y < surfaceHeight) {
blocks[x][z][y] = DIRT; // 泥土层
} else if (y == surfaceHeight) {
blocks[x][z][y] = GRASS; // 草地层
} else if (y < surfaceHeight + 3 && rand() % 20 == 0) {
blocks[x][z][y] = WATER; // 水池
}
}
}
}
}
void displayWorld() {
cout << "=== 我的世界 ===" << endl;
cout << "世界大小: " << worldSize << "x" << worldSize << "x" << worldHeight << endl;
cout << "方块类型说明:" << endl;
cout << "0-空气 1-草地 2-泥土 3-石头 4-水" << endl;
cout << "================" << endl;
// 显示世界的一个切片
int sliceY = worldHeight / 2;
cout << "Y=" << sliceY << " 层的切片视图:" << endl;
for (int x = 0; x < worldSize && x < 20; x++) {
for (int z = 0; z < worldSize && z < 20; z++) {
cout << blocks[x][z][sliceY] << " ";
}
cout << endl;
}
}
int getBlock(int x, int y, int z) {
if (x >= 0 && x < worldSize && y >= 0 && y < worldHeight && z >= 0 && z < worldSize) {
return blocks[x][z][y];
}
return AIR;
}
void setBlock(int x, int y, int z, int type) {
if (x >= 0 && x < worldSize && y >= 0 && y < worldHeight && z >= 0 && z < worldSize) {
blocks[x][z][y] = type;
}
}
void printHelp() {
cout << "=== 游戏指令 ===" << endl;
cout << "w - 显示世界" << endl;
cout << "d x y z - 挖掘方块" << endl;
cout << "p x y z type - 放置方块" << endl;
cout << "h - 显示帮助" << endl;
cout << "q - 退出游戏" << endl;
cout << "================" << endl;
}
};
int main() {
World world(32, 16);
world.displayWorld();
world.printHelp();
char command;
while (true) {
cout << "> ";
cin >> command;
switch (command) {
case 'w':
world.displayWorld();
break;
case 'd': {
int x, y, z;
cin >> x >> y >> z;
world.setBlock(x, y, z, AIR);
cout << "已挖掘 (" << x << ", " << y << ", " << z << ")" << endl;
break;
}
case 'p': {
int x, y, z, type;
cin >> x >> y >> z >> type;
world.setBlock(x, y, z, type);
cout << "已放置 " << type << " 在 (" << x << ", " << y << ", " << z << ")" << endl;
break;
}
case 'h':
world.printHelp();
break;
case 'q':
cout << "感谢游玩!" << endl;
return 0;
default:
cout << "未知指令,输入 'h' 查看帮助" << endl;
}
}
return 0;
}