How to find all the blocks in a circle, in a grid, fficently?
I am trying to create a server plugin for the popular Indie game Minecraft. What I have so far is a non recursive method of finding al开发者_StackOverflow社区l the blocks 2 spaces away from the player's location. I am looking to create a method to do this efficently. I would like to be able to specify a distance. Here is what I have currently:
Block b = player.getLocation().getBlock();
b.getRelative(BlockFace.NORTH).getRelative(BlockFace.NORTH).setType(Material.FIRE);
b.getRelative(BlockFace.NORTH).getRelative(BlockFace.EAST).setType(Material.FIRE);
b.getRelative(BlockFace.EAST).getRelative(BlockFace.EAST).setType(Material.FIRE);
b.getRelative(BlockFace.EAST).getRelative(BlockFace.SOUTH).setType(Material.FIRE);
b.getRelative(BlockFace.WEST).getRelative(BlockFace.WEST).setType(Material.FIRE);
b.getRelative(BlockFace.SOUTH).getRelative(BlockFace.SOUTH).setType(Material.FIRE);
b.getRelative(BlockFace.SOUTH).getRelative(BlockFace.WEST).setType(Material.FIRE);
b.getRelative(BlockFace.NORTH).getRelative(BlockFace.WEST).setType(Material.FIRE);
Could you help me out? Thank you.
If I understand rightly for problem, you need a non-recursive algorithm to find all points on a 2D square grid at a given Manhattan distance d
from the origin. Those points lie on a tiled square, and they can easily be generated in sequence. For example:
public class Points {
public static void points(int d) {
int px = d;
int py = 0;
int dx = -1, dy = 1;
int n = d * 4;
for( int i = 0; i < n; i++ ) {
if( px == d && dx > 0 ) dx = -1;
else if( px == -d && dx < 0 ) dx = 1;
if( py == d && dy > 0 ) dy = -1;
else if( py == -d && dy < 0 ) dy = 1;
px += dx;
py += dy;
doSomething(px, py);
}
}
private static void doSomething(int px, int py) {
System.out.printf("(%2d,%2d)\n", px, py);
// do whatever you need
}
public static void main(String[] args) {
points(2);
}
}
This prints
( 1, 1)
( 0, 2)
(-1, 1)
(-2, 0)
(-1,-1)
( 0,-2)
( 1,-1)
( 2, 0)
You only need to code inside doSomething()
your action, according to the passed coordinates.
精彩评论