I'm coding from scratch a small experimental game on a medium-sized random rectangular square tile map. (Say, a map of a dungeon.)
There are several types of tiles (for example: floor, wall, monster, boss, treasure, player etc.). There are no extra information stored in the map tiles, just tile type.
Most parts of map are randomly generated. However there are several features that are to appear on every generated map in pre-set places. Say, walls around the dungeon, boss locations, player spawn point and the treasure.
Note: Since the game is small, coded for fun, and the only game designer is a programmer (that is, me myself), I do not plan to spend resources on coding a level editor or supporting an existing one. Also, I do not plan to support existing tile map libraries as I want to dig into some of the related coding problems myself (see above about fun), but I be happy happily to look at relevant existing code as a reference.
When I look at my map generation code, I find it rather ugly.
Is there an elegant way to deal with the problem? If that matters, I'm writing this game in JavaScript, but I will be happy to see a relevant reference in any programming language.
Here is a partial pseudocode to illustrate how my current tile generator solution looks like:
this.init = function(w, h) {
this.w = w;
this.h = h;
this.tile_presets_ = { };
var mid_h = Math.floor(h / 2);
var quarter_w = Math.floor(w / 4);
/* Here is the part I don't like -- a set of generator rules: */
this.preset_col_(0, Tile.GRASS);
this.preset_tile_(0, mid_h, Tile.FLOOR);
this.preset_col_(1, Tile.GRASS);
this.preset_tile_(1, mid_h, Tile.FLOOR);
this.preset_col_(2, Tile.WALL);
this.preset_tile_(2, mid_h, Tile.FLOOR);
this.preset_tile_(2, mid_h, Tile.PLAYER);
this.preset_tile_(1 * quarter_w, mid_h, Tile.BOSS);
this.preset_tile_(2 * quarter_w, mid_h, Tile.BOSS);
this.preset_tile_(3 * quarter_w, mid_h_, Tile.TREASURE);
this.preset_col_(w - 1, Tile.WALL);
};
Implementation details that may help to understand the code above:
this.tile = function(x, y) {
var preset = this.tile_presets_[x + y * this.w];
if (preset !== undefined) {
return preset;
}
return this.random_tile_();
};
this.preset_tile_ = function(x, y, tile) {
this.tile_presets_[x + y * this.w] = tile;
};
this.preset_col_ = function(x, tile) {
for (var y = 0; y < this.h; ++y) {
this.preset_tile_(x, y, tile);
}
};
Note that I shown a rather simple set of generator rules above. Actual thing is several times longer.
I hate that the code looks imperative — and it is hard to figure out what is going on from the first glance. I think that declarative approach could help. But so far I can't figure out a good solution.
Any clues?