Developing a tile based game, I needed a function to get the adjacent nodes to a certain node, this is what I finally came up with:
- Node[] getAdjacentNodes(int range, int offset) {
- int numberOfNodes = int(pow((1 + 2*range), 2) - 1 - (pow((1 + 2*offset), 2) - 1));
- Node[] nodes = new Node[numberOfNodes];
- for (int i = -range; i < range; i++) {
- for (int j = -range; j < range; j++) {
- if (abs(i) > offset && abs(j) > offset) { // dont select nodes within the given offset...
- if (this.x + i > 0 && this.x + i < game.cols && this.y + j > 0 && this.y + j < game.rows) { // prevent trying to access not existing nodes
- nodes = (Node[])append(nodes, game.terrain[this.x + i][this.y + j]);
- }
- }
- }
- }
- return nodes;
- }
This is a function inside the Node-class (basically consisting out of a x and a y var); game.terrain is the 2D array storing the map, range = 1 selects the 8 nodes around, range = 2 selects the 8 nodes around AND the 16 nodes around around, with offset = 1 and range = 2, only the 16 nodes around around would be selected
When I call the function like
- Node[] nodes = game.terrain[4][4].getAdjacentNodes(1, 0);
and output it, there's this:
[0] null[1] null[2] null[3] null[4] null[5] null[6] null[7] null[8] game_js$Node@3aff84
first of all: I don't understand why there are 9 elements (around a certain node there are only 8...), the formular for numberOfNodes works perfectly
secondly: why are 8 out of 9 elements null?
1