How to elegantly load objects from a text file?

Started by
2 comments, last by armond 17 years, 5 months ago
Hi guys! I'm creating a classic shooter and right now I am really enjoying it. I have a text file that looks something like this... xxxxxxxxxxoooooxxwwwww wwwwwwwwxxxwwxxooooooo xxwwwwxwxwxwwwwooooooo that's just some random text up there. Each character represents a certain object. Like x could be enemy1, w being enemy2 and o as such background stuff... Now I still try to do anything like this... if (myChar == 'x') { //load object //add on some kind of List } if (myChar == 'w') { //load object //add on some kind of List } if (myChar == 'o') { //something else to do here... } ... ... ... and so on... Maybe there's some kind of pattern related to this? I don't know... Which is why I'm asking. How would you do this if you were me? Thank you!
We should never stop learning...
Advertisement
This could be made more elegant using the factory pattern.

On the other hand, if you don't have that many different kinds of objects, then
it easily can double or triple the amount of code needed.

What you didn't bring out was what language you are using. With C++ a factory can be pretty neatly implemented with a couple of templates.

-Riku
Well, assuming it wasn't a large job ahead,

I'd be going for a SWITCH statement!
wooO!

something like this would do the trick:

enum{
BLOCK_ENEMY = 'x',
BLOCK_WALL = 'W'
};

char blocktype = fgetc();

switch(blockType){
case BLOCK_ENEMY:

break;
case BLOCK_WALL:

break;
//You know, your normal switch statement ;)
}
Thank you guys! This thing I'm doing(in C++) is relatively small. But I better be prepared so the C++ factory would be a great idea. Thanks guys! :)
We should never stop learning...

This topic is closed to new replies.

Advertisement