Greg Baldcock
📎 1 file 11,808 chars
📄
pasted-code-1791879104695.txt
txt 331 lines
▶
from pathlib import Path
import json
import textwrap

ROOT = Path("Timebound")

FILES = {
    "settings.gradle": r"""
pluginManagement {
    repositories {
        maven { url = 'https://maven.fabricmc.net/' }
        gradlePluginPortal()
        mavenCentral()
    }
}
rootProject.name = 'Timebound'
""",
    "gradle.properties": r"""
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
minecraft_version=1.21.11
loader_version=0.18.1
fabric_version=0.141.1+1.21.11
loom_version=1.14-SNAPSHOT
mod_version=1.0.0
maven_group=com.timebound
archives_base_name=timebound
""",
    "build.gradle": r"""
plugins {
    id 'net.fabricmc.fabric-loom-remap' version "${loom_version}"
}

version = project.mod_version
group = project.maven_group

base {
    archivesName = project.archives_base_name
}

repositories {
    mavenCentral()
}

dependencies {
    minecraft "com.mojang:minecraft:${minecraft_version}"
    mappings loom.officialMojangMappings()
    modImplementation "net.fabricmc:fabric-loader:${loader_version}"
    modImplementation "net.fabricmc.fabric-api:fabric-api:${fabric_version}"
}

processResources {
    inputs.property 'version', project.version
    filesMatching('fabric.mod.json') {
        expand 'version': project.version
    }
}

tasks.withType(JavaCompile).configureEach {
    options.release = 21
    options.encoding = 'UTF-8'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
    withSourcesJar()
}
""",
    "src/main/resources/fabric.mod.json": r"""
{
  "schemaVersion": 1,
  "id": "timebound",
  "version": "${version}",
  "name": "Timebound",
  "description": "Lifetime is your most valuable resource.",
  "authors": ["Timebound"],
  "license": "MIT",
  "environment": "*",
  "entrypoints": {
    "main": ["com.timebound.Timebound"]
  },
  "depends": {
    "fabricloader": ">=0.18.1",
    "minecraft": "~1.21.11",
    "java": ">=21",
    "fabric-api": "*"
  }
}
""",
    "src/main/java/com/timebound/Timebound.java": r"""
package com.timebound;

import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.WorldSavePath;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.argument.EntityArgumentType.player;

public class Timebound implements ModInitializer {
    public static final String MOD_ID = "timebound";
    private static final long HOUR = 3600L;
    private static final long START_TIME = 48L * HOUR;
    private static final long MAX_TIME = 1000L * HOUR;

    private static final Map TIMES =
        new ConcurrentHashMap<>();
    private static final Map NAMES =
        new ConcurrentHashMap<>();

    private static Path dataFile;
    private static long ticks;

    @Override
    public void onInitialize() {
        ServerLifecycleEvents.SERVER_STARTED.register(server -> load(server));
        ServerLifecycleEvents.SERVER_STOPPING.register(server -> save());

        ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
            ServerPlayerEntity p = handler.getPlayer();
            TIMES.putIfAbsent(p.getUuid(), START_TIME);
            NAMES.put(p.getUuid(), p.getName().getString());
            p.sendMessage(Text.literal(
                "Timebound: " + format(get(p.getUuid()))), false);
            save();
        });

        ServerTickEvents.END_SERVER_TICK.register(server -> {
            ticks++;
            if (ticks % 20 == 0) {
                for (ServerPlayerEntity p :
                        server.getPlayerManager().getPlayerList()) {
                    TIMES.putIfAbsent(p.getUuid(), START_TIME);
                    NAMES.put(p.getUuid(), p.getName().getString());
                    if (get(p.getUuid()) > 0) {
                        change(p.getUuid(), -1);
                    }
                }
            }
            if (ticks % 200 == 0) save();
        });

        CommandRegistrationCallback.EVENT.register(
            (dispatcher, registryAccess, environment) -> {
                dispatcher.register(literal("time").executes(ctx -> {
                    ServerPlayerEntity p =
                        ctx.getSource().getPlayerOrThrow();
                    long seconds = get(p.getUuid());
                    p.sendMessage(Text.literal(
                        "TIME " + format(seconds)), false);
                    p.sendMessage(Text.literal(
                        "TIER " + tier(seconds)), false);
                    return 1;
                }));

                dispatcher.register(literal("givetime")
                    .requires(src -> src.hasPermissionLevel(2))
                    .then(argument("player", player())
                    .then(argument("hours",
                        com.mojang.brigadier.arguments.LongArgumentType
                            .longArg(1, 1000))
                    .executes(ctx -> {
                        ServerPlayerEntity target =
                            player().getPlayer(ctx.getSource(), "player");
                        long hours =
                            com.mojang.brigadier.arguments.LongArgumentType
                                .getLong(ctx, "hours");
                        change(target.getUuid(), hours * HOUR);
                        save();
                        target.sendMessage(Text.literal(
                            "You received " + hours + " hours."), false);
                        ctx.getSource().sendFeedback(
                            () -> Text.literal("Lifetime granted."), true);
                        return 1;
                    }))));

                dispatcher.register(literal("timeleaderboard")
                    .executes(ctx -> {
                        var entries = TIMES.entrySet().stream()
                            .sorted(Map.Entry.comparingByValue()
                                .reversed())
                            .limit(10).toList();
                        ctx.getSource().sendFeedback(
                            () -> Text.literal("=== TIMEBOUND LEADERBOARD ==="),
                            false);
                        int rank = 1;
                        for (var e : entries) {
                            String line = "#" + rank++ + " "
                                + NAMES.getOrDefault(e.getKey(), "Unknown")
                                + " | " + format(e.getValue())
                                + " | " + tier(e.getValue());
                            ctx.getSource().sendFeedback(
                                () -> Text.literal(line), false);
                        }
                        return entries.size();
                    }));
            });
    }

    private static long get(UUID id) {
        return TIMES.getOrDefault(id, START_TIME);
    }

    private static synchronized void change(UUID id, long delta) {
        long current = get(id);
        long result;
        try {
            result = Math.addExact(current, delta);
        } catch (ArithmeticException e) {
            result = delta > 0 ? MAX_TIME : 0;
        }
        TIMES.put(id, Math.max(0, Math.min(MAX_TIME, result)));
    }

    private static String tier(long seconds) {
        if (seconds < HOUR) return "FRACTURED";
        if (seconds < 12 * HOUR) return "UNSTABLE";
        if (seconds < 72 * HOUR) return "STABLE";
        if (seconds < 168 * HOUR) return "ENHANCED";
        if (seconds < 500 * HOUR) return "ASCENDANT";
        return "CHRONOLORD";
    }

    private static String format(long seconds) {
        return String.format("%02dh %02dm %02ds",
            seconds / 3600, (seconds % 3600) / 60, seconds % 60);
    }

    private static synchronized void load(MinecraftServer server) {
        dataFile = server.getSavePath(WorldSavePath.ROOT)
            .resolve("timebound.properties");
        TIMES.clear();
        NAMES.clear();
        Properties props = new Properties();

        if (Files.exists(dataFile)) {
            try (InputStream in = Files.newInputStream(dataFile)) {
                props.load(in);
            } catch (IOException e) {
                throw new IllegalStateException(
                    "Cannot load Timebound data", e);
            }
        }

        for (String key : props.stringPropertyNames()) {
            try {
                if (key.startsWith("time.")) {
                    TIMES.put(UUID.fromString(key.substring(5)),
                        Math.max(0, Math.min(MAX_TIME,
                            Long.parseLong(props.getProperty(key)))));
                } else if (key.startsWith("name.")) {
                    NAMES.put(UUID.fromString(key.substring(5)),
                        props.getProperty(key));
                }
            } catch (IllegalArgumentException ignored) {
                // Ignore invalid save entries.
            }
        }
        ticks = 0;
    }

    private static synchronized void save() {
        if (dataFile == null) return;
        Properties props = new Properties();
        TIMES.forEach((id, time) ->
            props.setProperty("time." + id, time.toString()));
        NAMES.forEach((id, name) ->
            props.setProperty("name." + id, name));

        try {
            Files.createDirectories(dataFile.getParent());
            try (OutputStream out = Files.newOutputStream(dataFile)) {
                props.store(out, "Timebound player lifetime");
            }
        } catch (IOException e) {
            throw new IllegalStateException(
                "Cannot save Timebound data", e);
        }
    }
}
""",
    "src/main/resources/assets/timebound/lang/en_us.json": r"""
{
  "key.category.timebound": "Timebound",
  "block.timebound.time_bank": "Time Bank",
  "item.timebound.time_crystal": "Time Crystal",
  "item.timebound.lesser_crystal": "Lesser Time Crystal",
  "item.timebound.greater_crystal": "Greater Time Crystal",
  "item.timebound.ancient_crystal": "Ancient Time Crystal"
}
""",
    "LICENSE": r"""
MIT License

Copyright (c) 2026 Timebound contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
"""
}

