From fb4719187abe82136643906ccf947ffd5c9e3a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Thu, 22 Aug 2024 22:45:00 +0200 Subject: feat: support translation to enable configuration of all mod strings. --- src/client/resources/assets/molehunt/lang/en_us.json | 15 +++++++++++++++ src/main/java/world/anhgelus/molehunt/Game.java | 18 +++++++++--------- src/main/java/world/anhgelus/molehunt/Molehunt.java | 16 +++++++++------- 3 files changed, 33 insertions(+), 16 deletions(-) create mode 100644 src/client/resources/assets/molehunt/lang/en_us.json diff --git a/src/client/resources/assets/molehunt/lang/en_us.json b/src/client/resources/assets/molehunt/lang/en_us.json new file mode 100644 index 0000000..d68fd0e --- /dev/null +++ b/src/client/resources/assets/molehunt/lang/en_us.json @@ -0,0 +1,15 @@ +{ + "commands.molehunt.stop.failed": "The Molehunt game has not been started yet.", + "commands.molehunt.timer.show": "Showing Molehunt timer.", + "commands.molehunt.timer.hide": "Hiding Molehunt timer.", + "commands.molehunt.moles.list": "List of moles:", + "commands.molehunt.stop.success": "The Molehunt game has been stopped.", + "molehunt.game.end.suspense.title": "And the winners are...", + "molehunt.game.end.winners.moles.title": "§cThe Moles!", + "molehunt.game.end.winners.survivors.title": "§aThe survivors!", + "molehunt.game.end.winners.subtitle": "The moles were", + "molehunt.game.start.suspense": "You are...", + "molehunt.game.start.mole.title": "§cThe Mole!", + "molehunt.game.start.mole.subtitle": "Get the list of moles with §6/molehunt moles", + "molehunt.game.start.survivor": "§aNot the Mole!" +} \ No newline at end of file diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index 9c3910b..c680a8f 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -53,7 +53,7 @@ public class Game { gamerules.get(GameRules.DO_IMMEDIATE_RESPAWN).set(true, server); gamerules.get(GameRules.DO_ENTITY_DROPS).set(false, server); - final var title = new TitleS2CPacket(Text.of("You are...")); + final var title = new TitleS2CPacket(Text.translatable("molehunt.game.start.suspense")); playerManager.getPlayerList().forEach(p -> { p.kill(); p.networkHandler.sendPacket(timing); @@ -69,10 +69,10 @@ public class Game { playerManager.getPlayerList().forEach(p -> { p.networkHandler.sendPacket(timing); if (moles.contains(p)) { - p.networkHandler.sendPacket(new TitleS2CPacket(Text.of("The Mole!"))); - p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.of("Get the list of moles with /molehunt moles"))); + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("molehunt.game.start.mole.title"))); + p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.translatable("molehunt.game.start.mole.subtitle"))); } else { - p.networkHandler.sendPacket(new TitleS2CPacket(Text.of("Not the Mole!"))); + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("molehunt.game.start.survivor"))); } // reset health and food level p.setHealth(p.getMaxHealth()); @@ -110,7 +110,7 @@ public class Game { } public void stop() { - server.getPlayerManager().broadcast(Text.of("Game stopped"), false); + server.getPlayerManager().broadcast(Text.translatable("commands.molehunt.stop.success"), false); end(); } @@ -119,7 +119,7 @@ public class Game { timer = new Timer(); started = false; final var pm = server.getPlayerManager(); - final var winnerSuspense = new TitleS2CPacket(Text.of("And the winners are...")); + final var winnerSuspense = new TitleS2CPacket(Text.translatable("molehunt.game.end.suspense.title")); pm.getPlayerList().forEach(p -> { p.networkHandler.sendPacket(timing); p.networkHandler.sendPacket(winnerSuspense); @@ -130,11 +130,11 @@ public class Game { public void run() { TitleS2CPacket winner; if (gameWonByMoles()) { - winner = new TitleS2CPacket(Text.of("The Moles!")); + winner = new TitleS2CPacket(Text.translatable("molehunt.game.end.winners.moles.title")); } else { - winner = new TitleS2CPacket(Text.of("The survivors!")); + winner = new TitleS2CPacket(Text.translatable("molehunt.game.end.winners.survivors.title")); } - pm.sendToAll(new SubtitleS2CPacket(Text.of("The moles were " + getMolesAsString()))); + pm.sendToAll(new SubtitleS2CPacket(Text.translatable("molehunt.game.end.winners.subtitle").append(getMolesAsString()))); pm.sendToAll(winner); pm.sendToAll(timing); } diff --git a/src/main/java/world/anhgelus/molehunt/Molehunt.java b/src/main/java/world/anhgelus/molehunt/Molehunt.java index 49e775d..b2d3842 100644 --- a/src/main/java/world/anhgelus/molehunt/Molehunt.java +++ b/src/main/java/world/anhgelus/molehunt/Molehunt.java @@ -1,6 +1,7 @@ package world.anhgelus.molehunt; import com.mojang.brigadier.Command; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; @@ -9,7 +10,7 @@ import net.fabricmc.fabric.api.message.v1.ServerMessageEvents; import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.text.*; import net.minecraft.world.GameMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,13 +45,13 @@ public class Molehunt implements ModInitializer { command.then(literal("timer").requires(ServerCommandSource::isExecutedByPlayer).then( literal("show").executes(context -> { timerVisibility.put(context.getSource().getPlayer(), true); - context.getSource().sendFeedback(() -> Text.of("Showing molehunt timer"), false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.timer.show"), false); var player = context.getSource().getPlayer(); assert player != null; if (game == null || !game.hasStarted()) { - player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of("§cGame has not started yet"))); + player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.translatable("commands.molehunt.stop.failed").setStyle(Style.EMPTY.withColor(16733525)))); } else { player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of(game.getShortRemainingText()))); } @@ -60,18 +61,19 @@ public class Molehunt implements ModInitializer { ).then( literal("hide").executes(context -> { timerVisibility.put(context.getSource().getPlayer(), false); - context.getSource().sendFeedback(() -> Text.of("Hiding molehunt timer"), false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.timer.hide"), false); return Command.SINGLE_SUCCESS; }) )); command.then(literal("moles").requires(source -> (game != null) && game.hasStarted() && game.isAMole(source.getPlayer())).executes(context -> { - context.getSource().sendFeedback(() -> Text.literal("List of moles: " + game.getMolesAsString()),false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.moles.list").append(" " + game.getMolesAsString()),false); return Command.SINGLE_SUCCESS; })); command.then(literal("stop").requires(source -> source.hasPermissionLevel(1)).executes(context -> { if (game == null || !game.hasStarted()) { - context.getSource().sendError(Text.of("Game has not started yet")); - return Command.SINGLE_SUCCESS; + var e = new SimpleCommandExceptionType(Text.translatable("commands.molehunt.stop.failed")); + + throw e.create(); } game.stop(); -- cgit v1.2.3 From c74eeb19ff9d8c6472588dc88fa672a764ec8078 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Thu, 22 Aug 2024 22:48:28 +0200 Subject: docs: add translation feature in readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 06c25bd..b3084ed 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Stop the game when every innocent is dead or when the timer ended (one hour and The moles can see the name of other moles with `/molehunt moles`. +You can configure every text with a resource pack (for reference, check out [the default lang file](src/client/resources/assets/molehunt/lang/en_us.json)). + ## Technologies - Java 21 -- cgit v1.2.3 From 06f970b1bdb370afd38d321ec6225f47b6cf3d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Thu, 22 Aug 2024 22:45:00 +0200 Subject: feat: support translation to enable configuration of all mod strings. --- .../resources/assets/molehunt/lang/en_us.json | 15 +++++++++++++ src/main/java/world/anhgelus/molehunt/Game.java | 26 +++++++++------------- .../java/world/anhgelus/molehunt/Molehunt.java | 16 +++++++------ 3 files changed, 34 insertions(+), 23 deletions(-) create mode 100644 src/client/resources/assets/molehunt/lang/en_us.json diff --git a/src/client/resources/assets/molehunt/lang/en_us.json b/src/client/resources/assets/molehunt/lang/en_us.json new file mode 100644 index 0000000..d68fd0e --- /dev/null +++ b/src/client/resources/assets/molehunt/lang/en_us.json @@ -0,0 +1,15 @@ +{ + "commands.molehunt.stop.failed": "The Molehunt game has not been started yet.", + "commands.molehunt.timer.show": "Showing Molehunt timer.", + "commands.molehunt.timer.hide": "Hiding Molehunt timer.", + "commands.molehunt.moles.list": "List of moles:", + "commands.molehunt.stop.success": "The Molehunt game has been stopped.", + "molehunt.game.end.suspense.title": "And the winners are...", + "molehunt.game.end.winners.moles.title": "§cThe Moles!", + "molehunt.game.end.winners.survivors.title": "§aThe survivors!", + "molehunt.game.end.winners.subtitle": "The moles were", + "molehunt.game.start.suspense": "You are...", + "molehunt.game.start.mole.title": "§cThe Mole!", + "molehunt.game.start.mole.subtitle": "Get the list of moles with §6/molehunt moles", + "molehunt.game.start.survivor": "§aNot the Mole!" +} \ No newline at end of file diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index bf0f294..1091c0f 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -7,7 +7,6 @@ import net.minecraft.network.packet.s2c.play.TitleS2CPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; -import net.minecraft.text.TextContent; import net.minecraft.world.GameMode; import net.minecraft.world.GameRules; import world.anhgelus.molehunt.utils.TimeUtils; @@ -35,10 +34,9 @@ public class Game { } public void start() { - if (started) return; final int n = (server.getCurrentPlayerCount() - server.getCurrentPlayerCount() % 4)/4; final var playerManager = server.getPlayerManager(); - final var players = new ArrayList<>(playerManager.getPlayerList()); + final var players = playerManager.getPlayerList(); for (int i = 0; i < n; i++) { final var r = ThreadLocalRandom.current().nextInt(0, players.size()); final var mole = players.get(r); @@ -71,10 +69,10 @@ public class Game { playerManager.getPlayerList().forEach(p -> { p.networkHandler.sendPacket(timing); if (moles.contains(p)) { - p.networkHandler.sendPacket(new TitleS2CPacket(Text.of("§cThe Mole!"))); - p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.of("§6get the list of moles with /molehunt moles"))); + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("molehunt.game.start.mole.title"))); + p.networkHandler.sendPacket(new SubtitleS2CPacket(Text.translatable("molehunt.game.start.mole.subtitle"))); } else { - p.networkHandler.sendPacket(new TitleS2CPacket(Text.of("§aNot the Mole!"))); + p.networkHandler.sendPacket(new TitleS2CPacket(Text.translatable("molehunt.game.start.survivor"))); } // reset health and food level p.setHealth(p.getMaxHealth()); @@ -112,7 +110,7 @@ public class Game { } public void stop() { - server.getPlayerManager().broadcast(Text.of("Game stopped"), false); + server.getPlayerManager().broadcast(Text.translatable("commands.molehunt.stop.success"), false); end(); } @@ -121,7 +119,7 @@ public class Game { timer = new Timer(); started = false; final var pm = server.getPlayerManager(); - final var winnerSuspense = new TitleS2CPacket(Text.of("§eAnd the winners are...")); + final var winnerSuspense = new TitleS2CPacket(Text.translatable("molehunt.game.end.suspense.title")); pm.getPlayerList().forEach(p -> { p.networkHandler.sendPacket(timing); p.networkHandler.sendPacket(winnerSuspense); @@ -132,11 +130,11 @@ public class Game { public void run() { TitleS2CPacket winner; if (gameWonByMoles()) { - winner = new TitleS2CPacket(Text.of("§cThe Moles!")); + winner = new TitleS2CPacket(Text.translatable("molehunt.game.end.winners.moles.title")); } else { - winner = new TitleS2CPacket(Text.of("§aNot the Mole!")); + winner = new TitleS2CPacket(Text.translatable("molehunt.game.end.winners.survivors.title")); } - pm.sendToAll(new SubtitleS2CPacket(Text.of("§6Moles were " + getMolesAsString()))); + pm.sendToAll(new SubtitleS2CPacket(Text.translatable("molehunt.game.end.winners.subtitle").append(getMolesAsString()))); pm.sendToAll(winner); pm.sendToAll(timing); } @@ -160,11 +158,7 @@ public class Game { } public String getMolesAsString() { - return moles.stream() - .map(ServerPlayerEntity::getDisplayName) - .filter(Objects::nonNull) - .map(Text::getString) - .collect(Collectors.joining(", ")); + return moles.stream().map(ServerPlayerEntity::getDisplayName).filter(Objects::nonNull).map(Text::toString).collect(Collectors.joining(", ")); } public boolean isAMole(ServerPlayerEntity player) { diff --git a/src/main/java/world/anhgelus/molehunt/Molehunt.java b/src/main/java/world/anhgelus/molehunt/Molehunt.java index 49e775d..b2d3842 100644 --- a/src/main/java/world/anhgelus/molehunt/Molehunt.java +++ b/src/main/java/world/anhgelus/molehunt/Molehunt.java @@ -1,6 +1,7 @@ package world.anhgelus.molehunt; import com.mojang.brigadier.Command; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents; @@ -9,7 +10,7 @@ import net.fabricmc.fabric.api.message.v1.ServerMessageEvents; import net.minecraft.network.packet.s2c.play.OverlayMessageS2CPacket; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.text.*; import net.minecraft.world.GameMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,13 +45,13 @@ public class Molehunt implements ModInitializer { command.then(literal("timer").requires(ServerCommandSource::isExecutedByPlayer).then( literal("show").executes(context -> { timerVisibility.put(context.getSource().getPlayer(), true); - context.getSource().sendFeedback(() -> Text.of("Showing molehunt timer"), false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.timer.show"), false); var player = context.getSource().getPlayer(); assert player != null; if (game == null || !game.hasStarted()) { - player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of("§cGame has not started yet"))); + player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.translatable("commands.molehunt.stop.failed").setStyle(Style.EMPTY.withColor(16733525)))); } else { player.networkHandler.sendPacket(new OverlayMessageS2CPacket(Text.of(game.getShortRemainingText()))); } @@ -60,18 +61,19 @@ public class Molehunt implements ModInitializer { ).then( literal("hide").executes(context -> { timerVisibility.put(context.getSource().getPlayer(), false); - context.getSource().sendFeedback(() -> Text.of("Hiding molehunt timer"), false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.timer.hide"), false); return Command.SINGLE_SUCCESS; }) )); command.then(literal("moles").requires(source -> (game != null) && game.hasStarted() && game.isAMole(source.getPlayer())).executes(context -> { - context.getSource().sendFeedback(() -> Text.literal("List of moles: " + game.getMolesAsString()),false); + context.getSource().sendFeedback(() -> Text.translatable("commands.molehunt.moles.list").append(" " + game.getMolesAsString()),false); return Command.SINGLE_SUCCESS; })); command.then(literal("stop").requires(source -> source.hasPermissionLevel(1)).executes(context -> { if (game == null || !game.hasStarted()) { - context.getSource().sendError(Text.of("Game has not started yet")); - return Command.SINGLE_SUCCESS; + var e = new SimpleCommandExceptionType(Text.translatable("commands.molehunt.stop.failed")); + + throw e.create(); } game.stop(); -- cgit v1.2.3 From 29e19bca3f4b1f7b6e2e9ea35ab72bc62c4c4868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Thu, 22 Aug 2024 22:48:28 +0200 Subject: docs: add translation feature in readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 06c25bd..b3084ed 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Stop the game when every innocent is dead or when the timer ended (one hour and The moles can see the name of other moles with `/molehunt moles`. +You can configure every text with a resource pack (for reference, check out [the default lang file](src/client/resources/assets/molehunt/lang/en_us.json)). + ## Technologies - Java 21 -- cgit v1.2.3 From ecfc9f0d622672fbdccce80583eab7974cc4cc15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Thu, 22 Aug 2024 23:04:28 +0200 Subject: fix: bad merging --- src/main/java/world/anhgelus/molehunt/Game.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index 10ef74e..c680a8f 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -53,7 +53,6 @@ public class Game { gamerules.get(GameRules.DO_IMMEDIATE_RESPAWN).set(true, server); gamerules.get(GameRules.DO_ENTITY_DROPS).set(false, server); - final var title = new TitleS2CPacket(Text.of("§eYou are...")); final var title = new TitleS2CPacket(Text.translatable("molehunt.game.start.suspense")); playerManager.getPlayerList().forEach(p -> { p.kill(); -- cgit v1.2.3 From 67e912c50efd23228932b011676ec128aedf58bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 12:05:59 +0200 Subject: style: add more colors to text --- src/client/resources/assets/molehunt/lang/en_us.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/client/resources/assets/molehunt/lang/en_us.json b/src/client/resources/assets/molehunt/lang/en_us.json index d68fd0e..63ac06d 100644 --- a/src/client/resources/assets/molehunt/lang/en_us.json +++ b/src/client/resources/assets/molehunt/lang/en_us.json @@ -4,12 +4,12 @@ "commands.molehunt.timer.hide": "Hiding Molehunt timer.", "commands.molehunt.moles.list": "List of moles:", "commands.molehunt.stop.success": "The Molehunt game has been stopped.", - "molehunt.game.end.suspense.title": "And the winners are...", + "molehunt.game.end.suspense.title": "§eAnd the winners are...", "molehunt.game.end.winners.moles.title": "§cThe Moles!", - "molehunt.game.end.winners.survivors.title": "§aThe survivors!", - "molehunt.game.end.winners.subtitle": "The moles were", - "molehunt.game.start.suspense": "You are...", + "molehunt.game.end.winners.survivors.title": "§aNot the Moles!", + "molehunt.game.end.winners.subtitle": "§6The moles were", + "molehunt.game.start.suspense": "§eYou are...", "molehunt.game.start.mole.title": "§cThe Mole!", - "molehunt.game.start.mole.subtitle": "Get the list of moles with §6/molehunt moles", + "molehunt.game.start.mole.subtitle": "§eGet the list of moles with §6/molehunt moles", "molehunt.game.start.survivor": "§aNot the Mole!" } \ No newline at end of file -- cgit v1.2.3 From 2ec447626c1b87a74cb3201ecc5407ee3f447cc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 13:07:31 +0200 Subject: feat: add config file --- README.md | 6 +- src/main/java/world/anhgelus/molehunt/Game.java | 15 +- .../java/world/anhgelus/molehunt/Molehunt.java | 4 + .../world/anhgelus/molehunt/config/Config.java | 38 ++++ .../anhgelus/molehunt/config/SimpleConfig.java | 252 +++++++++++++++++++++ 5 files changed, 312 insertions(+), 3 deletions(-) create mode 100644 src/main/java/world/anhgelus/molehunt/config/Config.java create mode 100644 src/main/java/world/anhgelus/molehunt/config/SimpleConfig.java diff --git a/README.md b/README.md index b3084ed..401b81f 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,11 @@ Stop the game when every innocent is dead or when the timer ended (one hour and The moles can see the name of other moles with `/molehunt moles`. -You can configure every text with a resource pack (for reference, check out [the default lang file](src/client/resources/assets/molehunt/lang/en_us.json)). +You can configure every text line and the skin with a resource pack (for reference, check out +[the default lang file](src/client/resources/assets/molehunt/lang/en_us.json) and [the default +skin file](src/client/resources/assets/molehunt/textures/skin.png)). + +Also, more server-side values can be changed in the configuration file, located in your server config directory. ## Technologies diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index c680a8f..3092bc9 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -18,7 +18,7 @@ import java.util.stream.Collectors; public class Game { private Timer timer = new Timer(); - public final static int DEFAULT_TIME = 90*60; // 1:30 + public final static int DEFAULT_TIME = Molehunt.CONFIG.GAME_DURATION; private int remaining = DEFAULT_TIME; private final MinecraftServer server; @@ -34,10 +34,21 @@ public class Game { } public void start() { - final int n = (server.getCurrentPlayerCount() - server.getCurrentPlayerCount() % 4)/4; + final int n; + if (Molehunt.CONFIG.MOLE_COUNT < 0) { + n = Math.floorDiv(server.getCurrentPlayerCount(), Math.floorDiv(100, (int) Molehunt.CONFIG.MOLE_PERCENTAGE)); + } else { + n = Molehunt.CONFIG.MOLE_COUNT; + } +// final int n = (server.getCurrentPlayerCount() - server.getCurrentPlayerCount() % 4)/4; + final var playerManager = server.getPlayerManager(); + final var players = playerManager.getPlayerList(); for (int i = 0; i < n; i++) { + // Can happen if the mole count is greater than the player count + if (players.isEmpty()) break; + final var r = ThreadLocalRandom.current().nextInt(0, players.size()); final var mole = players.get(r); if (mole == null) throw new IllegalStateException("Mole is null!"); diff --git a/src/main/java/world/anhgelus/molehunt/Molehunt.java b/src/main/java/world/anhgelus/molehunt/Molehunt.java index b2d3842..078afa6 100644 --- a/src/main/java/world/anhgelus/molehunt/Molehunt.java +++ b/src/main/java/world/anhgelus/molehunt/Molehunt.java @@ -14,6 +14,7 @@ import net.minecraft.text.*; import net.minecraft.world.GameMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import world.anhgelus.molehunt.config.Config; import java.util.HashMap; @@ -24,6 +25,8 @@ public class Molehunt implements ModInitializer { public static final String MOD_ID = "molehunt"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + public static final Config CONFIG = new Config(MOD_ID); + public Game game; public static HashMap timerVisibility = new HashMap<>(); @@ -31,6 +34,7 @@ public class Molehunt implements ModInitializer { @Override public void onInitialize() { LOGGER.info("Initializing Molehunt"); + LOGGER.info(String.valueOf(CONFIG.GAME_DURATION)); final var command = literal("molehunt"); command.then(literal("start").requires(source -> source.hasPermissionLevel(1)).executes(context -> { diff --git a/src/main/java/world/anhgelus/molehunt/config/Config.java b/src/main/java/world/anhgelus/molehunt/config/Config.java new file mode 100644 index 0000000..fc5104d --- /dev/null +++ b/src/main/java/world/anhgelus/molehunt/config/Config.java @@ -0,0 +1,38 @@ +package world.anhgelus.molehunt.config; + +import world.anhgelus.molehunt.Molehunt; + +public class Config { + public final int GAME_DURATION; + public final double MOLE_PERCENTAGE; + public final int MOLE_COUNT; + + public Config(String fileName) { + final SimpleConfig CONFIG = SimpleConfig.of(fileName).provider(Config::defaultConfig).request(); + + // In seconds + GAME_DURATION = CONFIG.getOrDefault("game_duration", 90) * 60; + MOLE_PERCENTAGE = CONFIG.getOrDefault("mole_percentage", 25); + MOLE_COUNT = CONFIG.getOrDefault("mole_count", -1); + } + + private static String defaultConfig(String s) { + return """ + # Molehunt mod configuration file + + # The duration of a molehunt game, in minutes. + # Default : 90 minutes (1 hour 30 minutes). + game_duration = 90 + + # Mole percentage. + # For example, a mole percentage of 25% will get 1 mole every 4 players. + # Default : 25 %. + mole_percentage = 25 + + # Mole count (absolute) + # If set, this setting will overwrite the mole_percentage setting. + # Default : not set + #mole_count = 2 + """; + } +} diff --git a/src/main/java/world/anhgelus/molehunt/config/SimpleConfig.java b/src/main/java/world/anhgelus/molehunt/config/SimpleConfig.java new file mode 100644 index 0000000..ef8bef3 --- /dev/null +++ b/src/main/java/world/anhgelus/molehunt/config/SimpleConfig.java @@ -0,0 +1,252 @@ +package world.anhgelus.molehunt.config; + +/* + * Copyright (c) 2021 magistermaks + * Slightly modified by Léo-21 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import net.fabricmc.loader.api.FabricLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Scanner; + +public class SimpleConfig { + + private static final Logger LOGGER = LogManager.getLogger("SimpleConfig"); + private final HashMap config = new HashMap<>(); + private final ConfigRequest request; + private boolean broken = false; + + public interface DefaultConfig { + String get( String namespace ); + + static String empty( String namespace ) { + return ""; + } + } + + public static class ConfigRequest { + + private final File file; + private final String filename; + private DefaultConfig provider; + + private ConfigRequest(File file, String filename ) { + this.file = file; + this.filename = filename; + this.provider = DefaultConfig::empty; + } + + /** + * Sets the default config provider, used to generate the + * config if it's missing. + * + * @param provider default config provider + * @return current config request object + * @see DefaultConfig + */ + public ConfigRequest provider( DefaultConfig provider ) { + this.provider = provider; + return this; + } + + /** + * Loads the config from the filesystem. + * + * @return config object + * @see SimpleConfig + */ + public SimpleConfig request() { + return new SimpleConfig( this ); + } + + private String getConfig() { + return provider.get( filename ) + "\n"; + } + + } + + /** + * Creates new config request object, ideally `namespace` + * should be the name of the mod id of the requesting mod + * + * @param filename - name of the config file + * @return new config request object + */ + public static ConfigRequest of( String filename ) { + Path path = FabricLoader.getInstance().getConfigDir(); + return new ConfigRequest( path.resolve( filename + ".properties" ).toFile(), filename ); + } + + private void createConfig() throws IOException { + + // try creating missing files + request.file.getParentFile().mkdirs(); + Files.createFile( request.file.toPath() ); + + // write default config data + PrintWriter writer = new PrintWriter(request.file, "UTF-8"); + writer.write( request.getConfig() ); + writer.close(); + + } + + private void loadConfig() throws IOException { + Scanner reader = new Scanner( request.file ); + for( int line = 1; reader.hasNextLine(); line ++ ) { + parseConfigEntry( reader.nextLine(), line ); + } + } + + private void parseConfigEntry( String entry, int line ) { + if( !entry.isEmpty() && !entry.startsWith( "#" ) ) { + String[] parts = entry.split("=", 2); + if( parts.length == 2 ) { + config.put( parts[0].stripTrailing(), parts[1].strip() ); + }else{ + throw new RuntimeException("Syntax error in config file on line " + line + "!"); + } + } + } + + private SimpleConfig( ConfigRequest request ) { + this.request = request; + String identifier = "Config '" + request.filename + "'"; + + if( !request.file.exists() ) { + LOGGER.info( identifier + " is missing, generating default one..." ); + + try { + createConfig(); + } catch (IOException e) { + LOGGER.error( identifier + " failed to generate!" ); + LOGGER.trace( e ); + broken = true; + } + } + + if( !broken ) { + try { + loadConfig(); + } catch (Exception e) { + LOGGER.error( identifier + " failed to load!" ); + LOGGER.trace( e ); + broken = true; + } + } + + } + + /** + * Queries a value from config, returns `null` if the + * key does not exist. + * + * @return value corresponding to the given key + * @see SimpleConfig#getOrDefault + */ + @Deprecated + public String get( String key ) { + return config.get( key ); + } + + /** + * Returns string value from config corresponding to the given + * key, or the default string if the key is missing. + * + * @return value corresponding to the given key, or the default value + */ + public String getOrDefault( String key, String def ) { + String val = get(key); + return val == null ? def : val; + } + + /** + * Returns integer value from config corresponding to the given + * key, or the default integer if the key is missing or invalid. + * + * @return value corresponding to the given key, or the default value + */ + public int getOrDefault( String key, int def ) { + try { + return Integer.parseInt( get(key) ); + } catch (Exception e) { + return def; + } + } + + /** + * Returns boolean value from config corresponding to the given + * key, or the default boolean if the key is missing. + * + * @return value corresponding to the given key, or the default value + */ + public boolean getOrDefault( String key, boolean def ) { + String val = get(key); + if( val != null ) { + return val.equalsIgnoreCase("true"); + } + + return def; + } + + /** + * Returns double value from config corresponding to the given + * key, or the default string if the key is missing or invalid. + * + * @return value corresponding to the given key, or the default value + */ + public double getOrDefault( String key, double def ) { + try { + return Double.parseDouble( get(key) ); + } catch (Exception e) { + return def; + } + } + + /** + * If any error occurred during loading or reading from the config + * a 'broken' flag is set, indicating that the config's state + * is undefined and should be discarded using `delete()` + * + * @return the 'broken' flag of the configuration + */ + public boolean isBroken() { + return broken; + } + + /** + * deletes the config file from the filesystem + * + * @return true if the operation was successful + */ + public boolean delete() { + LOGGER.warn( "Config '" + request.filename + "' was removed from existence! Restart the game to regenerate it." ); + return request.file.delete(); + } + +} \ No newline at end of file -- cgit v1.2.3 From da7d7c502a8c99dfeae5d3294c54ad4f892edcb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 13:08:20 +0200 Subject: style: remove unnecessary imports --- src/main/java/world/anhgelus/molehunt/config/Config.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/world/anhgelus/molehunt/config/Config.java b/src/main/java/world/anhgelus/molehunt/config/Config.java index fc5104d..519166d 100644 --- a/src/main/java/world/anhgelus/molehunt/config/Config.java +++ b/src/main/java/world/anhgelus/molehunt/config/Config.java @@ -1,7 +1,5 @@ package world.anhgelus.molehunt.config; -import world.anhgelus.molehunt.Molehunt; - public class Config { public final int GAME_DURATION; public final double MOLE_PERCENTAGE; -- cgit v1.2.3 From 007ad4b3f9eb0d683f72a3008ec3208c1121217d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 13:11:40 +0200 Subject: style: remove commented and unused code --- src/main/java/world/anhgelus/molehunt/Game.java | 9 --------- src/main/java/world/anhgelus/molehunt/Molehunt.java | 4 ---- 2 files changed, 13 deletions(-) diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index 3092bc9..df90044 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -40,7 +40,6 @@ public class Game { } else { n = Molehunt.CONFIG.MOLE_COUNT; } -// final int n = (server.getCurrentPlayerCount() - server.getCurrentPlayerCount() % 4)/4; final var playerManager = server.getPlayerManager(); @@ -152,14 +151,6 @@ public class Game { }, 4*1000); } - public int getRemaining() { - return remaining; - } - - public Text getRemainingText() { - return Text.of("Time remaining: "+ TimeUtils.printTime(remaining)); - } - public Text getShortRemainingText() { return Text.of("§c" + TimeUtils.printShortTime(remaining)); } diff --git a/src/main/java/world/anhgelus/molehunt/Molehunt.java b/src/main/java/world/anhgelus/molehunt/Molehunt.java index 078afa6..1752d26 100644 --- a/src/main/java/world/anhgelus/molehunt/Molehunt.java +++ b/src/main/java/world/anhgelus/molehunt/Molehunt.java @@ -42,10 +42,6 @@ public class Molehunt implements ModInitializer { game.start(); return Command.SINGLE_SUCCESS; })); -// command.then(literal("time").executes(context -> { -// context.getSource().sendFeedback(() -> game.getRemainingText(), false); -// return Command.SINGLE_SUCCESS; -// })); command.then(literal("timer").requires(ServerCommandSource::isExecutedByPlayer).then( literal("show").executes(context -> { timerVisibility.put(context.getSource().getPlayer(), true); -- cgit v1.2.3 From f2537409c7705f53f8a612a67b2af2497cd3830d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 14:24:19 +0200 Subject: fix: convert player list to arraylist --- src/main/java/world/anhgelus/molehunt/Game.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index df90044..32dea83 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -43,7 +43,7 @@ public class Game { final var playerManager = server.getPlayerManager(); - final var players = playerManager.getPlayerList(); + final var players = new ArrayList<>(playerManager.getPlayerList()); for (int i = 0; i < n; i++) { // Can happen if the mole count is greater than the player count if (players.isEmpty()) break; -- cgit v1.2.3 From d89d380f3229ab22a47e43e6cef50c604629bda1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 14:27:22 +0200 Subject: style: improve code as suggested by @anhgelus --- src/main/java/world/anhgelus/molehunt/Game.java | 11 ++++++----- src/main/java/world/anhgelus/molehunt/Molehunt.java | 5 +---- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/java/world/anhgelus/molehunt/Game.java b/src/main/java/world/anhgelus/molehunt/Game.java index 32dea83..54e5c3a 100644 --- a/src/main/java/world/anhgelus/molehunt/Game.java +++ b/src/main/java/world/anhgelus/molehunt/Game.java @@ -44,10 +44,7 @@ public class Game { final var playerManager = server.getPlayerManager(); final var players = new ArrayList<>(playerManager.getPlayerList()); - for (int i = 0; i < n; i++) { - // Can happen if the mole count is greater than the player count - if (players.isEmpty()) break; - + for (int i = 0; i < n && !players.isEmpty(); i++) { final var r = ThreadLocalRandom.current().nextInt(0, players.size()); final var mole = players.get(r); if (mole == null) throw new IllegalStateException("Mole is null!"); @@ -160,7 +157,11 @@ public class Game { } public String getMolesAsString() { - return moles.stream().map(ServerPlayerEntity::getDisplayName).filter(Objects::nonNull).map(Text::toString).collect(Collectors.joining(", ")); + return moles.stream() + .map(ServerPlayerEntity::getDisplayName) + .filter(Objects::nonNull) + .map(Text::toString) + .collect(Collectors.joining(", ")); } public boolean isAMole(ServerPlayerEntity player) { diff --git a/src/main/java/world/anhgelus/molehunt/Molehunt.java b/src/main/java/world/anhgelus/molehunt/Molehunt.java index 1752d26..5df63b1 100644 --- a/src/main/java/world/anhgelus/molehunt/Molehunt.java +++ b/src/main/java/world/anhgelus/molehunt/Molehunt.java @@ -34,7 +34,6 @@ public class Molehunt implements ModInitializer { @Override public void onInitialize() { LOGGER.info("Initializing Molehunt"); - LOGGER.info(String.valueOf(CONFIG.GAME_DURATION)); final var command = literal("molehunt"); command.then(literal("start").requires(source -> source.hasPermissionLevel(1)).executes(context -> { @@ -71,9 +70,7 @@ public class Molehunt implements ModInitializer { })); command.then(literal("stop").requires(source -> source.hasPermissionLevel(1)).executes(context -> { if (game == null || !game.hasStarted()) { - var e = new SimpleCommandExceptionType(Text.translatable("commands.molehunt.stop.failed")); - - throw e.create(); + throw (new SimpleCommandExceptionType(Text.translatable("commands.molehunt.stop.failed"))).create(); } game.stop(); -- cgit v1.2.3 From a3fbb77bfc0490e8dfac39d0466ff9b87a14fec4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Kosman?= Date: Fri, 23 Aug 2024 15:07:51 +0200 Subject: style: change default config mole_count --- src/main/java/world/anhgelus/molehunt/config/Config.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/world/anhgelus/molehunt/config/Config.java b/src/main/java/world/anhgelus/molehunt/config/Config.java index 519166d..75301ad 100644 --- a/src/main/java/world/anhgelus/molehunt/config/Config.java +++ b/src/main/java/world/anhgelus/molehunt/config/Config.java @@ -27,10 +27,11 @@ public class Config { # Default : 25 %. mole_percentage = 25 - # Mole count (absolute) - # If set, this setting will overwrite the mole_percentage setting. - # Default : not set - #mole_count = 2 + # Mole count (absolute). + # This setting will overwrite the mole_percentage setting. + # If set below 0, this setting is disabled. + # Default : -1. + mole_count = -1 """; } } -- cgit v1.2.3