Files
src
build.gradle
settings.gradle
Code
5 386
src/main/java/dev/kodari/timeplay/TimePlayPlugin.java
package dev.kodari.timeplay;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import com.mojang.brigadier.arguments.LongArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandSource;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.argument;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal;
public final class TimePlayPlugin implements ClientModInitializer {
private final TimeController timeController = new TimeController();
@Override
public void onInitializeClient() {
ServerTickEvents.END_SERVER_TICK.register(timeController::tick);
ServerLifecycleEvents.SERVER_STOPPING.register(timeController::shutdown);
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> registerCommands(dispatcher));
}
private void registerCommands(CommandDispatcher<net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource> dispatcher) {
dispatcher.register(literal("timeplay")
.executes(context -> sendUsage())
.then(literal("set")
.then(argument("time", StringArgumentType.word())
.executes(context -> setTime(StringArgumentType.getString(context, "time"), null))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> setTime(StringArgumentType.getString(context, "time"), StringArgumentType.getString(context, "world"))))))
.then(literal("add")
.then(argument("ticks", LongArgumentType.longArg())
.executes(context -> addTime(LongArgumentType.getLong(context, "ticks"), null))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> addTime(LongArgumentType.getLong(context, "ticks"), StringArgumentType.getString(context, "world"))))))
.then(literal("freeze")
.executes(context -> changeFreeze(null, true))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> changeFreeze(StringArgumentType.getString(context, "world"), true))))
.then(literal("resume")
.executes(context -> changeFreeze(null, false))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> changeFreeze(StringArgumentType.getString(context, "world"), false))))
.then(literal("rate")
.then(argument("rate", DoubleArgumentType.doubleArg(0.1, 100.0))
.executes(context -> setRate(DoubleArgumentType.getDouble(context, "rate"), null))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> setRate(DoubleArgumentType.getDouble(context, "rate"), StringArgumentType.getString(context, "world"))))))
.then(literal("status")
.executes(context -> showStatus(null))
.then(argument("world", StringArgumentType.greedyString())
.suggests((context, builder) -> suggestWorlds(builder))
.executes(context -> showStatus(StringArgumentType.getString(context, "world"))))));
}
private int setTime(String value, String worldName) {
Long requestedTime = parseTime(value);
if (requestedTime == null) {
message("Укажи число тиков или время: day, noon, sunset, night, midnight, sunrise.");
return 0;
}
long time = Math.floorMod(requestedTime, 24000L);
withWorld(worldName, world -> {
long newTime = world.getTimeOfDay() + Math.floorMod(time - world.getTimeOfDay(), 24000L);
world.setTimeOfDay(newTime);
message("Время в мире " + world.getRegistryKey().getValue() + " установлено на " + time + " тиков.");
});
return 1;
}
private int addTime(long amount, String worldName) {
withWorld(worldName, world -> {
world.setTimeOfDay(world.getTimeOfDay() + amount);
message("Время в мире " + world.getRegistryKey().getValue() + " изменено. Сейчас: "
+ Math.floorMod(world.getTimeOfDay(), 24000L) + " тиков.");
});
return 1;
}
private int changeFreeze(String worldName, boolean freeze) {
withWorld(worldName, world -> {
if (freeze) {
timeController.freeze(world);
message("Время в мире " + world.getRegistryKey().getValue() + " остановлено.");
} else if (timeController.resume(world)) {
message("Ход времени в мире " + world.getRegistryKey().getValue() + " возобновлён.");
} else {
message("Время в мире " + world.getRegistryKey().getValue() + " уже идёт в обычном режиме.");
}
});
return 1;
}
private int setRate(double rate, String worldName) {
withWorld(worldName, world -> {
timeController.setRate(world, rate);
message("Скорость времени в мире " + world.getRegistryKey().getValue() + ": " + rate + "x.");
});
return 1;
}
private int showStatus(String worldName) {
withWorld(worldName, world -> {
String state = timeController.isFrozen(world) ? "остановлено" : "идёт";
message("Время мира " + world.getRegistryKey().getValue() + ": "
+ Math.floorMod(world.getTimeOfDay(), 24000L) + " тиков; состояние: " + state
+ "; скорость: " + timeController.getRate(world) + "x.");
});
return 1;
}
private void withWorld(String worldName, Consumer<ServerWorld> action) {
MinecraftClient client = MinecraftClient.getInstance();
MinecraftServer server = client.getServer();
if (server == null) {
message("TimePlay управляет временем только в одиночном мире с клиентским модом.");
return;
}
RegistryKey<World> worldKey;
if (worldName == null) {
if (client.world == null) {
message("Сначала войди в мир.");
return;
}
worldKey = client.world.getRegistryKey();
} else {
Identifier identifier = Identifier.tryParse(worldName);
if (identifier == null) {
message("Неверный ID мира: " + worldName);
return;
}
worldKey = RegistryKey.of(RegistryKeys.WORLD, identifier);
}
RegistryKey<World> requestedWorldKey = worldKey;
server.execute(() -> {
ServerWorld world = server.getWorld(requestedWorldKey);
if (world == null) {
message("Мир " + worldName + " не найден или не загружен.");
return;
}
action.accept(world);
});
}
private Long parseTime(String value) {
switch (value.toLowerCase(Locale.ROOT)) {
case "day" -> { return 1000L; }
case "noon" -> { return 6000L; }
case "sunset" -> { return 12000L; }
case "night" -> { return 13000L; }
case "midnight" -> { return 18000L; }
case "sunrise" -> { return 23000L; }
default -> {
try {
return Long.parseLong(value);
} catch (NumberFormatException exception) {
return null;
}
}
}
}
private int sendUsage() {
message("Команды: /timeplay set <day|noon|sunset|night|midnight|sunrise|тики> [мир]; "
+ "add <тики> [мир]; freeze|resume [мир]; rate <0.1-100> [мир]; status [мир].");
return 1;
}
private static CompletableFuture<Suggestions> suggestWorlds(SuggestionsBuilder builder) {
MinecraftServer server = MinecraftClient.getInstance().getServer();
if (server == null) {
return builder.buildFuture();
}
return CommandSource.suggestMatching(server.getWorlds().stream()
.map(world -> world.getRegistryKey().getValue().toString()), builder);