是否有更优雅/更短/有组织的方式来编写这段代码?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
第一个改进可能是使用开关/案例结构,但在你的情况下,一个简单的map(Map<Char,Image>
)会更好.
更进一步,您可以使用枚举而不是字符来识别对象,这将帮助您避免打字错误,但至少您应该使用字符常量,如
public static final char MAP_ITEM = '@';
public static final char MAP_GROUND = ' ';
Run Code Online (Sandbox Code Playgroud)
等等.
归档时间: |
|
查看次数: |
357 次 |
最近记录: |