reformatted project

This commit is contained in:
2025-10-16 00:58:52 +02:00
parent cf0499df44
commit 794dc1dbb1
150 changed files with 1594 additions and 1771 deletions

View File

@@ -24,16 +24,17 @@ public class Main {
private final static Logger logger = Logger.getGlobal();
public static ConfigurationNode globalConfig;
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void main(String[] args) throws ConfigurateException {
//noinspection ResultOfMethodCallIgnored
Resource.values(); // This initializes and preloads the enum and extracts the resources
Languages.getInstance(); //Preload languages into the jvm
globalConfig = YamlConfigurationLoader
.builder()
.path(Resource.CONFIG.getPath())
.build()
.load();
.builder()
.path(Resource.CONFIG.getPath())
.build()
.load();
ConfigurationNode serverConfig = globalConfig.node("server");

View File

@@ -21,6 +21,7 @@ public enum Resource {
private final Path path;
private final String name;
Resource(String name, boolean keepOutdated) {
this.name = name;
this.path = Path.of("resources/" + name);
@@ -28,7 +29,7 @@ public enum Resource {
try {
Logger.getLogger("ressource").info("extracting resource " + name + " ... ");
ResourceUtils.extractResource(name, keepOutdated);
} catch (URISyntaxException | IOException e) {
} catch(URISyntaxException | IOException e) {
throw new RuntimeException(e);
}
}
@@ -38,10 +39,10 @@ public enum Resource {
}
public Path getPath() {
return path;
return this.path;
}
public String getName() {
return name;
return this.name;
}
}

View File

@@ -12,11 +12,11 @@ public abstract class Controller<Q, R> implements Route {
@SuppressWarnings("unchecked")
public Controller() {
this.requestType = ((Class<Q>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
this.requestType = ((Class<Q>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
@Override
public Object handle(Request request, Response response) throws Exception {
public Object handle(Request request, Response response) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "*");
@@ -28,7 +28,7 @@ public abstract class Controller<Q, R> implements Route {
req = new Gson().fromJson(request.body(), this.requestType);
}
return new Gson().toJson(handle(req, response));
return new Gson().toJson(this.handle(req, response));
}
public abstract R handle(Q request, Response response);

View File

@@ -10,6 +10,7 @@ import static spark.Spark.*;
public class HttpServer {
private static final ConfigurationNode apiConfig = Main.globalConfig.node("api");
public HttpServer() {
if(!apiConfig.node("enabled").getBoolean()) return;

View File

@@ -6,8 +6,12 @@ import spark.Response;
import java.util.UUID;
record Req(UUID room) {}
record Resp() {}
record Req(UUID room) {
}
record Resp() {
}
public class CloseRoom extends Controller<Req, Resp> {
@Override
public Resp handle(Req request, Response response) {

View File

@@ -6,8 +6,12 @@ import spark.Response;
import java.util.UUID;
record Req() {}
record Resp(UUID uuid) {}
record Req() {
}
record Resp(UUID uuid) {
}
public class CreateRoom extends Controller<Req, Resp> {
@Override
public Resp handle(Req request, Response response) {

View File

@@ -8,8 +8,12 @@ import spark.Response;
import java.util.UUID;
record Req(UUID player, UUID room) {}
record Resp(String error) {}
record Req(UUID player, UUID room) {
}
record Resp(String error) {
}
public class QueueRoom extends Controller<Req, Resp> {
@Override
public Resp handle(Req request, Response response) {

View File

@@ -1,9 +1,8 @@
package eu.mhsl.minenet.minigames.command;
import eu.mhsl.minenet.minigames.command.privileged.SkinCommand;
import eu.mhsl.minenet.minigames.command.privileged.*;
import eu.mhsl.minenet.minigames.command.anonymous.HubCommand;
import eu.mhsl.minenet.minigames.command.anonymous.LeaveCommand;
import eu.mhsl.minenet.minigames.command.privileged.*;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import net.minestom.server.MinecraftServer;
@@ -33,10 +32,6 @@ public enum Commands {
PLAYERLIMIT(new PlayerLimitCommand()),
SETMEMORIAL(new SetMemorialCommand());
Commands(Command handler) {
MinecraftServer.getCommandManager().register(handler);
}
static {
MinecraftServer.getCommandManager().setUnknownCommandCallback((sender, command) -> {
if(command.isBlank()) return;
@@ -47,4 +42,8 @@ public enum Commands {
.send(sender);
});
}
Commands(Command handler) {
MinecraftServer.getCommandManager().register(handler);
}
}

View File

@@ -11,20 +11,21 @@ import java.util.List;
public class PrivilegedCommand extends Command {
private final List<CommandCondition> conditions = new ArrayList<>();
public PrivilegedCommand(@NotNull String name, @Nullable String... aliases) {
super(name, aliases);
construct();
this.construct();
}
public PrivilegedCommand(@NotNull String name) {
super(name);
construct();
this.construct();
}
private void construct() {
addCondition(isPrivileged());
this.addCondition(this.isPrivileged());
setCondition((sender, commandString) -> conditions.parallelStream().allMatch(condition -> condition.canUse(sender, commandString)));
this.setCondition((sender, commandString) -> this.conditions.parallelStream().allMatch(condition -> condition.canUse(sender, commandString)));
}
protected CommandCondition isPrivileged() {
@@ -32,6 +33,6 @@ public class PrivilegedCommand extends Command {
}
protected void addCondition(CommandCondition condition) {
conditions.add(condition);
this.conditions.add(condition);
}
}

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.command.anonymous;
import eu.mhsl.minenet.minigames.util.MoveInstance;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.util.MoveInstance;
import net.minestom.server.command.builder.Command;
import net.minestom.server.entity.Player;
@@ -10,12 +10,12 @@ public class HubCommand extends Command {
public HubCommand() {
super("hub");
setCondition(
this.setCondition(
(sender, commandString) ->
((Player) sender).getInstance() instanceof Room room && !room.apiDriven
);
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
if(Room.getRoom((Player) sender).orElseThrow().apiDriven) return;
Room.unsetRoom((Player) sender);
MoveInstance.move((Player) sender, Hub.INSTANCE);

View File

@@ -9,8 +9,8 @@ public class LeaveCommand extends Command {
public LeaveCommand() {
super("leave");
setCondition((sender, commandString) -> ((Player) sender).getInstance() instanceof Game);
this.setCondition((sender, commandString) -> ((Player) sender).getInstance() instanceof Game);
setDefaultExecutor((sender, context) -> Room.setOwnRoom((Player) sender));
this.setDefaultExecutor((sender, context) -> Room.setOwnRoom((Player) sender));
}
}

View File

@@ -14,26 +14,26 @@ public class DebugCommand extends PrivilegedCommand {
public DebugCommand() {
super("debug");
setDefaultExecutor((sender, args) -> {
this.setDefaultExecutor((sender, args) -> {
new ChatMessage(Icon.CHAT).appendTranslated("sample").send(sender);
new ActionBarMessage().appendTranslated("sample").send(sender);
new TitleMessage().subtitle(subtitleMessage -> subtitleMessage.appendTranslated("sample")).appendTranslated("sample").send(sender);
List<String> testplayers = new ArrayList<>() {
{
add("MineTec");
add("Goldi187");
add("Test");
this.add("MineTec");
this.add("Goldi187");
this.add("Test");
}
};
new ChatMessage(Icon.STAR, true)
.appendTranslated("score#result")
.newLine()
.indent()
.numberedList(testplayers)
.undent()
.newLine()
.appendTranslated("score#thanks")
.send(sender);
.appendTranslated("score#result")
.newLine()
.indent()
.numberedList(testplayers)
.undent()
.newLine()
.appendTranslated("score#thanks")
.send(sender);
new ChatMessage(Icon.SCIENCE).appendStatic(((Player) sender).getUuid().toString()).send(sender);
});

View File

@@ -8,7 +8,7 @@ public class FlyCommand extends PrivilegedCommand {
public FlyCommand() {
super("fly");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
Player p = (Player) sender;
p.setVelocity(new Vec(0, 5, 0));
p.setFlying(!p.isFlying());

View File

@@ -7,11 +7,11 @@ import net.minestom.server.entity.Player;
public class GameStartCommand extends PrivilegedCommand {
public GameStartCommand() {
super("gameStart");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
Player player = (Player) sender;
if(player.getInstance() instanceof StatelessGame game) {
game.startAccessor();
}
});
});
}
}

View File

@@ -7,7 +7,7 @@ import net.minestom.server.entity.Player;
public class GameStopCommand extends PrivilegedCommand {
public GameStopCommand() {
super("gameStop");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
Player player = (Player) sender;
if(player.getInstance() instanceof StatelessGame game) {
game.stop();

View File

@@ -12,7 +12,7 @@ public class GameTimeoutCommand extends PrivilegedCommand {
ArgumentInteger timeout = ArgumentType.Integer("timeout");
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
Player player = (Player) sender;
if(player.getInstance() instanceof StatelessGame game) {
game.setTimeLimit(context.get(timeout));

View File

@@ -11,9 +11,9 @@ public class GamemodeCommand extends PrivilegedCommand {
super("gamemode", "gm");
addSyntax((sender, context) -> ((Player) sender).setGameMode(
this.addSyntax((sender, context) -> ((Player) sender).setGameMode(
context.get("target")),
ArgumentType.Enum("target", GameMode.class).setFormat(ArgumentEnum.Format.LOWER_CASED)
ArgumentType.Enum("target", GameMode.class).setFormat(ArgumentEnum.Format.LOWER_CASED)
);
}
}

View File

@@ -1,17 +1,18 @@
package eu.mhsl.minenet.minigames.command.privileged;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.util.Monitoring;
public class GcCommand extends PrivilegedCommand {
private static long lastRun = System.currentTimeMillis();
public GcCommand() {
super("gc");
setDefaultExecutor((sender, context) -> {
long nextRun = (lastRun - (System.currentTimeMillis() - 30*1000)) / 1000;
this.setDefaultExecutor((sender, context) -> {
long nextRun = (lastRun - (System.currentTimeMillis() - 30 * 1000)) / 1000;
if(nextRun > 0) {
new ChatMessage(Icon.ERROR).appendStatic("Please wait ").appendStatic(String.valueOf(nextRun)).appendStatic(" seconds before running GC again!").send(sender);
return;
@@ -24,10 +25,10 @@ public class GcCommand extends PrivilegedCommand {
long after = Monitoring.getRamUsage();
new ChatMessage(Icon.SUCCESS).appendStatic("Garbage collector ran successfully!").newLine()
.appendStatic("before: ").appendStatic(String.valueOf(before)).appendStatic("MB").newLine()
.appendStatic("now: ").appendStatic(String.valueOf(after)).appendStatic("MB").newLine()
.appendStatic("difference: ").appendStatic(String.valueOf(before-after)).appendStatic("MB")
.send(sender);
.appendStatic("before: ").appendStatic(String.valueOf(before)).appendStatic("MB").newLine()
.appendStatic("now: ").appendStatic(String.valueOf(after)).appendStatic("MB").newLine()
.appendStatic("difference: ").appendStatic(String.valueOf(before - after)).appendStatic("MB")
.send(sender);
});
}
}

View File

@@ -13,7 +13,7 @@ public class InstanceProxyMoveCommand extends PrivilegedCommand {
ArgumentWord serverArgument = new ArgumentWord("server");
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
Instance room = ((Player) sender).getInstance();
room.getPlayers().forEach(player -> {
Room.unsetRoom(player);

View File

@@ -11,17 +11,17 @@ public class KickCommand extends PrivilegedCommand {
public KickCommand() {
super("kick");
addSyntax(
this.addSyntax(
(sender, context) ->
kick(context.getRaw("player"), ""),
ArgumentType.Entity("player").onlyPlayers(true)
this.kick(context.getRaw("player"), ""),
ArgumentType.Entity("player").onlyPlayers(true)
);
addSyntax(
this.addSyntax(
(sender, context) ->
kick(context.getRaw("player"), context.getRaw("reason")),
ArgumentType.Entity("player").onlyPlayers(true),
ArgumentType.String("reason")
this.kick(context.getRaw("player"), context.getRaw("reason")),
ArgumentType.Entity("player").onlyPlayers(true),
ArgumentType.String("reason")
);
}

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.command.privileged;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.lang.Languages;
import eu.mhsl.minenet.minigames.lang.Lang;
import eu.mhsl.minenet.minigames.lang.Languages;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.TranslatableMessage;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
@@ -13,11 +13,11 @@ public class LangTestCommand extends PrivilegedCommand {
public LangTestCommand() {
super("langtest");
setDefaultExecutor((sender, context) -> sendMessage(Languages.getInstance().getLanguage((Player) sender), "sample").send(sender));
this.setDefaultExecutor((sender, context) -> this.sendMessage(Languages.getInstance().getLanguage((Player) sender), "sample").send(sender));
var targetString = ArgumentType.String("mapId");
addSyntax((sender, context) -> sendMessage(Languages.getInstance().getLanguage((Player) sender), context.get("mapId")).send(sender), targetString);
this.addSyntax((sender, context) -> this.sendMessage(Languages.getInstance().getLanguage((Player) sender), context.get("mapId")).send(sender), targetString);
}
private TranslatableMessage sendMessage(Lang lang, String mapId) {

View File

@@ -11,7 +11,7 @@ public class OpCommand extends PrivilegedCommand {
public OpCommand() {
super("op");
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
Player target = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(context.getRaw("target"));
if(target != null) {
target.setPermissionLevel(4);

View File

@@ -10,8 +10,9 @@ public class PlayerLimitCommand extends PrivilegedCommand {
ArgumentInteger count = ArgumentType.Integer("count");
addSyntax((sender, context) -> {
System.setProperty("minenet.playerlimit", String.valueOf(context.get(count)));
}, count);
this.addSyntax((sender, context) -> System.setProperty(
"minenet.playerlimit",
String.valueOf(context.get(count))
), count);
}
}

View File

@@ -13,10 +13,11 @@ import java.net.http.HttpResponse;
public class PublishRewardCommand extends PrivilegedCommand {
private final HttpClient rewardPublishClient = HttpClient.newHttpClient();
public PublishRewardCommand() {
super("publishReward");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
try {
Room room = Room.getRoom((Player) sender).orElseThrow();
TournamentDisplay world = new TournamentDisplay(room.getTournament());
@@ -24,14 +25,14 @@ public class PublishRewardCommand extends PrivilegedCommand {
String rewardRequestJson = new Gson().toJson(room.getTournament().getRewards());
HttpRequest giveRewardsRequest = HttpRequest.newBuilder()
.uri(new URI("http://10.20.7.1:8080/api/event/reward"))
.POST(HttpRequest.BodyPublishers.ofString(rewardRequestJson))
.build();
.uri(new URI("http://10.20.7.1:8080/api/event/reward"))
.POST(HttpRequest.BodyPublishers.ofString(rewardRequestJson))
.build();
room.getTournament().getRewards();
HttpResponse<Void> rawResponse = rewardPublishClient.send(giveRewardsRequest, HttpResponse.BodyHandlers.discarding());
HttpResponse<Void> rawResponse = this.rewardPublishClient.send(giveRewardsRequest, HttpResponse.BodyHandlers.discarding());
sender.sendMessage(String.format("Rewards published: HTTP %s", rawResponse.statusCode()));
} catch (Exception e) {
} catch(Exception e) {
sender.sendMessage(e.getMessage());
}
});

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.command.privileged;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
@@ -10,7 +10,7 @@ public class RefreshCommandsCommand extends PrivilegedCommand {
public RefreshCommandsCommand() {
super("refreshCommands");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
MinecraftServer.getConnectionManager().getOnlinePlayers().forEach(Player::refreshCommands);
new ChatMessage(Icon.SUCCESS).appendStatic("Updated command syntax!").send(sender);
});

View File

@@ -1,10 +1,10 @@
package eu.mhsl.minenet.minigames.command.privileged;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.TranslatableMessage;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.instance.room.Room;
import net.minestom.server.entity.Player;
import java.util.stream.Collectors;
@@ -13,14 +13,14 @@ public class RoomCommand extends PrivilegedCommand {
public RoomCommand() {
super("room");
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
TranslatableMessage out = new ChatMessage(Icon.SCIENCE).appendStatic("Rooms:").newLine();
Room.getAllRooms().forEach((roomInstance) -> out
.newLine()
.appendStatic("Owner: ").appendStatic(roomInstance.getOwner() != null ? roomInstance.getOwner().getUsername() : "none").newLine()
.appendStatic("Players: ").appendStatic(String.valueOf(roomInstance.getAllMembers().size())).newLine()
.list(roomInstance.getAllMembers().stream().map(Player::getUsername).collect(Collectors.toList())).newLine());
.newLine()
.appendStatic("Owner: ").appendStatic(roomInstance.getOwner() != null ? roomInstance.getOwner().getUsername() : "none").newLine()
.appendStatic("Players: ").appendStatic(String.valueOf(roomInstance.getAllMembers().size())).newLine()
.list(roomInstance.getAllMembers().stream().map(Player::getUsername).collect(Collectors.toList())).newLine());
out.send(sender);
});

View File

@@ -20,37 +20,37 @@ public class SetMemorialCommand extends PrivilegedCommand {
ArgumentString titleArgument = ArgumentType.String("title");
ArgumentString loreArgument = ArgumentType.String("lore");
materialArgument.setSuggestionCallback((sender, context, suggestion) -> {
Material
.values()
.stream()
.map(material -> new SuggestionEntry(material.name(), Component.text(material.name())))
.forEach(suggestion::addEntry);
});
materialArgument.setSuggestionCallback(
(sender, context, suggestion) -> Material
.values()
.stream()
.map(material -> new SuggestionEntry(material.name(), Component.text(material.name())))
.forEach(suggestion::addEntry)
);
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
Room
.getRoom((Player) sender)
.orElseThrow()
.getTournament()
.setMemorialConfiguration(
new MemorialConfiguration(
Material.fromNamespaceId(context.get(materialArgument)),
context.get(titleArgument),
context.get(loreArgument)
)
);
.getRoom((Player) sender)
.orElseThrow()
.getTournament()
.setMemorialConfiguration(
new MemorialConfiguration(
Material.fromNamespaceId(context.get(materialArgument)),
context.get(titleArgument),
context.get(loreArgument)
)
);
sender.sendMessage(
Component.text()
.append(Component.text("Memorial gesetzt:", NamedTextColor.GOLD))
.appendNewline()
.append(Component.text(context.get(materialArgument), NamedTextColor.AQUA))
.appendNewline()
.append(Component.text(context.get(titleArgument), NamedTextColor.RED))
.appendNewline()
.append(Component.text(context.get(loreArgument), NamedTextColor.DARK_RED))
.build()
Component.text()
.append(Component.text("Memorial gesetzt:", NamedTextColor.GOLD))
.appendNewline()
.append(Component.text(context.get(materialArgument), NamedTextColor.AQUA))
.appendNewline()
.append(Component.text(context.get(titleArgument), NamedTextColor.RED))
.appendNewline()
.append(Component.text(context.get(loreArgument), NamedTextColor.DARK_RED))
.build()
);
}, materialArgument, titleArgument, loreArgument);
}

View File

@@ -22,34 +22,34 @@ public class SetRewardCommand extends PrivilegedCommand {
ArgumentWord materialArgument = ArgumentType.Word("material");
ArgumentStringArray amountsArgument = ArgumentType.StringArray("amount");
materialArgument.setSuggestionCallback((sender, context, suggestion) -> {
Material
.values()
.stream()
.map(material -> new SuggestionEntry(material.name(), Component.text(material.name())))
.forEach(suggestion::addEntry);
});
materialArgument.setSuggestionCallback(
(sender, context, suggestion) -> Material
.values()
.stream()
.map(material -> new SuggestionEntry(material.name(), Component.text(material.name())))
.forEach(suggestion::addEntry)
);
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
Room
.getRoom((Player) sender)
.orElseThrow()
.getTournament()
.setRewardConfiguration(
new RewardConfiguration(
Material.fromNamespaceId(context.get(materialArgument)),
Arrays.stream(context.get(amountsArgument)).map(Integer::valueOf).collect(Collectors.toList())
)
);
.getRoom((Player) sender)
.orElseThrow()
.getTournament()
.setRewardConfiguration(
new RewardConfiguration(
Material.fromNamespaceId(context.get(materialArgument)),
Arrays.stream(context.get(amountsArgument)).map(Integer::valueOf).collect(Collectors.toList())
)
);
sender.sendMessage(
Component.text()
.append(Component.text("Belohnung gesetzt:", NamedTextColor.GOLD))
.appendNewline()
.append(Component.text(context.get(materialArgument), NamedTextColor.AQUA))
.appendNewline()
.append(Component.text(String.join(", ", context.get(amountsArgument)), NamedTextColor.RED))
.build()
Component.text()
.append(Component.text("Belohnung gesetzt:", NamedTextColor.GOLD))
.appendNewline()
.append(Component.text(context.get(materialArgument), NamedTextColor.AQUA))
.appendNewline()
.append(Component.text(String.join(", ", context.get(amountsArgument)), NamedTextColor.RED))
.build()
);
}, materialArgument, amountsArgument);
}

View File

@@ -15,16 +15,16 @@ public class SetRoomOwnerCommand extends PrivilegedCommand {
public SetRoomOwnerCommand() {
super("setRoomOwner");
addCondition((sender, commandString) -> ((Player) sender).getInstance() instanceof Room);
this.addCondition((sender, commandString) -> ((Player) sender).getInstance() instanceof Room);
setDefaultExecutor((sender, context) -> {
this.setDefaultExecutor((sender, context) -> {
if(sender instanceof Player p) {
Room.getRoom(p).orElseThrow().setOwner(p);
new ChatMessage(Icon.SUCCESS).appendTranslated("room#ownerSelf").send(sender);
}
});
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
System.out.println("Test");
if(sender instanceof Player p) {
Player newOwner = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(context.getRaw("player"));

View File

@@ -9,7 +9,7 @@ public class SkinCommand extends PrivilegedCommand {
public SkinCommand() {
super("skin");
addSyntax((sender, context) -> {
this.addSyntax((sender, context) -> {
if(sender instanceof Player p) {
p.setSkin(PlayerSkin.fromUsername(context.getRaw("target")));
}

View File

@@ -1,6 +1,9 @@
package eu.mhsl.minenet.minigames.handler;
import eu.mhsl.minenet.minigames.handler.global.*;
import eu.mhsl.minenet.minigames.handler.global.AddEntityToInstanceEventListener;
import eu.mhsl.minenet.minigames.handler.global.ChatFormatHandler;
import eu.mhsl.minenet.minigames.handler.global.PlayerLeaveHandler;
import eu.mhsl.minenet.minigames.handler.global.PlayerLoginHandler;
import net.minestom.server.MinecraftServer;
import net.minestom.server.event.EventListener;

View File

@@ -2,13 +2,13 @@ package eu.mhsl.minenet.minigames.handler.global;
import eu.mhsl.minenet.minigames.Main;
import eu.mhsl.minenet.minigames.api.QueuedPlayerRooms;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.instance.transfer.Transfer;
import eu.mhsl.minenet.minigames.skin.SkinCache;
import eu.mhsl.minenet.minigames.util.MoveInstance;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import net.minestom.server.event.EventListener;
import net.minestom.server.event.player.AsyncPlayerConfigurationEvent;
import net.minestom.server.network.packet.server.play.TeamsPacket;
@@ -61,7 +61,8 @@ public class PlayerLoginHandler implements EventListener<AsyncPlayerConfiguratio
if(Objects.requireNonNull(Main.globalConfig.node("admins").getList(String.class)).stream().anyMatch(s -> s.equalsIgnoreCase(p.getUsername()))) {
p.setPermissionLevel(4);
}
} catch (SerializationException | NullPointerException ignored) {}
} catch(SerializationException | NullPointerException ignored) {
}
Logger.getLogger("user").info(p.getUsername() + " joined");

View File

@@ -10,39 +10,40 @@ import net.minestom.server.world.DimensionType;
*/
public enum Dimension {
OVERWORLD(
NamespaceID.from("minenet:fullbright_overworld"),
DimensionType
.builder()
.ambientLight(2.0f)
.build()
NamespaceID.from("minenet:fullbright_overworld"),
DimensionType
.builder()
.ambientLight(2.0f)
.build()
),
NETHER(
NamespaceID.from("minenet:fullbright_nether"),
DimensionType
.builder()
.ambientLight(2.0f)
.effects("minecraft:the_nether")
.build()
NamespaceID.from("minenet:fullbright_nether"),
DimensionType
.builder()
.ambientLight(2.0f)
.effects("minecraft:the_nether")
.build()
),
THE_END(
NamespaceID.from("minenet:fullbright_end"),
DimensionType
.builder()
.ambientLight(2.0f)
.effects("minecraft:the_end")
.build()
NamespaceID.from("minenet:fullbright_end"),
DimensionType
.builder()
.ambientLight(2.0f)
.effects("minecraft:the_end")
.build()
);
public final DimensionType DIMENSION;
public final NamespaceID namespaceID;
public final DynamicRegistry.Key<DimensionType> key;
Dimension(NamespaceID namespaceID, DimensionType dimType) {
this.DIMENSION = dimType;
this.namespaceID = namespaceID;
this.key = MinecraftServer.getDimensionTypeRegistry().register(namespaceID, DIMENSION);
this.key = MinecraftServer.getDimensionTypeRegistry().register(namespaceID, this.DIMENSION);
}
}

View File

@@ -7,7 +7,6 @@ import net.minestom.server.event.instance.AddEntityToInstanceEvent;
import net.minestom.server.event.instance.RemoveEntityFromInstanceEvent;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.instance.InstanceManager;
import net.minestom.server.registry.DynamicRegistry;
import net.minestom.server.timer.TaskSchedule;
import net.minestom.server.world.DimensionType;
@@ -19,9 +18,9 @@ public class MineNetInstance extends InstanceContainer {
super(UUID.randomUUID(), type);
MinecraftServer.getInstanceManager().registerInstance(this);
eventNode()
.addListener(AddEntityToInstanceEvent.class, this::onEntityAdd)
.addListener(RemoveEntityFromInstanceEvent.class, this::onEntityRemove);
this.eventNode()
.addListener(AddEntityToInstanceEvent.class, this::onEntityAdd)
.addListener(RemoveEntityFromInstanceEvent.class, this::onEntityRemove);
}
private void onEntityRemove(RemoveEntityFromInstanceEvent removeEntityFromInstanceEvent) {
@@ -38,6 +37,7 @@ public class MineNetInstance extends InstanceContainer {
/**
* Called when Player joins this instance
*
* @param p player who is joining
* @return setCanceled
*/
@@ -47,18 +47,15 @@ public class MineNetInstance extends InstanceContainer {
/**
* Called when Player leaves this instance
*
* @param p player who is leaving
*/
protected void onPlayerLeave(Player p) {
}
/**
*
* @param target
*/
public void destroy(Instance target) {
getPlayers().forEach(player -> {
this.getPlayers().forEach(player -> {
if(target != null)
player.setInstance(target);
else
@@ -66,9 +63,9 @@ public class MineNetInstance extends InstanceContainer {
});
MinecraftServer.getSchedulerManager().scheduleTask(
() -> MinecraftServer.getInstanceManager().unregisterInstance(this),
TaskSchedule.seconds(10),
TaskSchedule.stop()
() -> MinecraftServer.getInstanceManager().unregisterInstance(this),
TaskSchedule.seconds(10),
TaskSchedule.stop()
);
}
}

View File

@@ -1,14 +1,14 @@
package eu.mhsl.minenet.minigames.instance.game;
import eu.mhsl.minenet.minigames.instance.MineNetInstance;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.score.Score;
import eu.mhsl.minenet.minigames.util.CommonEventHandles;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.room.Room;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.Player;
@@ -28,34 +28,26 @@ import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;
public abstract class Game extends MineNetInstance implements Spawnable {
protected final Random rnd = new Random();
protected final Logger logger;
protected Room parentRoom;
protected boolean isRunning = false;
protected boolean isBeforeBeginning = true;
protected final Random rnd = new Random(); //TODO better way than ths?
protected final Logger logger;
public Game(DynamicRegistry.Key<DimensionType> dimensionType) {
super(dimensionType);
MinecraftServer.getInstanceManager().registerInstance(this);
logger = Logger.getLogger("Game:" + getUuid());
this.logger = Logger.getLogger("Game:" + this.getUuid());
eventNode()
this.eventNode()
.addListener(PlayerMoveEvent.class, this::onPlayerMove)
.addListener(PlayerBlockBreakEvent.class, this::onBlockBreak)
.addListener(PlayerBlockPlaceEvent.class, this::onBlockPlace)
.addListener(ItemDropEvent.class, this::onItemDrop);
}
public Game setParent(Room parentRoom) {
this.parentRoom = parentRoom;
return this;
}
public static void initialize(GameFactory factory, List<Option<?>> options, Player owner) {
try {
Room originRoom = Room.getRoom(owner).orElseThrow();
@@ -69,18 +61,23 @@ public abstract class Game extends MineNetInstance implements Spawnable {
.appendTranslated(factory.description())
.send(originRoom.getAllMembers());
} catch (Exception e) {
} catch(Exception e) {
new ChatMessage(Icon.ERROR).appendStatic("Instance crashed: " + e.getMessage()).send(owner);
MinecraftServer.getSchedulerManager().scheduleNextTick(() -> Room.getRoom(owner).orElseThrow().moveMembersToRoomLobby());
e.printStackTrace(System.err);
}
}
public Game setParent(Room parentRoom) {
this.parentRoom = parentRoom;
return this;
}
/**
* Load and start countdown
*/
public void load() {
scheduler().submitTask(() -> {
this.scheduler().submitTask(() -> {
CompletableFuture<Void> callback = new CompletableFuture<>();
this.onLoad(callback);
// callback.whenComplete((unused, throwable) -> this.start());
@@ -90,13 +87,13 @@ public abstract class Game extends MineNetInstance implements Spawnable {
}
protected void start() {
isRunning = true;
isBeforeBeginning = false;
this.isRunning = true;
this.isBeforeBeginning = false;
this.onStart();
}
public void stop() {
isRunning = false;
this.isRunning = false;
this.onStop();
this.unload();
}
@@ -104,12 +101,12 @@ public abstract class Game extends MineNetInstance implements Spawnable {
public void unload() {
this.onUnload();
getPlayers().forEach(Room::setOwnRoom);
this.getPlayers().forEach(Room::setOwnRoom);
scheduler().scheduleTask(() -> {
this.scheduler().scheduleTask(() -> {
logger.info("stopping game instance " + this.uuid);
getPlayers().forEach(player -> player.kick("timeout"));
this.logger.info("stopping game instance " + this.uuid);
this.getPlayers().forEach(player -> player.kick("timeout"));
MinecraftServer.getInstanceManager().unregisterInstance(this);
@@ -120,9 +117,14 @@ public abstract class Game extends MineNetInstance implements Spawnable {
callback.complete(null);
}
protected void onStart() {}
protected void onStop() {}
protected void onUnload() {}
protected void onStart() {
}
protected void onStop() {
}
protected void onUnload() {
}
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
@@ -146,7 +148,7 @@ public abstract class Game extends MineNetInstance implements Spawnable {
}
protected void checkAbandoned() {
scheduleNextTick((instance) -> {
this.scheduleNextTick((instance) -> {
if(instance.getPlayers().isEmpty()) this.unload();
});
}
@@ -156,10 +158,10 @@ public abstract class Game extends MineNetInstance implements Spawnable {
}
public boolean isRunning() {
return isRunning;
return this.isRunning;
}
public Pos getSpawn() {
return new Pos(0,50,0);
return new Pos(0, 50, 0);
}
}

View File

@@ -1,14 +1,14 @@
package eu.mhsl.minenet.minigames.instance.game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.acidRain.AcidRainFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.anvilRun.AnvilRunFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.blockBreakRace.BlockBreakRaceFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.bowSpleef.BowSpleefFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.elytraRace.ElytraRaceFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.backrooms.BackroomsFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.bedwars.BedwarsFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.acidRain.AcidRainFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.blockBreakRace.BlockBreakRaceFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.bowSpleef.BowSpleefFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.deathcube.DeathcubeFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.elytraRace.ElytraRaceFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.fastbridge.FastbridgeFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.highGround.HighGroundFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.jumpDive.JumpDiveFactory;
@@ -16,8 +16,8 @@ import eu.mhsl.minenet.minigames.instance.game.stateless.types.minerun.MinerunFa
import eu.mhsl.minenet.minigames.instance.game.stateless.types.spaceSnake.SpaceSnakeFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.spleef.SpleefFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.stickfight.StickFightFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris.TetrisFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.sumo.SumoFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris.TetrisFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tntrun.TntRunFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.towerdefense.TowerdefenseFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.trafficlightrace.TrafficLightRaceFactory;
@@ -48,10 +48,12 @@ public enum GameList {
private final GameFactory factory;
private final GameType type;
GameList(GameFactory factory, GameType type) {
this.factory = factory;
this.type = type;
}
public GameFactory getFactory() {
return this.factory;
}

View File

@@ -22,15 +22,15 @@ public enum GameType {
}
public Material getIcon() {
return icon;
return this.icon;
}
public TranslatedComponent getTitle() {
return title;
return this.title;
}
public TranslatedComponent getDescription() {
return description;
return this.description;
}

View File

@@ -37,7 +37,7 @@ public class StatelessGame extends Game {
}
public String getName() {
return name;
return this.name;
}
public void setTimeLimit(int limit) {
@@ -47,24 +47,23 @@ public class StatelessGame extends Game {
this.timePlayed = 0;
}
if(this.timeLimit > 0) {
this.timeLimitTask = scheduler().submitTask(() -> {
if(!isRunning || timeLimit == 0) return TaskSchedule.stop();
if(timeLimit <= timePlayed) {
stop();
this.timeLimitTask = this.scheduler().submitTask(() -> {
if(!this.isRunning || this.timeLimit == 0) return TaskSchedule.stop();
if(this.timeLimit <= this.timePlayed) {
this.stop();
return TaskSchedule.stop();
}
int timeLeft = timeLimit - timePlayed;
switch (timeLeft) {
case 90, 60, 30, 10, 5, 4, 3, 2, 1 ->
new ChatMessage(Icon.TIME)
.appendStatic(String.valueOf(timeLeft))
.appendSpace()
.appendTranslated(timeLeft == 1 ? "common#secondsLeft_singular" : "common#secondsLeft_plural")
.send(getPlayers());
int timeLeft = this.timeLimit - this.timePlayed;
switch(timeLeft) {
case 90, 60, 30, 10, 5, 4, 3, 2, 1 -> new ChatMessage(Icon.TIME)
.appendStatic(String.valueOf(timeLeft))
.appendSpace()
.appendTranslated(timeLeft == 1 ? "common#secondsLeft_singular" : "common#secondsLeft_plural")
.send(this.getPlayers());
}
timePlayed++;
this.timePlayed++;
return TaskSchedule.seconds(1);
}, ExecutionType.TICK_START);
@@ -84,7 +83,7 @@ public class StatelessGame extends Game {
Duration fadeIn = Duration.ofMillis(300);
Duration stay = Duration.ofMillis(700);
return new Countdown(TitleMessage.class)
return new Countdown()
.countdown(
Audience.audience(this.getPlayers()),
5,
@@ -102,26 +101,27 @@ public class StatelessGame extends Game {
public void startAccessor() {
this.start();
}
@Override
protected void start() {
score.setInstance(this);
score.attachListeners();
this.score.setInstance(this);
this.score.attachListeners();
countdownStart().thenRun(super::start);
this.countdownStart().thenRun(super::start);
}
@Override
public void stop() {
isRunning = false;
this.isRunning = false;
this.onStop();
getScore().insertRemainingPlayers(getPlayers());
this.publishScore(getScore());
this.getScore().insertRemainingPlayers(this.getPlayers());
this.publishScore(this.getScore());
countdownUnload();
this.countdownUnload();
}
private void countdownUnload() {
new TitleMessage(Duration.ofSeconds(1)).appendTranslated("score#done").send(getPlayers());
scheduler().scheduleTask(this::unload, TaskSchedule.seconds(5), TaskSchedule.stop());
new TitleMessage(Duration.ofSeconds(1)).appendTranslated("score#done").send(this.getPlayers());
this.scheduler().scheduleTask(this::unload, TaskSchedule.seconds(5), TaskSchedule.stop());
}
}

View File

@@ -5,12 +5,12 @@ import java.util.ArrayList;
public class ConfigManager {
private final ArrayList<Option<?>> items = new ArrayList<>();
public ConfigManager addOption(Option option) {
items.add(option);
public ConfigManager addOption(Option<?> option) {
this.items.add(option);
return this;
}
public ArrayList<Option<?>> getAll() {
return items;
return this.items;
}
}

View File

@@ -4,15 +4,14 @@ import eu.mhsl.minenet.minigames.instance.game.Game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.restriction.Restriction;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.restriction.RestrictionData;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.restriction.RestrictionHandler;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
import eu.mhsl.minenet.minigames.shared.inventory.InteractableInventory;
import eu.mhsl.minenet.minigames.util.InventoryItemAlignment;
import eu.mhsl.minenet.minigames.instance.room.Room;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.format.NamedTextColor;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
import net.minestom.server.event.EventListener;
import net.minestom.server.event.instance.AddEntityToInstanceEvent;
import net.minestom.server.event.instance.RemoveEntityFromInstanceEvent;
import net.minestom.server.inventory.InventoryType;
@@ -40,54 +39,54 @@ public class GameConfigurationInventory extends InteractableInventory {
this.factory = factory;
room.eventNode()
.addListener(AddEntityToInstanceEvent.class, addEntityToInstanceEvent -> MinecraftServer.getSchedulerManager().scheduleNextTick(this::updatePlayButton))
.addListener(RemoveEntityFromInstanceEvent.class, removeEntityFromInstanceEvent -> MinecraftServer.getSchedulerManager().scheduleNextTick(this::updatePlayButton));
.addListener(AddEntityToInstanceEvent.class, addEntityToInstanceEvent -> MinecraftServer.getSchedulerManager().scheduleNextTick(this::updatePlayButton))
.addListener(RemoveEntityFromInstanceEvent.class, removeEntityFromInstanceEvent -> MinecraftServer.getSchedulerManager().scheduleNextTick(this::updatePlayButton));
ConfigManager config = factory.configuration();
setClickableItem(
ItemStack.builder(Material.RED_WOOL)
.customName(
TranslatedComponent.byId("common#back")
.setColor(NamedTextColor.RED)
.getAssembled(p)
)
.build(),
0,
itemClick -> itemClick.getPlayer().closeInventory(),
true
this.setClickableItem(
ItemStack.builder(Material.RED_WOOL)
.customName(
TranslatedComponent.byId("common#back")
.setColor(NamedTextColor.RED)
.getAssembled(p)
)
.build(),
0,
itemClick -> itemClick.getPlayer().closeInventory(),
true
);
setDummyItem(Material.BLACK_STAINED_GLASS_PANE,1);
this.setDummyItem(Material.BLACK_STAINED_GLASS_PANE, 1);
setDummyItem(
ItemStack.builder(Material.NAME_TAG)
.customName(
factory.name().setColor(NamedTextColor.GOLD).getAssembled(p)
)
.build(),
4
this.setDummyItem(
ItemStack.builder(Material.NAME_TAG)
.customName(
factory.name().setColor(NamedTextColor.GOLD).getAssembled(p)
)
.build(),
4
);
setDummyItem(Material.BLACK_STAINED_GLASS_PANE,7);
this.setDummyItem(Material.BLACK_STAINED_GLASS_PANE, 7);
updatePlayButton();
this.updatePlayButton();
for(int i = 9; i <= 17; i++) {
setDummyItem(Material.BLACK_STAINED_GLASS_PANE, i);
this.setDummyItem(Material.BLACK_STAINED_GLASS_PANE, i);
}
if(config == null) {
setDummyItem(
ItemStack.builder(Material.BARRIER)
.customName(
TranslatedComponent.byId("room#noOption").setColor(NamedTextColor.RED).getAssembled(p)
)
.lore(
TranslatedComponent.assemble("room#noOptionDescription", p)
)
.build(),
31
this.setDummyItem(
ItemStack.builder(Material.BARRIER)
.customName(
TranslatedComponent.byId("room#noOption").setColor(NamedTextColor.RED).getAssembled(p)
)
.lore(
TranslatedComponent.assemble("room#noOptionDescription", p)
)
.build(),
31
);
} else {
@@ -95,11 +94,11 @@ public class GameConfigurationInventory extends InteractableInventory {
InventoryItemAlignment itemAlignment = new InventoryItemAlignment(config.getAll().size(), 3);
for(Option<?> item : config.getAll()) {
InventoryItemAlignment.ItemOffset current = itemAlignment.next();
map.put(offset + current.get(), item);
this.map.put(offset + current.get(), item);
setDummyItem(
item.getCurrent(p),
offset + current.get()
this.setDummyItem(
item.getCurrent(p),
offset + current.get()
);
}
}
@@ -110,59 +109,59 @@ public class GameConfigurationInventory extends InteractableInventory {
protected void onClick(Player player, int slot, ClickType clickType, InventoryConditionResult inventoryConditionResult) {
inventoryConditionResult.setCancel(true);
if(!map.containsKey(slot)) return;
if(!this.map.containsKey(slot)) return;
Option<?> item = map.get(slot);
setDummyItem(
item.getNext(p),
slot
Option<?> item = this.map.get(slot);
this.setDummyItem(
item.getNext(this.p),
slot
);
update();
this.update();
}
private void updatePlayButton() {
RestrictionHandler restrictionHandler = factory.globalRestrictions();
RestrictionData restrictionData = new RestrictionData(room);
RestrictionHandler restrictionHandler = this.factory.globalRestrictions();
RestrictionData restrictionData = new RestrictionData(this.room);
if(restrictionHandler.canPlay(restrictionData)) {
setClickableItem(
ItemStack.builder(restrictionHandler.getWarnings(restrictionData).size() > 0 ? Material.YELLOW_WOOL : Material.GREEN_WOOL)
.customName(TranslatedComponent.byId("restriction#success").setColor(NamedTextColor.GREEN).getAssembled(p))
.lore(restrictionHandler.getWarnings(restrictionData).stream().map(translatedComponent -> translatedComponent.getAssembled(p)).collect(Collectors.toList()))
.build(),
8,
itemClick -> Game.initialize(factory, map.values().stream().toList(), itemClick.getPlayer()),
true
this.setClickableItem(
ItemStack.builder(!restrictionHandler.getWarnings(restrictionData).isEmpty() ? Material.YELLOW_WOOL : Material.GREEN_WOOL)
.customName(TranslatedComponent.byId("restriction#success").setColor(NamedTextColor.GREEN).getAssembled(this.p))
.lore(restrictionHandler.getWarnings(restrictionData).stream().map(translatedComponent -> translatedComponent.getAssembled(this.p)).collect(Collectors.toList()))
.build(),
8,
itemClick -> Game.initialize(this.factory, this.map.values().stream().toList(), itemClick.getPlayer()),
true
);
} else {
setClickableItem(
ItemStack.builder(Material.RED_WOOL)
.customName(TranslatedComponent.byId("restriction#fail").setColor(NamedTextColor.RED).getAssembled(p))
.lore(
restrictionHandler.getRestrictions()
.stream()
.filter(iRestriction -> iRestriction.calculate(restrictionData).type().equals(Restriction.Type.FAIL))
.map(iRestriction -> iRestriction.calculate(restrictionData).description().getAssembled(p))
.collect(Collectors.toList()))
.build(),
8,
itemClick -> {
if(restrictionHandler.canPlay(restrictionData)) {
updatePlayButton();
return;
}
itemClick.getPlayer().playSound(Sound.sound(SoundEvent.ENTITY_SILVERFISH_DEATH, Sound.Source.AMBIENT, 1f, 1f));
},
false
this.setClickableItem(
ItemStack.builder(Material.RED_WOOL)
.customName(TranslatedComponent.byId("restriction#fail").setColor(NamedTextColor.RED).getAssembled(this.p))
.lore(
restrictionHandler.getRestrictions()
.stream()
.filter(iRestriction -> iRestriction.calculate(restrictionData).type().equals(Restriction.Type.FAIL))
.map(iRestriction -> iRestriction.calculate(restrictionData).description().getAssembled(this.p))
.collect(Collectors.toList()))
.build(),
8,
itemClick -> {
if(restrictionHandler.canPlay(restrictionData)) {
this.updatePlayButton();
return;
}
itemClick.getPlayer().playSound(Sound.sound(SoundEvent.ENTITY_SILVERFISH_DEATH, Sound.Source.AMBIENT, 1f, 1f));
},
false
);
}
update();
this.update();
}
}

View File

@@ -12,9 +12,11 @@ import java.util.Map;
public interface GameFactory {
TranslatedComponent name();
default ConfigManager configuration() {
return null;
}
default RestrictionHandler globalRestrictions() {
return new RestrictionHandler();
}
@@ -22,6 +24,7 @@ public interface GameFactory {
default Material symbol() {
return Material.GRASS_BLOCK;
}
default TranslatedComponent description() {
return TranslatedComponent.byId("GameFactory#missingDescription");
}
@@ -29,17 +32,17 @@ public interface GameFactory {
Game manufacture(Room parent, Map<String, Option<?>> configuration) throws Exception;
default Game manufacture(Room parent, List<Option<?>> configuration) throws Exception {
if(configuration == null) return manufacture(parent);
if(configuration == null) return this.manufacture(parent);
Map<String, Option<?>> cnf = new HashMap<>();
configuration.forEach(option -> cnf.put(option.getId(), option));
return manufacture(parent, cnf);
return this.manufacture(parent, cnf);
}
default Game manufacture(Room parent) throws Exception {
if(this.configuration() == null) return manufacture(parent, List.of());
if(this.configuration() == null) return this.manufacture(parent, List.of());
return manufacture(parent, this.configuration().getAll());
return this.manufacture(parent, this.configuration().getAll());
}
}

View File

@@ -12,12 +12,12 @@ import java.util.List;
import java.util.Objects;
public abstract class Option<T> {
private RestrictionHandler restrictionHandler;
private final Material item;
private final TranslatedComponent name;
private final String id;
protected T currentValue;
private final List<T> options;
protected T currentValue;
private RestrictionHandler restrictionHandler;
private int pointer = 0;
public Option(String id, Material item, TranslatedComponent name, List<T> options) {
@@ -26,46 +26,45 @@ public abstract class Option<T> {
this.name = name;
this.options = options;
currentValue = options.getFirst();
this.currentValue = options.getFirst();
}
public RestrictionHandler getRestrictionHandler() {
return this.restrictionHandler;
}
public void setRestrictionHandler(RestrictionHandler restrictionHandler) {
this.restrictionHandler = restrictionHandler;
}
public RestrictionHandler getRestrictionHandler() {
return restrictionHandler;
}
public ItemStack getNext(Player p) {
if(++pointer >= options.size()) pointer = 0;
currentValue = options.get(pointer);
return getCurrent(p);
if(++this.pointer >= this.options.size()) this.pointer = 0;
this.currentValue = this.options.get(this.pointer);
return this.getCurrent(p);
}
public ItemStack getCurrent(Player p) {
String value = options.get(pointer).toString();
return ItemStack.builder(item)
.customName(name.getAssembled(p))
.lore(TranslatedComponent.byId("optionCommon#value").setColor(NamedTextColor.GOLD).getAssembled(p)
.append(Component.text(": ")).append(Component.text(value)))
.build();
String value = this.options.get(this.pointer).toString();
return ItemStack.builder(this.item)
.customName(this.name.getAssembled(p))
.lore(TranslatedComponent.byId("optionCommon#value").setColor(NamedTextColor.GOLD).getAssembled(p)
.append(Component.text(": ")).append(Component.text(value)))
.build();
}
public int getAsInt() {
return Integer.parseInt(getAsString());
return Integer.parseInt(this.getAsString());
}
public boolean getAsBoolean() {
return Objects.equals(getAsString(), "true") || Objects.equals(getAsString(), "1");
return Objects.equals(this.getAsString(), "true") || Objects.equals(this.getAsString(), "1");
}
public String getAsString() {
return currentValue.toString();
return this.currentValue.toString();
}
public String getId() {
return id;
return this.id;
}
}

View File

@@ -10,7 +10,7 @@ public record Restriction(TranslatedComponent name, TranslatedComponent descript
this.warnMessage = warnMessage;
this.type = type;
if (this.warnMessage == null && this.type.equals(Type.WARN)) {
if(this.warnMessage == null && this.type.equals(Type.WARN)) {
throw new IllegalStateException("warnMessage cannot be null when RestrictionType is WARN");
}
}

View File

@@ -22,18 +22,18 @@ public class RestrictionHandler {
}
public List<IRestriction> getRestrictions() {
return restrictions;
return this.restrictions;
}
public boolean canPlay(RestrictionData data) {
if(restrictions.size() < 1) return true;
if(this.restrictions.isEmpty()) return true;
return this.restrictions.stream()
.noneMatch(iRestriction -> iRestriction.calculate(data).type().equals(Restriction.Type.FAIL));
.noneMatch(iRestriction -> iRestriction.calculate(data).type().equals(Restriction.Type.FAIL));
}
public List<TranslatedComponent> getWarnings(RestrictionData data) {
List<TranslatedComponent> warnings = new ArrayList<>();
for (IRestriction r : this.restrictions) {
for(IRestriction r : this.restrictions) {
Restriction calculated = r.calculate(data);
if(!calculated.type().equals(Restriction.Type.WARN)) continue;

View File

@@ -15,10 +15,10 @@ public class MaximalPlayeramountGameRestriction implements IRestriction {
@Override
public Restriction calculate(RestrictionData data) {
return new Restriction(
TranslatedComponent.byId("restriction#maxPlayersInRoom"),
TranslatedComponent.byId("restriction#maxPlayersInRoomDescription"),
null,
data.room().getAllMembers().size() > this.max ? Restriction.Type.FAIL : Restriction.Type.OK
TranslatedComponent.byId("restriction#maxPlayersInRoom"),
TranslatedComponent.byId("restriction#maxPlayersInRoomDescription"),
null,
data.room().getAllMembers().size() > this.max ? Restriction.Type.FAIL : Restriction.Type.OK
);
}
}

View File

@@ -15,10 +15,10 @@ public class MinimalPlayeramountGameRestriction implements IRestriction {
@Override
public Restriction calculate(RestrictionData data) {
return new Restriction(
TranslatedComponent.byId("restriction#minPlayersInRoom"),
TranslatedComponent.byId("restriction#minPlayersInRoomDescription"),
null,
data.room().getAllMembers().size() < this.min ? Restriction.Type.FAIL : Restriction.Type.OK
TranslatedComponent.byId("restriction#minPlayersInRoom"),
TranslatedComponent.byId("restriction#minPlayersInRoomDescription"),
null,
data.room().getAllMembers().size() < this.min ? Restriction.Type.FAIL : Restriction.Type.OK
);
}
}

View File

@@ -27,26 +27,26 @@ import java.util.concurrent.CompletableFuture;
public class AcidRain extends StatelessGame {
final private int radius = 20;
private int generationOffset = 0;
final private int roofHeight = 55;
private int difficulty = 0;
final JNoise noise = JNoise.newBuilder()
.fastSimplex()
.setSeed(rnd.nextLong())
.setFrequency(0.09)
.build();
.fastSimplex()
.setSeed(this.rnd.nextLong())
.setFrequency(0.09)
.build();
final private int radius = 20;
final private int roofHeight = 55;
private int generationOffset = 0;
private int difficulty = 0;
public AcidRain() {
super(Dimension.OVERWORLD.key, "acidRain", new LastWinsScore());
setGenerator(
new CircularPlateTerrainGenerator(radius)
.setPlateHeight(50)
.setPlatePallet(BlockPallet.STONE)
this.setGenerator(
new CircularPlateTerrainGenerator(this.radius)
.setPlateHeight(50)
.setPlatePallet(BlockPallet.STONE)
);
eventNode().addListener(PlayerTickEvent.class, this::onPlayerTick);
this.eventNode().addListener(PlayerTickEvent.class, this::onPlayerTick);
}
@Override
@@ -61,39 +61,40 @@ public class AcidRain extends StatelessGame {
MinecraftServer.getSchedulerManager().submitTask(() -> {
getPlayers().forEach(player -> {
player.sendPacket(new ParticlePacket(Particle.SNEEZE, 0, 60, 0, radius, radius, radius, 1f, 500));
player.sendPacket(new ParticlePacket(Particle.ITEM_SLIME, 0, 60, 0, radius, radius, radius, 1f, 500));
this.getPlayers().forEach(player -> {
player.sendPacket(new ParticlePacket(Particle.SNEEZE, 0, 60, 0, this.radius, this.radius, this.radius, 1f, 500));
player.sendPacket(new ParticlePacket(Particle.ITEM_SLIME, 0, 60, 0, this.radius, this.radius, this.radius, 1f, 500));
});
if(!isRunning) return TaskSchedule.stop();
if(!this.isRunning) return TaskSchedule.stop();
return TaskSchedule.millis(100);
}, ExecutionType.TICK_END);
MinecraftServer.getSchedulerManager().submitTask(() -> {
generationOffset++;
generatePlatform(generationOffset);
this.generationOffset++;
this.generatePlatform(this.generationOffset);
if(!isRunning) return TaskSchedule.stop();
return TaskSchedule.millis((long) NumberUtil.map(50 - difficulty, 0, 50, 100, 1000));
if(!this.isRunning) return TaskSchedule.stop();
return TaskSchedule.millis((long) NumberUtil.map(50 - this.difficulty, 0, 50, 100, 1000));
}, ExecutionType.TICK_END);
MinecraftServer.getSchedulerManager().submitTask(() -> {
difficulty++;
this.difficulty++;
if(difficulty >= 50) return TaskSchedule.stop();
if(this.difficulty >= 50) return TaskSchedule.stop();
return TaskSchedule.seconds(3);
});
}
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < 50) playerDeath(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().y() < 50) this.playerDeath(playerMoveEvent.getPlayer());
}
private void onPlayerTick(PlayerTickEvent playerTickEvent) {
if(isBeforeBeginning) return;
if(getBlock(playerTickEvent.getPlayer().getPosition().withY(roofHeight)).isAir()) playerDeath(playerTickEvent.getPlayer());
if(this.isBeforeBeginning) return;
if(this.getBlock(playerTickEvent.getPlayer().getPosition().withY(this.roofHeight)).isAir())
this.playerDeath(playerTickEvent.getPlayer());
}
private void generatePlatform(long offset) {
@@ -102,19 +103,20 @@ public class AcidRain extends StatelessGame {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
batch.setBlock(x, roofHeight, z, Block.AIR);
batch.setBlock(x, this.roofHeight, z, Block.AIR);
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
if(noise.getNoise(x + offset, z + offset) > 0.4) continue;
if(this.noise.getNoise(x + offset, z + offset) > 0.4) continue;
batch.setBlock(x, roofHeight, z, Block.OAK_PLANKS);
batch.setBlock(x, this.roofHeight, z, Block.OAK_PLANKS);
}
}
BatchUtil.loadAndApplyBatch(batch, this, () -> {});
BatchUtil.loadAndApplyBatch(batch, this, () -> {
});
}
private void playerDeath(Player p) {
p.setGameMode(GameMode.SPECTATOR);
getScore().insertResult(p);
this.getScore().insertResult(p);
}
@Override

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.anvilRun;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.LastWinsScore;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import eu.mhsl.minenet.minigames.world.generator.terrain.CircularPlateTerrainGenerator;
import net.minestom.server.MinecraftServer;
@@ -27,10 +27,10 @@ class AnvilRun extends StatelessGame {
final int spawnHeight = 30;
final int radius;
int anvilsPerSecond;
final int seconds;
final int anvilHeight = 200;
final List<Pos> anvilSpawnPositions = new ArrayList<>();
int anvilsPerSecond;
public AnvilRun(int radius, int seconds) {
super(Dimension.OVERWORLD.key, "Anvil Run", new LastWinsScore());
@@ -38,25 +38,25 @@ class AnvilRun extends StatelessGame {
this.seconds = seconds;
this.setGenerator(new CircularPlateTerrainGenerator(radius));
eventNode().addListener(EntityTickEvent.class, this::onEntityTick);
this.eventNode().addListener(EntityTickEvent.class, this::onEntityTick);
}
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
anvilSpawnPositions.add(new Pos(x+0.5, anvilHeight, z+0.5));
this.anvilSpawnPositions.add(new Pos(x + 0.5, this.anvilHeight, z + 0.5));
batch.setBlock(x, spawnHeight-1, z, Block.SNOW_BLOCK);
batch.setBlock(x, this.spawnHeight - 1, z, Block.SNOW_BLOCK);
}
}
this.anvilsPerSecond = anvilSpawnPositions.size() / this.seconds;
Collections.shuffle(anvilSpawnPositions);
this.anvilsPerSecond = this.anvilSpawnPositions.size() / this.seconds;
Collections.shuffle(this.anvilSpawnPositions);
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
}
@@ -72,12 +72,12 @@ class AnvilRun extends StatelessGame {
super.onStart();
Scheduler scheduler = MinecraftServer.getSchedulerManager();
for(int i=0; i<this.anvilSpawnPositions.size(); i++) {
for(int i = 0; i < this.anvilSpawnPositions.size(); i++) {
final int j = i;
scheduler.scheduleTask(
() -> spawnAnvil(this.anvilSpawnPositions.get(j)),
() -> this.spawnAnvil(this.anvilSpawnPositions.get(j)),
TaskSchedule.millis(
(long) Math.floor((double) i/this.anvilsPerSecond * 1000)
(long) Math.floor((double) i / this.anvilsPerSecond * 1000)
),
TaskSchedule.stop()
);
@@ -87,25 +87,26 @@ class AnvilRun extends StatelessGame {
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
super.onPlayerMove(playerMoveEvent);
if(isBeforeBeginning && playerMoveEvent.getNewPosition().y() < spawnHeight - 2) {
if(this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() < this.spawnHeight - 2) {
playerMoveEvent.setCancelled(true);
playerMoveEvent.getPlayer().teleport(getSpawn());
playerMoveEvent.getPlayer().teleport(this.getSpawn());
return;
}
if(playerMoveEvent.getNewPosition().y() < spawnHeight - 2) getScore().insertResult(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().y() < this.spawnHeight - 2)
this.getScore().insertResult(playerMoveEvent.getPlayer());
}
protected void onEntityTick(@NotNull EntityTickEvent entityTickEvent) {
if(!entityTickEvent.getEntity().getEntityType().equals(EntityType.FALLING_BLOCK)) return;
Pos anvilPosition = entityTickEvent.getEntity().getPosition();
if(anvilPosition.y() > spawnHeight + 0.5) return;
if(anvilPosition.y() < spawnHeight - 3) entityTickEvent.getEntity().remove();
if(this.getBlock(anvilPosition.withY(spawnHeight-1)).isAir()) return;
this.setBlock(anvilPosition.withY(spawnHeight-1), Block.AIR);
if(anvilPosition.y() > this.spawnHeight + 0.5) return;
if(anvilPosition.y() < this.spawnHeight - 3) entityTickEvent.getEntity().remove();
if(this.getBlock(anvilPosition.withY(this.spawnHeight - 1)).isAir()) return;
this.setBlock(anvilPosition.withY(this.spawnHeight - 1), Block.AIR);
}
@Override
public Pos getSpawn() {
return new Pos(0, spawnHeight, 0);
return new Pos(0, this.spawnHeight, 0);
}
}

View File

@@ -1,9 +1,9 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.anvilRun;
import eu.mhsl.minenet.minigames.instance.game.Game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;

View File

@@ -10,7 +10,7 @@ public class Backrooms extends StatelessGame {
public Backrooms() {
super(Dimension.NETHER.key, "Backrooms", new NoScore());
BackroomsGenerator generator = new BackroomsGenerator();
setGenerator(unit -> generator.generateRoom(unit, 50));
this.setGenerator(unit -> generator.generateRoom(unit, 50));
}
@Override

View File

@@ -3,6 +3,7 @@ package eu.mhsl.minenet.minigames.instance.game.stateless.types.backrooms;
import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.generator.GenerationUnit;
import net.minestom.server.instance.generator.UnitModifier;
import java.util.concurrent.ThreadLocalRandom;
public class BackroomsGenerator {
@@ -11,8 +12,8 @@ public class BackroomsGenerator {
var start = unit.absoluteStart();
var yPos = start.blockY() + y;
for (int x = 0; x < unit.size().blockX(); x++) {
for (int z = 0; z < unit.size().blockZ(); z++) {
for(int x = 0; x < unit.size().blockX(); x++) {
for(int z = 0; z < unit.size().blockZ(); z++) {
var xPos = start.blockX() + x;
var zPos = start.blockZ() + z;
@@ -23,27 +24,27 @@ public class BackroomsGenerator {
modifier.setBlock(xPos, yPos + 4, zPos, Block.SMOOTH_STONE_SLAB);
// idk man... dont ask about this
if (
(x - 2) % 4 == 0 && (
((z - 2) % 8 == 0) ||
((z - 2) % 8 == 1) ||
((z - 2) % 8 == 3) ||
((z - 2) % 8 == 4)
)
if(
(x - 2) % 4 == 0 && (
((z - 2) % 8 == 0) ||
((z - 2) % 8 == 1) ||
((z - 2) % 8 == 3) ||
((z - 2) % 8 == 4)
)
) {
modifier.setBlock(xPos, yPos + 4, zPos, Block.SEA_LANTERN);
}
}
}
generateWalls(modifier, start.blockX() + 0, yPos + 1, start.blockZ() + 0);
generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ() + 0);
generateWalls(modifier, start.blockX() + 0, yPos + 1, start.blockZ() + 8);
generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ() + 8);
this.generateWalls(modifier, start.blockX(), yPos + 1, start.blockZ());
this.generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ());
this.generateWalls(modifier, start.blockX(), yPos + 1, start.blockZ() + 8);
this.generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ() + 8);
}
private void generateWalls(UnitModifier modifier, int xPos, int yPos, int zPos) {
generatePillar(modifier, xPos, yPos, zPos, Block.CHISELED_SANDSTONE);
this.generatePillar(modifier, xPos, yPos, zPos, Block.CHISELED_SANDSTONE);
var random = ThreadLocalRandom.current();
@@ -55,31 +56,31 @@ public class BackroomsGenerator {
var door1pos = random.nextInt(2, 6);
var door2pos = random.nextInt(2, 6);
if (wall1) {
for (int x = xPos; x < xPos + 8; x++) {
generatePillar(modifier, x, yPos, zPos, Block.SMOOTH_SANDSTONE);
if(wall1) {
for(int x = xPos; x < xPos + 8; x++) {
this.generatePillar(modifier, x, yPos, zPos, Block.SMOOTH_SANDSTONE);
}
}
if (wall2) {
for (int z = zPos; z < zPos + 8; z++) {
generatePillar(modifier, xPos, yPos, z, Block.SMOOTH_SANDSTONE);
if(wall2) {
for(int z = zPos; z < zPos + 8; z++) {
this.generatePillar(modifier, xPos, yPos, z, Block.SMOOTH_SANDSTONE);
}
}
if (door1 && wall1) {
generatePillar(modifier, xPos + door1pos, yPos, zPos, Block.AIR);
generatePillar(modifier, xPos + door1pos + 1, yPos, zPos, Block.AIR);
if(door1 && wall1) {
this.generatePillar(modifier, xPos + door1pos, yPos, zPos, Block.AIR);
this.generatePillar(modifier, xPos + door1pos + 1, yPos, zPos, Block.AIR);
}
if (door2 && wall2) {
generatePillar(modifier, xPos, yPos, zPos + door2pos, Block.AIR);
generatePillar(modifier, xPos, yPos, zPos + door2pos + 1, Block.AIR);
if(door2 && wall2) {
this.generatePillar(modifier, xPos, yPos, zPos + door2pos, Block.AIR);
this.generatePillar(modifier, xPos, yPos, zPos + door2pos + 1, Block.AIR);
}
}
private void generatePillar(UnitModifier modifier, int xPos, int yPos, int zPos, Block material) {
for (int y = yPos; y < yPos + 3; y++) {
for(int y = yPos; y < yPos + 3; y++) {
modifier.setBlock(xPos, y, zPos, material);
}
}

View File

@@ -29,7 +29,9 @@ import net.minestom.server.timer.TaskSchedule;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Bedwars extends StatelessGame {
@@ -39,22 +41,22 @@ public class Bedwars extends StatelessGame {
public Bedwars() throws IOException {
super(Dimension.OVERWORLD.key, "Bedwars", new LastWinsScore());
setChunkLoader(new AnvilLoader(Resource.GAME_MAP.getPath().resolve("bedwars/test")));
this.setChunkLoader(new AnvilLoader(Resource.GAME_MAP.getPath().resolve("bedwars/test")));
Configuration config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(Resource.GAME_MAP.getPath().resolve("bedwars/test/config.yml").toFile());
List<String> teamNames = config.getStringList("setup.teams");
teamNames.forEach(teamName -> {
String path = "teams." + teamName;
teams.add(new BedwarsTeam(
config.getString(path + ".name"),
Position.getPosFromCommaSeparated(config.getString(path + ".pos.spawn")),
Position.getPosFromCommaSeparated(config.getString(path + ".pos.spawner")),
config.getStringList(path + ".pos.bed").stream().map(Position::getPosFromCommaSeparated).toList().toArray(new Pos[0]),
MaterialUtil.fromString(config.getString(path + ".material.block"), Material.BLACK_WOOL)
this.teams.add(new BedwarsTeam(
config.getString(path + ".name"),
Position.getPosFromCommaSeparated(config.getString(path + ".pos.spawn")),
Position.getPosFromCommaSeparated(config.getString(path + ".pos.spawner")),
config.getStringList(path + ".pos.bed").stream().map(Position::getPosFromCommaSeparated).toList().toArray(new Pos[0]),
MaterialUtil.fromString(config.getString(path + ".material.block"), Material.BLACK_WOOL)
));
});
eventNode().addListener(PickupItemEvent.class, pickupItemEvent -> {
this.eventNode().addListener(PickupItemEvent.class, pickupItemEvent -> {
if(pickupItemEvent.getEntity() instanceof Player p) {
p.getInventory().addItemStack(pickupItemEvent.getItemStack());
}
@@ -68,10 +70,10 @@ public class Bedwars extends StatelessGame {
@Override
protected void onStart() {
scheduler().submitTask(() -> {
if(!isRunning) return TaskSchedule.stop();
this.scheduler().submitTask(() -> {
if(!this.isRunning) return TaskSchedule.stop();
teams.forEach(bedwarsTeam -> {
this.teams.forEach(bedwarsTeam -> {
ItemEntity item = new ItemEntity(ItemStack.of(bedwarsTeam.getBlock()));
item.setNoGravity(true);
item.setInstance(this, bedwarsTeam.getSpawner());
@@ -84,16 +86,17 @@ public class Bedwars extends StatelessGame {
@Override
protected void onBlockPlace(@NotNull PlayerBlockPlaceEvent playerBlockPlaceEvent) {
placedBlocks.add(playerBlockPlaceEvent.getBlockPosition());
this.placedBlocks.add(playerBlockPlaceEvent.getBlockPosition());
}
@Override
protected void onBlockBreak(@NotNull PlayerBlockBreakEvent playerBlockBreakEvent) {
if(!placedBlocks.contains(playerBlockBreakEvent.getBlockPosition())) playerBlockBreakEvent.setCancelled(true);
if(!this.placedBlocks.contains(playerBlockBreakEvent.getBlockPosition()))
playerBlockBreakEvent.setCancelled(true);
teams.forEach(bedwarsTeam -> {
this.teams.forEach(bedwarsTeam -> {
if(Arrays.stream(bedwarsTeam.getBed()).anyMatch(pos -> pos.sameBlock(playerBlockBreakEvent.getBlockPosition())))
breakBed(bedwarsTeam);
this.breakBed(bedwarsTeam);
});
if(playerBlockBreakEvent.isCancelled())
@@ -102,13 +105,13 @@ public class Bedwars extends StatelessGame {
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < 0) death(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().y() < 0) this.death(playerMoveEvent.getPlayer());
}
private void breakBed(BedwarsTeam team) {
team.removeBed();
for (Pos blockPos : team.getBed()) {
setBlock(blockPos, Material.AIR.block());
for(Pos blockPos : team.getBed()) {
this.setBlock(blockPos, Material.AIR.block());
}
}

View File

@@ -20,7 +20,7 @@ public class BedwarsFactory implements GameFactory {
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(1));
.addRestriction(new MinimalPlayeramountGameRestriction(1));
}
@Override

View File

@@ -8,16 +8,12 @@ import java.util.ArrayList;
import java.util.List;
public class BedwarsTeam {
private List<Player> members = new ArrayList<>();
private final String name;
private final Pos spawn;
private final Pos spawner;
private final Pos[] bed;
private final Material block;
private List<Player> members = new ArrayList<>();
private boolean hasBed = true;
public BedwarsTeam(String name, Pos spawn, Pos spawner, Pos[] bed, Material block) {
@@ -33,11 +29,11 @@ public class BedwarsTeam {
}
public boolean isHasBed() {
return hasBed;
return this.hasBed;
}
public List<Player> getMembers() {
return members;
return this.members;
}
public void setMembers(List<Player> members) {
@@ -45,22 +41,22 @@ public class BedwarsTeam {
}
public String getName() {
return name;
return this.name;
}
public Pos getSpawn() {
return spawn;
return this.spawn;
}
public Pos getSpawner() {
return spawner;
return this.spawner;
}
public Pos[] getBed() {
return bed;
return this.bed;
}
public Material getBlock() {
return block;
return this.block;
}
}

View File

@@ -16,8 +16,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.List;
public class BlockBreakRace extends StatelessGame {
private int spawnCount = 0;
private final int height;
private int spawnCount = 0;
public BlockBreakRace(int height) {
super(Dimension.OVERWORLD.key, "blockBreakRace", new FirstWinsScore());

View File

@@ -11,16 +11,14 @@ import java.util.concurrent.ThreadLocalRandom;
public class BlockBreakRaceGenerator extends BaseGenerator {
public static final int BOTTOM_Y = 50;
public final int TOP_Y;
public static final int[] ROW_OFFSETS_X = {4, 8, 12};
public static final int[] ROW_OFFSETS_Z = {4, 8, 12};
private static final Block[] FILL_BLOCKS = {
Block.STONE,
Block.DIRT,
Block.OAK_PLANKS
};
public final int TOP_Y;
private final Random random = ThreadLocalRandom.current();
public BlockBreakRaceGenerator(int height) {
@@ -34,8 +32,8 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
this.addMixIn(unit -> {
if(unit.absoluteStart().chunkX() != 0) return;
for (int localX : ROW_OFFSETS_X) {
for (int localZ : ROW_OFFSETS_Z) {
for(int localX : ROW_OFFSETS_X) {
for(int localZ : ROW_OFFSETS_Z) {
final int absZ = unit.absoluteStart().blockZ() + localZ;
this.placeTube(unit, localX, absZ);
}
@@ -44,7 +42,7 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
}
private void placeTube(GenerationUnit unit, int x, int z) {
for (int y = BOTTOM_Y; y < this.TOP_Y; y++) {
for(int y = BOTTOM_Y; y < this.TOP_Y; y++) {
Block fill = FILL_BLOCKS[this.random.nextInt(FILL_BLOCKS.length)];
unit.modifier().fill(
new Pos(x, y, z),
@@ -53,9 +51,9 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
);
}
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
if (dx == 0 && dz == 0) continue; // Zentrum überspringen
for(int dx = -1; dx <= 1; dx++) {
for(int dz = -1; dz <= 1; dz++) {
if(dx == 0 && dz == 0) continue; // Zentrum überspringen
unit.modifier().fill(
new Pos(x + dx, BOTTOM_Y, z + dz),
new Pos(x + dx, this.TOP_Y + 3, z + dz).add(1),

View File

@@ -9,7 +9,9 @@ import eu.mhsl.minenet.minigames.util.GeneratorUtils;
import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.*;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.EntityType;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.metadata.other.PrimedTntMeta;
import net.minestom.server.event.EventListener;
import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent;
@@ -29,6 +31,7 @@ public class BowSpleef extends StatelessGame {
private static final Tag<Boolean> ARROW_FIRST_HIT = Tag.Boolean("ARROW_ALREADY_LIT");
private final int radius = 30;
private final int totalElevation = 50;
public BowSpleef() {
super(Dimension.OVERWORLD.key, "bowSpleef", new LastWinsScore());
@@ -67,41 +70,41 @@ public class BowSpleef extends StatelessGame {
// .build()
// );
eventNode().addListener(
EventListener
.builder(ProjectileCollideWithBlockEvent.class)
.handler(projectileBlockHitEvent -> {
Entity projectile = projectileBlockHitEvent.getEntity();
if(!projectile.getTag(ARROW_FIRST_HIT)) {
projectile.remove();
return;
}
this.eventNode().addListener(
EventListener
.builder(ProjectileCollideWithBlockEvent.class)
.handler(projectileBlockHitEvent -> {
Entity projectile = projectileBlockHitEvent.getEntity();
if(!projectile.getTag(ARROW_FIRST_HIT)) {
projectile.remove();
return;
}
float radius = 0.5F;
Point arrowPos = projectile.getPosition();
GeneratorUtils.foreachXZ(arrowPos.add(radius), arrowPos.sub(radius), point -> {
Point location = point.add(projectile.getVelocity().mul(0.04)).withY(totalElevation);
if(!getBlock(location).isAir()) {
setBlock(location, Block.AIR);
float radius = 0.5F;
Point arrowPos = projectile.getPosition();
GeneratorUtils.foreachXZ(arrowPos.add(radius), arrowPos.sub(radius), point -> {
Point location = point.add(projectile.getVelocity().mul(0.04)).withY(this.totalElevation);
if(!this.getBlock(location).isAir()) {
this.setBlock(location, Block.AIR);
Entity fallingTnt = new Entity(EntityType.TNT);
PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta();
fallingTntMeta.setFuseTime(20);
fallingTnt.setInstance(this, location);
fallingTnt.setVelocity(new Vec(0, 3, 0));
}
});
Entity fallingTnt = new Entity(EntityType.TNT);
PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta();
fallingTntMeta.setFuseTime(20);
fallingTnt.setInstance(this, location);
fallingTnt.setVelocity(new Vec(0, 3, 0));
}
});
projectile.setTag(ARROW_FIRST_HIT, false);
})
.build()
projectile.setTag(ARROW_FIRST_HIT, false);
})
.build()
);
eventNode().addListener(
EventListener
.builder(ProjectileCollideWithEntityEvent.class)
.handler(projectileEntityHitEvent -> projectileEntityHitEvent.setCancelled(true))
.build()
this.eventNode().addListener(
EventListener
.builder(ProjectileCollideWithEntityEvent.class)
.handler(projectileEntityHitEvent -> projectileEntityHitEvent.setCancelled(true))
.build()
);
}
@@ -109,11 +112,11 @@ public class BowSpleef extends StatelessGame {
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
batch.setBlock(x, totalElevation, z, Block.TNT);
batch.setBlock(x, this.totalElevation, z, Block.TNT);
}
}
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
@@ -121,28 +124,28 @@ public class BowSpleef extends StatelessGame {
@Override
protected void onStart() {
getPlayers().forEach(player -> {
this.getPlayers().forEach(player -> {
player.getInventory().setItemStack(
0,
ItemStack
.builder(Material.BOW)
.customName(TranslatedComponent.byId("bow").getAssembled(player))
.glowing(true)
.build()
0,
ItemStack
.builder(Material.BOW)
.customName(TranslatedComponent.byId("bow").getAssembled(player))
.glowing(true)
.build()
);
});
}
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) {
getScore().insertResult(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
}
}
@Override
public Pos getSpawn() {
return new Pos(0, totalElevation + 1, 0);
return new Pos(0, this.totalElevation + 1, 0);
}
}

View File

@@ -35,6 +35,6 @@ public class BowSpleefFactory implements GameFactory {
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2));
.addRestriction(new MinimalPlayeramountGameRestriction(2));
}
}

View File

@@ -1,9 +1,9 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.deathcube;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.world.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.CircularPlateTerrainGenerator;
import io.github.togar2.pvp.feature.CombatFeatures;
@@ -26,9 +26,9 @@ class Deathcube extends StatelessGame {
this.radius = radius;
this.height = height + 49;
this.percentage = percentage;
this.setGenerator(new CircularPlateTerrainGenerator(radius+10).setPlateHeight(50));
this.setGenerator(new CircularPlateTerrainGenerator(radius + 10).setPlateHeight(50));
if(pvpEnabled == 1) eventNode().addChild(
if(pvpEnabled == 1) this.eventNode().addChild(
CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE)
@@ -42,12 +42,12 @@ class Deathcube extends StatelessGame {
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
for (int y = 49; y < height; y++) {
if(super.rnd.nextInt(1, 100) <= percentage) {
for(int y = 49; y < this.height; y++) {
if(super.rnd.nextInt(1, 100) <= this.percentage) {
batch.setBlock(x, y, z, BlockPallet.WOOD.rnd());
}
}
@@ -62,20 +62,20 @@ class Deathcube extends StatelessGame {
super.onPlayerMove(playerMoveEvent);
if(playerMoveEvent.getNewPosition().y() < 48) {
playerMoveEvent.setCancelled(true);
playerMoveEvent.getPlayer().teleport(getSpawn());
playerMoveEvent.getPlayer().teleport(this.getSpawn());
return;
}
if(isBeforeBeginning && playerMoveEvent.getNewPosition().y() > 51.5) {
if(this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() > 51.5) {
playerMoveEvent.setCancelled(true);
return;
}
if(playerMoveEvent.getNewPosition().y() <= height) return;
getScore().insertResult(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().y() <= this.height) return;
this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
}
@Override
public Pos getSpawn() {
return new Pos(0, 50, -(radius+5));
return new Pos(0, 50, -(this.radius + 5));
}
}

View File

@@ -1,9 +1,9 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.deathcube;
import eu.mhsl.minenet.minigames.instance.game.Game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
@@ -25,10 +25,10 @@ public class DeathcubeFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("height", Material.SCAFFOLDING, TranslatedComponent.byId("optionCommon#height"), 10, 30, 50))
.addOption(new NumericOption("percentage", Material.COBWEB, TranslatedComponent.byId("game_Deathcube#optionPercentageBlocks"), 5, 7, 9, 11, 13))
.addOption(new NumericOption("pvpEnabled", Material.STICK, TranslatedComponent.byId("game_Deathcube#optionPvpEnabled"), 0, 1));
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("height", Material.SCAFFOLDING, TranslatedComponent.byId("optionCommon#height"), 10, 30, 50))
.addOption(new NumericOption("percentage", Material.COBWEB, TranslatedComponent.byId("game_Deathcube#optionPercentageBlocks"), 5, 7, 9, 11, 13))
.addOption(new NumericOption("pvpEnabled", Material.STICK, TranslatedComponent.byId("game_Deathcube#optionPvpEnabled"), 0, 1));
}

View File

@@ -69,12 +69,12 @@ public class ElytraRace extends StatelessGame {
Player player = playerUseItemEvent.getPlayer();
Material usedMaterial = playerUseItemEvent.getItemStack().material();
if (usedMaterial.equals(this.boostMaterial)) {
if (!player.isFlyingWithElytra()) return;
if(usedMaterial.equals(this.boostMaterial)) {
if(!player.isFlyingWithElytra()) return;
this.boost(player);
InventoryUtil.removeItemFromPlayer(player, this.boostMaterial, 1);
} else if (usedMaterial.equals(this.resetMaterial)) {
} else if(usedMaterial.equals(this.resetMaterial)) {
this.toCheckpoint(player);
InventoryUtil.removeItemFromPlayer(player, this.resetMaterial, 1);
}
@@ -82,7 +82,7 @@ public class ElytraRace extends StatelessGame {
this.eventNode().addListener(PlayerStopFlyingWithElytraEvent.class, playerStopFlyingWithElytraEvent -> {
Player player = playerStopFlyingWithElytraEvent.getPlayer();
if (Position.blocksBelowPlayer(this, player).contains(this.ringMaterial.block())) {
if(Position.blocksBelowPlayer(this, player).contains(this.ringMaterial.block())) {
player.setFlyingWithElytra(true);
this.boost(player);
} else {
@@ -93,7 +93,7 @@ public class ElytraRace extends StatelessGame {
});
this.eventNode().addListener(PlayerStartFlyingWithElytraEvent.class, playerStartFlyingWithElytraEvent -> {
if (!this.isRunning) {
if(!this.isRunning) {
playerStartFlyingWithElytraEvent.getPlayer().setFlyingWithElytra(false);
return;
}
@@ -116,7 +116,7 @@ public class ElytraRace extends StatelessGame {
protected void onStart() {
this.getPlayers().forEach(player -> {
player.getInventory().setEquipment(EquipmentSlot.CHESTPLATE, (byte) 0, ItemStack.of(Material.ELYTRA));
for (int i = 0; i < 3; i++) {
for(int i = 0; i < 3; i++) {
player.getInventory().setItemStack(i, ItemStack.builder(this.boostMaterial).customName(TranslatedComponent.byId("boost").getAssembled(player)).build());
}
this.addResetItemToPlayer(player);
@@ -128,23 +128,23 @@ public class ElytraRace extends StatelessGame {
Player player = playerMoveEvent.getPlayer();
Point newPos = playerMoveEvent.getNewPosition();
if (this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() < this.getSpawn().y()) {
if(this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() < this.getSpawn().y()) {
player.teleport(this.getSpawn());
return;
}
this.playerCheckpoints.putIfAbsent(player, new CheckPointData(this.ringSpacing, this.ringSpacing * 2));
if (newPos.z() > this.generatedUntil - this.ringSpacing) {
if(newPos.z() > this.generatedUntil - this.ringSpacing) {
this.generateRing(this.generatedUntil + this.ringSpacing);
}
if (newPos.z() > this.playerCheckpoints.get(player).nextCheckpoint) {
if(newPos.z() > this.playerCheckpoints.get(player).nextCheckpoint) {
this.playerCheckpoints.put(player, this.playerCheckpoints.get(player).next(this.ringSpacing));
this.boost(player);
}
if (newPos.y() > this.gameHeight - 5) {
if(newPos.y() > this.gameHeight - 5) {
Point particlePoint = newPos.withY(this.gameHeight);
ParticlePacket particle = new ParticlePacket(
Particle.WAX_ON,
@@ -160,11 +160,11 @@ public class ElytraRace extends StatelessGame {
player.sendPacket(particle);
}
if (this.getBlock(player.getPosition()).equals(Block.WATER)) {
if(this.getBlock(player.getPosition()).equals(Block.WATER)) {
this.toCheckpoint(player);
}
if (newPos.z() > this.ringCount * this.ringSpacing) {
if(newPos.z() > this.ringCount * this.ringSpacing) {
this.getScore().insertResult(player);
player.setGameMode(GameMode.SPECTATOR);
player.setFlyingWithElytra(false);
@@ -185,8 +185,8 @@ public class ElytraRace extends StatelessGame {
return new Pos(this.vale.getXShiftAtZ(z), -45 + random.nextInt(-5, 15), z);
}
private CompletableFuture<Void> generateRing(int zPos) {
if (zPos > this.ringCount * this.ringSpacing) return null;
private void generateRing(int zPos) {
if(zPos > this.ringCount * this.ringSpacing) return;
boolean isLast = (zPos == this.ringCount * this.ringSpacing);
this.generatedUntil = zPos;
@@ -211,7 +211,6 @@ public class ElytraRace extends StatelessGame {
BatchUtil.loadAndApplyBatch(batch, this, () -> {
});
return null;
}
private void boost(Player player) {
@@ -233,7 +232,7 @@ public class ElytraRace extends StatelessGame {
p.setFlying(true);
p.setFlyingSpeed(0);
new Countdown(TitleMessage.class)
new Countdown()
.countdown(
Audience.audience(p),
3,

View File

@@ -30,7 +30,7 @@ public class ElytraRaceFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("ringCount", Material.DIAMOND_BLOCK, TranslatedComponent.byId("game_ElytraRace#ringCount"), 5, 10, 20, 30, 40, 50));
.addOption(new NumericOption("ringCount", Material.DIAMOND_BLOCK, TranslatedComponent.byId("game_ElytraRace#ringCount"), 5, 10, 20, 30, 40, 50));
}
@Override

View File

@@ -28,8 +28,8 @@ public class Fastbridge extends StatelessGame {
Pos newPos = playerMoveEvent.getNewPosition();
if(this.getScore().hasResult(player)) return;
if(newPos.y() < 0) {
player.teleport(getSpawn());
if(!isBeforeBeginning) this.resetPlayer(player);
player.teleport(this.getSpawn());
if(!this.isBeforeBeginning) this.resetPlayer(player);
}
if(newPos.x() > 53) {
this.getScore().insertResult(player);
@@ -39,19 +39,19 @@ public class Fastbridge extends StatelessGame {
@Override
protected void onStart() {
getPlayers().forEach(player -> {
this.getPlayers().forEach(player -> {
player.setGameMode(GameMode.SURVIVAL);
resetPlayer(player);
this.resetPlayer(player);
});
}
@Override
protected void onBlockPlace(@NotNull PlayerBlockPlaceEvent playerBlockPlaceEvent) {
if(isBeforeBeginning) playerBlockPlaceEvent.setCancelled(true);
if(this.isBeforeBeginning) playerBlockPlaceEvent.setCancelled(true);
}
private void resetPlayer(Player player) {
if(isBeforeBeginning) return;
if(this.isBeforeBeginning) return;
PlayerInventory inventory = player.getInventory();
inventory.clear();
inventory.addItemStack(ItemStack.of(Material.WHITE_WOOL, 64));
@@ -59,6 +59,6 @@ public class Fastbridge extends StatelessGame {
@Override
public synchronized Pos getSpawn() {
return new Pos(24, 1, currentSpawn++*Chunk.CHUNK_SIZE_Z*2-8, -90, 0);
return new Pos(24, 1, this.currentSpawn++ * Chunk.CHUNK_SIZE_Z * 2 - 8, -90, 0);
}
}

View File

@@ -7,14 +7,14 @@ import net.minestom.server.instance.block.Block;
public class FastbridgeChunkgenerator extends BaseGenerator {
public FastbridgeChunkgenerator() {
this.addMixIn(unit -> {
if (unit.absoluteStart().chunkZ() % 2 == 0) {
if(unit.absoluteStart().chunkZ() % 2 == 0) {
unit.modifier().fill(Block.BARRIER);
return;
}
if (unit.absoluteStart().chunkX() != 1 && unit.absoluteStart().chunkX() != 3) return;
for (int x = 5; x <= 10; x++){
for (int z = 5; z <= 10; z++){
if(unit.absoluteStart().chunkX() != 1 && unit.absoluteStart().chunkX() != 3) return;
for(int x = 5; x <= 10; x++) {
for(int z = 5; z <= 10; z++) {
unit.modifier().setRelative(x, 64, z, unit.absoluteStart().chunkX() == 3 ? Block.GOLD_BLOCK : Block.GRASS_BLOCK);
}
}

View File

@@ -43,7 +43,7 @@ class HighGround extends StatelessGame {
);
this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if(this.isBeforeBeginning){
if(this.isBeforeBeginning) {
prepareAttackEvent.setCancelled(true);
}
});
@@ -53,10 +53,10 @@ class HighGround extends StatelessGame {
entityKnockbackEvent -> entityKnockbackEvent.setStrength(1.1f)
);
this.eventNode().addListener(InstanceTickEvent.class, instanceTickEvent -> {
if (this.isBeforeBeginning || !this.isRunning) return;
this.eventNode().addListener(InstanceTickEvent.class, instanceTickEvent -> {
if(this.isBeforeBeginning || !this.isRunning) return;
this.getPlayers().forEach(player -> {
if((player.isOnGround() && player.getPosition().y() >= 1) || (!player.isOnGround() && player.getPosition().y() >= 1.5)){
if((player.isOnGround() && player.getPosition().y() >= 1) || (!player.isOnGround() && player.getPosition().y() >= 1.5)) {
this.scoreMap.put(player, this.scoreMap.get(player) + 1);
player.setLevel(this.scoreMap.get(player) / 20);
player.setExp((this.scoreMap.get(player) % 20) / 20.0f);
@@ -67,20 +67,20 @@ class HighGround extends StatelessGame {
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
for (int y = 0; y >= -3; y--) {
for(int y = 0; y >= -3; y--) {
int radius = (Math.abs(y) * 5) + this.radius;
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
double distance = new Pos(x, 0, z).distance(0, 0, 0);
if (distance <= radius) {
if(distance <= radius) {
this.setBlock(x, y, z, y == 0 ? Block.DIAMOND_BLOCK : Block.GRASS_BLOCK);
Pos featurePosition = new Pos(x, y + 1, z);
if(y >= 0 || this.getBlock(featurePosition).isSolid()) continue;
if (this.rnd.nextDouble() < 0.1){
if(this.rnd.nextDouble() < 0.1) {
this.setBlock(featurePosition, Block.SHORT_GRASS);
}
if (this.rnd.nextDouble() < 0.01){
if(this.rnd.nextDouble() < 0.01) {
this.setBlock(featurePosition, BlockPallet.FLOWER.rnd());
}
}
@@ -92,7 +92,7 @@ class HighGround extends StatelessGame {
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
Player player = playerMoveEvent.getPlayer();
if(playerMoveEvent.getNewPosition().y() < -10){
if(playerMoveEvent.getNewPosition().y() < -10) {
player.teleport(this.getSpawn());
}
}

View File

@@ -32,8 +32,8 @@ public class HighGroundFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 3, 5, 7, 10))
.addOption(new NumericOption("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 3, 5, 7, 10))
.addOption(new NumericOption("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
}
@Override
@@ -44,6 +44,6 @@ public class HighGroundFactory implements GameFactory {
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2));
.addRestriction(new MinimalPlayeramountGameRestriction(2));
}
}

View File

@@ -35,10 +35,10 @@ public class JumpDive extends StatelessGame {
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius*2; x <= radius*2; x++) {
for(int z = -radius*2; z <= radius*2; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) {
batch.setBlock(x, height, z, BlockPallet.STONE.rnd());
for(int x = -this.radius * 2; x <= this.radius * 2; x++) {
for(int z = -this.radius * 2; z <= this.radius * 2; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) {
batch.setBlock(x, this.height, z, BlockPallet.STONE.rnd());
} else {
batch.setBlock(x, 0, z, BlockPallet.GROUND.rnd());
batch.setBlock(x, 1, z, Block.WATER);
@@ -51,7 +51,7 @@ public class JumpDive extends StatelessGame {
@Override
protected void onStart() {
setTimeLimit(timeLimit);
this.setTimeLimit(this.timeLimit);
}
@Override
@@ -59,22 +59,22 @@ public class JumpDive extends StatelessGame {
Player p = playerMoveEvent.getPlayer();
if(
p.isOnGround() && playerMoveEvent.getNewPosition().y() < height
|| playerMoveEvent.getNewPosition().y() < 0
|| isBeforeBeginning && playerMoveEvent.getNewPosition().y() < height
p.isOnGround() && playerMoveEvent.getNewPosition().y() < this.height
|| playerMoveEvent.getNewPosition().y() < 0
|| this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() < this.height
) {
p.teleport(getSpawn());
p.teleport(this.getSpawn());
playerMoveEvent.setCancelled(true);
}
if(
playerMoveEvent.getNewPosition().y() <= 1
&& playerMoveEvent.getNewPosition().distance(0, 1, 0) < radius + 0.5
&& !(!isBeforeBeginning && !isRunning)
&& playerMoveEvent.getNewPosition().distance(0, 1, 0) < this.radius + 0.5
&& !(!this.isBeforeBeginning && !this.isRunning)
) {
setBlock(playerMoveEvent.getNewPosition().withY(1), Block.REDSTONE_BLOCK);
scores.merge(p, 1, Integer::sum);
p.teleport(getSpawn());
this.setBlock(playerMoveEvent.getNewPosition().withY(1), Block.REDSTONE_BLOCK);
this.scores.merge(p, 1, Integer::sum);
p.teleport(this.getSpawn());
playerMoveEvent.setCancelled(true);
p.playSound(Sound.sound(SoundEvent.ENTITY_EXPERIENCE_ORB_PICKUP, Sound.Source.PLAYER, 2f, 2f));
}
@@ -82,18 +82,18 @@ public class JumpDive extends StatelessGame {
@Override
protected void onStop() {
getPlayers().forEach(player -> getScore().insertResult(player, scores.getOrDefault(player, 0)));
this.getPlayers().forEach(player -> this.getScore().insertResult(player, this.scores.getOrDefault(player, 0)));
}
@Override
public Pos getSpawn() {
double theta = rnd.nextDouble() * 2 * Math.PI;
double theta = this.rnd.nextDouble() * 2 * Math.PI;
double spawnRadius = radius + 2;
double spawnRadius = this.radius + 2;
double x = spawnRadius * Math.cos(theta);
double z = spawnRadius * Math.sin(theta);
return new Pos(x, height + 2, z).withLookAt(new Pos(0, height, 0));
return new Pos(x, this.height + 2, z).withLookAt(new Pos(0, this.height, 0));
}
}

View File

@@ -1,11 +1,11 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.minerun;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import eu.mhsl.minenet.minigames.util.CommonProperties;
import eu.mhsl.minenet.minigames.util.Intersect;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.world.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator;
import net.kyori.adventure.sound.Sound;
@@ -18,7 +18,7 @@ import net.minestom.server.instance.block.Block;
import net.minestom.server.sound.SoundEvent;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
class Minerun extends StatelessGame {
@@ -33,7 +33,7 @@ class Minerun extends StatelessGame {
public Minerun(int width, int length, int minePercentage) {
super(Dimension.THE_END.key, "Minerun", new FirstWinsScore());
setGenerator(new SquarePlateTerrainGenerator(width, length + preRun + afterFinishLine).setPlateHeight(50).setGenerateBorders(true));
this.setGenerator(new SquarePlateTerrainGenerator(width, length + this.preRun + this.afterFinishLine).setPlateHeight(50).setGenerateBorders(true));
this.width = width;
this.length = length;
@@ -42,24 +42,24 @@ class Minerun extends StatelessGame {
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
int spawnToFinishLine = preRun + length + afterMines;
int spawnToFinishLine = this.preRun + this.length + this.afterMines;
Random random = new Random();
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) {
for(int z = preRun; z <= length + preRun; z++) {
for(int x = 0; x <= this.width; x++) {
for(int z = this.preRun; z <= this.length + this.preRun; z++) {
if (random.nextInt(0, 100) < minePercentage) {
if(random.nextInt(0, 100) < this.minePercentage) {
batch.setBlock(x, 50, z, BlockPallet.PRESSURE_PLATES.rnd());
}
}
}
for(int x = 0; x <= width; x++) {
for(int x = 0; x <= this.width; x++) {
batch.setBlock(x, 49, spawnToFinishLine, Block.GOLD_BLOCK);
batch.setBlock(x, 49, preRun, Block.GOLD_BLOCK);
batch.setBlock(x, 50, preRun, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
batch.setBlock(x, 49, this.preRun, Block.GOLD_BLOCK);
batch.setBlock(x, 50, this.preRun, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
}
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
}
@@ -67,11 +67,11 @@ class Minerun extends StatelessGame {
@Override
protected void onStart() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) {
batch.setBlock(x, 50, preRun, Block.AIR);
for(int x = 0; x <= this.width; x++) {
batch.setBlock(x, 50, this.preRun, Block.AIR);
}
BatchUtil.loadAndApplyBatch(batch, this, () -> playSound(Sound.sound(SoundEvent.BLOCK_WOOD_BREAK, Sound.Source.BLOCK, 1f, 1f)));
BatchUtil.loadAndApplyBatch(batch, this, () -> this.playSound(Sound.sound(SoundEvent.BLOCK_WOOD_BREAK, Sound.Source.BLOCK, 1f, 1f)));
}
@Override
@@ -80,23 +80,23 @@ class Minerun extends StatelessGame {
Player p = playerMoveEvent.getPlayer();
Pos middle = playerMoveEvent.getNewPosition();
if(isBeforeBeginning && middle.z() > preRun+0.5) { //player cannot go forward before the game start
if(this.isBeforeBeginning && middle.z() > this.preRun + 0.5) { //player cannot go forward before the game start
playerMoveEvent.setCancelled(true);
}
if(Intersect.withPressurePlate(this, BlockPallet.PRESSURE_PLATES, middle)) { //Player died
p.playSound(Sound.sound(SoundEvent.ENTITY_GENERIC_EXPLODE, Sound.Source.PLAYER, 1f, 1f));
p.teleport(new Pos(p.getPosition().x(), getSpawn().y(), getSpawn().z()));
p.teleport(new Pos(p.getPosition().x(), this.getSpawn().y(), this.getSpawn().z()));
}
if(middle.z() > preRun + length + afterMines) { // Player finished
getScore().insertResult(p);
if(middle.z() > this.preRun + this.length + this.afterMines) { // Player finished
this.getScore().insertResult(p);
p.setGameMode(GameMode.SPECTATOR);
}
}
@Override
public Pos getSpawn() {
return new Pos((double) width /2, 50, 3);
return new Pos((double) this.width / 2, 50, 3);
}
}

View File

@@ -20,9 +20,9 @@ public class MinerunFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("optionCommon#width"), 10, 30, 50, 100))
.addOption(new NumericOption("length", Material.ZOMBIE_HEAD, TranslatedComponent.byId("optionCommon#length"), 50, 100, 150, 200))
.addOption(new NumericOption("percentage", Material.LIGHT_WEIGHTED_PRESSURE_PLATE, TranslatedComponent.byId("game_Minerun#optionPercentageMines"), 30, 40, 50, 60, 70));
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("optionCommon#width"), 10, 30, 50, 100))
.addOption(new NumericOption("length", Material.ZOMBIE_HEAD, TranslatedComponent.byId("optionCommon#length"), 50, 100, 150, 200))
.addOption(new NumericOption("percentage", Material.LIGHT_WEIGHTED_PRESSURE_PLATE, TranslatedComponent.byId("game_Minerun#optionPercentageMines"), 30, 40, 50, 60, 70));
}
@Override

View File

@@ -10,7 +10,10 @@ import io.github.togar2.pvp.feature.CombatFeatures;
import net.kyori.adventure.sound.Sound;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.*;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.EntityType;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.entity.metadata.other.FallingBlockMeta;
import net.minestom.server.event.entity.EntityTickEvent;
import net.minestom.server.event.player.PlayerBlockPlaceEvent;
@@ -29,25 +32,17 @@ import java.util.function.Consumer;
import java.util.function.Supplier;
public class SpaceSnake extends StatelessGame {
record PlayState(AtomicInteger length, Queue<Pos> blocks, Material blockType, Pos spawn) {
public void cutToLength(Consumer<Pos> removed) {
while (this.blocks.size() > this.length.get()) {
removed.accept(this.blocks.poll());
}
}
}
private final Map<Player, PlayState> playerStates = new WeakHashMap<>();
private int mapSize;
private final Supplier<Integer> posInBoundsW = () -> this.rnd.nextInt(-this.mapSize/2, this.mapSize/2);
private final Supplier<Integer> posInBoundsH = () -> this.rnd.nextInt(-60, 300);
private int mapSize;
private final Supplier<Integer> posInBoundsW = () -> this.rnd.nextInt(-this.mapSize / 2, this.mapSize / 2);
public SpaceSnake(int mapSize, int powerUpCount) {
super(Dimension.THE_END.key, "spaceSnake", new PointsWinScore());
this.mapSize = mapSize;
this.setWorldBorder(new WorldBorder(this.mapSize, 0, 0, 0, 0));
for (int i = 0; i < powerUpCount; i++) {
for(int i = 0; i < powerUpCount; i++) {
this.spawnPowerUp();
}
@@ -61,7 +56,7 @@ public class SpaceSnake extends StatelessGame {
);
this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if (this.isBeforeBeginning) prepareAttackEvent.setCancelled(true);
if(this.isBeforeBeginning) prepareAttackEvent.setCancelled(true);
});
this.eventNode().addListener(FinalAttackEvent.class, finalAttackEvent -> {
@@ -179,4 +174,12 @@ public class SpaceSnake extends StatelessGame {
player.setLevel(player.getLevel() + 1);
player.playSound(Sound.sound(SoundEvent.ENTITY_EXPERIENCE_ORB_PICKUP, Sound.Source.PLAYER, 1f, 1f));
}
record PlayState(AtomicInteger length, Queue<Pos> blocks, Material blockType, Pos spawn) {
public void cutToLength(Consumer<Pos> removed) {
while(this.blocks.size() > this.length.get()) {
removed.accept(this.blocks.poll());
}
}
}
}

View File

@@ -14,40 +14,40 @@ import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.event.player.PlayerStartDiggingEvent;
import net.minestom.server.instance.batch.AbsoluteBlockBatch;
import net.minestom.server.instance.block.Block;
import net.minestom.server.item.*;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class Spleef extends StatelessGame {
final int heightPerLevel = 20;
final int totalElevation = 50;
int radius;
int stackCount;
final int heightPerLevel = 20;
final int totalElevation = 50;
public Spleef(int radius, int stackCount) {
super(Dimension.OVERWORLD.key, "Spleef", new LastWinsScore());
getScore().setIgnoreLastPlayers(1);
this.getScore().setIgnoreLastPlayers(1);
this.radius = radius;
this.stackCount = stackCount;
setGenerator(new CircularPlateTerrainGenerator(50));
this.setGenerator(new CircularPlateTerrainGenerator(50));
eventNode().addListener(PlayerStartDiggingEvent.class, this::destroyBlock);
this.eventNode().addListener(PlayerStartDiggingEvent.class, this::destroyBlock);
}
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch circle = new AbsoluteBlockBatch();
for (int level = 0; level < stackCount; level++) {
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
for(int level = 0; level < this.stackCount; level++) {
for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
circle.setBlock(x, totalElevation + (level * heightPerLevel), z, BlockPallet.WINTER.rnd());
circle.setBlock(x, this.totalElevation + (level * this.heightPerLevel), z, BlockPallet.WINTER.rnd());
}
}
}
@@ -57,13 +57,13 @@ public class Spleef extends StatelessGame {
@Override
protected void onStart() {
getPlayers().forEach(player -> {
this.getPlayers().forEach(player -> {
player.setGameMode(GameMode.SURVIVAL);
player.getInventory().addItemStack(
ItemStack
.builder(Material.DIAMOND_SHOVEL)
.customName(TranslatedComponent.byId("game_Spleef#shovelName").getAssembled(player))
.build()
ItemStack
.builder(Material.DIAMOND_SHOVEL)
.customName(TranslatedComponent.byId("game_Spleef#shovelName").getAssembled(player))
.build()
);
player.setHeldItemSlot((byte) 0);
});
@@ -71,29 +71,29 @@ public class Spleef extends StatelessGame {
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) {
if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
playerMoveEvent.getPlayer().getInventory().clear();
getScore().insertResult(playerMoveEvent.getPlayer());
this.getScore().insertResult(playerMoveEvent.getPlayer());
}
}
@Override
protected void onBlockBreak(@NotNull PlayerBlockBreakEvent event) {
if(!isRunning) {
if(!this.isRunning) {
event.setCancelled(true);
return;
}
setBlock(event.getBlockPosition(), Block.AIR);
this.setBlock(event.getBlockPosition(), Block.AIR);
}
private void destroyBlock(PlayerStartDiggingEvent event) {
if(!isRunning) return;
setBlock(event.getBlockPosition(), Block.AIR);
if(!this.isRunning) return;
this.setBlock(event.getBlockPosition(), Block.AIR);
}
@Override
public Pos getSpawn() {
return new Pos(0, totalElevation + heightPerLevel * (stackCount-1) + 1, 0);
return new Pos(0, this.totalElevation + this.heightPerLevel * (this.stackCount - 1) + 1, 0);
}
}

View File

@@ -22,7 +22,7 @@ public class SpleefFactory implements GameFactory {
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2));
.addRestriction(new MinimalPlayeramountGameRestriction(2));
}
@Override
@@ -33,8 +33,8 @@ public class SpleefFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("stackCount", Material.SCAFFOLDING, TranslatedComponent.byId("game_Spleef#stackCount"), 1, 2, 3, 4, 5));
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("stackCount", Material.SCAFFOLDING, TranslatedComponent.byId("game_Spleef#stackCount"), 1, 2, 3, 4, 5));
}
@Override

View File

@@ -28,14 +28,14 @@ public class StickFightFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("length", Material.SANDSTONE, TranslatedComponent.byId("optionCommon#length"), 7, 10, 13, 16, 19));
.addOption(new NumericOption("length", Material.SANDSTONE, TranslatedComponent.byId("optionCommon#length"), 7, 10, 13, 16, 19));
}
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2))
.addRestriction(new MaximalPlayeramountGameRestriction(4));
.addRestriction(new MinimalPlayeramountGameRestriction(2))
.addRestriction(new MaximalPlayeramountGameRestriction(4));
}
@Override

View File

@@ -27,7 +27,7 @@ public class Stickfight extends StatelessGame {
super(Dimension.OVERWORLD.key, "Stickfight", new LowestPointsWinScore());
this.radius = length;
eventNode().addChild(
this.eventNode().addChild(
CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE)
@@ -35,13 +35,13 @@ public class Stickfight extends StatelessGame {
.build().createNode()
);
eventNode().addListener(FinalAttackEvent.class, finalAttackEvent -> {
if(isBeforeBeginning) finalAttackEvent.setCancelled(true);
this.eventNode().addListener(FinalAttackEvent.class, finalAttackEvent -> {
if(this.isBeforeBeginning) finalAttackEvent.setCancelled(true);
finalAttackEvent.setBaseDamage(0);
((Player) finalAttackEvent.getTarget()).setHealth(20);
});
setGenerator(new CircularPlateTerrainGenerator(20));
this.setGenerator(new CircularPlateTerrainGenerator(20));
}
@Override
@@ -51,8 +51,8 @@ public class Stickfight extends StatelessGame {
private void replaceCircle(Block block) {
int radius = 8;
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
Pos blockPosition = this.getSpawn().add(x, -1, z);
if(blockPosition.distance(this.getSpawn().sub(0, 1, 0)) <= radius) this.setBlock(blockPosition, block);
}
@@ -61,60 +61,60 @@ public class Stickfight extends StatelessGame {
@Override
protected void start() {
List<Player> players = getPlayers().stream().toList();
List<Player> players = this.getPlayers().stream().toList();
int numPlayers = players.size();
this.countdownStarted = true;
this.replaceCircle(Block.AIR);
for (int i = 0; i < numPlayers; i++) {
for(int i = 0; i < numPlayers; i++) {
double angle = (2 * Math.PI / numPlayers) * i;
int spawnX = (int) (radius * Math.cos(angle));
int spawnZ = (int) (radius * Math.sin(angle));
int spawnX = (int) (this.radius * Math.cos(angle));
int spawnZ = (int) (this.radius * Math.sin(angle));
int spawnY = 50;
Pos spawnpoint = new Pos(spawnX, spawnY + 1, spawnZ).add(0.5);
spawnPoints.put(players.get(i), spawnpoint.withLookAt(getSpawn()));
this.spawnPoints.put(players.get(i), spawnpoint.withLookAt(this.getSpawn()));
players.get(i).teleport(spawnpoint);
generateBridge(spawnX, spawnY, spawnZ);
this.generateBridge(spawnX, spawnY, spawnZ);
}
setBlock(0, 50, 0, Block.GOLD_BLOCK);
this.setBlock(0, 50, 0, Block.GOLD_BLOCK);
super.start();
}
@Override
protected void onStop() {
this.scoreMap.forEach((player, score) -> getScore().insertResult(player, score));
this.scoreMap.forEach((player, score) -> this.getScore().insertResult(player, score));
}
private void generateBridge(int startX, int startY, int startZ) {
int steps = (int) (radius * 1.5);
for (int i = 0; i < steps; i++) {
int steps = (int) (this.radius * 1.5);
for(int i = 0; i < steps; i++) {
double t = (double) i / steps;
int x = (int) (startX * (1 - t));
int z = (int) (startZ * (1 - t));
setBlock(x, startY, z, Block.SANDSTONE);
this.setBlock(x, startY, z, Block.SANDSTONE);
}
}
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
Player player = playerMoveEvent.getPlayer();
if(!spawnPoints.containsKey(player)) {
if(!this.spawnPoints.containsKey(player)) {
if(playerMoveEvent.getNewPosition().y() < 45) player.teleport(this.getSpawn());
if(this.countdownStarted) playerMoveEvent.setCancelled(true);
return;
}
if(isBeforeBeginning) {
if(spawnPoints.get(player).distance(playerMoveEvent.getNewPosition()) < 1) return;
if(this.isBeforeBeginning) {
if(this.spawnPoints.get(player).distance(playerMoveEvent.getNewPosition()) < 1) return;
playerMoveEvent.setCancelled(true);
player.teleport(spawnPoints.get(player));
player.teleport(this.spawnPoints.get(player));
}
if(playerMoveEvent.getNewPosition().y() < 40) {
player.teleport(spawnPoints.get(player));
player.teleport(this.spawnPoints.get(player));
this.scoreMap.putIfAbsent(player, 0);
this.scoreMap.put(player, this.scoreMap.get(player) + 1);
}

View File

@@ -42,16 +42,16 @@ public class Sumo extends StatelessGame {
this.timer = seconds;
this.eventNode().addChild(
CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE)
.add(CombatFeatures.VANILLA_KNOCKBACK)
.build()
.createNode()
CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE)
.add(CombatFeatures.VANILLA_KNOCKBACK)
.build()
.createNode()
);
this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if (this.isBeforeBeginning)
if(this.isBeforeBeginning)
prepareAttackEvent.setCancelled(true);
});
@@ -74,7 +74,7 @@ public class Sumo extends StatelessGame {
this.timer--;
double percent = (double) this.timer / this.seconds;
int radius = (int) (this.originalRadius * percent);
if (this.radius >= 5) {
if(this.radius >= 5) {
this.radius = radius;
this.generatePlatform();
return TaskSchedule.seconds(1);
@@ -115,7 +115,7 @@ public class Sumo extends StatelessGame {
player.teleport(this.getSpawn());
this.healthMap.put(player, this.healthMap.get(player) - 1);
player.setLevel(this.healthMap.get(player));
if (this.healthMap.get(player) == 0) {
if(this.healthMap.get(player) == 0) {
this.getScore().insertResult(player);
player.setGameMode(GameMode.SPECTATOR);
}
@@ -124,6 +124,6 @@ public class Sumo extends StatelessGame {
@Override
public Pos getSpawn() {
return new Pos(0, 2, 0);
return new Pos(0, 2, 0);
}
}

View File

@@ -31,9 +31,9 @@ public class SumoFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("health", Material.GOLDEN_APPLE, TranslatedComponent.byId("game_Sumo#lives"), 1, 2, 3, 4, 5))
.addOption(new NumericOption("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30))
.addOption(new NumericOption("health", Material.GOLDEN_APPLE, TranslatedComponent.byId("game_Sumo#lives"), 1, 2, 3, 4, 5))
.addOption(new NumericOption("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
}
@Override
@@ -44,6 +44,6 @@ public class SumoFactory implements GameFactory {
@Override
public RestrictionHandler globalRestrictions() {
return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2));
.addRestriction(new MinimalPlayeramountGameRestriction(2));
}
}

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris.game.TetrisGame;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris.game.Tetromino;
import eu.mhsl.minenet.minigames.score.PointsWinScore;
import net.kyori.adventure.text.Component;
@@ -10,20 +10,25 @@ import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.*;
import net.minestom.server.event.player.PlayerHandAnimationEvent;
import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.event.player.PlayerTickEvent;
import net.minestom.server.event.player.PlayerUseItemEvent;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
class Tetris extends StatelessGame {
private final Map<Player, TetrisGame> tetrisGames = new WeakHashMap<>();
private final int nextTetrominoesCount;
private final boolean isFast;
private final boolean hasCombat;
private boolean setTimeLimit = false;
private final long randomSeed;
private boolean setTimeLimit = false;
public Tetris(int nextTetrominoesCount, boolean isFast, boolean hasCombat) {
super(Dimension.THE_END.key, "Tetris", new PointsWinScore());
@@ -136,7 +141,7 @@ class Tetris extends StatelessGame {
if(this.tetrisGames.get(p) == null) {
this.tetrisGames.put(p, new TetrisGame(
this,
this.getSpawn().sub(6, 8, 15).add(this.tetrisGames.size()*30, 0, 0),
this.getSpawn().sub(6, 8, 15).add(this.tetrisGames.size() * 30, 0, 0),
Tetromino.Shape.J,
this.nextTetrominoesCount,
this.isFast,

View File

@@ -1,9 +1,9 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris;
import eu.mhsl.minenet.minigames.instance.game.Game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.BoolOption;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room;

View File

@@ -10,10 +10,10 @@ import org.apache.commons.lang3.ArrayUtils;
import java.util.Random;
public class Playfield {
private final Pos lowerLeftCorner;
private final StatelessGame instance;
private final static int height = 22;
private final static Block scoreBlock = Block.STONE;
private final Pos lowerLeftCorner;
private final StatelessGame instance;
private final int nextTetrominoesCount;
private final Random random;
@@ -41,19 +41,19 @@ public class Playfield {
}
public Pos getScorePosition() {
return this.lowerLeftCorner.add(-5, height+3, 0);
return this.lowerLeftCorner.add(-5, height + 3, 0);
}
public void generate() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
// actual playfield:
for(int x=0; x<12; x++) {
for(int y = 0; y< height; y++) {
for(int x = 0; x < 12; x++) {
for(int y = 0; y < height; y++) {
batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GLASS);
batch.setBlock(this.lowerLeftCorner.add(x, y, -1), Block.BLACK_CONCRETE);
if(x==0 || x==11 || y==0) {
if(x == 0 || x == 11 || y == 0) {
batch.setBlock(this.lowerLeftCorner.add(x, y, 1), Block.GRAY_CONCRETE);
batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GRAY_CONCRETE);
}
@@ -63,14 +63,14 @@ public class Playfield {
// hold position:
for(int x = 0; x < 4; x++) {
for(int y = 0; y < 4; y++) {
batch.setBlock(this.getHoldPosition().add(x-1, y-1, -1), Block.QUARTZ_BLOCK);
batch.setBlock(this.getHoldPosition().add(x - 1, y - 1, -1), Block.QUARTZ_BLOCK);
}
}
// next positions:
for(int x = 0; x < 4; x++) {
for(int y = -4*this.nextTetrominoesCount+4; y < 4; y++) {
batch.setBlock(this.getNextPosition().add(x-1, y-1, -1), Block.QUARTZ_BLOCK);
for(int y = -4 * this.nextTetrominoesCount + 4; y < 4; y++) {
batch.setBlock(this.getNextPosition().add(x - 1, y - 1, -1), Block.QUARTZ_BLOCK);
}
}
@@ -79,14 +79,15 @@ public class Playfield {
batch.setBlock(this.getPlayerSpawnPosition().sub(1, 1, 1), Block.STONE);
batch.setBlock(this.getPlayerSpawnPosition().sub(0, 1, 1), Block.STONE);
BatchUtil.loadAndApplyBatch(batch, this.instance, () -> {});
BatchUtil.loadAndApplyBatch(batch, this.instance, () -> {
});
}
public int removeFullLines() {
int removedLinesCounter = 0;
for(int y = 1; y< height; y++) {
for(int y = 1; y < height; y++) {
boolean isFullLine = true;
for(int x=1; x<11; x++) {
for(int x = 1; x < 11; x++) {
if(this.instance.getBlock(this.lowerLeftCorner.add(x, y, 1)) == Block.AIR) isFullLine = false;
}
if(isFullLine) {
@@ -101,9 +102,9 @@ public class Playfield {
public void addLines(int lines) {
int xPosMissing = this.random.nextInt(1, 10);
for (int i = 0; i < lines; i++) {
for(int i = 0; i < lines; i++) {
this.moveAllLinesUp();
for (int x = 1; x < 11; x++) {
for(int x = 1; x < 11; x++) {
if(x != xPosMissing) {
this.instance.setBlock(this.lowerLeftCorner.add(x, 1, 1), Block.LIGHT_GRAY_CONCRETE);
} else {
@@ -114,7 +115,7 @@ public class Playfield {
}
public void updateAttackingLines(int attackingLines) {
for (int y = 0; y < height + 5; y++) {
for(int y = 0; y < height + 5; y++) {
if(attackingLines > 0) {
this.instance.setBlock(this.lowerLeftCorner.add(12, y, 1), Block.REDSTONE_BLOCK);
attackingLines -= 1;
@@ -132,48 +133,49 @@ public class Playfield {
for(int i = 6; i > 0; i--) {
char digit;
if(i <= characters.length) {
digit = characters[i-1];
digit = characters[i - 1];
} else {
digit = '0';
}
this.displayDigit(digit, 6-i);
this.displayDigit(digit, 6 - i);
}
}
private void displayDigit(char digit, int positionFromLeft) {
int[][] digitArray;
switch (digit) {
case '1' -> digitArray = new int[][]{{0,0,1},{0,1,1},{0,0,1},{0,0,1},{0,0,1}};
case '2' -> digitArray = new int[][]{{1,1,1},{0,0,1},{1,1,1},{1,0,0},{1,1,1}};
case '3' -> digitArray = new int[][]{{1,1,1},{0,0,1},{0,1,1},{0,0,1},{1,1,1}};
case '4' -> digitArray = new int[][]{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{0,0,1}};
case '5' -> digitArray = new int[][]{{1,1,1},{1,0,0},{1,1,1},{0,0,1},{1,1,1}};
case '6' -> digitArray = new int[][]{{1,1,1},{1,0,0},{1,1,1},{1,0,1},{1,1,1}};
case '7' -> digitArray = new int[][]{{1,1,1},{0,0,1},{0,1,0},{0,1,0},{0,1,0}};
case '8' -> digitArray = new int[][]{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,1,1}};
case '9' -> digitArray = new int[][]{{1,1,1},{1,0,1},{1,1,1},{0,0,1},{1,1,1}};
default -> digitArray = new int[][]{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1}};
switch(digit) {
case '1' -> digitArray = new int[][]{{0, 0, 1}, {0, 1, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}};
case '2' -> digitArray = new int[][]{{1, 1, 1}, {0, 0, 1}, {1, 1, 1}, {1, 0, 0}, {1, 1, 1}};
case '3' -> digitArray = new int[][]{{1, 1, 1}, {0, 0, 1}, {0, 1, 1}, {0, 0, 1}, {1, 1, 1}};
case '4' -> digitArray = new int[][]{{1, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 0, 1}, {0, 0, 1}};
case '5' -> digitArray = new int[][]{{1, 1, 1}, {1, 0, 0}, {1, 1, 1}, {0, 0, 1}, {1, 1, 1}};
case '6' -> digitArray = new int[][]{{1, 1, 1}, {1, 0, 0}, {1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
case '7' -> digitArray = new int[][]{{1, 1, 1}, {0, 0, 1}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0}};
case '8' -> digitArray = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
case '9' -> digitArray = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}, {0, 0, 1}, {1, 1, 1}};
default -> digitArray = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 0, 1}, {1, 0, 1}, {1, 1, 1}};
}
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 5; y++) {
if(digitArray[4-y][x] == 1) this.instance.setBlock(this.getScorePosition().add(positionFromLeft*4+x, y, 0), scoreBlock);
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 5; y++) {
if(digitArray[4 - y][x] == 1)
this.instance.setBlock(this.getScorePosition().add(positionFromLeft * 4 + x, y, 0), scoreBlock);
}
}
}
private void removeDigits() {
for (int x = 0; x < 4 * 6; x++) {
for (int y = 0; y < 5; y++) {
for(int x = 0; x < 4 * 6; x++) {
for(int y = 0; y < 5; y++) {
this.instance.setBlock(this.getScorePosition().add(x, y, 0), Block.AIR);
}
}
}
private void moveAllLinesUp() {
for (int y = height + 3; y > 1; y--) {
for (int x = 1; x < 11; x++) {
for(int y = height + 3; y > 1; y--) {
for(int x = 1; x < 11; x++) {
Block blockBeneath = this.instance.getBlock(this.lowerLeftCorner.add(x, y - 1, 1));
this.instance.setBlock(this.lowerLeftCorner.add(x, y, 1), blockBeneath);
}
@@ -181,9 +183,9 @@ public class Playfield {
}
private void removeFullLine(int positionY) {
for(int y = positionY; y< height; y++) {
for(int x=1; x<11; x++) {
Block blockAbove = this.instance.getBlock(this.lowerLeftCorner.add(x, y+1, 1));
for(int y = positionY; y < height; y++) {
for(int x = 1; x < 11; x++) {
Block blockAbove = this.instance.getBlock(this.lowerLeftCorner.add(x, y + 1, 1));
this.instance.setBlock(this.lowerLeftCorner.add(x, y, 1), blockAbove);
}
}

View File

@@ -14,36 +14,26 @@ public class TetrisGame {
private final StatelessGame instance;
private final Playfield playfield;
private final boolean isFast;
private final boolean hasCombat;
private final List<Tetromino> nextTetrominoes = new ArrayList<>();
private final List<Tetromino> tetrominoBag = new ArrayList<>();
private final Pos nextPosition;
private final Pos holdPosition;
private final Pos tetrominoSpawnPosition;
private final Map<Button, Long> lastPresses = new HashMap<>();
private final List<TetrisGame> otherTetrisGames = new ArrayList<>();
private final Random random;
public boolean lost = false;
public boolean paused = true;
public Tetromino currentTetromino;
public Sidebar sidebar = new Sidebar(Component.text("Info:"));
private int level = 1;
private int lines = 0;
private int score = 0;
private int combo = 0;
private int attackingLines = 0;
public boolean lost = false;
public boolean paused = true;
private final boolean hasCombat;
public Tetromino currentTetromino;
private final List<Tetromino> nextTetrominoes = new ArrayList<>();
private Tetromino holdTetromino;
private final List<Tetromino> tetrominoBag = new ArrayList<>();
private boolean holdPossible = true;
private final Pos nextPosition;
private final Pos holdPosition;
private final Pos tetrominoSpawnPosition;
public Sidebar sidebar = new Sidebar(Component.text("Info:"));
private final Map<Button, Long> lastPresses = new HashMap<>();
private final List<TetrisGame> otherTetrisGames = new ArrayList<>();
private final Random random;
public enum Button {
W,
A,
S,
D,
mouseLeft,
mouseRight,
space
}
public TetrisGame(StatelessGame instance, Pos lowerLeftCorner, Tetromino.Shape startTetrominoShape, int nextTetrominoesCount, boolean isfast, boolean hasCombat, long randomSeed) {
this.isFast = isfast;
@@ -58,7 +48,7 @@ public class TetrisGame {
this.buildSidebar();
this.currentTetromino = new Tetromino(this.instance, startTetrominoShape);
for (int i = 0; i < nextTetrominoesCount; i++) {
for(int i = 0; i < nextTetrominoesCount; i++) {
this.updateNextTetrominoes();
}
}
@@ -67,15 +57,15 @@ public class TetrisGame {
final int standardButtonDelay = 100;
final int buttonDebounce = 70;
if(this.lastPresses.getOrDefault(button, 0L) >= System.currentTimeMillis()-standardButtonDelay) return;
if(this.lastPresses.getOrDefault(button, 0L) >= System.currentTimeMillis() - standardButtonDelay) return;
this.lastPresses.put(button, System.currentTimeMillis());
if(button == Button.W) this.lastPresses.put(button, System.currentTimeMillis()+buttonDebounce);
if(button == Button.S) this.lastPresses.put(button, System.currentTimeMillis()-buttonDebounce);
if(button == Button.W) this.lastPresses.put(button, System.currentTimeMillis() + buttonDebounce);
if(button == Button.S) this.lastPresses.put(button, System.currentTimeMillis() - buttonDebounce);
if(this.lost || this.paused) return;
switch (button) {
switch(button) {
case A -> this.currentTetromino.moveLeft();
case S -> this.moveDown();
case D -> this.currentTetromino.moveRight();
@@ -98,7 +88,7 @@ public class TetrisGame {
int standardTickDelay = 40;
if(this.isFast) standardTickDelay = 20;
TaskSchedule nextTick = TaskSchedule.tick(Math.round((float) standardTickDelay /this.level));
TaskSchedule nextTick = TaskSchedule.tick(Math.round((float) standardTickDelay / this.level));
if(this.paused) return nextTick;
this.tick();
return nextTick;
@@ -107,7 +97,7 @@ public class TetrisGame {
this.updateInfo();
this.nextTetrominoes.forEach(tetromino -> {
double xChange = -tetromino.getXChange();
tetromino.setPosition(this.nextPosition.sub(xChange, 4*this.nextTetrominoes.indexOf(tetromino), 0));
tetromino.setPosition(this.nextPosition.sub(xChange, 4 * this.nextTetrominoes.indexOf(tetromino), 0));
tetromino.drawAsEntities();
});
}
@@ -149,7 +139,6 @@ public class TetrisGame {
this.lost = true;
}
private boolean moveDown() {
if(!this.currentTetromino.moveDown()) {
this.setActiveTetrominoDown();
@@ -203,7 +192,6 @@ public class TetrisGame {
return true;
}
private void updateNextTetrominoes() {
if(this.tetrominoBag.isEmpty()) {
for(Tetromino.Shape shape : Tetromino.Shape.values()) {
@@ -217,7 +205,7 @@ public class TetrisGame {
this.nextTetrominoes.add(newTetromino);
this.nextTetrominoes.forEach(tetromino -> {
double xChange = -tetromino.getXChange();
tetromino.setPosition(this.nextPosition.sub(xChange, 4*this.nextTetrominoes.indexOf(tetromino), 0));
tetromino.setPosition(this.nextPosition.sub(xChange, 4 * this.nextTetrominoes.indexOf(tetromino), 0));
tetromino.drawAsEntities();
});
}
@@ -242,7 +230,7 @@ public class TetrisGame {
private void updateInfo() {
this.playfield.updateScore(this.score);
this.sidebar.updateLineScore("0", this.score);
this.sidebar.updateLineScore("0", this.score);
this.sidebar.updateLineScore("1", this.lines);
this.sidebar.updateLineScore("2", this.level);
}
@@ -256,7 +244,7 @@ public class TetrisGame {
int removedLines = this.playfield.removeFullLines();
int combatLines = 0;
this.combo += 1;
switch (removedLines) {
switch(removedLines) {
case 0 -> this.combo = 0;
case 1 -> {
this.lines += 1;
@@ -281,7 +269,7 @@ public class TetrisGame {
this.score += 50 * this.combo * this.level;
if(this.combo >= 2) {
combatLines += (int) Math.floor((double) this.combo /2);
combatLines += (int) Math.floor((double) this.combo / 2);
}
if(this.hasCombat && this.attackingLines > 0) {
@@ -315,4 +303,14 @@ public class TetrisGame {
this.loose();
}
}
public enum Button {
W,
A,
S,
D,
mouseLeft,
mouseRight,
space
}
}

View File

@@ -14,37 +14,27 @@ import java.util.List;
import java.util.UUID;
public class Tetromino {
private final static EntityType ghostEntityType = EntityType.FALLING_BLOCK;
private final static Tag<String> uuidTag = Tag.String("uuid");
private final Shape shape;
private final StatelessGame instance;
private final UUID uuid;
private Pos position;
private int[][] shapeArray;
private final static EntityType ghostEntityType = EntityType.FALLING_BLOCK;
private final UUID uuid;
private final static Tag<String> uuidTag = Tag.String("uuid");
public enum Shape {
I,
J,
L,
O,
S,
T,
Z
}
public Tetromino(StatelessGame instance, Shape shape) {
this.instance = instance;
this.shape = shape;
this.uuid = UUID.randomUUID();
switch (this.shape) {
switch(this.shape) {
case I -> this.shapeArray = new int[][]{{0, 0, 0, 0}, {1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}};
case J -> this.shapeArray = new int[][]{{1,0,0}, {1,1,1}, {0,0,0}};
case L -> this.shapeArray = new int[][]{{0,0,1}, {1,1,1}, {0,0,0}};
case O -> this.shapeArray = new int[][]{{1,1}, {1,1}};
case S -> this.shapeArray = new int[][]{{0,1,1}, {1,1,0}, {0,0,0}};
case T -> this.shapeArray = new int[][]{{0,1,0}, {1,1,1}, {0,0,0}};
case Z -> this.shapeArray = new int[][]{{1,1,0}, {0,1,1}, {0,0,0}};
case J -> this.shapeArray = new int[][]{{1, 0, 0}, {1, 1, 1}, {0, 0, 0}};
case L -> this.shapeArray = new int[][]{{0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
case O -> this.shapeArray = new int[][]{{1, 1}, {1, 1}};
case S -> this.shapeArray = new int[][]{{0, 1, 1}, {1, 1, 0}, {0, 0, 0}};
case T -> this.shapeArray = new int[][]{{0, 1, 0}, {1, 1, 1}, {0, 0, 0}};
case Z -> this.shapeArray = new int[][]{{1, 1, 0}, {0, 1, 1}, {0, 0, 0}};
}
}
@@ -83,7 +73,7 @@ public class Tetromino {
public void draw(boolean withGhost) {
if(withGhost) {
Pos ghostPos = this.position;
while (!this.checkCollision(ghostPos.sub(0, 1, 0), this.shapeArray)) {
while(!this.checkCollision(ghostPos.sub(0, 1, 0), this.shapeArray)) {
ghostPos = ghostPos.sub(0, 1, 0);
}
Pos positionChange = this.position.sub(ghostPos);
@@ -117,7 +107,7 @@ public class Tetromino {
public Block getColoredBlock() {
Block returnBlock;
switch (this.shape) {
switch(this.shape) {
case I -> returnBlock = Block.LIGHT_BLUE_CONCRETE;
case J -> returnBlock = Block.BLUE_CONCRETE;
case L -> returnBlock = Block.ORANGE_CONCRETE;
@@ -141,7 +131,7 @@ public class Tetromino {
}
public double getXChange() {
switch (this.shape) {
switch(this.shape) {
case O, I -> {
return 0;
}
@@ -151,14 +141,13 @@ public class Tetromino {
}
}
public Shape getShape() {
return this.shape;
}
private Block getGhostBlock() {
Block returnBlock;
switch (this.shape) {
switch(this.shape) {
case I -> returnBlock = Block.LIGHT_BLUE_STAINED_GLASS;
case J -> returnBlock = Block.BLUE_STAINED_GLASS;
case L -> returnBlock = Block.ORANGE_STAINED_GLASS;
@@ -179,10 +168,10 @@ public class Tetromino {
int[][] startArray = Arrays.stream(this.shapeArray).map(int[]::clone).toArray(int[][]::new);
int[][] returnArray = new int[arrayLength][arrayLength];
for(int k=0; k<iterations; k++) {
for(int i=0; i<arrayLength; i++) {
for(int j=0; j<arrayLength; j++) {
returnArray[i][arrayLength-1-j] = startArray[j][i];
for(int k = 0; k < iterations; k++) {
for(int i = 0; i < arrayLength; i++) {
for(int j = 0; j < arrayLength; j++) {
returnArray[i][arrayLength - 1 - j] = startArray[j][i];
}
}
startArray = Arrays.stream(returnArray).map(int[]::clone).toArray(int[][]::new);
@@ -206,13 +195,13 @@ public class Tetromino {
int arrayLength = shapeArray.length;
for(int x=0; x<arrayLength; x++) {
for(int y=0; y<arrayLength; y++) {
if(shapeArray[arrayLength-1-y][x] == 1) {
switch (this.shape) {
case I -> returnList.add(position.add(x-1, y-2, 0));
for(int x = 0; x < arrayLength; x++) {
for(int y = 0; y < arrayLength; y++) {
if(shapeArray[arrayLength - 1 - y][x] == 1) {
switch(this.shape) {
case I -> returnList.add(position.add(x - 1, y - 2, 0));
case O -> returnList.add(position.add(x, y, 0));
default -> returnList.add(position.add(x-1, y-1, 0));
default -> returnList.add(position.add(x - 1, y - 1, 0));
}
}
}
@@ -243,4 +232,14 @@ public class Tetromino {
}
return false;
}
public enum Shape {
I,
J,
L,
O,
S,
T,
Z
}
}

View File

@@ -23,22 +23,23 @@ public class TntRun extends StatelessGame {
final int radius;
final int stackCount;
public TntRun(int radius, int stackCount) {
super(Dimension.OVERWORLD.key, "tntRun", new LastWinsScore());
this.radius = radius;
this.stackCount = stackCount;
setGenerator(new CircularPlateTerrainGenerator(radius));
this.setGenerator(new CircularPlateTerrainGenerator(radius));
}
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for (int level = 0; level < stackCount; level++) {
for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue;
for(int level = 0; level < this.stackCount; level++) {
for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
batch.setBlock(x, totalElevation + (level * heightPerLevel), z, Block.TNT);
batch.setBlock(x, this.totalElevation + (level * this.heightPerLevel), z, Block.TNT);
}
}
}
@@ -50,25 +51,25 @@ public class TntRun extends StatelessGame {
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) {
if(isBeforeBeginning) {
playerMoveEvent.getPlayer().teleport(getSpawn());
if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
if(this.isBeforeBeginning) {
playerMoveEvent.getPlayer().teleport(this.getSpawn());
return;
}
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
getScore().insertResult(playerMoveEvent.getPlayer());
this.getScore().insertResult(playerMoveEvent.getPlayer());
}
if(isRunning && !getScore().hasResult(playerMoveEvent.getPlayer())) {
if(this.isRunning && !this.getScore().hasResult(playerMoveEvent.getPlayer())) {
MinecraftServer.getSchedulerManager().scheduleTask(() -> {
float radius = 0.5F;
for (float x = -radius; x <= radius; x++) {
for (float z = -radius; z <= radius; z++) {
for(float x = -radius; x <= radius; x++) {
for(float z = -radius; z <= radius; z++) {
Pos firstLocation = playerMoveEvent.getNewPosition().add(x, -1, z);
Pos secondLocation = firstLocation.withY(y -> y-1);
if(!getBlock(firstLocation).isAir() || !getBlock(secondLocation).isAir()) {
setBlock(firstLocation, Block.AIR);
setBlock(secondLocation, Block.AIR);
Pos secondLocation = firstLocation.withY(y -> y - 1);
if(!this.getBlock(firstLocation).isAir() || !this.getBlock(secondLocation).isAir()) {
this.setBlock(firstLocation, Block.AIR);
this.setBlock(secondLocation, Block.AIR);
// Entity fallingTnt = new Entity(EntityType.TNT);
// PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta();
@@ -83,6 +84,6 @@ public class TntRun extends StatelessGame {
@Override
public Pos getSpawn() {
return new Pos(0, totalElevation + heightPerLevel * (stackCount-1) + 1, 0);
return new Pos(0, this.totalElevation + this.heightPerLevel * (this.stackCount - 1) + 1, 0);
}
}

View File

@@ -30,8 +30,8 @@ public class TntRunFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("radius", Material.STICK, TranslatedComponent.byId("optionCommon#radius"), 20, 30, 50, 60))
.addOption(new NumericOption("levels", Material.SCAFFOLDING, TranslatedComponent.byId("game_TntRun#levels"), 1, 2, 3, 4, 5));
.addOption(new NumericOption("radius", Material.STICK, TranslatedComponent.byId("optionCommon#radius"), 20, 30, 50, 60))
.addOption(new NumericOption("levels", Material.SCAFFOLDING, TranslatedComponent.byId("game_TntRun#levels"), 1, 2, 3, 4, 5));
}
@Override

View File

@@ -18,12 +18,12 @@ public class Towerdefense extends StatelessGame {
private final Random random = new Random();
private final AbsoluteBlockBatch mazeBatch = new AbsoluteBlockBatch();
private final List<Pos> mazePath = new ArrayList<>();
private List<TowerdefenseRoom> instances = new ArrayList<>();
private final List<TowerdefenseRoom> instances = new ArrayList<>();
public Towerdefense() {
super(Dimension.NETHER.key, "Towerdefense", new LastWinsScore());
setGenerator(new MazeGenerator());
this.setGenerator(new MazeGenerator());
this.generateMaze();
}
@@ -33,9 +33,9 @@ public class Towerdefense extends StatelessGame {
List<Integer> previousDirections = new ArrayList<>();
int direction = 1; // 0 -> right; 1 -> straight; 2 -> left
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 3; j++) {
position = position.add(direction-1,0,direction%2);
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 3; j++) {
position = position.add(direction - 1, 0, direction % 2);
this.addMazePosition(position, Block.WHITE_WOOL);
}
@@ -48,13 +48,13 @@ public class Towerdefense extends StatelessGame {
previousDirections.add(direction);
}
this.addMazePosition(position, Block.WHITE_WOOL);
this.addMazePosition(position.add(0,0,1), Block.WHITE_WOOL);
this.addMazePosition(position.add(0,0,2), Block.RED_WOOL);
this.addMazePosition(position.add(0, 0, 1), Block.WHITE_WOOL);
this.addMazePosition(position.add(0, 0, 2), Block.RED_WOOL);
}
private void addMazePosition(Pos position, Block pathBlock) {
this.mazeBatch.setBlock(position, pathBlock);
this.mazePath.add(position.add(0.5,1,0.5));
this.mazePath.add(position.add(0.5, 1, 0.5));
}
public AbsoluteBlockBatch getMazeBatch() {

View File

@@ -14,6 +14,7 @@ public class TowerdefenseFactory implements GameFactory {
public TranslatedComponent name() {
return TranslatedComponent.byId("game_Towerdefense#name");
}
@Override
public Material symbol() {
return Material.ARMOR_STAND;

View File

@@ -4,7 +4,10 @@ import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.towerdefense.generator.MazeGenerator;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.*;
import net.minestom.server.entity.EntityCreature;
import net.minestom.server.entity.EntityType;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.entity.attribute.Attribute;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.item.ItemStack;
@@ -27,8 +30,9 @@ public class TowerdefenseRoom extends InstanceContainer {
this.player.setAllowFlying(true);
this.player.getInventory().setItemStack(0, ItemStack.of(Material.ARMOR_STAND));
setGenerator(new MazeGenerator());
BatchUtil.loadAndApplyBatch(this.game.getMazeBatch(), this, () -> {});
this.setGenerator(new MazeGenerator());
BatchUtil.loadAndApplyBatch(this.game.getMazeBatch(), this, () -> {
});
}
public void startWave(List<EntityType> entities) {
@@ -37,7 +41,7 @@ public class TowerdefenseRoom extends InstanceContainer {
MinecraftServer.getSchedulerManager().scheduleTask(() -> {
this.addEntity(new EntityCreature(entityType));
return TaskSchedule.stop();
}, TaskSchedule.millis(800L*counter));
}, TaskSchedule.millis(800L * counter));
counter++;
}
}
@@ -45,14 +49,14 @@ public class TowerdefenseRoom extends InstanceContainer {
private void addEntity(EntityCreature entity) {
entity.setInstance(this, this.game.getMazePath().getFirst());
entity.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(0.15);
entity.getNavigator().setPathTo(this.game.getMazePath().get(1), 0.7, () -> changeEntityGoal(entity, 1));
entity.getNavigator().setPathTo(this.game.getMazePath().get(1), 0.7, () -> this.changeEntityGoal(entity, 1));
}
private void changeEntityGoal(EntityCreature entity, int positionIndex) {
if(positionIndex == this.game.getMazePath().size()-1) {
if(positionIndex == this.game.getMazePath().size() - 1) {
return;
}
entity.getNavigator().setPathTo(this.game.getMazePath().get(positionIndex+1), 0.7, () -> changeEntityGoal(entity, positionIndex+1));
entity.getNavigator().setPathTo(this.game.getMazePath().get(positionIndex + 1), 0.7, () -> this.changeEntityGoal(entity, positionIndex + 1));
}
}

View File

@@ -11,10 +11,10 @@ enum LightPhase {
YELLOW(Material.YELLOW_WOOL, 500, 1500),
GREEN(Material.GREEN_WOOL, 2000, 5000);
private static final Random rnd = new Random();
public final ItemStack item;
private final int minDuration;
private final int maxDuration;
private static final Random rnd = new Random();
LightPhase(Material material, int minDuration, int maxDuration) {
this.item = ItemStack.of(material);
@@ -23,7 +23,7 @@ enum LightPhase {
}
public TaskSchedule taskScheduleRandomDuration() {
return TaskSchedule.millis(rnd.nextLong(minDuration, maxDuration));
return TaskSchedule.millis(rnd.nextLong(this.minDuration, this.maxDuration));
}
}

View File

@@ -1,10 +1,10 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.trafficlightrace;
import de.articdive.jnoise.JNoise;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.util.CommonProperties;
import eu.mhsl.minenet.minigames.world.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator;
@@ -26,56 +26,55 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
class TrafficLightRace extends StatelessGame {
private LightPhase phase = LightPhase.RED;
private int phaseCounter = 0;
private final int width;
private final int length;
private final int preRun = 10;
private final int afterRun = 10;
private final List<Pos> trafficLights = new ArrayList<>();
private LightPhase phase = LightPhase.RED;
private int phaseCounter = 0;
public TrafficLightRace(int width, int length) {
super(Dimension.THE_END.key, "Ampelrennen", new FirstWinsScore());
this.width = width;
this.length = length;
setGenerator(
new SquarePlateTerrainGenerator(width, length + preRun + afterRun)
.setPlateHeight(50)
.setGenerateBorders(true)
this.setGenerator(
new SquarePlateTerrainGenerator(width, length + this.preRun + this.afterRun)
.setPlateHeight(50)
.setGenerateBorders(true)
);
}
@Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) {
final JNoise slowBatches = JNoise.newBuilder()
.fastSimplex()
.setSeed(rnd.nextLong())
.setFrequency(0.1)
.build();
.fastSimplex()
.setSeed(this.rnd.nextLong())
.setFrequency(0.1)
.build();
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for (int x = 0; x <= width; x++) {
for (int z = 0; z <= preRun; z++) {
for(int x = 0; x <= this.width; x++) {
for(int z = 0; z <= this.preRun; z++) {
batch.setBlock(x, 50, z, BlockPallet.GROUND.rnd());
}
for (int z = preRun; z <= length + preRun; z++) {
for(int z = this.preRun; z <= this.length + this.preRun; z++) {
batch.setBlock(x, 50, z, slowBatches.getNoise(x, z) > 0.6 ? Block.SOUL_SAND : BlockPallet.STREET.rnd());
}
for (int z = preRun + length; z <= preRun + length + afterRun; z++) {
for(int z = this.preRun + this.length; z <= this.preRun + this.length + this.afterRun; z++) {
batch.setBlock(x, 50, z, BlockPallet.GROUND.rnd());
}
batch.setBlock(x, 51, preRun-1, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
batch.setBlock(x, 50, preRun + length, Block.GOLD_BLOCK);
batch.setBlock(x, 51, this.preRun - 1, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
batch.setBlock(x, 50, this.preRun + this.length, Block.GOLD_BLOCK);
}
record TrafficLightsInput(int x, int z) {}
record TrafficLightsInput(int x, int z) {
}
Consumer<TrafficLightsInput> generateTrafficLight = (input) -> {
batch.setBlock(input.x, 51, input.z, Block.ANVIL);
@@ -84,36 +83,36 @@ class TrafficLightRace extends StatelessGame {
batch.setBlock(input.x, y, input.z, Block.ANDESITE_WALL);
}
for (int x = input.x-3; x <= input.x+3; x++) {
for(int x = input.x - 3; x <= input.x + 3; x++) {
batch.setBlock(x, 60, input.z, Block.SMOOTH_STONE_SLAB);
}
batch.setBlock(input.x-2, 59, input.z, Block.STONE_BRICK_WALL);
trafficLights.add(new Pos(input.x-2, 58, input.z));
trafficLights.add(new Pos(input.x-2, 57, input.z));
batch.setBlock(input.x - 2, 59, input.z, Block.STONE_BRICK_WALL);
this.trafficLights.add(new Pos(input.x - 2, 58, input.z));
this.trafficLights.add(new Pos(input.x - 2, 57, input.z));
batch.setBlock(input.x+2, 59, input.z, Block.STONE_BRICK_WALL);
trafficLights.add(new Pos(input.x+2, 58, input.z));
trafficLights.add(new Pos(input.x+2, 57, input.z));
batch.setBlock(input.x + 2, 59, input.z, Block.STONE_BRICK_WALL);
this.trafficLights.add(new Pos(input.x + 2, 58, input.z));
this.trafficLights.add(new Pos(input.x + 2, 57, input.z));
for (Pos trafficLight : trafficLights) {
for(Pos trafficLight : this.trafficLights) {
batch.setBlock(trafficLight, Block.WHITE_WOOL);
}
};
for (int count = 0; count <= this.rnd.nextInt(1, 2); count++) {
generateTrafficLight.accept(new TrafficLightsInput(0, this.rnd.nextInt(preRun + 10, length + preRun - 10)));
generateTrafficLight.accept(new TrafficLightsInput(width, this.rnd.nextInt(preRun + 10, length + preRun - 10)));
for(int count = 0; count <= this.rnd.nextInt(1, 2); count++) {
generateTrafficLight.accept(new TrafficLightsInput(0, this.rnd.nextInt(this.preRun + 10, this.length + this.preRun - 10)));
generateTrafficLight.accept(new TrafficLightsInput(this.width, this.rnd.nextInt(this.preRun + 10, this.length + this.preRun - 10)));
}
if(width > 30) {
for (int count = 0; count <= this.rnd.nextInt(1, 2); count++) {
generateTrafficLight.accept(new TrafficLightsInput(width/2, this.rnd.nextInt(preRun, length + preRun)));
if(this.width > 30) {
for(int count = 0; count <= this.rnd.nextInt(1, 2); count++) {
generateTrafficLight.accept(new TrafficLightsInput(this.width / 2, this.rnd.nextInt(this.preRun, this.length + this.preRun)));
}
}
generateTrafficLight.accept(new TrafficLightsInput(0, length + preRun));
generateTrafficLight.accept(new TrafficLightsInput(width, length + preRun));
generateTrafficLight.accept(new TrafficLightsInput(0, this.length + this.preRun));
generateTrafficLight.accept(new TrafficLightsInput(this.width, this.length + this.preRun));
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
}
@@ -121,50 +120,51 @@ class TrafficLightRace extends StatelessGame {
@Override
protected void onStart() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) {
batch.setBlock(x, 51, preRun-1, Block.AIR);
for(int x = 0; x <= this.width; x++) {
batch.setBlock(x, 51, this.preRun - 1, Block.AIR);
}
BatchUtil.loadAndApplyBatch(batch, this, () -> playSound(Sound.sound(SoundEvent.BLOCK_WOOD_BREAK, Sound.Source.BLOCK, 1f, 1f)));
BatchUtil.loadAndApplyBatch(batch, this, () -> this.playSound(Sound.sound(SoundEvent.BLOCK_WOOD_BREAK, Sound.Source.BLOCK, 1f, 1f)));
scheduler().submitTask(() -> {
this.scheduler().submitTask(() -> {
if(!super.isRunning) return TaskSchedule.stop();
phaseCounter++;
if(phaseCounter >= 3) phaseCounter = 0;
this.phaseCounter++;
if(this.phaseCounter >= 3) this.phaseCounter = 0;
if(phaseCounter == 0) phase = LightPhase.RED;
if(phaseCounter == 1) phase = LightPhase.GREEN;
if(phaseCounter == 2) phase = LightPhase.YELLOW;
if(this.phaseCounter == 0) this.phase = LightPhase.RED;
if(this.phaseCounter == 1) this.phase = LightPhase.GREEN;
if(this.phaseCounter == 2) this.phase = LightPhase.YELLOW;
getPlayers().forEach(player -> {
this.getPlayers().forEach(player -> {
for(int i = 0; i < 9; i++) {
player.getInventory().setItemStack(i, phase.item);
player.getInventory().setItemStack(i, this.phase.item);
}
});
AbsoluteBlockBatch changeLightsBatch = new AbsoluteBlockBatch();
for (Pos trafficLight : trafficLights) {
changeLightsBatch.setBlock(trafficLight, phase.item.material().block());
for(Pos trafficLight : this.trafficLights) {
changeLightsBatch.setBlock(trafficLight, this.phase.item.material().block());
}
BatchUtil.loadAndApplyBatch(changeLightsBatch, this, () -> {});
BatchUtil.loadAndApplyBatch(changeLightsBatch, this, () -> {
});
return phase.taskScheduleRandomDuration();
return this.phase.taskScheduleRandomDuration();
}, ExecutionType.TICK_END);
}
@Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(isBeforeBeginning) return;
if(getScore().hasResult(playerMoveEvent.getPlayer())) return;
if(this.isBeforeBeginning) return;
if(this.getScore().hasResult(playerMoveEvent.getPlayer())) return;
if(phase.equals(LightPhase.RED) && playerMoveEvent.getNewPosition().z()-0.01 > playerMoveEvent.getPlayer().getPosition().z()) {
if(this.phase.equals(LightPhase.RED) && playerMoveEvent.getNewPosition().z() - 0.01 > playerMoveEvent.getPlayer().getPosition().z()) {
playerMoveEvent.getPlayer().setVelocity(new Vec(0, 8, -15));
playerMoveEvent.getPlayer().playSound(Sound.sound(SoundEvent.ENTITY_BLAZE_SHOOT, Sound.Source.PLAYER, 1f, 1f));
}
if(playerMoveEvent.getNewPosition().z() > preRun+length) {
getScore().insertResult(playerMoveEvent.getPlayer());
if(playerMoveEvent.getNewPosition().z() > this.preRun + this.length) {
this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().getInventory().clear();
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
}
@@ -172,6 +172,6 @@ class TrafficLightRace extends StatelessGame {
@Override
public Pos getSpawn() {
return new Pos((double) width/2, 51, 3);
return new Pos((double) this.width / 2, 51, 3);
}
}

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.trafficlightrace;
import eu.mhsl.minenet.minigames.instance.game.Game;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.ConfigManager;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room;
@@ -25,8 +25,8 @@ public class TrafficLightRaceFactory implements GameFactory {
@Override
public ConfigManager configuration() {
return new ConfigManager()
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("game_TrafficlightRace#width"), 20, 30, 40))
.addOption(new NumericOption("length", Material.BLACK_CONCRETE_POWDER, TranslatedComponent.byId("game_TrafficlightRace#length"), 50, 80, 100, 120, 150));
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("game_TrafficlightRace#width"), 20, 30, 40))
.addOption(new NumericOption("length", Material.BLACK_CONCRETE_POWDER, TranslatedComponent.byId("game_TrafficlightRace#length"), 50, 80, 100, 120, 150));
}
@Override

View File

@@ -10,7 +10,10 @@ import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.*;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.EntityType;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.entity.metadata.other.FallingBlockMeta;
import net.minestom.server.event.player.PlayerStartSneakingEvent;
import net.minestom.server.event.player.PlayerStopSneakingEvent;
@@ -171,7 +174,7 @@ class TurtleGame extends StatelessGame {
}
private void generateNewSnacks(int count) {
for (int i = 0; i < count; i++) {
for(int i = 0; i < count; i++) {
this.generateNewSnack();
}
}
@@ -192,7 +195,7 @@ class TurtleGame extends StatelessGame {
}
private void generateNewBombs(int count) {
for (int i = 0; i < count; i++) {
for(int i = 0; i < count; i++) {
this.generateNewBomb();
}
}
@@ -222,21 +225,21 @@ class TurtleGame extends StatelessGame {
boolean isInRadius, collides;
do {
if(counter > 200) return null;
int x = this.rnd.nextInt(-this.radius+2, this.radius-2);
int z = this.rnd.nextInt(-this.radius+2, this.radius-2);
int x = this.rnd.nextInt(-this.radius + 2, this.radius - 2);
int z = this.rnd.nextInt(-this.radius + 2, this.radius - 2);
spawnPosition = new Pos(x, 1, z).add(0.5, 0, 0.5);
Pos checkPosition = spawnPosition;
isInRadius = checkPosition.distance(0, 1, 0) < this.radius-2;
isInRadius = checkPosition.distance(0, 1, 0) < this.radius - 2;
collides = this.getEntities().stream()
.filter(e -> !e.equals(entity))
.anyMatch(e -> entity.getBoundingBox().intersectBox(e.getPosition().sub(checkPosition), e.getBoundingBox()));
if(!collides && !nearPlayers) collides = this.turtlePlayerMap.values().stream()
.filter(turtle -> !turtle.equals(entity))
.anyMatch(turtle -> entity.getBoundingBox()
.growSymmetrically(turtle.getBombBorder(), 1, turtle.getBombBorder())
.intersectBox(turtle.getPosition().sub(checkPosition), turtle.getBoundingBox()));
.filter(turtle -> !turtle.equals(entity))
.anyMatch(turtle -> entity.getBoundingBox()
.growSymmetrically(turtle.getBombBorder(), 1, turtle.getBombBorder())
.intersectBox(turtle.getPosition().sub(checkPosition), turtle.getBoundingBox()));
counter++;
} while (!isInRadius || collides);
} while(!isInRadius || collides);
return spawnPosition;
}

View File

@@ -1,14 +1,16 @@
package eu.mhsl.minenet.minigames.instance.hub;
import eu.mhsl.minenet.minigames.Resource;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.MineNetInstance;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.hub.entity.RoomSelector;
import eu.mhsl.minenet.minigames.util.CommonEventHandles;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.Dimension;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.event.player.*;
import net.minestom.server.event.player.PlayerBlockBreakEvent;
import net.minestom.server.event.player.PlayerBlockInteractEvent;
import net.minestom.server.event.player.PlayerBlockPlaceEvent;
import net.minestom.server.instance.anvil.AnvilLoader;
import java.nio.file.Path;
@@ -22,19 +24,19 @@ public class Hub extends MineNetInstance implements Spawnable {
INSTANCE.setChunkLoader(new AnvilLoader(Resource.HUB_MAP.getPath()));
INSTANCE.eventNode()
.addListener(PlayerBlockBreakEvent.class, CommonEventHandles::cancel)
.addListener(PlayerBlockPlaceEvent.class, CommonEventHandles::cancel)
.addListener(PlayerBlockInteractEvent.class, CommonEventHandles::cancel);
.addListener(PlayerBlockBreakEvent.class, CommonEventHandles::cancel)
.addListener(PlayerBlockPlaceEvent.class, CommonEventHandles::cancel)
.addListener(PlayerBlockInteractEvent.class, CommonEventHandles::cancel);
new RoomSelector().setInstance(INSTANCE, new Pos(0.5, 11, 4.5));
}
private Hub() {
super(Dimension.THE_END.key);
setChunkLoader(new AnvilLoader(Path.of("maps/hub")));
this.setChunkLoader(new AnvilLoader(Path.of("maps/hub")));
setTime(18000);
setTimeRate(0);
this.setTime(18000);
this.setTimeRate(0);
}

View File

@@ -11,10 +11,11 @@ import org.jetbrains.annotations.NotNull;
public class RoomSelector extends InteractableEntity {
final AbstractVillagerMeta abstractVillagerMeta;
public RoomSelector() {
super(EntityType.VILLAGER);
abstractVillagerMeta = (AbstractVillagerMeta) this.getEntityMeta();
this.abstractVillagerMeta = (AbstractVillagerMeta) this.getEntityMeta();
}
@Override
@@ -25,7 +26,7 @@ public class RoomSelector extends InteractableEntity {
@Override
public void onAttack(@NotNull EntityAttackEvent entityAttackEvent) {
super.onAttack(entityAttackEvent);
abstractVillagerMeta.setHeadShakeTimer(20);
this.abstractVillagerMeta.setHeadShakeTimer(20);
}
@Override

View File

@@ -12,25 +12,25 @@ public class HubInventory extends InteractableInventory {
public HubInventory(Player p) {
super(InventoryType.CHEST_3_ROW, TranslatedComponent.assemble("hub#invTitle", p));
setClickableItem(
ItemStack
.builder(Material.WRITABLE_BOOK)
.customName(TranslatedComponent.assemble("hub#create", p))
.lore(TranslatedComponent.assemble("hub#create_description", p))
.build(),
12,
itemClick -> Room.createRoom(itemClick.getPlayer()),
true
this.setClickableItem(
ItemStack
.builder(Material.WRITABLE_BOOK)
.customName(TranslatedComponent.assemble("hub#create", p))
.lore(TranslatedComponent.assemble("hub#create_description", p))
.build(),
12,
itemClick -> Room.createRoom(itemClick.getPlayer()),
true
);
setClickableItem(
ItemStack
.builder(Material.KNOWLEDGE_BOOK)
.customName(TranslatedComponent.assemble("hub#join", p))
.lore(TranslatedComponent.assemble("hub#join_description", p))
.build(),
14,
itemClick -> itemClick.getPlayer().openInventory(new JoinInventory(itemClick.getPlayer()))
this.setClickableItem(
ItemStack
.builder(Material.KNOWLEDGE_BOOK)
.customName(TranslatedComponent.assemble("hub#join", p))
.lore(TranslatedComponent.assemble("hub#join_description", p))
.build(),
14,
itemClick -> itemClick.getPlayer().openInventory(new JoinInventory(itemClick.getPlayer()))
);
}
}

View File

@@ -1,11 +1,11 @@
package eu.mhsl.minenet.minigames.instance.hub.inventory;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.shared.inventory.InteractableInventory;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import net.kyori.adventure.text.Component;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
@@ -21,23 +21,24 @@ import java.util.Locale;
import java.util.Optional;
public class JoinInventory extends InteractableInventory {
private String typedText = "";
private final String prefix = "Suche: ";
private String typedText = "";
public JoinInventory(Player p) {
super(InventoryType.ANVIL, TranslatedComponent.assemble("hub#join_title", p));
setClickableItem(
ItemStack.builder(Material.GREEN_STAINED_GLASS_PANE)
.customName(Component.text(prefix))
.build(),
0,
itemClick -> {}
this.setClickableItem(
ItemStack.builder(Material.GREEN_STAINED_GLASS_PANE)
.customName(Component.text(this.prefix))
.build(),
0,
itemClick -> {
}
);
Hub.INSTANCE.eventNode().addListener(PlayerPacketEvent.class, event -> {
if (event.getPacket() instanceof ClientNameItemPacket packet) {
typedText = packet.itemName();
if(event.getPacket() instanceof ClientNameItemPacket(String itemName)) {
this.typedText = itemName;
}
});
@@ -49,22 +50,22 @@ public class JoinInventory extends InteractableInventory {
inventoryConditionResult.setCancel(true);
player.closeInventory();
typedText = formatInput(typedText);
this.typedText = this.formatInput(this.typedText);
Optional<Room> target = Room.getRoom(MinecraftServer.getConnectionManager().findOnlinePlayer(typedText));
Optional<Room> target = Room.getRoom(MinecraftServer.getConnectionManager().findOnlinePlayer(this.typedText));
if(target.isPresent())
Room.setRoom(player, target.get());
else
new ChatMessage(Icon.ERROR)
.appendTranslated("hub#join_notFound")
.appendSpace()
.quote(typedText.trim())
.quote(this.typedText.trim())
.send(player);
}
private String formatInput(String raw) {
if(raw.startsWith(prefix)) {
raw = raw.split(prefix)[1];
if(raw.startsWith(this.prefix)) {
raw = raw.split(this.prefix)[1];
}
return raw.toLowerCase(Locale.ROOT).trim();

View File

@@ -1,16 +1,16 @@
package eu.mhsl.minenet.minigames.instance.room;
import eu.mhsl.minenet.minigames.Resource;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.MineNetInstance;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.entity.GameSelector;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.score.tournament.Tournament;
import eu.mhsl.minenet.minigames.util.CommonEventHandles;
import eu.mhsl.minenet.minigames.util.MoveInstance;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.entity.GameSelector;
import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.entity.GameMode;
@@ -27,6 +27,24 @@ public class Room extends MineNetInstance implements Spawnable {
private static final Set<Room> rooms = new HashSet<>();
private static final Map<Player, Room> players = new WeakHashMap<>();
private static final Logger logger = Logger.getLogger("room");
public final UUID uuid = UUID.randomUUID();
public final boolean apiDriven;
private final Tournament tournament = new Tournament();
private Player owner;
private GameSelector gameSelector;
private Room(Player owner) {
super(Dimension.THE_END.key);
this.apiDriven = false;
this.construct();
this.setOwner(owner);
}
protected Room() {
super(Dimension.THE_END.key);
this.apiDriven = true;
this.construct();
}
public static Room createRoom(Player owner) {
logger.info("Creating room with owner " + owner.getUsername());
@@ -82,24 +100,6 @@ public class Room extends MineNetInstance implements Spawnable {
return rooms;
}
private Player owner;
public final UUID uuid = UUID.randomUUID();
public final boolean apiDriven;
private GameSelector gameSelector;
private final Tournament tournament = new Tournament();
private Room(Player owner) {
super(Dimension.THE_END.key);
this.apiDriven = false;
this.construct();
this.setOwner(owner);
}
protected Room() {
super(Dimension.THE_END.key);
this.apiDriven = true;
this.construct();
}
private void construct() {
MinecraftServer.getInstanceManager().registerInstance(this);
this.setChunkLoader(new AnvilLoader(Resource.LOBBY_MAP.getPath()));
@@ -126,12 +126,12 @@ public class Room extends MineNetInstance implements Spawnable {
if(p != this.owner) return;
this.getAllMembers().stream()
.filter(player -> player != p) // exclude the current leaving owner
.findFirst()
.ifPresentOrElse(
this::setOwner,
() -> Room.getRoom(p).ifPresent(Room::deleteRoom) // delete room if no players are left
);
.filter(player -> player != p) // exclude the current leaving owner
.findFirst()
.ifPresentOrElse(
this::setOwner,
() -> Room.getRoom(p).ifPresent(Room::deleteRoom) // delete room if no players are left
);
Room.unsetRoom(p);
@@ -159,8 +159,8 @@ public class Room extends MineNetInstance implements Spawnable {
public Set<Player> getAllMembers() {
return players.keySet().stream()
.filter(player -> getRoom(player).orElse(null) == this)
.collect(Collectors.toSet());
.filter(player -> getRoom(player).orElse(null) == this)
.collect(Collectors.toSet());
}
public Tournament getTournament() {

View File

@@ -14,10 +14,11 @@ import org.jetbrains.annotations.NotNull;
public class GameSelector extends InteractableEntity {
final AbstractVillagerMeta abstractVillagerMeta;
public GameSelector() {
super(EntityType.VILLAGER);
abstractVillagerMeta = (AbstractVillagerMeta) this.getEntityMeta();
this.abstractVillagerMeta = (AbstractVillagerMeta) this.getEntityMeta();
}
@Override
@@ -32,10 +33,10 @@ public class GameSelector extends InteractableEntity {
@Override
public void onInteract(@NotNull PlayerEntityInteractEvent playerEntityInteractEvent) {
Room room = (Room) instance;
Room room = (Room) this.instance;
if(playerEntityInteractEvent.getPlayer() != room.getOwner()) {
abstractVillagerMeta.setHeadShakeTimer(20);
this.abstractVillagerMeta.setHeadShakeTimer(20);
new ChatMessage(Icon.ERROR)
.appendTranslated("room#onlyOwnerCanStart")

View File

@@ -19,25 +19,26 @@ import java.util.List;
public class MinigameSelectInventory extends InteractableInventory {
final private Room room;
final private Player p;
public MinigameSelectInventory(Room room, Player p) {
super(InventoryType.CHEST_6_ROW, TranslatedComponent.assemble("room#invTitle", p));
this.room = room;
this.p = p;
InventoryItemAlignment itemAlignment = new InventoryItemAlignment(GameType.values().length, 1);
for (GameType type : GameType.values()) {
setClickableItem(
ItemStack.builder(type.getIcon())
.customName(type.getTitle().getAssembled(p))
.lore(type.getDescription().addWrap().getWrappedAssembled(p))
.build(),
itemAlignment.next().get(),
itemClick -> drawGames(type)
for(GameType type : GameType.values()) {
this.setClickableItem(
ItemStack.builder(type.getIcon())
.customName(type.getTitle().getAssembled(p))
.lore(type.getDescription().addWrap().getWrappedAssembled(p))
.build(),
itemAlignment.next().get(),
itemClick -> this.drawGames(type)
);
}
for(int i = 9; i <= 17; i++) {
setDummyItem(Material.CYAN_STAINED_GLASS_PANE, i);
this.setDummyItem(Material.CYAN_STAINED_GLASS_PANE, i);
}
@@ -45,23 +46,23 @@ public class MinigameSelectInventory extends InteractableInventory {
private void drawGames(GameType type) {
for(int i = 18; i <= 53; i++) {
setDummyItem(Material.AIR, i);
this.setDummyItem(Material.AIR, i);
}
int offset = 18;
List<GameList> games = Arrays.stream(GameList.values()).filter(gameList -> gameList.getType().equals(type)).toList();
InventoryItemAlignment itemAlignment = new InventoryItemAlignment(games.size(), 4);
for (GameList game : games) {
for(GameList game : games) {
GameFactory gameFactory = game.getFactory();
setClickableItem(
ItemStack.builder(gameFactory.symbol())
.customName(gameFactory.name().getAssembled(p))
.lore(gameFactory.description().addWrap().getWrappedAssembled(p))
.build(),
offset + itemAlignment.next().get(),
itemClick -> itemClick.getPlayer().openInventory(new GameConfigurationInventory(room, itemClick.getPlayer(), gameFactory))
this.setClickableItem(
ItemStack.builder(gameFactory.symbol())
.customName(gameFactory.name().getAssembled(this.p))
.lore(gameFactory.description().addWrap().getWrappedAssembled(this.p))
.build(),
offset + itemAlignment.next().get(),
itemClick -> itemClick.getPlayer().openInventory(new GameConfigurationInventory(this.room, itemClick.getPlayer(), gameFactory))
);
}
}

View File

@@ -11,8 +11,8 @@ import net.minestom.server.instance.block.Block;
public class Transfer extends MineNetInstance implements Spawnable {
public Transfer() {
super(Dimension.THE_END.key);
eventNode().addListener(PlayerMoveEvent.class, CommonEventHandles::cancel);
setBlock(0, 0, 0, Block.BARRIER);
this.eventNode().addListener(PlayerMoveEvent.class, CommonEventHandles::cancel);
this.setBlock(0, 0, 0, Block.BARRIER);
}
@Override

View File

@@ -14,17 +14,17 @@ public class Lang {
}
public void addEntry(String key, String value) {
entries.put(key, value);
this.entries.put(key, value);
}
public String getEntry(String key) {
return entries.computeIfAbsent(key, s -> {
return this.entries.computeIfAbsent(key, s -> {
Logger.getLogger("localisation").warning(s + " is not known by translation files!");
return new DummyLang().getEntry(s);
});
}
public String getLangId() {
return langId;
return this.langId;
}
}

View File

@@ -8,35 +8,37 @@ import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
public class Languages {
private static Languages instance;
public static final String defaultLanguage = "de_de";
private static final Logger logger = Logger.getLogger("translation");
private static Languages instance;
private final Map<String, Lang> languages = new HashMap<>();
public static final String defaultLanguage = "de_de";
private Languages() {
this.readAll();
}
public static Languages getInstance() {
if(instance == null) instance = new Languages();
return instance;
}
private Languages() {
readAll();
public Lang getLanguage(Player p) {
return this.getLanguage(p.getSettings().locale().toString());
}
public Lang getLanguage(Player p) {
return getLanguage(p.getSettings().locale().toString()); // TODO funktioniert die locale noch?
}
public Lang getLanguage(String mapId) {
return languages.computeIfAbsent(mapId.toLowerCase(), unused -> languages.computeIfAbsent(defaultLanguage, (key) -> new DummyLang()));
return this.languages.computeIfAbsent(mapId.toLowerCase(), unused -> this.languages.computeIfAbsent(defaultLanguage, (key) -> new DummyLang()));
}
private void readAll() {
File locales = new File(Resource.LOCALES.getPath().toString());
File[] files = Arrays.stream(locales.listFiles(File::canRead)).filter(file -> file.getName().endsWith("map.csv")).toArray(File[]::new);
File[] files = Arrays.stream(Objects.requireNonNull(locales.listFiles(File::canRead)))
.filter(file -> file.getName().endsWith("map.csv"))
.toArray(File[]::new);
if(files.length == 0) {
logger.warning("Failed to find any Language-files!");
@@ -66,20 +68,22 @@ public class Languages {
index++;
if(langId.endsWith("map")) continue;
languages.computeIfAbsent(langId, Lang::new);
Lang lang = languages.get(langId);
this.languages.computeIfAbsent(langId, Lang::new);
Lang lang = this.languages.get(langId);
langColumn.put(index, lang);
languages.put(langId, lang);
this.languages.put(langId, lang);
}
} else if(columns[0].startsWith("ns:")) {
if(!computedFileHeader) throw new IllegalStateException("Cannot compute namespace data before file-header was red!");
if(!computedFileHeader)
throw new IllegalStateException("Cannot compute namespace data before file-header was red!");
namespace = columns[0].split(":")[1];
} else {
// file contents
if(!computedFileHeader) throw new IllegalStateException("Cannot compute translation data before file-header was red!");
if(!computedFileHeader)
throw new IllegalStateException("Cannot compute translation data before file-header was red!");
int index = 0;
String mapId = "";
for(String translation : columns) {
@@ -97,7 +101,7 @@ public class Languages {
}
}
} catch (Exception e) {
} catch(Exception e) {
logger.warning("Exception while parsing lang-files: " + e.getMessage());
e.printStackTrace();
}

Some files were not shown because too many files have changed in this diff Show More