Representing a Hex Map in Java
Ok so I might just be missing something but I am trying to make a hex board map, like in civilizations. The idea is to have each hex as an object that has various properties(ie, color, type, etc). Then have a board of all these various hexes. There would be 3 board types, rectangle, circle, triangle.
The issue I am having is how to represent each hex in a data type. I figured a 2 dimensional array would be the way to go, which would be fine if I just needed to know the hex locations themselves. But I will need to know the vertexes and edges of each hex so that I can do things like on the edge between these to hexes add this. That is what is confusing me. How to represent each hex with all sides and points in an way in which I can ask for neighbors connected to that point or edge etc.
Any ideas, I have read many articles about this, but for some reason I still don't understand, maybe开发者_JAVA技巧 because it is all ideas and I have no clue hoe to implement it.
A 2-dimensional array would reinforce the concept of a rectangular grid.
Why not instead define a Cell
class, with references to the neighbouring cells thus:
public class Cell {
private Cell north;
private Cell south;
private Cell northWest;
// etc.
}
The references would be null for Cells
on the boundaries of your grid.
You'd have to construct the grid by iterating through the rows, creating each Cell
and tying it to its neighbours as appropriate.
You can use a class based on a 2D array, with some additional methods to compute neighbors.
In a standard array, cell E shares sides with B, D, F and H
+-----+-----+-----+
| | | |
| A | B* | C |
| | | |
+-----+-----+-----+
| | | |
| D* | *E* | F* |
| | | |
+-----+-----+-----+
| | | |
| G | H* | I |
| | | |
+-----+-----+-----+
If you imagine displacing alternate columns by half a cell;
+-----+ +-----+
| | | |
| A +-----+ C |
| | | |
+-----+ B* +-----+
| | | |
| D* +-----+ F* |
| | | |
+-----+ *E* +-----+
| | | |
| G* +-----+ I* |
| | | |
+-----+ H* +-----+
| |
+-----+
Now cell E shares sides with B, D, F, G H I. In fact, this arrangement is the same as for a hex grid - just with misshapen hexes. If my ASCII art skills were up to it, the squares could be redrawn as hexes.
You can't physically displace the grid, of course, but you can provide methods that control access to the grid and implement the neighbor cell calculations.
+-----+-----+-----+
| | | |
| A | B* | C | B = E - 1xRowLength
| | | | D = E - 1
+-----+-----+-----+ F = E + 1
| | | | G = E + 1xRowLength - 1
| D* | *E* | F* | H = E + 1xRowLength
| | | | I = E + 1xRowLength + 1
+-----+-----+-----+
| | | |
| G* | H* | I* |
| | | |
+-----+-----+-----+
hexGrid.listNeighbors(E) = B,D,F,G,H,I
hexGrid.NeighborAbove(E) = B
hexGrid.NeighborAboveLeft(E) = D
hexGrid.NeighborAboveRight(E) = F
hexGrid.NeighborBelowLeft(E) = G
hexGrid.NeighborBelowRight(E) = I
hexGrid.NeighborBelow(E) = H
etc
精彩评论