make char-to-terrain lookup dictionary-based instead of switch-based

GitOrigin-RevId: 0d81e95bf047fab204bff8cf46ece2ab5470bf09
This commit is contained in:
Colin McMillen 2020-02-02 10:32:32 -05:00
parent b731e1a785
commit 1f7da03515

View File

@ -90,6 +90,18 @@ namespace SemiColinGames {
====================> <====..========..======..=========..=========> <=============> <==============================================================> <=======..==============..============================== ====================> <====..========..======..=========..=========> <=============> <==============================================================> <=======..==============..==============================
....................] [............................................] [.............] [..............................................................] [......................................................."; ....................] [............................................] [.............] [..............................................................] [.......................................................";
private static readonly Dictionary<char, Terrain> charToTerrain =
new Dictionary<char, Terrain>() {
{ '=', Terrain.Grass },
{ '<', Terrain.GrassL },
{ '>', Terrain.GrassR },
{ '.', Terrain.Rock },
{ '[', Terrain.RockL },
{ ']', Terrain.RockR },
{ '~', Terrain.Water },
{ 'X', Terrain.Block }
};
public World(Texture2D texture) { public World(Texture2D texture) {
var tilesList = new List<Tile>(); var tilesList = new List<Tile>();
string[] worldDesc = worldString.Split('\n'); string[] worldDesc = worldString.Split('\n');
@ -98,38 +110,13 @@ namespace SemiColinGames {
Debug.WriteLine("world size: {0}x{1}", tileWidth, tileHeight); Debug.WriteLine("world size: {0}x{1}", tileWidth, tileHeight);
for (int i = 0; i < tileWidth; i++) { for (int i = 0; i < tileWidth; i++) {
for (int j = 0; j < tileHeight; j++) { for (int j = 0; j < tileHeight; j++) {
Terrain? terrain = null;
if (i < worldDesc[j].Length) { if (i < worldDesc[j].Length) {
switch (worldDesc[j][i]) { char key = worldDesc[j][i];
case '=': if (charToTerrain.ContainsKey(key)) {
terrain = Terrain.Grass; Terrain terrain = charToTerrain[key];
break;
case '<':
terrain = Terrain.GrassL;
break;
case '>':
terrain = Terrain.GrassR;
break;
case '.':
terrain = Terrain.Rock;
break;
case '[':
terrain = Terrain.RockL;
break;
case ']':
terrain = Terrain.RockR;
break;
case '~':
terrain = Terrain.Water;
break;
case 'X':
terrain = Terrain.Block;
break;
}
}
if (terrain != null) {
var position = new Rectangle(i * TileSize, j * TileSize, TileSize, TileSize); var position = new Rectangle(i * TileSize, j * TileSize, TileSize, TileSize);
tilesList.Add(new Tile(texture, terrain.Value, position)); tilesList.Add(new Tile(texture, terrain, position));
}
} }
} }
} }