gpt4 book ai didi

java - 在java中正确表示一个二维世界

转载 作者:行者123 更新时间:2023-12-01 13:18:16 25 4
gpt4 key购买 nike

我正在用Java制作一个滚动游戏,我想澄清一点。我不以任何java结构保存游戏关卡,我只是读取一个文件(.gif)我对其进行了修改:

  • 我使用颜色解密来逐个像素地解析并放置
    对象满足我已建立的要求。

例如:

  .
.
.


int w = image.getWidth(); //store the dimensions of the level image.
int h = image.getHeight();
for(int x = 0; x < w; x++){
for(int y = 0; y < h; y++){ //check every single pixel with this nested loop
int pixel = image.getRGB(x, y); //get the pixel's rgb value
TYPE_INT_ARGB formatint red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;

if(red == 255 && green == 255 && blue == 0)
controller.addPlayer((float)x, (float)y);
else if(red == 255 && green == 255 && blue == 255)
controller.addTerrain(x, y);
}

如您所见,我没有将关卡保存在任何结构中,但我只是扫描代表它的图像文件。

  • 这样做是个好主意吗?

当然,我使用 Controller 类存储所有对象,在其中创建一个包含所有游戏对象的数组列表。

 

最佳答案

您可以创建一个 .txt 文件并创建一个如下所示的 map :

20
10
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0

0 代表空气,1 代表可行走的方 block 。第一个值是 map 宽度,第二个值是 map 高度。我还建议您使用二维数组来存储 map 信息。现在您可以使用 BufferedReader 读取 txt 文件。希望下面的代码有帮助

private final int TILE_SIZE = 30;
private int[][] blocks;

private void loadMap(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
mapWidth = Integer.parseInt(reader.readLine());
mapHeight = Integer.parseInt(reader.readLine());
blocks = new int[mapHeight][mapWidth];

for(int col = 0; col < mapHeight; col ++) {
String line = reader.readLine();
String[] tokens = line.split(" ");
for(int row = 0; row < numBlocksRow; row++) {
blocks[col][row] = Integer.parseInt(tokens[row]);
}
}
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}

private void render(Graphics2D g) {
for(int col = 0; col < mapHeight; col ++) {
for(int row = 0; row < numBlocksRow; row++) {
int block = blocks[col][row];
Color color;
if(block == 1) {
color = Color.white;
} else {
color = Color.black;
}
g.fillRect(row * TILE_SIZE, col * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}

关于java - 在java中正确表示一个二维世界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com