forked from jzitnik/twodcraft
83 lines
2.5 KiB
Java
83 lines
2.5 KiB
Java
package cz.jzitnik.game.handlers.place;
|
|
|
|
import cz.jzitnik.game.Game;
|
|
import cz.jzitnik.game.annotations.BlockDropPercentage;
|
|
import cz.jzitnik.game.annotations.PlaceOnSolid;
|
|
import cz.jzitnik.game.annotations.ResetDataOnMine;
|
|
import cz.jzitnik.game.entities.Block;
|
|
|
|
import java.lang.reflect.Constructor;
|
|
import java.lang.reflect.InvocationTargetException;
|
|
import java.util.Random;
|
|
|
|
public class CustomAnnotationHandler implements CustomPlaceHandler {
|
|
private final Class<?> clazz;
|
|
private final DefaultPlaceHandler defaultPlaceHandler = new DefaultPlaceHandler();
|
|
|
|
public CustomAnnotationHandler(Class<?> clazz) {
|
|
this.clazz = clazz;
|
|
}
|
|
|
|
@Override
|
|
public boolean place(Game game, int x, int y) {
|
|
if (clazz.isAnnotationPresent(PlaceOnSolid.class)) {
|
|
return placeOnSolid(game, x, y);
|
|
}
|
|
|
|
return defaultPlaceHandler.place(game, x, y);
|
|
}
|
|
|
|
@Override
|
|
public boolean mine(Game game, int x, int y) {
|
|
if (clazz.isAnnotationPresent(ResetDataOnMine.class)) {
|
|
resetDataOnMine(game, x, y);
|
|
}
|
|
|
|
boolean drop = true;
|
|
|
|
if (clazz.isAnnotationPresent(BlockDropPercentage.class)) {
|
|
drop = blockDropPercentage(game, x, y);
|
|
}
|
|
|
|
defaultPlaceHandler.mine(game, x, y);
|
|
|
|
return drop;
|
|
}
|
|
|
|
private boolean blockDropPercentage(Game game, int x, int y) {
|
|
var annotation = clazz.getAnnotation(BlockDropPercentage.class);
|
|
int percentage = annotation.value();
|
|
|
|
Random random = new Random();
|
|
return random.nextInt(100) < percentage;
|
|
}
|
|
|
|
private boolean placeOnSolid(Game game, int x, int y) {
|
|
var blocksBottom = game.getWorld()[y + 1][x];
|
|
|
|
if (blocksBottom.stream().allMatch(Block::isGhost)) {
|
|
return false;
|
|
}
|
|
|
|
return defaultPlaceHandler.place(game, x, y);
|
|
}
|
|
|
|
private void resetDataOnMine(Game game, int x, int y) {
|
|
var blocks = game.getWorld()[y][x].stream().filter(i -> !i.getBlockId().equals("air")).toList();
|
|
|
|
for (Block block : blocks) {
|
|
if (block.getData() == null) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
Constructor<?> constructor = block.getData().getClass().getDeclaredConstructor();
|
|
Object object = constructor.newInstance();
|
|
block.setData(object);
|
|
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException |
|
|
InvocationTargetException _) {
|
|
}
|
|
}
|
|
}
|
|
}
|