Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 153
src/main/java/com/example/wanted/WantedMod.java
package com.example.wanted;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.AttackEntityCallback;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class WantedMod implements ModInitializer {
private static final int MAX_WANTED_LEVEL = 3;
private static final int TICKS_TO_ESCAPE = 1200;
private static final Map<UUID, WantedStatus> WANTED_PLAYERS = new HashMap<>();
@Override
public void onInitialize() {
AttackEntityCallback.EVENT.register(WantedMod::onAttackEntity);
ServerTickEvents.END_SERVER_TICK.register(WantedMod::tickServer);
}
private static InteractionResult onAttackEntity(Player player, Level level,
net.minecraft.world.InteractionHand hand,
net.minecraft.world.entity.Entity target,
net.minecraft.world.phys.EntityHitResult hitResult) {
if (!(level instanceof ServerLevel) || (target.getType() != EntityTypes.VILLAGER
&& target.getType() != EntityTypes.IRON_GOLEM)) {
return InteractionResult.PASS;
}
WantedStatus status = WANTED_PLAYERS.computeIfAbsent(player.getUUID(), ignored -> new WantedStatus());
status.level = Math.min(MAX_WANTED_LEVEL, status.level + 1);
status.ticksSinceCrime = 0;
return InteractionResult.PASS;
}
private static void tickServer(MinecraftServer server) {
Iterator<Map.Entry<UUID, WantedStatus>> iterator = WANTED_PLAYERS.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<UUID, WantedStatus> entry = iterator.next();
var player = server.getPlayerList().getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
WantedStatus status = entry.getValue();
if (status.copsSpawned < status.level && player.level() instanceof ServerLevel serverLevel) {
var cop = EntityTypes.IRON_GOLEM.create(serverLevel, EntitySpawnReason.COMMAND);
if (cop != null) {
cop.setPos(player.getX() + 8.0, player.getY(), player.getZ() + 8.0);
cop.setTarget(player);
if (serverLevel.addFreshEntity(cop)) {
status.copsSpawned++;
}
}
}
status.ticksSinceCrime++;
if (status.ticksSinceCrime >= TICKS_TO_ESCAPE) {
status.level--;
status.ticksSinceCrime = 0;
status.copsSpawned = Math.min(status.copsSpawned, status.level);
if (status.level == 0) {
iterator.remove();
}
}
}
}
private static final class WantedStatus {
private int level;
private int ticksSinceCrime;
private int copsSpawned;
}
}