gpt4 book ai didi

Java用图像编写if语句的更优雅的方式

转载 作者:行者123 更新时间:2023-11-29 07:20:33 24 4
gpt4 key购买 nike

是否有更优雅/更短/更有条理的方式来编写这段代码?

for (int i = 0; i < SCREENSIZE; i++) {
for (int j = 0; j < SCREENSIZE; j++) {
if (map[y + i][x + j] == '@')
g.drawImage(item, j * TILESIZE,i * TILESIZE, null);
else if (map[y + i][x + j] == ' ')
g.drawImage(ground, j * TILESIZE,i * TILESIZE, null);
else if (map[y + i][x + j] == 'i')
g.drawImage(bush, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '~')
g.drawImage(ocean, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '=')
g.drawImage(fence, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '#')
g.drawImage(grass, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == 'Y')
g.drawImage(townsPerson, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '/')
g.drawImage(house01, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '¯')
g.drawImage(house02, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '\\')
g.drawImage(house03, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '[')
g.drawImage(house04, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == 'n')
g.drawImage(house05, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '_')
g.drawImage(house06, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == ']')
g.drawImage(house07, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '`')
g.drawImage(cground, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == 'O')
g.drawImage(boulder, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == 'Ÿ')
g.drawImage(alien, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == '.')
g.drawImage(tree01, j * TILESIZE, i * TILESIZE, null);
else if (map[y + i][x + j] == 'T')
g.drawImage(tree02, j * TILESIZE, i * TILESIZE, null);
}
}

最佳答案

第一个改进可能是使用 switch/case 结构,但在您的情况下,一个简单的映射 ( Map<Char,Image>) 会更好。

更进一步,您可以使用枚举而不是字符来标识对象,这将帮助您避免打字错误,但至少您应该使用字符常量,例如

public static final char MAP_ITEM = '@';
public static final char MAP_GROUND = ' ';

等等。

关于Java用图像编写if语句的更优雅的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5238508/

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