Skip to content

Instantly share code, notes, and snippets.

@Maxopoly
Created March 30, 2018 03:42
Show Gist options
  • Save Maxopoly/a1139d54e4660ea16e015595d2b2215b to your computer and use it in GitHub Desktop.
Save Maxopoly/a1139d54e4660ea16e015595d2b2215b to your computer and use it in GitHub Desktop.
package com.github.maxopoly.WPCommon.model.areagrid;
public class AreaGrid <E extends AreaGridElement> implements AreaGridElement{
private int x;
private int z;
private int elementSize;
private AreaGridElement [] [] elements;
public AreaGrid(int x, int z,int length,int elementSize) {
this.x = x;
this.z = z;
this.elementSize = elementSize;
int amount = length / elementSize;
this.elements = new AreaGridElement [amount] [amount];
}
public void put(AreaGridElement element, int eleX, int eleZ) {
if (isLowestLevel()) {
elements [eleX - x] [eleZ - z] = element;
}
else {
int xPos = (eleX - x) / elementSize;
int zPos = (eleZ - z) / elementSize;
@SuppressWarnings("unchecked")
AreaGrid <E> sect = (AreaGrid <E>) elements [xPos] [zPos];
if (sect == null) {
sect = new AreaGrid <E>(xPos, zPos, elementSize, elementSize / elements.length);
elements [xPos] [zPos] = sect;
}
sect.put(element, eleX, eleZ);
}
}
@SuppressWarnings("unchecked")
public E get(int eleX, int eleZ) {
if (isLowestLevel()) {
return (E) elements [eleX - x] [eleZ - z];
}
else {
AreaGrid <E> sect = (AreaGrid <E>) elements [(eleX - x) / elementSize] [(eleZ - z) / elementSize];
if (sect == null) {
return null;
}
return sect.get(eleX, eleZ);
}
}
private boolean isLowestLevel() {
return elementSize == 1;
}
}
package com.github.maxopoly.WPCommon.model.areagrid;
public interface AreaGridElement {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment