I have a Zoo (JPanel grid) full of animals (Arraylists). I wrote the nearBy(x, y) method to return the coordinates of any nearby animals in a 3x3 grid around X & Y, but realized my implementation would only cover 3 squares.
public int[] nearBy(int x, int y) {
int[] pair;
int[] grid = new int[]{-1,0,1};
for(int i; i>grid.size(); i++) {
if(z.at(grid[i],grid[i]).size()>=1) { //See At method in Zoo
return pair[] = new int[]{grid[i],grid[i]}
}
else{
return pair[] = new int[]{x, y};
}
}
}
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Zoo extends JPanel {
// zoo grid size
public static final int ZOO_ROWS = 30; // grid height
public static final int ZOO_COLS = 40; // grid width
// screen size is the zoo grid sizes * SCALE
public static final int SCALE = 30;
public static Random rand = new Random();
//
private int width, height;
private ArrayList<ArrayList<LinkedList<Entity>>> grid;
public Zoo(int w, int h) {
// initalize the grid using ArrayLists for the rows and colums and LinkedLists for the cell stack
grid = new ArrayList<>(h);
for(int y = 0; y < h; y++) {
ArrayList<LinkedList<Entity>> row = new ArrayList<>(w);
for(int x = 0; x < w; x++) {
row.add(new LinkedList<Entity>());
}
grid.add(row);
}
width = w;
height = h;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.GREEN);
// draw cell grids
g.setColor(new Color(0, 200, 0)); // dark green
for(int y = 0; y < height; y++) {
g.drawLine(0, y * SCALE, width * SCALE, y * SCALE);
}
for(int x = 0; x < width; x++) {
g.drawLine(x * SCALE, 0, x * SCALE, height * SCALE);
}
// draw Entities
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
for(Entity e : grid.get(y).get(x)) {
e.draw(g);
}
}
}
// get a list of Entities at position x, y in the grid
public ArrayList<Entity> at(int x, int y) {
int atX = wrap(x, width);
int atY = wrap(y, height);
// ArrayList constructor copies references from the passed LinkedList
return new ArrayList<Entity>(grid.get(atY).get(atX));
}
}
I've tried bruteforcing it with if statements, but it's clunky and inefficient.