Optimization and Saving/Loading
- by MrPlosion1243
I'm developing a 2D tile based game and I have a few questions regarding it.
First I would like to know if this is the correct way to structure my Tile class:
namespace TileGame.Engine {
public enum TileType {
Air,
Stone
}
class Tile {
TileType type;
bool collidable;
static Tile air = new Tile(TileType.Air);
static Tile stone = new Tile(TileType.Stone);
public Tile(TileType type) {
this.type = type;
collidable = true;
}
}
}
With this method I just say world[y, x] = Tile.Stone and this seems right to me but I'm not a very experienced coder and would like assistance.
Now the reason I doubt this so much is because I like everything to be as optimized as possible and there is a major flaw in this that I need help overcoming. It has to do with saving and loading... well more on loading actually. The way it's done relies on the principle of casting an enumeration into a byte which gives you the corresponding number where its declared in the enumeration. Each TileType is cast as a byte and written out to a file. So TileType.Air would appear as 0 and TileType.Stone would appear as 1 in the file (well in byte form obviously). Loading in the file is alot different though because I can't just loop through all the bytes in the file cast them as a TileType and assign it:
for(int x = 0; x < size.X; x++) {
for(int y = 0; y < size.Y; y+) {
world[y, x].Type = (TileType)byteReader.ReadByte();
}
}
This just wont work presumably because I have to actually say world[y, x] = Tile.Stone as apposed to world[y, x].Type = TileType.Stone. In order to be able to say that I need a gigantic switch case statement (I only have 2 tiles but you could imagine what it would look like with hundreds):
Tile tile;
for(int x = 0; x < size.X; x++) {
for(int y = 0; y < size.Y; y+) {
switch(byteReader.ReadByte()){
case 0:
tile = Tile.Air;
break;
case 1:
tile = Tile.Stone;
break;
}
world[y, x] = tile;
}
}
Now you can see how unoptimized this is and I don't know what to do. I would really just like to cast the byte as a TileType and use that but as said before I have to say world[y, x] = Tile.whatever and TileType can't be used this way.
So what should I do? I would imagine I need to restructure my Tile class to fit the requirements but I don't know how I would do that. Please help!
Thanks.