Reputation: 23
I have a tile-based RPG system where a specific tile type is represented by a string (i.e. Grass = "g", Dirt = "d"). The problem is that I do not know how to represent a map (a group of tiles gathered in a specific order) in a way where each tile can be accessed by their x/y coordinates efficiently. Should the maps be represented in array format :
map[0].coords[x][y] = "g";
Or perhaps in some other way?
Upvotes: 0
Views: 390
Reputation: 5491
A two dimensional array is fine.
You can also use a one-dimensional array. Here's a snippet of Java code I have lying around:
char [] cells = new char[WORLD_WIDTH * WORLD_HEIGHT];
public char get(int x, int y) {
return cells[x + y * WORLD_WIDTH];
}
public void set(int x, int y, char c) {
cells[x + y * WORLD_WIDTH] = c;
}
Suppose your world is 10 by 10 tiles, then the first row is in cells[0]
to cells[9]
, the last row in cells[90]
to cells[99]
, and so on.
Of course, you may want to add additional checks to ensure that the x
and y
parameters are valid.
Upvotes: 0
Reputation: 3936
A few things, dependant on the language:
1: If possible, set constant integers for terrain type. Constants use less memory and are quicker to referance/retrieve, same with integers over strings
2: A two dimensional would probably be the most efficant way of doing it.
An example
CONST(INT) GRASS = 1;
CONST(INT) DIRT = 2;
CONST(INT) SNOW = 3;
// assuming map is an array containing objects, and coords is a 2d
// array of said object:
map[0].coords[x,y] = GRASS;
Upvotes: 2
Reputation: 20264
It depends on what language you are using, but a 2-dimensional array is usually an efficient way to do this.
Accessing elements in an array is usually quick because the position of a given element in memory can be calculated based on the array indexes provided, without having to iterate over other elements. Other data structures, (eg linked lists) are much slower for this type of retrieval.
Upvotes: 3