Tilemaps are very useful for making game levels.
A tilemap is a 'map of tiles' of a level. Each type of tile is given a number.
For example, in a space where you want a wall, you can use the number 2. In a place where you want nothing to appear, you can use 0 (and most people do.)
A typical tilemap looks like this:
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 0 0 0 2
2 0 1 0 2 0 4 0 0 0 0 0 0 0 0 0 0 3 0 2
2 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0 2
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 2
2 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0 2
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 2
2 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 2
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
It's made for a 640*480px large window where each tiles are 32*32px large.
Save it as "level1.map" in your project folder.
Open your project and your c++ file.
Add the headers and namespace to the top of the project.
#include <iostream> #include <fstream> using namespace std;
Now we will make a function that reads the map file and load it into a global array.
int tile[20][15]; void load_tilemap(string filename) { ifstream map; map.open(filename.c_str()); for (int x=0;x<20;x++) { for (int y=0;y<15;y++) { int tiletype = 0; map >> tiletype; tile[x][y] = tiletype; } } }
In our main function we will call the function with the filename argument.
It is a void non-returning function, so everything have now been putted in the tile array.
In this example it will write the content of the tile array to the console window.
int main() { int count = 0; load_tilemap("level1.map"); for (int x=0;x<20;x++) { for (int y=0;y<15;y++) { count += 1; if (count < 20) { cout << tile[x][y] << " "; } else { cout << tile[x][y] << endl; count = 0; } } } return 0; }
But in your game, you would check the content of the tile and draw the correct tile on the screen.
Like this:
if (tile[x][y] == 1) { apply_surface(x*32,y*32,surface_player,surface_screen); }
| Categories: Tutorials |