for relative, contents in FILES.items():
    path = ROOT / relative
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(textwrap.dedent(contents).lstrip(), encoding="utf-8")

print(f"Created project at: {ROOT.resolve()}")
print("Next: install Java 21 and Gradle, then run the build commands.")
Kodari AI
KodariOct 13 at 8:26 am 2
Timebound
A Minecraft Fabric mod where player lifetime is a finite resource. Each player starts with 48 hours and loses one second per real second online. Players can check their remaining time, tier status, and leaderboard rankings via commands. Admins can grant additional hours. Time is persisted to a properties file in the world save directory, surviving server restarts. The mod features six lifetime tiers from FRACTURED to CHRONOLORD, with time capped at 1000 hours. Includes localization files for future item and block additions like Time Crystals and a Time Bank.
  1. Create the Fabric 1.21.11 project files with Yarn mappings and current dependency versions.

  2. Implement the attached Timebound mechanics and commands against verified 1.21.11 APIs.

  3. Add the mod metadata, language file, and license.

Created the Timebound Fabric 1.21.11 project with Yarn mappings and split source sets. Players start with 48 hours; their time decreases while online and is saved in the world’s timebound.properties file.

Commands: /time shows remaining time and tier, /givetime <player> <hours> grants time to admins, and /timeleaderboard lists the top players. No items or blocks were added.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
LICENSE
settings.gradle
Code
7 289
src/main/java/com/timebound/Timebound.java
package com.timebound;

