c++写我的世界
时间: 2023-08-03 14:11:41 浏览: 1514
我的世界简易版(C++编写,源代码+程序)
5星 · 资源好评率100%
写一个简单的我的世界游戏需要很多的工作,包括图形界面的设计、物理引擎的实现、游戏逻辑的编写等等。下面是一个简单的C++控制台版本的我的世界游戏示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
const int WORLD_WIDTH = 10;
const int WORLD_HEIGHT = 10;
enum BlockType {
BLOCK_AIR,
BLOCK_DIRT,
BLOCK_GRASS,
BLOCK_STONE
};
class Block {
public:
Block(BlockType type = BLOCK_AIR) : type(type) {}
BlockType getType() const { return type; }
private:
BlockType type;
};
class World {
public:
World(int width, int height) : width(width), height(height) {
blocks.resize(height);
for (int i = 0; i < height; i++) {
blocks[i].resize(width);
for (int j = 0; j < width; j++) {
if (i == 0 || i == height - 1 || j == 0 || j == width - 1) {
blocks[i][j] = Block(BLOCK_STONE);
} else if (i == height - 2) {
blocks[i][j] = Block(BLOCK_GRASS);
} else {
blocks[i][j] = Block(BLOCK_DIRT);
}
}
}
}
void print() const {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
switch (blocks[i][j].getType()) {
case BLOCK_AIR: cout << " "; break;
case BLOCK_DIRT: cout << "#"; break;
case BLOCK_GRASS: cout << "*"; break;
case BLOCK_STONE: cout << "@"; break;
}
}
cout << endl;
}
}
Block getBlock(int x, int y) const {
if (x < 0 || x >= width || y < 0 || y >= height) {
return Block(BLOCK_AIR);
} else {
return blocks[y][x];
}
}
private:
int width, height;
vector<vector<Block>> blocks;
};
class Player {
public:
Player(int x, int y) : x(x), y(y) {}
void move(int dx, int dy, const World& world) {
if (world.getBlock(x + dx, y + dy).getType() == BLOCK_AIR) {
x += dx;
y += dy;
}
}
int getX() const { return x; }
int getY() const { return y; }
private:
int x, y;
};
int main() {
World world(WORLD_WIDTH, WORLD_HEIGHT);
Player player(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
while (true) {
system("cls");
world.print();
cout << "Player is at (" << player.getX() << ", " << player.getY() << ")" << endl;
char input;
cin >> input;
switch (input) {
case 'w': player.move(0, -1, world); break;
case 'a': player.move(-1, 0, world); break;
case 's': player.move(0, 1, world); break;
case 'd': player.move(1, 0, world); break;
}
}
return 0;
}
```
这个示例中,我们定义了一个World类和一个Player类,分别表示游戏世界和玩家。在World类中,我们使用二维数组来存储所有的方块,然后在构造函数中初始化它们。在Player类中,我们使用x和y来表示玩家的坐标,在move函数中,我们判断目标位置是否为空气块,如果是,则移动玩家。最后,在主函数中,我们循环输出游戏世界和玩家位置,并根据用户的输入移动玩家。
阅读全文