Files
src
build.gradle
gradle.properties
settings.gradle
Code
11 226
src/main/java/dev/kodari/heartslots/HeartSlots.java
package dev.kodari.heartslots;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.entity.attribute.EntityAttributeInstance;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
public class HeartSlots implements ModInitializer {
public static final Identifier COST = Identifier.of("heartslots", "slot_cost");
public static int unlocked(PlayerEntity player) {
EntityAttributeInstance health = player.getAttributeInstance(EntityAttributes.MAX_HEALTH);
EntityAttributeModifier modifier = health == null ? null : health.getModifier(COST);
return Math.max(18, Math.min(36, 18 + (modifier == null ? 0 : (int) -modifier.value())));
}
public static boolean locked(PlayerEntity player, int index) {
return index >= unlocked(player) && index < 36;
}
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
CommandManager.literal("slots")
.executes(context -> {
ServerPlayerEntity player = context.getSource().getPlayerOrThrow();
context.getSource().sendFeedback(() -> Text.translatable("heartslots.status", unlocked(player)), false);
return 1;
})
.then(CommandManager.literal("buy").executes(context -> {
ServerPlayerEntity player = context.getSource().getPlayerOrThrow();
int count = unlocked(player);
if (count >= 36) {
context.getSource().sendError(Text.translatable("heartslots.full"));
return 0;
}
if (player.getMaxHealth() < 3.0f) {
context.getSource().sendError(Text.translatable("heartslots.health"));
return 0;
}
EntityAttributeInstance health = player.getAttributeInstance(EntityAttributes.MAX_HEALTH);
if (health == null) return 0;
health.removeModifier(COST);
health.addPersistentModifier(new EntityAttributeModifier(COST, -(count - 17), EntityAttributeModifier.Operation.ADD_VALUE));
player.setHealth(Math.min(player.getHealth(), player.getMaxHealth()));
context.getSource().sendFeedback(() -> Text.translatable("heartslots.bought", count + 1), false);
return 1;
}))
));
}
}