Files
src
build.gradle
gradle.properties
settings.gradle
Code
10 351
src/main/java/com/kodari/lifesteal/LifestealMod.java
package com.kodari.lifesteal;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.serialization.Codec;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.entity.event.v1.ServerEntityWorldChangeEvents;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents;
import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents;
import net.minecraft.datafixer.DataFixTypes;
import net.minecraft.entity.attribute.EntityAttributeInstance;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.Identifier;
import net.minecraft.world.PersistentState;
import net.minecraft.world.PersistentStateManager;
import net.minecraft.world.PersistentStateType;
import net.minecraft.world.World;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class LifestealMod implements ModInitializer {
public static final String MOD_ID = "lifesteal";
private static final int DEFAULT_HEARTS = 10;
private static final int MIN_HEARTS = 6;
private static final int MAX_HEARTS = 20;
private static final Identifier HEART_MODIFIER_ID = Identifier.of(MOD_ID, "permanent_hearts");
private static final RegistryKey<Item> HEART_KEY = RegistryKey.of(RegistryKeys.ITEM, Identifier.of(MOD_ID, "heart"));
private static final RegistryKey<ItemGroup> INGREDIENTS_GROUP = RegistryKey.of(
RegistryKeys.ITEM_GROUP, Identifier.of("minecraft", "ingredients")
);
public static final Item HEART = Registry.register(
Registries.ITEM, HEART_KEY, new HeartItem(new Item.Settings().registryKey(HEART_KEY))
);
private static final Codec<Map<String, Integer>> HEARTS_CODEC = Codec.unboundedMap(Codec.STRING, Codec.INT);
private static final PersistentStateType<HeartState> HEART_STATE_TYPE = new PersistentStateType<>(
MOD_ID + "_hearts",
HeartState::new,
HEARTS_CODEC.xmap(HeartState::new, state -> state.hearts),
DataFixTypes.SAVED_DATA_COMMAND_STORAGE
);
@Override
public void onInitialize() {
ItemGroupEvents.modifyEntriesEvent(INGREDIENTS_GROUP).register(entries -> entries.prepend(HEART));
ServerPlayerEvents.JOIN.register(LifestealMod::refreshPlayer);
ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> refreshPlayer(newPlayer));
ServerEntityWorldChangeEvents.AFTER_PLAYER_CHANGE_WORLD.register(
(player, origin, destination) -> refreshPlayer(player)
);
ServerLivingEntityEvents.AFTER_DEATH.register(LifestealMod::handlePlayerDeath);
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) ->
dispatcher.register(CommandManager.literal("withdraw")
.then(CommandManager.argument("amount", IntegerArgumentType.integer())
.executes(context -> withdraw(context.getSource(),
IntegerArgumentType.getInteger(context, "amount"))))));
}
private static void refreshPlayer(ServerPlayerEntity player) {
HeartState state = stateFor(player);
applyHeartAttribute(player, state.getHearts(player.getUuid()));
}
private static void handlePlayerDeath(LivingEntity entity, DamageSource damageSource) {
if (!(entity instanceof ServerPlayerEntity victim)
|| !(damageSource.getAttacker() instanceof ServerPlayerEntity killer)
|| victim == killer) {
return;
}
HeartState state = stateFor(killer);
int victimHearts = state.getHearts(victim.getUuid());
int killerHearts = state.getHearts(killer.getUuid());
boolean victimAtMinimum = victimHearts <= MIN_HEARTS;
boolean killerAtMaximum = killerHearts >= MAX_HEARTS;
if (victimAtMinimum) {
killer.sendMessage(Text.literal("This player has no hearts left to steal."));
}
if (killerAtMaximum) {
killer.sendMessage(Text.literal("You already have the maximum of 20 permanent hearts."));
}
if (victimAtMinimum || killerAtMaximum) {
return;
}
state.setHearts(victim.getUuid(), victimHearts - 1);
state.setHearts(killer.getUuid(), killerHearts + 1);
applyHeartAttribute(victim, victimHearts - 1);
applyHeartAttribute(killer, killerHearts + 1);
victim.sendMessage(Text.literal("You lost 1 permanent heart to " + killer.getName().getString() + "."));
killer.sendMessage(Text.literal("You stole 1 permanent heart. You now have " + (killerHearts + 1) + "."));
}
private static int withdraw(ServerCommandSource source, int amount) {
ServerPlayerEntity player = source.getPlayer();
if (player == null) {
source.sendFeedback(() -> Text.literal("Only players can withdraw hearts."), false);
return 0;
}
if (amount <= 0) {
player.sendMessage(Text.literal("The amount must be a positive whole number."));
return 0;
}
HeartState state = stateFor(player);
int hearts = state.getHearts(player.getUuid());
if (hearts - amount < MIN_HEARTS) {
player.sendMessage(Text.literal("You must keep at least 6 permanent hearts."));
return 0;
}
state.setHearts(player.getUuid(), hearts - amount);
applyHeartAttribute(player, hearts - amount);
int remaining = amount;
while (remaining > 0) {
int stackSize = Math.min(64, remaining);
player.getInventory().offerOrDrop(new ItemStack(HEART, stackSize));
remaining -= stackSize;
}
player.sendMessage(Text.literal("Withdrew " + amount + " permanent heart(s) as heart items."));
return 1;
}
private static void applyHeartAttribute(ServerPlayerEntity player, int hearts) {
EntityAttributeInstance maxHealth = player.getAttributeInstance(EntityAttributes.MAX_HEALTH);
if (maxHealth == null) {
return;
}
maxHealth.overwritePersistentModifier(new EntityAttributeModifier(
HEART_MODIFIER_ID,
(hearts - DEFAULT_HEARTS) * 2.0,
EntityAttributeModifier.Operation.ADD_VALUE
));
player.setHealth(Math.min(player.getHealth(), player.getMaxHealth()));
}
private static HeartState stateFor(ServerPlayerEntity player) {
ServerWorld world = (ServerWorld) player.getEntityWorld();
PersistentStateManager manager = world.getServer().getOverworld().getPersistentStateManager();
return manager.getOrCreate(HEART_STATE_TYPE);
}
private static final class HeartItem extends Item {
private HeartItem(Settings settings) {
super(settings);
}
@Override
public ActionResult use(World world, PlayerEntity user, Hand hand) {
if (world.isClient()) {
return ActionResult.SUCCESS;
}
if (!(user instanceof ServerPlayerEntity player)) {
return ActionResult.PASS;
}
HeartState state = stateFor(player);
int hearts = state.getHearts(player.getUuid());
if (hearts >= MAX_HEARTS) {
player.sendMessage(Text.literal("You already have the maximum of 20 permanent hearts."));
return ActionResult.FAIL;
}
state.setHearts(player.getUuid(), hearts + 1);
applyHeartAttribute(player, hearts + 1);
player.getStackInHand(hand).decrement(1);
player.sendMessage(Text.literal("You gained 1 permanent heart. You now have " + (hearts + 1) + "."));
return ActionResult.SUCCESS;
}
}
private static final class HeartState extends PersistentState {
private final Map<String, Integer> hearts;