import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.WorldSavePath;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import static com.mojang.brigadier.arguments.LongArgumentType.getLong;
import static com.mojang.brigadier.arguments.LongArgumentType.longArg;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
import static net.minecraft.command.argument.EntityArgumentType.player;

public class Timebound implements ModInitializer {
    public static final String MOD_ID = "timebound";
    private static final long HOUR = 3600L;
    private static final long START_TIME = 48L * HOUR;
    private static final long MAX_TIME = 1000L * HOUR;

    private static final Map<UUID, Long> TIMES = new ConcurrentHashMap<>();
    private static final Map<UUID, String> NAMES = new ConcurrentHashMap<>();

    private static Path dataFile;
    private static long ticks;

    @Override
    public void onInitialize() {
        ServerLifecycleEvents.SERVER_STARTED.register(Timebound::load);
        ServerLifecycleEvents.SERVER_STOPPING.register(server -> save());

        ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
            ServerPlayerEntity player = handler.player;
            TIMES.putIfAbsent(player.getUuid(), START_TIME);
            NAMES.put(player.getUuid(), player.getName().getString());
            player.sendMessage(Text.literal("Timebound: " + format(get(player.getUuid()))), false);
            save();
        });

        ServerTickEvents.END_SERVER_TICK.register(server -> {
            ticks++;
            if (ticks % 20 == 0) {
                for (ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
                    TIMES.putIfAbsent(player.getUuid(), START_TIME);
                    NAMES.put(player.getUuid(), player.getName().getString());
                    if (get(player.getUuid()) > 0) {
                        change(player.getUuid(), -1);
                    }
                }
            }
            if (ticks % 200 == 0) {
                save();
            }
        });

        CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
            dispatcher.register(literal("time").executes(context -> {
                ServerPlayerEntity player = context.getSource().getPlayerOrThrow();
                long seconds = get(player.getUuid());
                player.sendMessage(Text.literal("TIME " + format(seconds)), false);
                player.sendMessage(Text.literal("TIER " + tier(seconds)), false);
                return 1;
            }));

            dispatcher.register(literal("givetime")
                .requires(source -> CommandManager.ADMINS_CHECK.allows(source.getPermissions()))
                .then(argument("player", player())
                    .then(argument("hours", longArg(1, 1000))
                        .executes(context -> {
                            ServerPlayerEntity target = EntityArgumentType.getPlayer(context, "player");
                            long hours = getLong(context, "hours");
                            change(target.getUuid(), hours * HOUR);
                            save();
                            target.sendMessage(Text.literal("You received " + hours + " hours."), false);
                            context.getSource().sendFeedback(() -> Text.literal("Lifetime granted."), true);
                            return 1;
                        }))));

            dispatcher.register(literal("timeleaderboard").executes(context -> {
                var entries = TIMES.entrySet().stream()
                    .sorted(Map.Entry.<UUID, Long>comparingByValue().reversed())
                    .limit(10)
                    .toList();
                context.getSource().sendFeedback(() -> Text.literal("=== TIMEBOUND LEADERBOARD ==="), false);
                int rank = 1;
                for (var entry : entries) {
                    String line = "#" + rank++ + " "
                        + NAMES.getOrDefault(entry.getKey(), "Unknown")
                        + " | " + format(entry.getValue())
                        + " | " + tier(entry.getValue());
                    context.getSource().sendFeedback(() -> Text.literal(line), false);
                }
                return entries.size();
            }));
        });
    }

    private static long get(UUID id) {
        return TIMES.getOrDefault(id, START_TIME);
    }

    private static synchronized void change(UUID id, long delta) {
        long current = get(id);
        long result;
        try {
            result = Math.addExact(current, delta);
        } catch (ArithmeticException exception) {
            result = delta > 0 ? MAX_TIME : 0;
        }
        TIMES.put(id, Math.max(0, Math.min(MAX_TIME, result)));
    }

    private static String tier(long seconds) {
        if (seconds < HOUR) return "FRACTURED";
        if (seconds < 12 * HOUR) return "UNSTABLE";
        if (seconds < 72 * HOUR) return "STABLE";
        if (seconds < 168 * HOUR) return "ENHANCED";
        if (seconds < 500 * HOUR) return "ASCENDANT";
        return "CHRONOLORD";
    }

    private static String format(long seconds) {
        return String.format("%02dh %02dm %02ds",
            seconds / 3600, (seconds % 3600) / 60, seconds % 60);
    }

    private static synchronized void load(MinecraftServer server) {
        dataFile = server.getSavePath(WorldSavePath.ROOT).resolve("timebound.properties");
        TIMES.clear();
        NAMES.clear();
        Properties properties = new Properties();

        if (Files.exists(dataFile)) {
            try (InputStream input = Files.newInputStream(dataFile)) {
                properties.load(input);
            } catch (IOException exception) {
                throw new IllegalStateException("Cannot load Timebound data", exception);
            }
        }

        for (String key : properties.stringPropertyNames()) {
            try {
                if (key.startsWith("time.")) {
                    TIMES.put(UUID.fromString(key.substring(5)),
                        Math.max(0, Math.min(MAX_TIME, Long.parseLong(properties.getProperty(key)))));
                } else if (key.startsWith("name.")) {
                    NAMES.put(UUID.fromString(key.substring(5)), properties.getProperty(key));
                }
            } catch (IllegalArgumentException ignored) {
            }
        }
        ticks = 0;
    }

    private static synchronized void save() {
        if (dataFile == null) return;
        Properties properties = new Properties();
        TIMES.forEach((id, time) -> properties.setProperty("time." + id, time.toString()));
        NAMES.forEach((id, name) -> properties.setProperty("name." + id, name));

        try {
            Files.createDirectories(dataFile.getParent());
            try (OutputStream output = Files.newOutputStream(dataFile)) {
                properties.store(output, "Timebound player lifetime");
            }
        } catch (IOException exception) {
            throw new IllegalStateException("Cannot save Timebound data", exception);
        }
    }
}