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

View File

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

View File

@@ -12,11 +12,11 @@ public abstract class Controller<Q, R> implements Route {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Controller() { public Controller() {
this.requestType = ((Class<Q>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); this.requestType = ((Class<Q>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
} }
@Override @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-Origin", "*");
response.header("Access-Control-Allow-Methods", "*"); 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); 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); public abstract R handle(Q request, Response response);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,20 +11,21 @@ import java.util.List;
public class PrivilegedCommand extends Command { public class PrivilegedCommand extends Command {
private final List<CommandCondition> conditions = new ArrayList<>(); private final List<CommandCondition> conditions = new ArrayList<>();
public PrivilegedCommand(@NotNull String name, @Nullable String... aliases) { public PrivilegedCommand(@NotNull String name, @Nullable String... aliases) {
super(name, aliases); super(name, aliases);
construct(); this.construct();
} }
public PrivilegedCommand(@NotNull String name) { public PrivilegedCommand(@NotNull String name) {
super(name); super(name);
construct(); this.construct();
} }
private void 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() { protected CommandCondition isPrivileged() {
@@ -32,6 +33,6 @@ public class PrivilegedCommand extends Command {
} }
protected void addCondition(CommandCondition condition) { 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; 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.hub.Hub;
import eu.mhsl.minenet.minigames.instance.room.Room; 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.command.builder.Command;
import net.minestom.server.entity.Player; import net.minestom.server.entity.Player;
@@ -10,12 +10,12 @@ public class HubCommand extends Command {
public HubCommand() { public HubCommand() {
super("hub"); super("hub");
setCondition( this.setCondition(
(sender, commandString) -> (sender, commandString) ->
((Player) sender).getInstance() instanceof Room room && !room.apiDriven ((Player) sender).getInstance() instanceof Room room && !room.apiDriven
); );
setDefaultExecutor((sender, context) -> { this.setDefaultExecutor((sender, context) -> {
if(Room.getRoom((Player) sender).orElseThrow().apiDriven) return; if(Room.getRoom((Player) sender).orElseThrow().apiDriven) return;
Room.unsetRoom((Player) sender); Room.unsetRoom((Player) sender);
MoveInstance.move((Player) sender, Hub.INSTANCE); MoveInstance.move((Player) sender, Hub.INSTANCE);

View File

@@ -9,8 +9,8 @@ public class LeaveCommand extends Command {
public LeaveCommand() { public LeaveCommand() {
super("leave"); 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() { public DebugCommand() {
super("debug"); super("debug");
setDefaultExecutor((sender, args) -> { this.setDefaultExecutor((sender, args) -> {
new ChatMessage(Icon.CHAT).appendTranslated("sample").send(sender); new ChatMessage(Icon.CHAT).appendTranslated("sample").send(sender);
new ActionBarMessage().appendTranslated("sample").send(sender); new ActionBarMessage().appendTranslated("sample").send(sender);
new TitleMessage().subtitle(subtitleMessage -> subtitleMessage.appendTranslated("sample")).appendTranslated("sample").send(sender); new TitleMessage().subtitle(subtitleMessage -> subtitleMessage.appendTranslated("sample")).appendTranslated("sample").send(sender);
List<String> testplayers = new ArrayList<>() { List<String> testplayers = new ArrayList<>() {
{ {
add("MineTec"); this.add("MineTec");
add("Goldi187"); this.add("Goldi187");
add("Test"); this.add("Test");
} }
}; };
new ChatMessage(Icon.STAR, true) new ChatMessage(Icon.STAR, true)
.appendTranslated("score#result") .appendTranslated("score#result")
.newLine() .newLine()
.indent() .indent()
.numberedList(testplayers) .numberedList(testplayers)
.undent() .undent()
.newLine() .newLine()
.appendTranslated("score#thanks") .appendTranslated("score#thanks")
.send(sender); .send(sender);
new ChatMessage(Icon.SCIENCE).appendStatic(((Player) sender).getUuid().toString()).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() { public FlyCommand() {
super("fly"); super("fly");
setDefaultExecutor((sender, context) -> { this.setDefaultExecutor((sender, context) -> {
Player p = (Player) sender; Player p = (Player) sender;
p.setVelocity(new Vec(0, 5, 0)); p.setVelocity(new Vec(0, 5, 0));
p.setFlying(!p.isFlying()); p.setFlying(!p.isFlying());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,8 @@
package eu.mhsl.minenet.minigames.command.privileged; package eu.mhsl.minenet.minigames.command.privileged;
import eu.mhsl.minenet.minigames.command.PrivilegedCommand; 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.Lang;
import eu.mhsl.minenet.minigames.lang.Languages;
import eu.mhsl.minenet.minigames.message.Icon; import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.TranslatableMessage; import eu.mhsl.minenet.minigames.message.TranslatableMessage;
import eu.mhsl.minenet.minigames.message.type.ChatMessage; import eu.mhsl.minenet.minigames.message.type.ChatMessage;
@@ -13,11 +13,11 @@ public class LangTestCommand extends PrivilegedCommand {
public LangTestCommand() { public LangTestCommand() {
super("langtest"); 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"); 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) { private TranslatableMessage sendMessage(Lang lang, String mapId) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -10,39 +10,40 @@ import net.minestom.server.world.DimensionType;
*/ */
public enum Dimension { public enum Dimension {
OVERWORLD( OVERWORLD(
NamespaceID.from("minenet:fullbright_overworld"), NamespaceID.from("minenet:fullbright_overworld"),
DimensionType DimensionType
.builder() .builder()
.ambientLight(2.0f) .ambientLight(2.0f)
.build() .build()
), ),
NETHER( NETHER(
NamespaceID.from("minenet:fullbright_nether"), NamespaceID.from("minenet:fullbright_nether"),
DimensionType DimensionType
.builder() .builder()
.ambientLight(2.0f) .ambientLight(2.0f)
.effects("minecraft:the_nether") .effects("minecraft:the_nether")
.build() .build()
), ),
THE_END( THE_END(
NamespaceID.from("minenet:fullbright_end"), NamespaceID.from("minenet:fullbright_end"),
DimensionType DimensionType
.builder() .builder()
.ambientLight(2.0f) .ambientLight(2.0f)
.effects("minecraft:the_end") .effects("minecraft:the_end")
.build() .build()
); );
public final DimensionType DIMENSION; public final DimensionType DIMENSION;
public final NamespaceID namespaceID; public final NamespaceID namespaceID;
public final DynamicRegistry.Key<DimensionType> key; public final DynamicRegistry.Key<DimensionType> key;
Dimension(NamespaceID namespaceID, DimensionType dimType) { Dimension(NamespaceID namespaceID, DimensionType dimType) {
this.DIMENSION = dimType; this.DIMENSION = dimType;
this.namespaceID = namespaceID; 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.event.instance.RemoveEntityFromInstanceEvent;
import net.minestom.server.instance.Instance; import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer; import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.instance.InstanceManager;
import net.minestom.server.registry.DynamicRegistry; import net.minestom.server.registry.DynamicRegistry;
import net.minestom.server.timer.TaskSchedule; import net.minestom.server.timer.TaskSchedule;
import net.minestom.server.world.DimensionType; import net.minestom.server.world.DimensionType;
@@ -19,9 +18,9 @@ public class MineNetInstance extends InstanceContainer {
super(UUID.randomUUID(), type); super(UUID.randomUUID(), type);
MinecraftServer.getInstanceManager().registerInstance(this); MinecraftServer.getInstanceManager().registerInstance(this);
eventNode() this.eventNode()
.addListener(AddEntityToInstanceEvent.class, this::onEntityAdd) .addListener(AddEntityToInstanceEvent.class, this::onEntityAdd)
.addListener(RemoveEntityFromInstanceEvent.class, this::onEntityRemove); .addListener(RemoveEntityFromInstanceEvent.class, this::onEntityRemove);
} }
private void onEntityRemove(RemoveEntityFromInstanceEvent removeEntityFromInstanceEvent) { private void onEntityRemove(RemoveEntityFromInstanceEvent removeEntityFromInstanceEvent) {
@@ -38,6 +37,7 @@ public class MineNetInstance extends InstanceContainer {
/** /**
* Called when Player joins this instance * Called when Player joins this instance
*
* @param p player who is joining * @param p player who is joining
* @return setCanceled * @return setCanceled
*/ */
@@ -47,18 +47,15 @@ public class MineNetInstance extends InstanceContainer {
/** /**
* Called when Player leaves this instance * Called when Player leaves this instance
*
* @param p player who is leaving * @param p player who is leaving
*/ */
protected void onPlayerLeave(Player p) { protected void onPlayerLeave(Player p) {
} }
/**
*
* @param target
*/
public void destroy(Instance target) { public void destroy(Instance target) {
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
if(target != null) if(target != null)
player.setInstance(target); player.setInstance(target);
else else
@@ -66,9 +63,9 @@ public class MineNetInstance extends InstanceContainer {
}); });
MinecraftServer.getSchedulerManager().scheduleTask( MinecraftServer.getSchedulerManager().scheduleTask(
() -> MinecraftServer.getInstanceManager().unregisterInstance(this), () -> MinecraftServer.getInstanceManager().unregisterInstance(this),
TaskSchedule.seconds(10), TaskSchedule.seconds(10),
TaskSchedule.stop() TaskSchedule.stop()
); );
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,9 +12,11 @@ import java.util.Map;
public interface GameFactory { public interface GameFactory {
TranslatedComponent name(); TranslatedComponent name();
default ConfigManager configuration() { default ConfigManager configuration() {
return null; return null;
} }
default RestrictionHandler globalRestrictions() { default RestrictionHandler globalRestrictions() {
return new RestrictionHandler(); return new RestrictionHandler();
} }
@@ -22,6 +24,7 @@ public interface GameFactory {
default Material symbol() { default Material symbol() {
return Material.GRASS_BLOCK; return Material.GRASS_BLOCK;
} }
default TranslatedComponent description() { default TranslatedComponent description() {
return TranslatedComponent.byId("GameFactory#missingDescription"); return TranslatedComponent.byId("GameFactory#missingDescription");
} }
@@ -29,17 +32,17 @@ public interface GameFactory {
Game manufacture(Room parent, Map<String, Option<?>> configuration) throws Exception; Game manufacture(Room parent, Map<String, Option<?>> configuration) throws Exception;
default Game manufacture(Room parent, List<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<>(); Map<String, Option<?>> cnf = new HashMap<>();
configuration.forEach(option -> cnf.put(option.getId(), option)); configuration.forEach(option -> cnf.put(option.getId(), option));
return manufacture(parent, cnf); return this.manufacture(parent, cnf);
} }
default Game manufacture(Room parent) throws Exception { 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; import java.util.Objects;
public abstract class Option<T> { public abstract class Option<T> {
private RestrictionHandler restrictionHandler;
private final Material item; private final Material item;
private final TranslatedComponent name; private final TranslatedComponent name;
private final String id; private final String id;
protected T currentValue;
private final List<T> options; private final List<T> options;
protected T currentValue;
private RestrictionHandler restrictionHandler;
private int pointer = 0; private int pointer = 0;
public Option(String id, Material item, TranslatedComponent name, List<T> options) { public Option(String id, Material item, TranslatedComponent name, List<T> options) {
@@ -26,46 +26,45 @@ public abstract class Option<T> {
this.name = name; this.name = name;
this.options = options; this.options = options;
currentValue = options.getFirst(); this.currentValue = options.getFirst();
}
public RestrictionHandler getRestrictionHandler() {
return this.restrictionHandler;
} }
public void setRestrictionHandler(RestrictionHandler restrictionHandler) { public void setRestrictionHandler(RestrictionHandler restrictionHandler) {
this.restrictionHandler = restrictionHandler; this.restrictionHandler = restrictionHandler;
} }
public RestrictionHandler getRestrictionHandler() {
return restrictionHandler;
}
public ItemStack getNext(Player p) { public ItemStack getNext(Player p) {
if(++pointer >= options.size()) pointer = 0; if(++this.pointer >= this.options.size()) this.pointer = 0;
currentValue = options.get(pointer); this.currentValue = this.options.get(this.pointer);
return getCurrent(p); return this.getCurrent(p);
} }
public ItemStack getCurrent(Player p) { public ItemStack getCurrent(Player p) {
String value = options.get(pointer).toString(); String value = this.options.get(this.pointer).toString();
return ItemStack.builder(item) return ItemStack.builder(this.item)
.customName(name.getAssembled(p)) .customName(this.name.getAssembled(p))
.lore(TranslatedComponent.byId("optionCommon#value").setColor(NamedTextColor.GOLD).getAssembled(p) .lore(TranslatedComponent.byId("optionCommon#value").setColor(NamedTextColor.GOLD).getAssembled(p)
.append(Component.text(": ")).append(Component.text(value))) .append(Component.text(": ")).append(Component.text(value)))
.build(); .build();
} }
public int getAsInt() { public int getAsInt() {
return Integer.parseInt(getAsString()); return Integer.parseInt(this.getAsString());
} }
public boolean getAsBoolean() { 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() { public String getAsString() {
return currentValue.toString(); return this.currentValue.toString();
} }
public String getId() { 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.warnMessage = warnMessage;
this.type = type; 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"); throw new IllegalStateException("warnMessage cannot be null when RestrictionType is WARN");
} }
} }

View File

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

View File

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

View File

@@ -15,10 +15,10 @@ public class MinimalPlayeramountGameRestriction implements IRestriction {
@Override @Override
public Restriction calculate(RestrictionData data) { public Restriction calculate(RestrictionData data) {
return new Restriction( return new Restriction(
TranslatedComponent.byId("restriction#minPlayersInRoom"), TranslatedComponent.byId("restriction#minPlayersInRoom"),
TranslatedComponent.byId("restriction#minPlayersInRoomDescription"), TranslatedComponent.byId("restriction#minPlayersInRoomDescription"),
null, null,
data.room().getAllMembers().size() < this.min ? Restriction.Type.FAIL : Restriction.Type.OK 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 { 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() final JNoise noise = JNoise.newBuilder()
.fastSimplex() .fastSimplex()
.setSeed(rnd.nextLong()) .setSeed(this.rnd.nextLong())
.setFrequency(0.09) .setFrequency(0.09)
.build(); .build();
final private int radius = 20;
final private int roofHeight = 55;
private int generationOffset = 0;
private int difficulty = 0;
public AcidRain() { public AcidRain() {
super(Dimension.OVERWORLD.key, "acidRain", new LastWinsScore()); super(Dimension.OVERWORLD.key, "acidRain", new LastWinsScore());
setGenerator( this.setGenerator(
new CircularPlateTerrainGenerator(radius) new CircularPlateTerrainGenerator(this.radius)
.setPlateHeight(50) .setPlateHeight(50)
.setPlatePallet(BlockPallet.STONE) .setPlatePallet(BlockPallet.STONE)
); );
eventNode().addListener(PlayerTickEvent.class, this::onPlayerTick); this.eventNode().addListener(PlayerTickEvent.class, this::onPlayerTick);
} }
@Override @Override
@@ -61,39 +61,40 @@ public class AcidRain extends StatelessGame {
MinecraftServer.getSchedulerManager().submitTask(() -> { MinecraftServer.getSchedulerManager().submitTask(() -> {
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
player.sendPacket(new ParticlePacket(Particle.SNEEZE, 0, 60, 0, radius, radius, radius, 1f, 500)); 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, radius, radius, 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); return TaskSchedule.millis(100);
}, ExecutionType.TICK_END); }, ExecutionType.TICK_END);
MinecraftServer.getSchedulerManager().submitTask(() -> { MinecraftServer.getSchedulerManager().submitTask(() -> {
generationOffset++; this.generationOffset++;
generatePlatform(generationOffset); this.generatePlatform(this.generationOffset);
if(!isRunning) return TaskSchedule.stop(); if(!this.isRunning) return TaskSchedule.stop();
return TaskSchedule.millis((long) NumberUtil.map(50 - difficulty, 0, 50, 100, 1000)); return TaskSchedule.millis((long) NumberUtil.map(50 - this.difficulty, 0, 50, 100, 1000));
}, ExecutionType.TICK_END); }, ExecutionType.TICK_END);
MinecraftServer.getSchedulerManager().submitTask(() -> { MinecraftServer.getSchedulerManager().submitTask(() -> {
difficulty++; this.difficulty++;
if(difficulty >= 50) return TaskSchedule.stop(); if(this.difficulty >= 50) return TaskSchedule.stop();
return TaskSchedule.seconds(3); return TaskSchedule.seconds(3);
}); });
} }
@Override @Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) { 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) { private void onPlayerTick(PlayerTickEvent playerTickEvent) {
if(isBeforeBeginning) return; if(this.isBeforeBeginning) return;
if(getBlock(playerTickEvent.getPlayer().getPosition().withY(roofHeight)).isAir()) playerDeath(playerTickEvent.getPlayer()); if(this.getBlock(playerTickEvent.getPlayer().getPosition().withY(this.roofHeight)).isAir())
this.playerDeath(playerTickEvent.getPlayer());
} }
private void generatePlatform(long offset) { private void generatePlatform(long offset) {
@@ -102,19 +103,20 @@ public class AcidRain extends StatelessGame {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) { for(int x = -radius; x <= radius; x++) {
for(int z = -radius; z <= radius; z++) { 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(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) { private void playerDeath(Player p) {
p.setGameMode(GameMode.SPECTATOR); p.setGameMode(GameMode.SPECTATOR);
getScore().insertResult(p); this.getScore().insertResult(p);
} }
@Override @Override

View File

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

View File

@@ -10,7 +10,7 @@ public class Backrooms extends StatelessGame {
public Backrooms() { public Backrooms() {
super(Dimension.NETHER.key, "Backrooms", new NoScore()); super(Dimension.NETHER.key, "Backrooms", new NoScore());
BackroomsGenerator generator = new BackroomsGenerator(); BackroomsGenerator generator = new BackroomsGenerator();
setGenerator(unit -> generator.generateRoom(unit, 50)); this.setGenerator(unit -> generator.generateRoom(unit, 50));
} }
@Override @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.block.Block;
import net.minestom.server.instance.generator.GenerationUnit; import net.minestom.server.instance.generator.GenerationUnit;
import net.minestom.server.instance.generator.UnitModifier; import net.minestom.server.instance.generator.UnitModifier;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
public class BackroomsGenerator { public class BackroomsGenerator {
@@ -11,8 +12,8 @@ public class BackroomsGenerator {
var start = unit.absoluteStart(); var start = unit.absoluteStart();
var yPos = start.blockY() + y; var yPos = start.blockY() + y;
for (int x = 0; x < unit.size().blockX(); x++) { for(int x = 0; x < unit.size().blockX(); x++) {
for (int z = 0; z < unit.size().blockZ(); z++) { for(int z = 0; z < unit.size().blockZ(); z++) {
var xPos = start.blockX() + x; var xPos = start.blockX() + x;
var zPos = start.blockZ() + z; var zPos = start.blockZ() + z;
@@ -23,27 +24,27 @@ public class BackroomsGenerator {
modifier.setBlock(xPos, yPos + 4, zPos, Block.SMOOTH_STONE_SLAB); modifier.setBlock(xPos, yPos + 4, zPos, Block.SMOOTH_STONE_SLAB);
// idk man... dont ask about this // idk man... dont ask about this
if ( if(
(x - 2) % 4 == 0 && ( (x - 2) % 4 == 0 && (
((z - 2) % 8 == 0) || ((z - 2) % 8 == 0) ||
((z - 2) % 8 == 1) || ((z - 2) % 8 == 1) ||
((z - 2) % 8 == 3) || ((z - 2) % 8 == 3) ||
((z - 2) % 8 == 4) ((z - 2) % 8 == 4)
) )
) { ) {
modifier.setBlock(xPos, yPos + 4, zPos, Block.SEA_LANTERN); modifier.setBlock(xPos, yPos + 4, zPos, Block.SEA_LANTERN);
} }
} }
} }
generateWalls(modifier, start.blockX() + 0, yPos + 1, start.blockZ() + 0); this.generateWalls(modifier, start.blockX(), yPos + 1, start.blockZ());
generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ() + 0); this.generateWalls(modifier, start.blockX() + 8, yPos + 1, start.blockZ());
generateWalls(modifier, start.blockX() + 0, yPos + 1, start.blockZ() + 8); this.generateWalls(modifier, start.blockX(), yPos + 1, start.blockZ() + 8);
generateWalls(modifier, start.blockX() + 8, 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) { 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(); var random = ThreadLocalRandom.current();
@@ -55,31 +56,31 @@ public class BackroomsGenerator {
var door1pos = random.nextInt(2, 6); var door1pos = random.nextInt(2, 6);
var door2pos = random.nextInt(2, 6); var door2pos = random.nextInt(2, 6);
if (wall1) { if(wall1) {
for (int x = xPos; x < xPos + 8; x++) { for(int x = xPos; x < xPos + 8; x++) {
generatePillar(modifier, x, yPos, zPos, Block.SMOOTH_SANDSTONE); this.generatePillar(modifier, x, yPos, zPos, Block.SMOOTH_SANDSTONE);
} }
} }
if (wall2) { if(wall2) {
for (int z = zPos; z < zPos + 8; z++) { for(int z = zPos; z < zPos + 8; z++) {
generatePillar(modifier, xPos, yPos, z, Block.SMOOTH_SANDSTONE); this.generatePillar(modifier, xPos, yPos, z, Block.SMOOTH_SANDSTONE);
} }
} }
if (door1 && wall1) { if(door1 && wall1) {
generatePillar(modifier, xPos + door1pos, yPos, zPos, Block.AIR); this.generatePillar(modifier, xPos + door1pos, yPos, zPos, Block.AIR);
generatePillar(modifier, xPos + door1pos + 1, yPos, zPos, Block.AIR); this.generatePillar(modifier, xPos + door1pos + 1, yPos, zPos, Block.AIR);
} }
if (door2 && wall2) { if(door2 && wall2) {
generatePillar(modifier, xPos, yPos, zPos + door2pos, Block.AIR); this.generatePillar(modifier, xPos, yPos, zPos + door2pos, Block.AIR);
generatePillar(modifier, xPos, yPos, zPos + door2pos + 1, 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) { 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); modifier.setBlock(xPos, y, zPos, material);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,16 +11,14 @@ import java.util.concurrent.ThreadLocalRandom;
public class BlockBreakRaceGenerator extends BaseGenerator { public class BlockBreakRaceGenerator extends BaseGenerator {
public static final int BOTTOM_Y = 50; 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_X = {4, 8, 12};
public static final int[] ROW_OFFSETS_Z = {4, 8, 12}; public static final int[] ROW_OFFSETS_Z = {4, 8, 12};
private static final Block[] FILL_BLOCKS = { private static final Block[] FILL_BLOCKS = {
Block.STONE, Block.STONE,
Block.DIRT, Block.DIRT,
Block.OAK_PLANKS Block.OAK_PLANKS
}; };
public final int TOP_Y;
private final Random random = ThreadLocalRandom.current(); private final Random random = ThreadLocalRandom.current();
public BlockBreakRaceGenerator(int height) { public BlockBreakRaceGenerator(int height) {
@@ -34,8 +32,8 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
this.addMixIn(unit -> { this.addMixIn(unit -> {
if(unit.absoluteStart().chunkX() != 0) return; if(unit.absoluteStart().chunkX() != 0) return;
for (int localX : ROW_OFFSETS_X) { for(int localX : ROW_OFFSETS_X) {
for (int localZ : ROW_OFFSETS_Z) { for(int localZ : ROW_OFFSETS_Z) {
final int absZ = unit.absoluteStart().blockZ() + localZ; final int absZ = unit.absoluteStart().blockZ() + localZ;
this.placeTube(unit, localX, absZ); this.placeTube(unit, localX, absZ);
} }
@@ -44,7 +42,7 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
} }
private void placeTube(GenerationUnit unit, int x, int z) { 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)]; Block fill = FILL_BLOCKS[this.random.nextInt(FILL_BLOCKS.length)];
unit.modifier().fill( unit.modifier().fill(
new Pos(x, y, z), new Pos(x, y, z),
@@ -53,9 +51,9 @@ public class BlockBreakRaceGenerator extends BaseGenerator {
); );
} }
for (int dx = -1; dx <= 1; dx++) { for(int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) { for(int dz = -1; dz <= 1; dz++) {
if (dx == 0 && dz == 0) continue; // Zentrum überspringen if(dx == 0 && dz == 0) continue; // Zentrum überspringen
unit.modifier().fill( unit.modifier().fill(
new Pos(x + dx, BOTTOM_Y, z + dz), new Pos(x + dx, BOTTOM_Y, z + dz),
new Pos(x + dx, this.TOP_Y + 3, z + dz).add(1), 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.Point;
import net.minestom.server.coordinate.Pos; import net.minestom.server.coordinate.Pos;
import net.minestom.server.coordinate.Vec; 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.entity.metadata.other.PrimedTntMeta;
import net.minestom.server.event.EventListener; import net.minestom.server.event.EventListener;
import net.minestom.server.event.entity.projectile.ProjectileCollideWithBlockEvent; 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 static final Tag<Boolean> ARROW_FIRST_HIT = Tag.Boolean("ARROW_ALREADY_LIT");
private final int radius = 30; private final int radius = 30;
private final int totalElevation = 50; private final int totalElevation = 50;
public BowSpleef() { public BowSpleef() {
super(Dimension.OVERWORLD.key, "bowSpleef", new LastWinsScore()); super(Dimension.OVERWORLD.key, "bowSpleef", new LastWinsScore());
@@ -67,41 +70,41 @@ public class BowSpleef extends StatelessGame {
// .build() // .build()
// ); // );
eventNode().addListener( this.eventNode().addListener(
EventListener EventListener
.builder(ProjectileCollideWithBlockEvent.class) .builder(ProjectileCollideWithBlockEvent.class)
.handler(projectileBlockHitEvent -> { .handler(projectileBlockHitEvent -> {
Entity projectile = projectileBlockHitEvent.getEntity(); Entity projectile = projectileBlockHitEvent.getEntity();
if(!projectile.getTag(ARROW_FIRST_HIT)) { if(!projectile.getTag(ARROW_FIRST_HIT)) {
projectile.remove(); projectile.remove();
return; return;
} }
float radius = 0.5F; float radius = 0.5F;
Point arrowPos = projectile.getPosition(); Point arrowPos = projectile.getPosition();
GeneratorUtils.foreachXZ(arrowPos.add(radius), arrowPos.sub(radius), point -> { GeneratorUtils.foreachXZ(arrowPos.add(radius), arrowPos.sub(radius), point -> {
Point location = point.add(projectile.getVelocity().mul(0.04)).withY(totalElevation); Point location = point.add(projectile.getVelocity().mul(0.04)).withY(this.totalElevation);
if(!getBlock(location).isAir()) { if(!this.getBlock(location).isAir()) {
setBlock(location, Block.AIR); this.setBlock(location, Block.AIR);
Entity fallingTnt = new Entity(EntityType.TNT); Entity fallingTnt = new Entity(EntityType.TNT);
PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta(); PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta();
fallingTntMeta.setFuseTime(20); fallingTntMeta.setFuseTime(20);
fallingTnt.setInstance(this, location); fallingTnt.setInstance(this, location);
fallingTnt.setVelocity(new Vec(0, 3, 0)); fallingTnt.setVelocity(new Vec(0, 3, 0));
} }
}); });
projectile.setTag(ARROW_FIRST_HIT, false); projectile.setTag(ARROW_FIRST_HIT, false);
}) })
.build() .build()
); );
eventNode().addListener( this.eventNode().addListener(
EventListener EventListener
.builder(ProjectileCollideWithEntityEvent.class) .builder(ProjectileCollideWithEntityEvent.class)
.handler(projectileEntityHitEvent -> projectileEntityHitEvent.setCancelled(true)) .handler(projectileEntityHitEvent -> projectileEntityHitEvent.setCancelled(true))
.build() .build()
); );
} }
@@ -109,11 +112,11 @@ public class BowSpleef extends StatelessGame {
@Override @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) { for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -radius; z <= radius; z++) { for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue; 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)); BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
@@ -121,28 +124,28 @@ public class BowSpleef extends StatelessGame {
@Override @Override
protected void onStart() { protected void onStart() {
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
player.getInventory().setItemStack( player.getInventory().setItemStack(
0, 0,
ItemStack ItemStack
.builder(Material.BOW) .builder(Material.BOW)
.customName(TranslatedComponent.byId("bow").getAssembled(player)) .customName(TranslatedComponent.byId("bow").getAssembled(player))
.glowing(true) .glowing(true)
.build() .build()
); );
}); });
} }
@Override @Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) { protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) { if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
getScore().insertResult(playerMoveEvent.getPlayer()); this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR); playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
} }
} }
@Override @Override
public Pos getSpawn() { 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 @Override
public RestrictionHandler globalRestrictions() { public RestrictionHandler globalRestrictions() {
return new RestrictionHandler() 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; 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.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore; import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil; 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.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.CircularPlateTerrainGenerator; import eu.mhsl.minenet.minigames.world.generator.terrain.CircularPlateTerrainGenerator;
import io.github.togar2.pvp.feature.CombatFeatures; import io.github.togar2.pvp.feature.CombatFeatures;
@@ -26,9 +26,9 @@ class Deathcube extends StatelessGame {
this.radius = radius; this.radius = radius;
this.height = height + 49; this.height = height + 49;
this.percentage = percentage; 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() CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK) .add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE) .add(CombatFeatures.VANILLA_DAMAGE)
@@ -42,12 +42,12 @@ class Deathcube extends StatelessGame {
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius; x <= radius; x++) { for(int x = -this.radius; x <= this.radius; x++) {
for (int z = -radius; z <= radius; z++) { for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue; if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) continue;
for (int y = 49; y < height; y++) { for(int y = 49; y < this.height; y++) {
if(super.rnd.nextInt(1, 100) <= percentage) { if(super.rnd.nextInt(1, 100) <= this.percentage) {
batch.setBlock(x, y, z, BlockPallet.WOOD.rnd()); batch.setBlock(x, y, z, BlockPallet.WOOD.rnd());
} }
} }
@@ -62,20 +62,20 @@ class Deathcube extends StatelessGame {
super.onPlayerMove(playerMoveEvent); super.onPlayerMove(playerMoveEvent);
if(playerMoveEvent.getNewPosition().y() < 48) { if(playerMoveEvent.getNewPosition().y() < 48) {
playerMoveEvent.setCancelled(true); playerMoveEvent.setCancelled(true);
playerMoveEvent.getPlayer().teleport(getSpawn()); playerMoveEvent.getPlayer().teleport(this.getSpawn());
return; return;
} }
if(isBeforeBeginning && playerMoveEvent.getNewPosition().y() > 51.5) { if(this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() > 51.5) {
playerMoveEvent.setCancelled(true); playerMoveEvent.setCancelled(true);
return; return;
} }
if(playerMoveEvent.getNewPosition().y() <= height) return; if(playerMoveEvent.getNewPosition().y() <= this.height) return;
getScore().insertResult(playerMoveEvent.getPlayer()); this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR); playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
} }
@Override @Override
public Pos getSpawn() { 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; 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.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.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option; 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.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room; import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent; import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
@@ -25,10 +25,10 @@ public class DeathcubeFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30)) .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("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("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("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(); Player player = playerUseItemEvent.getPlayer();
Material usedMaterial = playerUseItemEvent.getItemStack().material(); Material usedMaterial = playerUseItemEvent.getItemStack().material();
if (usedMaterial.equals(this.boostMaterial)) { if(usedMaterial.equals(this.boostMaterial)) {
if (!player.isFlyingWithElytra()) return; if(!player.isFlyingWithElytra()) return;
this.boost(player); this.boost(player);
InventoryUtil.removeItemFromPlayer(player, this.boostMaterial, 1); InventoryUtil.removeItemFromPlayer(player, this.boostMaterial, 1);
} else if (usedMaterial.equals(this.resetMaterial)) { } else if(usedMaterial.equals(this.resetMaterial)) {
this.toCheckpoint(player); this.toCheckpoint(player);
InventoryUtil.removeItemFromPlayer(player, this.resetMaterial, 1); InventoryUtil.removeItemFromPlayer(player, this.resetMaterial, 1);
} }
@@ -82,7 +82,7 @@ public class ElytraRace extends StatelessGame {
this.eventNode().addListener(PlayerStopFlyingWithElytraEvent.class, playerStopFlyingWithElytraEvent -> { this.eventNode().addListener(PlayerStopFlyingWithElytraEvent.class, playerStopFlyingWithElytraEvent -> {
Player player = playerStopFlyingWithElytraEvent.getPlayer(); 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); player.setFlyingWithElytra(true);
this.boost(player); this.boost(player);
} else { } else {
@@ -93,7 +93,7 @@ public class ElytraRace extends StatelessGame {
}); });
this.eventNode().addListener(PlayerStartFlyingWithElytraEvent.class, playerStartFlyingWithElytraEvent -> { this.eventNode().addListener(PlayerStartFlyingWithElytraEvent.class, playerStartFlyingWithElytraEvent -> {
if (!this.isRunning) { if(!this.isRunning) {
playerStartFlyingWithElytraEvent.getPlayer().setFlyingWithElytra(false); playerStartFlyingWithElytraEvent.getPlayer().setFlyingWithElytra(false);
return; return;
} }
@@ -116,7 +116,7 @@ public class ElytraRace extends StatelessGame {
protected void onStart() { protected void onStart() {
this.getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
player.getInventory().setEquipment(EquipmentSlot.CHESTPLATE, (byte) 0, ItemStack.of(Material.ELYTRA)); 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()); player.getInventory().setItemStack(i, ItemStack.builder(this.boostMaterial).customName(TranslatedComponent.byId("boost").getAssembled(player)).build());
} }
this.addResetItemToPlayer(player); this.addResetItemToPlayer(player);
@@ -128,23 +128,23 @@ public class ElytraRace extends StatelessGame {
Player player = playerMoveEvent.getPlayer(); Player player = playerMoveEvent.getPlayer();
Point newPos = playerMoveEvent.getNewPosition(); 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()); player.teleport(this.getSpawn());
return; return;
} }
this.playerCheckpoints.putIfAbsent(player, new CheckPointData(this.ringSpacing, this.ringSpacing * 2)); 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); 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.playerCheckpoints.put(player, this.playerCheckpoints.get(player).next(this.ringSpacing));
this.boost(player); this.boost(player);
} }
if (newPos.y() > this.gameHeight - 5) { if(newPos.y() > this.gameHeight - 5) {
Point particlePoint = newPos.withY(this.gameHeight); Point particlePoint = newPos.withY(this.gameHeight);
ParticlePacket particle = new ParticlePacket( ParticlePacket particle = new ParticlePacket(
Particle.WAX_ON, Particle.WAX_ON,
@@ -160,11 +160,11 @@ public class ElytraRace extends StatelessGame {
player.sendPacket(particle); player.sendPacket(particle);
} }
if (this.getBlock(player.getPosition()).equals(Block.WATER)) { if(this.getBlock(player.getPosition()).equals(Block.WATER)) {
this.toCheckpoint(player); this.toCheckpoint(player);
} }
if (newPos.z() > this.ringCount * this.ringSpacing) { if(newPos.z() > this.ringCount * this.ringSpacing) {
this.getScore().insertResult(player); this.getScore().insertResult(player);
player.setGameMode(GameMode.SPECTATOR); player.setGameMode(GameMode.SPECTATOR);
player.setFlyingWithElytra(false); 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); return new Pos(this.vale.getXShiftAtZ(z), -45 + random.nextInt(-5, 15), z);
} }
private CompletableFuture<Void> generateRing(int zPos) { private void generateRing(int zPos) {
if (zPos > this.ringCount * this.ringSpacing) return null; if(zPos > this.ringCount * this.ringSpacing) return;
boolean isLast = (zPos == this.ringCount * this.ringSpacing); boolean isLast = (zPos == this.ringCount * this.ringSpacing);
this.generatedUntil = zPos; this.generatedUntil = zPos;
@@ -211,7 +211,6 @@ public class ElytraRace extends StatelessGame {
BatchUtil.loadAndApplyBatch(batch, this, () -> { BatchUtil.loadAndApplyBatch(batch, this, () -> {
}); });
return null;
} }
private void boost(Player player) { private void boost(Player player) {
@@ -233,7 +232,7 @@ public class ElytraRace extends StatelessGame {
p.setFlying(true); p.setFlying(true);
p.setFlyingSpeed(0); p.setFlyingSpeed(0);
new Countdown(TitleMessage.class) new Countdown()
.countdown( .countdown(
Audience.audience(p), Audience.audience(p),
3, 3,

View File

@@ -30,7 +30,7 @@ public class ElytraRaceFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() 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 @Override

View File

@@ -28,8 +28,8 @@ public class Fastbridge extends StatelessGame {
Pos newPos = playerMoveEvent.getNewPosition(); Pos newPos = playerMoveEvent.getNewPosition();
if(this.getScore().hasResult(player)) return; if(this.getScore().hasResult(player)) return;
if(newPos.y() < 0) { if(newPos.y() < 0) {
player.teleport(getSpawn()); player.teleport(this.getSpawn());
if(!isBeforeBeginning) this.resetPlayer(player); if(!this.isBeforeBeginning) this.resetPlayer(player);
} }
if(newPos.x() > 53) { if(newPos.x() > 53) {
this.getScore().insertResult(player); this.getScore().insertResult(player);
@@ -39,19 +39,19 @@ public class Fastbridge extends StatelessGame {
@Override @Override
protected void onStart() { protected void onStart() {
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
resetPlayer(player); this.resetPlayer(player);
}); });
} }
@Override @Override
protected void onBlockPlace(@NotNull PlayerBlockPlaceEvent playerBlockPlaceEvent) { protected void onBlockPlace(@NotNull PlayerBlockPlaceEvent playerBlockPlaceEvent) {
if(isBeforeBeginning) playerBlockPlaceEvent.setCancelled(true); if(this.isBeforeBeginning) playerBlockPlaceEvent.setCancelled(true);
} }
private void resetPlayer(Player player) { private void resetPlayer(Player player) {
if(isBeforeBeginning) return; if(this.isBeforeBeginning) return;
PlayerInventory inventory = player.getInventory(); PlayerInventory inventory = player.getInventory();
inventory.clear(); inventory.clear();
inventory.addItemStack(ItemStack.of(Material.WHITE_WOOL, 64)); inventory.addItemStack(ItemStack.of(Material.WHITE_WOOL, 64));
@@ -59,6 +59,6 @@ public class Fastbridge extends StatelessGame {
@Override @Override
public synchronized Pos getSpawn() { 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 class FastbridgeChunkgenerator extends BaseGenerator {
public FastbridgeChunkgenerator() { public FastbridgeChunkgenerator() {
this.addMixIn(unit -> { this.addMixIn(unit -> {
if (unit.absoluteStart().chunkZ() % 2 == 0) { if(unit.absoluteStart().chunkZ() % 2 == 0) {
unit.modifier().fill(Block.BARRIER); unit.modifier().fill(Block.BARRIER);
return; return;
} }
if (unit.absoluteStart().chunkX() != 1 && unit.absoluteStart().chunkX() != 3) return; if(unit.absoluteStart().chunkX() != 1 && unit.absoluteStart().chunkX() != 3) return;
for (int x = 5; x <= 10; x++){ for(int x = 5; x <= 10; x++) {
for (int z = 5; z <= 10; z++){ for(int z = 5; z <= 10; z++) {
unit.modifier().setRelative(x, 64, z, unit.absoluteStart().chunkX() == 3 ? Block.GOLD_BLOCK : Block.GRASS_BLOCK); 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 -> { this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if(this.isBeforeBeginning){ if(this.isBeforeBeginning) {
prepareAttackEvent.setCancelled(true); prepareAttackEvent.setCancelled(true);
} }
}); });
@@ -53,10 +53,10 @@ class HighGround extends StatelessGame {
entityKnockbackEvent -> entityKnockbackEvent.setStrength(1.1f) entityKnockbackEvent -> entityKnockbackEvent.setStrength(1.1f)
); );
this.eventNode().addListener(InstanceTickEvent.class, instanceTickEvent -> { this.eventNode().addListener(InstanceTickEvent.class, instanceTickEvent -> {
if (this.isBeforeBeginning || !this.isRunning) return; if(this.isBeforeBeginning || !this.isRunning) return;
this.getPlayers().forEach(player -> { 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); this.scoreMap.put(player, this.scoreMap.get(player) + 1);
player.setLevel(this.scoreMap.get(player) / 20); player.setLevel(this.scoreMap.get(player) / 20);
player.setExp((this.scoreMap.get(player) % 20) / 20.0f); player.setExp((this.scoreMap.get(player) % 20) / 20.0f);
@@ -67,20 +67,20 @@ class HighGround extends StatelessGame {
@Override @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { 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; int radius = (Math.abs(y) * 5) + this.radius;
for (int x = -radius; x <= radius; x++) { for(int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) { for(int z = -radius; z <= radius; z++) {
double distance = new Pos(x, 0, z).distance(0, 0, 0); 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); this.setBlock(x, y, z, y == 0 ? Block.DIAMOND_BLOCK : Block.GRASS_BLOCK);
Pos featurePosition = new Pos(x, y + 1, z); Pos featurePosition = new Pos(x, y + 1, z);
if(y >= 0 || this.getBlock(featurePosition).isSolid()) continue; 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); this.setBlock(featurePosition, Block.SHORT_GRASS);
} }
if (this.rnd.nextDouble() < 0.01){ if(this.rnd.nextDouble() < 0.01) {
this.setBlock(featurePosition, BlockPallet.FLOWER.rnd()); this.setBlock(featurePosition, BlockPallet.FLOWER.rnd());
} }
} }
@@ -92,7 +92,7 @@ class HighGround extends StatelessGame {
@Override @Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) { protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
Player player = playerMoveEvent.getPlayer(); Player player = playerMoveEvent.getPlayer();
if(playerMoveEvent.getNewPosition().y() < -10){ if(playerMoveEvent.getNewPosition().y() < -10) {
player.teleport(this.getSpawn()); player.teleport(this.getSpawn());
} }
} }

View File

@@ -32,8 +32,8 @@ public class HighGroundFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 3, 5, 7, 10)) .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("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
} }
@Override @Override
@@ -44,6 +44,6 @@ public class HighGroundFactory implements GameFactory {
@Override @Override
public RestrictionHandler globalRestrictions() { public RestrictionHandler globalRestrictions() {
return new RestrictionHandler() 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) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = -radius*2; x <= radius*2; x++) { for(int x = -this.radius * 2; x <= this.radius * 2; x++) {
for(int z = -radius*2; z <= radius*2; z++) { for(int z = -this.radius * 2; z <= this.radius * 2; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) { if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > this.radius) {
batch.setBlock(x, height, z, BlockPallet.STONE.rnd()); batch.setBlock(x, this.height, z, BlockPallet.STONE.rnd());
} else { } else {
batch.setBlock(x, 0, z, BlockPallet.GROUND.rnd()); batch.setBlock(x, 0, z, BlockPallet.GROUND.rnd());
batch.setBlock(x, 1, z, Block.WATER); batch.setBlock(x, 1, z, Block.WATER);
@@ -51,7 +51,7 @@ public class JumpDive extends StatelessGame {
@Override @Override
protected void onStart() { protected void onStart() {
setTimeLimit(timeLimit); this.setTimeLimit(this.timeLimit);
} }
@Override @Override
@@ -59,22 +59,22 @@ public class JumpDive extends StatelessGame {
Player p = playerMoveEvent.getPlayer(); Player p = playerMoveEvent.getPlayer();
if( if(
p.isOnGround() && playerMoveEvent.getNewPosition().y() < height p.isOnGround() && playerMoveEvent.getNewPosition().y() < this.height
|| playerMoveEvent.getNewPosition().y() < 0 || playerMoveEvent.getNewPosition().y() < 0
|| isBeforeBeginning && playerMoveEvent.getNewPosition().y() < height || this.isBeforeBeginning && playerMoveEvent.getNewPosition().y() < this.height
) { ) {
p.teleport(getSpawn()); p.teleport(this.getSpawn());
playerMoveEvent.setCancelled(true); playerMoveEvent.setCancelled(true);
} }
if( if(
playerMoveEvent.getNewPosition().y() <= 1 playerMoveEvent.getNewPosition().y() <= 1
&& playerMoveEvent.getNewPosition().distance(0, 1, 0) < radius + 0.5 && playerMoveEvent.getNewPosition().distance(0, 1, 0) < this.radius + 0.5
&& !(!isBeforeBeginning && !isRunning) && !(!this.isBeforeBeginning && !this.isRunning)
) { ) {
setBlock(playerMoveEvent.getNewPosition().withY(1), Block.REDSTONE_BLOCK); this.setBlock(playerMoveEvent.getNewPosition().withY(1), Block.REDSTONE_BLOCK);
scores.merge(p, 1, Integer::sum); this.scores.merge(p, 1, Integer::sum);
p.teleport(getSpawn()); p.teleport(this.getSpawn());
playerMoveEvent.setCancelled(true); playerMoveEvent.setCancelled(true);
p.playSound(Sound.sound(SoundEvent.ENTITY_EXPERIENCE_ORB_PICKUP, Sound.Source.PLAYER, 2f, 2f)); p.playSound(Sound.sound(SoundEvent.ENTITY_EXPERIENCE_ORB_PICKUP, Sound.Source.PLAYER, 2f, 2f));
} }
@@ -82,18 +82,18 @@ public class JumpDive extends StatelessGame {
@Override @Override
protected void onStop() { 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 @Override
public Pos getSpawn() { 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 x = spawnRadius * Math.cos(theta);
double z = spawnRadius * Math.sin(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; 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.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore; import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil; import eu.mhsl.minenet.minigames.util.BatchUtil;
import eu.mhsl.minenet.minigames.util.CommonProperties; import eu.mhsl.minenet.minigames.util.CommonProperties;
import eu.mhsl.minenet.minigames.util.Intersect; 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.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator; import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator;
import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.Sound;
@@ -18,7 +18,7 @@ import net.minestom.server.instance.block.Block;
import net.minestom.server.sound.SoundEvent; import net.minestom.server.sound.SoundEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.Random;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
class Minerun extends StatelessGame { class Minerun extends StatelessGame {
@@ -33,7 +33,7 @@ class Minerun extends StatelessGame {
public Minerun(int width, int length, int minePercentage) { public Minerun(int width, int length, int minePercentage) {
super(Dimension.THE_END.key, "Minerun", new FirstWinsScore()); 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.width = width;
this.length = length; this.length = length;
@@ -42,24 +42,24 @@ class Minerun extends StatelessGame {
@Override @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
int spawnToFinishLine = preRun + length + afterMines; int spawnToFinishLine = this.preRun + this.length + this.afterMines;
Random random = new Random(); Random random = new Random();
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) { for(int x = 0; x <= this.width; x++) {
for(int z = preRun; z <= length + preRun; z++) { 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()); 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, spawnToFinishLine, Block.GOLD_BLOCK);
batch.setBlock(x, 49, preRun, Block.GOLD_BLOCK); batch.setBlock(x, 49, this.preRun, Block.GOLD_BLOCK);
batch.setBlock(x, 50, preRun, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest)); batch.setBlock(x, 50, this.preRun, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
} }
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null)); BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
} }
@@ -67,11 +67,11 @@ class Minerun extends StatelessGame {
@Override @Override
protected void onStart() { protected void onStart() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) { for(int x = 0; x <= this.width; x++) {
batch.setBlock(x, 50, preRun, Block.AIR); 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 @Override
@@ -80,23 +80,23 @@ class Minerun extends StatelessGame {
Player p = playerMoveEvent.getPlayer(); Player p = playerMoveEvent.getPlayer();
Pos middle = playerMoveEvent.getNewPosition(); 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); playerMoveEvent.setCancelled(true);
} }
if(Intersect.withPressurePlate(this, BlockPallet.PRESSURE_PLATES, middle)) { //Player died if(Intersect.withPressurePlate(this, BlockPallet.PRESSURE_PLATES, middle)) { //Player died
p.playSound(Sound.sound(SoundEvent.ENTITY_GENERIC_EXPLODE, Sound.Source.PLAYER, 1f, 1f)); 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 if(middle.z() > this.preRun + this.length + this.afterMines) { // Player finished
getScore().insertResult(p); this.getScore().insertResult(p);
p.setGameMode(GameMode.SPECTATOR); p.setGameMode(GameMode.SPECTATOR);
} }
} }
@Override @Override
public Pos getSpawn() { 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 @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("optionCommon#width"), 10, 30, 50, 100)) .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("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("percentage", Material.LIGHT_WEIGHTED_PRESSURE_PLATE, TranslatedComponent.byId("game_Minerun#optionPercentageMines"), 30, 40, 50, 60, 70));
} }
@Override @Override

View File

@@ -10,7 +10,10 @@ import io.github.togar2.pvp.feature.CombatFeatures;
import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.Sound;
import net.minestom.server.MinecraftServer; import net.minestom.server.MinecraftServer;
import net.minestom.server.coordinate.Pos; 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.entity.metadata.other.FallingBlockMeta;
import net.minestom.server.event.entity.EntityTickEvent; import net.minestom.server.event.entity.EntityTickEvent;
import net.minestom.server.event.player.PlayerBlockPlaceEvent; import net.minestom.server.event.player.PlayerBlockPlaceEvent;
@@ -29,25 +32,17 @@ import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
public class SpaceSnake extends StatelessGame { 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 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 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) { public SpaceSnake(int mapSize, int powerUpCount) {
super(Dimension.THE_END.key, "spaceSnake", new PointsWinScore()); super(Dimension.THE_END.key, "spaceSnake", new PointsWinScore());
this.mapSize = mapSize; this.mapSize = mapSize;
this.setWorldBorder(new WorldBorder(this.mapSize, 0, 0, 0, 0)); 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(); this.spawnPowerUp();
} }
@@ -61,7 +56,7 @@ public class SpaceSnake extends StatelessGame {
); );
this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> { this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if (this.isBeforeBeginning) prepareAttackEvent.setCancelled(true); if(this.isBeforeBeginning) prepareAttackEvent.setCancelled(true);
}); });
this.eventNode().addListener(FinalAttackEvent.class, finalAttackEvent -> { this.eventNode().addListener(FinalAttackEvent.class, finalAttackEvent -> {
@@ -179,4 +174,12 @@ public class SpaceSnake extends StatelessGame {
player.setLevel(player.getLevel() + 1); player.setLevel(player.getLevel() + 1);
player.playSound(Sound.sound(SoundEvent.ENTITY_EXPERIENCE_ORB_PICKUP, Sound.Source.PLAYER, 1f, 1f)); 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.event.player.PlayerStartDiggingEvent;
import net.minestom.server.instance.batch.AbsoluteBlockBatch; import net.minestom.server.instance.batch.AbsoluteBlockBatch;
import net.minestom.server.instance.block.Block; 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 org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public class Spleef extends StatelessGame { public class Spleef extends StatelessGame {
final int heightPerLevel = 20;
final int totalElevation = 50;
int radius; int radius;
int stackCount; int stackCount;
final int heightPerLevel = 20;
final int totalElevation = 50;
public Spleef(int radius, int stackCount) { public Spleef(int radius, int stackCount) {
super(Dimension.OVERWORLD.key, "Spleef", new LastWinsScore()); super(Dimension.OVERWORLD.key, "Spleef", new LastWinsScore());
getScore().setIgnoreLastPlayers(1); this.getScore().setIgnoreLastPlayers(1);
this.radius = radius; this.radius = radius;
this.stackCount = stackCount; 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 @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch circle = new AbsoluteBlockBatch(); AbsoluteBlockBatch circle = new AbsoluteBlockBatch();
for (int level = 0; level < stackCount; level++) { for(int level = 0; level < this.stackCount; level++) {
for(int x = -radius; x <= radius; x++) { for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -radius; z <= radius; z++) { for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue; 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 @Override
protected void onStart() { protected void onStart() {
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
player.getInventory().addItemStack( player.getInventory().addItemStack(
ItemStack ItemStack
.builder(Material.DIAMOND_SHOVEL) .builder(Material.DIAMOND_SHOVEL)
.customName(TranslatedComponent.byId("game_Spleef#shovelName").getAssembled(player)) .customName(TranslatedComponent.byId("game_Spleef#shovelName").getAssembled(player))
.build() .build()
); );
player.setHeldItemSlot((byte) 0); player.setHeldItemSlot((byte) 0);
}); });
@@ -71,29 +71,29 @@ public class Spleef extends StatelessGame {
@Override @Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) { protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) { if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR); playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
playerMoveEvent.getPlayer().getInventory().clear(); playerMoveEvent.getPlayer().getInventory().clear();
getScore().insertResult(playerMoveEvent.getPlayer()); this.getScore().insertResult(playerMoveEvent.getPlayer());
} }
} }
@Override @Override
protected void onBlockBreak(@NotNull PlayerBlockBreakEvent event) { protected void onBlockBreak(@NotNull PlayerBlockBreakEvent event) {
if(!isRunning) { if(!this.isRunning) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
setBlock(event.getBlockPosition(), Block.AIR); this.setBlock(event.getBlockPosition(), Block.AIR);
} }
private void destroyBlock(PlayerStartDiggingEvent event) { private void destroyBlock(PlayerStartDiggingEvent event) {
if(!isRunning) return; if(!this.isRunning) return;
setBlock(event.getBlockPosition(), Block.AIR); this.setBlock(event.getBlockPosition(), Block.AIR);
} }
@Override @Override
public Pos getSpawn() { 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 @Override
public RestrictionHandler globalRestrictions() { public RestrictionHandler globalRestrictions() {
return new RestrictionHandler() return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2)); .addRestriction(new MinimalPlayeramountGameRestriction(2));
} }
@Override @Override
@@ -33,8 +33,8 @@ public class SpleefFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30)) .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("stackCount", Material.SCAFFOLDING, TranslatedComponent.byId("game_Spleef#stackCount"), 1, 2, 3, 4, 5));
} }
@Override @Override

View File

@@ -28,14 +28,14 @@ public class StickFightFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() 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 @Override
public RestrictionHandler globalRestrictions() { public RestrictionHandler globalRestrictions() {
return new RestrictionHandler() return new RestrictionHandler()
.addRestriction(new MinimalPlayeramountGameRestriction(2)) .addRestriction(new MinimalPlayeramountGameRestriction(2))
.addRestriction(new MaximalPlayeramountGameRestriction(4)); .addRestriction(new MaximalPlayeramountGameRestriction(4));
} }
@Override @Override

View File

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

View File

@@ -42,16 +42,16 @@ public class Sumo extends StatelessGame {
this.timer = seconds; this.timer = seconds;
this.eventNode().addChild( this.eventNode().addChild(
CombatFeatures.empty() CombatFeatures.empty()
.add(CombatFeatures.VANILLA_ATTACK) .add(CombatFeatures.VANILLA_ATTACK)
.add(CombatFeatures.VANILLA_DAMAGE) .add(CombatFeatures.VANILLA_DAMAGE)
.add(CombatFeatures.VANILLA_KNOCKBACK) .add(CombatFeatures.VANILLA_KNOCKBACK)
.build() .build()
.createNode() .createNode()
); );
this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> { this.eventNode().addListener(PrepareAttackEvent.class, prepareAttackEvent -> {
if (this.isBeforeBeginning) if(this.isBeforeBeginning)
prepareAttackEvent.setCancelled(true); prepareAttackEvent.setCancelled(true);
}); });
@@ -74,7 +74,7 @@ public class Sumo extends StatelessGame {
this.timer--; this.timer--;
double percent = (double) this.timer / this.seconds; double percent = (double) this.timer / this.seconds;
int radius = (int) (this.originalRadius * percent); int radius = (int) (this.originalRadius * percent);
if (this.radius >= 5) { if(this.radius >= 5) {
this.radius = radius; this.radius = radius;
this.generatePlatform(); this.generatePlatform();
return TaskSchedule.seconds(1); return TaskSchedule.seconds(1);
@@ -115,7 +115,7 @@ public class Sumo extends StatelessGame {
player.teleport(this.getSpawn()); player.teleport(this.getSpawn());
this.healthMap.put(player, this.healthMap.get(player) - 1); this.healthMap.put(player, this.healthMap.get(player) - 1);
player.setLevel(this.healthMap.get(player)); player.setLevel(this.healthMap.get(player));
if (this.healthMap.get(player) == 0) { if(this.healthMap.get(player) == 0) {
this.getScore().insertResult(player); this.getScore().insertResult(player);
player.setGameMode(GameMode.SPECTATOR); player.setGameMode(GameMode.SPECTATOR);
} }
@@ -124,6 +124,6 @@ public class Sumo extends StatelessGame {
@Override @Override
public Pos getSpawn() { 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 @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("radius", Material.HEART_OF_THE_SEA, TranslatedComponent.byId("optionCommon#radius"), 10, 20, 30)) .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("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("seconds", Material.CLOCK, TranslatedComponent.byId("optionCommon#seconds"), 30, 60, 90, 120));
} }
@Override @Override
@@ -44,6 +44,6 @@ public class SumoFactory implements GameFactory {
@Override @Override
public RestrictionHandler globalRestrictions() { public RestrictionHandler globalRestrictions() {
return new RestrictionHandler() 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; 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.StatelessGame;
import eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris.game.TetrisGame; 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.instance.game.stateless.types.tetris.game.Tetromino;
import eu.mhsl.minenet.minigames.score.PointsWinScore; import eu.mhsl.minenet.minigames.score.PointsWinScore;
import net.kyori.adventure.text.Component; 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.Entity;
import net.minestom.server.entity.GameMode; import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player; 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.ItemStack;
import net.minestom.server.item.Material; import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
class Tetris extends StatelessGame { class Tetris extends StatelessGame {
private final Map<Player, TetrisGame> tetrisGames = new WeakHashMap<>(); private final Map<Player, TetrisGame> tetrisGames = new WeakHashMap<>();
private final int nextTetrominoesCount; private final int nextTetrominoesCount;
private final boolean isFast; private final boolean isFast;
private final boolean hasCombat; private final boolean hasCombat;
private boolean setTimeLimit = false;
private final long randomSeed; private final long randomSeed;
private boolean setTimeLimit = false;
public Tetris(int nextTetrominoesCount, boolean isFast, boolean hasCombat) { public Tetris(int nextTetrominoesCount, boolean isFast, boolean hasCombat) {
super(Dimension.THE_END.key, "Tetris", new PointsWinScore()); super(Dimension.THE_END.key, "Tetris", new PointsWinScore());
@@ -136,7 +141,7 @@ class Tetris extends StatelessGame {
if(this.tetrisGames.get(p) == null) { if(this.tetrisGames.get(p) == null) {
this.tetrisGames.put(p, new TetrisGame( this.tetrisGames.put(p, new TetrisGame(
this, 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, Tetromino.Shape.J,
this.nextTetrominoesCount, this.nextTetrominoesCount,
this.isFast, this.isFast,

View File

@@ -1,9 +1,9 @@
package eu.mhsl.minenet.minigames.instance.game.stateless.types.tetris; 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.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.GameFactory;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.Option; 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.BoolOption;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption; import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room; import eu.mhsl.minenet.minigames.instance.room.Room;

View File

@@ -10,10 +10,10 @@ import org.apache.commons.lang3.ArrayUtils;
import java.util.Random; import java.util.Random;
public class Playfield { public class Playfield {
private final Pos lowerLeftCorner;
private final StatelessGame instance;
private final static int height = 22; private final static int height = 22;
private final static Block scoreBlock = Block.STONE; private final static Block scoreBlock = Block.STONE;
private final Pos lowerLeftCorner;
private final StatelessGame instance;
private final int nextTetrominoesCount; private final int nextTetrominoesCount;
private final Random random; private final Random random;
@@ -41,19 +41,19 @@ public class Playfield {
} }
public Pos getScorePosition() { public Pos getScorePosition() {
return this.lowerLeftCorner.add(-5, height+3, 0); return this.lowerLeftCorner.add(-5, height + 3, 0);
} }
public void generate() { public void generate() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
// actual playfield: // actual playfield:
for(int x=0; x<12; x++) { for(int x = 0; x < 12; x++) {
for(int y = 0; y< height; y++) { for(int y = 0; y < height; y++) {
batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GLASS); batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GLASS);
batch.setBlock(this.lowerLeftCorner.add(x, y, -1), Block.BLACK_CONCRETE); 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, 1), Block.GRAY_CONCRETE);
batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GRAY_CONCRETE); batch.setBlock(this.lowerLeftCorner.add(x, y, 0), Block.GRAY_CONCRETE);
} }
@@ -63,14 +63,14 @@ public class Playfield {
// hold position: // hold position:
for(int x = 0; x < 4; x++) { for(int x = 0; x < 4; x++) {
for(int y = 0; y < 4; y++) { 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: // next positions:
for(int x = 0; x < 4; x++) { for(int x = 0; x < 4; x++) {
for(int y = -4*this.nextTetrominoesCount+4; y < 4; y++) { for(int y = -4 * this.nextTetrominoesCount + 4; y < 4; y++) {
batch.setBlock(this.getNextPosition().add(x-1, y-1, -1), Block.QUARTZ_BLOCK); 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(1, 1, 1), Block.STONE);
batch.setBlock(this.getPlayerSpawnPosition().sub(0, 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() { public int removeFullLines() {
int removedLinesCounter = 0; int removedLinesCounter = 0;
for(int y = 1; y< height; y++) { for(int y = 1; y < height; y++) {
boolean isFullLine = true; 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(this.instance.getBlock(this.lowerLeftCorner.add(x, y, 1)) == Block.AIR) isFullLine = false;
} }
if(isFullLine) { if(isFullLine) {
@@ -101,9 +102,9 @@ public class Playfield {
public void addLines(int lines) { public void addLines(int lines) {
int xPosMissing = this.random.nextInt(1, 10); int xPosMissing = this.random.nextInt(1, 10);
for (int i = 0; i < lines; i++) { for(int i = 0; i < lines; i++) {
this.moveAllLinesUp(); this.moveAllLinesUp();
for (int x = 1; x < 11; x++) { for(int x = 1; x < 11; x++) {
if(x != xPosMissing) { if(x != xPosMissing) {
this.instance.setBlock(this.lowerLeftCorner.add(x, 1, 1), Block.LIGHT_GRAY_CONCRETE); this.instance.setBlock(this.lowerLeftCorner.add(x, 1, 1), Block.LIGHT_GRAY_CONCRETE);
} else { } else {
@@ -114,7 +115,7 @@ public class Playfield {
} }
public void updateAttackingLines(int attackingLines) { public void updateAttackingLines(int attackingLines) {
for (int y = 0; y < height + 5; y++) { for(int y = 0; y < height + 5; y++) {
if(attackingLines > 0) { if(attackingLines > 0) {
this.instance.setBlock(this.lowerLeftCorner.add(12, y, 1), Block.REDSTONE_BLOCK); this.instance.setBlock(this.lowerLeftCorner.add(12, y, 1), Block.REDSTONE_BLOCK);
attackingLines -= 1; attackingLines -= 1;
@@ -132,48 +133,49 @@ public class Playfield {
for(int i = 6; i > 0; i--) { for(int i = 6; i > 0; i--) {
char digit; char digit;
if(i <= characters.length) { if(i <= characters.length) {
digit = characters[i-1]; digit = characters[i - 1];
} else { } else {
digit = '0'; digit = '0';
} }
this.displayDigit(digit, 6-i); this.displayDigit(digit, 6 - i);
} }
} }
private void displayDigit(char digit, int positionFromLeft) { private void displayDigit(char digit, int positionFromLeft) {
int[][] digitArray; int[][] digitArray;
switch (digit) { switch(digit) {
case '1' -> digitArray = new int[][]{{0,0,1},{0,1,1},{0,0,1},{0,0,1},{0,0,1}}; 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 '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 '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 '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 '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 '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 '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 '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}}; 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}}; 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 x = 0; x < 3; x++) {
for (int y = 0; y < 5; y++) { 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); if(digitArray[4 - y][x] == 1)
this.instance.setBlock(this.getScorePosition().add(positionFromLeft * 4 + x, y, 0), scoreBlock);
} }
} }
} }
private void removeDigits() { private void removeDigits() {
for (int x = 0; x < 4 * 6; x++) { for(int x = 0; x < 4 * 6; x++) {
for (int y = 0; y < 5; y++) { for(int y = 0; y < 5; y++) {
this.instance.setBlock(this.getScorePosition().add(x, y, 0), Block.AIR); this.instance.setBlock(this.getScorePosition().add(x, y, 0), Block.AIR);
} }
} }
} }
private void moveAllLinesUp() { private void moveAllLinesUp() {
for (int y = height + 3; y > 1; y--) { for(int y = height + 3; y > 1; y--) {
for (int x = 1; x < 11; x++) { for(int x = 1; x < 11; x++) {
Block blockBeneath = this.instance.getBlock(this.lowerLeftCorner.add(x, y - 1, 1)); Block blockBeneath = this.instance.getBlock(this.lowerLeftCorner.add(x, y - 1, 1));
this.instance.setBlock(this.lowerLeftCorner.add(x, y, 1), blockBeneath); this.instance.setBlock(this.lowerLeftCorner.add(x, y, 1), blockBeneath);
} }
@@ -181,9 +183,9 @@ public class Playfield {
} }
private void removeFullLine(int positionY) { private void removeFullLine(int positionY) {
for(int y = positionY; y< height; y++) { for(int y = positionY; y < height; y++) {
for(int x=1; x<11; x++) { for(int x = 1; x < 11; x++) {
Block blockAbove = this.instance.getBlock(this.lowerLeftCorner.add(x, y+1, 1)); Block blockAbove = this.instance.getBlock(this.lowerLeftCorner.add(x, y + 1, 1));
this.instance.setBlock(this.lowerLeftCorner.add(x, y, 1), blockAbove); 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 StatelessGame instance;
private final Playfield playfield; private final Playfield playfield;
private final boolean isFast; 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 level = 1;
private int lines = 0; private int lines = 0;
private int score = 0; private int score = 0;
private int combo = 0; private int combo = 0;
private int attackingLines = 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 Tetromino holdTetromino;
private final List<Tetromino> tetrominoBag = new ArrayList<>();
private boolean holdPossible = true; 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) { public TetrisGame(StatelessGame instance, Pos lowerLeftCorner, Tetromino.Shape startTetrominoShape, int nextTetrominoesCount, boolean isfast, boolean hasCombat, long randomSeed) {
this.isFast = isfast; this.isFast = isfast;
@@ -58,7 +48,7 @@ public class TetrisGame {
this.buildSidebar(); this.buildSidebar();
this.currentTetromino = new Tetromino(this.instance, startTetrominoShape); this.currentTetromino = new Tetromino(this.instance, startTetrominoShape);
for (int i = 0; i < nextTetrominoesCount; i++) { for(int i = 0; i < nextTetrominoesCount; i++) {
this.updateNextTetrominoes(); this.updateNextTetrominoes();
} }
} }
@@ -67,15 +57,15 @@ public class TetrisGame {
final int standardButtonDelay = 100; final int standardButtonDelay = 100;
final int buttonDebounce = 70; 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()); this.lastPresses.put(button, System.currentTimeMillis());
if(button == Button.W) 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(button == Button.S) this.lastPresses.put(button, System.currentTimeMillis() - buttonDebounce);
if(this.lost || this.paused) return; if(this.lost || this.paused) return;
switch (button) { switch(button) {
case A -> this.currentTetromino.moveLeft(); case A -> this.currentTetromino.moveLeft();
case S -> this.moveDown(); case S -> this.moveDown();
case D -> this.currentTetromino.moveRight(); case D -> this.currentTetromino.moveRight();
@@ -98,7 +88,7 @@ public class TetrisGame {
int standardTickDelay = 40; int standardTickDelay = 40;
if(this.isFast) standardTickDelay = 20; 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; if(this.paused) return nextTick;
this.tick(); this.tick();
return nextTick; return nextTick;
@@ -107,7 +97,7 @@ public class TetrisGame {
this.updateInfo(); this.updateInfo();
this.nextTetrominoes.forEach(tetromino -> { this.nextTetrominoes.forEach(tetromino -> {
double xChange = -tetromino.getXChange(); 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(); tetromino.drawAsEntities();
}); });
} }
@@ -149,7 +139,6 @@ public class TetrisGame {
this.lost = true; this.lost = true;
} }
private boolean moveDown() { private boolean moveDown() {
if(!this.currentTetromino.moveDown()) { if(!this.currentTetromino.moveDown()) {
this.setActiveTetrominoDown(); this.setActiveTetrominoDown();
@@ -203,7 +192,6 @@ public class TetrisGame {
return true; return true;
} }
private void updateNextTetrominoes() { private void updateNextTetrominoes() {
if(this.tetrominoBag.isEmpty()) { if(this.tetrominoBag.isEmpty()) {
for(Tetromino.Shape shape : Tetromino.Shape.values()) { for(Tetromino.Shape shape : Tetromino.Shape.values()) {
@@ -217,7 +205,7 @@ public class TetrisGame {
this.nextTetrominoes.add(newTetromino); this.nextTetrominoes.add(newTetromino);
this.nextTetrominoes.forEach(tetromino -> { this.nextTetrominoes.forEach(tetromino -> {
double xChange = -tetromino.getXChange(); 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(); tetromino.drawAsEntities();
}); });
} }
@@ -242,7 +230,7 @@ public class TetrisGame {
private void updateInfo() { private void updateInfo() {
this.playfield.updateScore(this.score); 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("1", this.lines);
this.sidebar.updateLineScore("2", this.level); this.sidebar.updateLineScore("2", this.level);
} }
@@ -256,7 +244,7 @@ public class TetrisGame {
int removedLines = this.playfield.removeFullLines(); int removedLines = this.playfield.removeFullLines();
int combatLines = 0; int combatLines = 0;
this.combo += 1; this.combo += 1;
switch (removedLines) { switch(removedLines) {
case 0 -> this.combo = 0; case 0 -> this.combo = 0;
case 1 -> { case 1 -> {
this.lines += 1; this.lines += 1;
@@ -281,7 +269,7 @@ public class TetrisGame {
this.score += 50 * this.combo * this.level; this.score += 50 * this.combo * this.level;
if(this.combo >= 2) { 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) { if(this.hasCombat && this.attackingLines > 0) {
@@ -315,4 +303,14 @@ public class TetrisGame {
this.loose(); 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; import java.util.UUID;
public class Tetromino { 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 Shape shape;
private final StatelessGame instance; private final StatelessGame instance;
private final UUID uuid;
private Pos position; private Pos position;
private int[][] shapeArray; 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) { public Tetromino(StatelessGame instance, Shape shape) {
this.instance = instance; this.instance = instance;
this.shape = shape; this.shape = shape;
this.uuid = UUID.randomUUID(); 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 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 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 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 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 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 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 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) { public void draw(boolean withGhost) {
if(withGhost) { if(withGhost) {
Pos ghostPos = this.position; 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); ghostPos = ghostPos.sub(0, 1, 0);
} }
Pos positionChange = this.position.sub(ghostPos); Pos positionChange = this.position.sub(ghostPos);
@@ -117,7 +107,7 @@ public class Tetromino {
public Block getColoredBlock() { public Block getColoredBlock() {
Block returnBlock; Block returnBlock;
switch (this.shape) { switch(this.shape) {
case I -> returnBlock = Block.LIGHT_BLUE_CONCRETE; case I -> returnBlock = Block.LIGHT_BLUE_CONCRETE;
case J -> returnBlock = Block.BLUE_CONCRETE; case J -> returnBlock = Block.BLUE_CONCRETE;
case L -> returnBlock = Block.ORANGE_CONCRETE; case L -> returnBlock = Block.ORANGE_CONCRETE;
@@ -141,7 +131,7 @@ public class Tetromino {
} }
public double getXChange() { public double getXChange() {
switch (this.shape) { switch(this.shape) {
case O, I -> { case O, I -> {
return 0; return 0;
} }
@@ -151,14 +141,13 @@ public class Tetromino {
} }
} }
public Shape getShape() { public Shape getShape() {
return this.shape; return this.shape;
} }
private Block getGhostBlock() { private Block getGhostBlock() {
Block returnBlock; Block returnBlock;
switch (this.shape) { switch(this.shape) {
case I -> returnBlock = Block.LIGHT_BLUE_STAINED_GLASS; case I -> returnBlock = Block.LIGHT_BLUE_STAINED_GLASS;
case J -> returnBlock = Block.BLUE_STAINED_GLASS; case J -> returnBlock = Block.BLUE_STAINED_GLASS;
case L -> returnBlock = Block.ORANGE_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[][] startArray = Arrays.stream(this.shapeArray).map(int[]::clone).toArray(int[][]::new);
int[][] returnArray = new int[arrayLength][arrayLength]; int[][] returnArray = new int[arrayLength][arrayLength];
for(int k=0; k<iterations; k++) { for(int k = 0; k < iterations; k++) {
for(int i=0; i<arrayLength; i++) { for(int i = 0; i < arrayLength; i++) {
for(int j=0; j<arrayLength; j++) { for(int j = 0; j < arrayLength; j++) {
returnArray[i][arrayLength-1-j] = startArray[j][i]; returnArray[i][arrayLength - 1 - j] = startArray[j][i];
} }
} }
startArray = Arrays.stream(returnArray).map(int[]::clone).toArray(int[][]::new); startArray = Arrays.stream(returnArray).map(int[]::clone).toArray(int[][]::new);
@@ -206,13 +195,13 @@ public class Tetromino {
int arrayLength = shapeArray.length; int arrayLength = shapeArray.length;
for(int x=0; x<arrayLength; x++) { for(int x = 0; x < arrayLength; x++) {
for(int y=0; y<arrayLength; y++) { for(int y = 0; y < arrayLength; y++) {
if(shapeArray[arrayLength-1-y][x] == 1) { if(shapeArray[arrayLength - 1 - y][x] == 1) {
switch (this.shape) { switch(this.shape) {
case I -> returnList.add(position.add(x-1, y-2, 0)); case I -> returnList.add(position.add(x - 1, y - 2, 0));
case O -> returnList.add(position.add(x, y, 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; 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 radius;
final int stackCount; final int stackCount;
public TntRun(int radius, int stackCount) { public TntRun(int radius, int stackCount) {
super(Dimension.OVERWORLD.key, "tntRun", new LastWinsScore()); super(Dimension.OVERWORLD.key, "tntRun", new LastWinsScore());
this.radius = radius; this.radius = radius;
this.stackCount = stackCount; this.stackCount = stackCount;
setGenerator(new CircularPlateTerrainGenerator(radius)); this.setGenerator(new CircularPlateTerrainGenerator(radius));
} }
@Override @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for (int level = 0; level < stackCount; level++) { for(int level = 0; level < this.stackCount; level++) {
for(int x = -radius; x <= radius; x++) { for(int x = -this.radius; x <= this.radius; x++) {
for(int z = -radius; z <= radius; z++) { for(int z = -this.radius; z <= this.radius; z++) {
if(new Pos(x, 0, z).distance(new Pos(0, 0, 0)) > radius) continue; 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) { protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(playerMoveEvent.getNewPosition().y() < totalElevation) { if(playerMoveEvent.getNewPosition().y() < this.totalElevation) {
if(isBeforeBeginning) { if(this.isBeforeBeginning) {
playerMoveEvent.getPlayer().teleport(getSpawn()); playerMoveEvent.getPlayer().teleport(this.getSpawn());
return; return;
} }
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR); 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(() -> { MinecraftServer.getSchedulerManager().scheduleTask(() -> {
float radius = 0.5F; float radius = 0.5F;
for (float x = -radius; x <= radius; x++) { for(float x = -radius; x <= radius; x++) {
for (float z = -radius; z <= radius; z++) { for(float z = -radius; z <= radius; z++) {
Pos firstLocation = playerMoveEvent.getNewPosition().add(x, -1, z); Pos firstLocation = playerMoveEvent.getNewPosition().add(x, -1, z);
Pos secondLocation = firstLocation.withY(y -> y-1); Pos secondLocation = firstLocation.withY(y -> y - 1);
if(!getBlock(firstLocation).isAir() || !getBlock(secondLocation).isAir()) { if(!this.getBlock(firstLocation).isAir() || !this.getBlock(secondLocation).isAir()) {
setBlock(firstLocation, Block.AIR); this.setBlock(firstLocation, Block.AIR);
setBlock(secondLocation, Block.AIR); this.setBlock(secondLocation, Block.AIR);
// Entity fallingTnt = new Entity(EntityType.TNT); // Entity fallingTnt = new Entity(EntityType.TNT);
// PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta(); // PrimedTntMeta fallingTntMeta = (PrimedTntMeta) fallingTnt.getEntityMeta();
@@ -83,6 +84,6 @@ public class TntRun extends StatelessGame {
@Override @Override
public Pos getSpawn() { 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 @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("radius", Material.STICK, TranslatedComponent.byId("optionCommon#radius"), 20, 30, 50, 60)) .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("levels", Material.SCAFFOLDING, TranslatedComponent.byId("game_TntRun#levels"), 1, 2, 3, 4, 5));
} }
@Override @Override

View File

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

View File

@@ -14,6 +14,7 @@ public class TowerdefenseFactory implements GameFactory {
public TranslatedComponent name() { public TranslatedComponent name() {
return TranslatedComponent.byId("game_Towerdefense#name"); return TranslatedComponent.byId("game_Towerdefense#name");
} }
@Override @Override
public Material symbol() { public Material symbol() {
return Material.ARMOR_STAND; 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.instance.game.stateless.types.towerdefense.generator.MazeGenerator;
import eu.mhsl.minenet.minigames.util.BatchUtil; import eu.mhsl.minenet.minigames.util.BatchUtil;
import net.minestom.server.MinecraftServer; 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.entity.attribute.Attribute;
import net.minestom.server.instance.InstanceContainer; import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.item.ItemStack; import net.minestom.server.item.ItemStack;
@@ -27,8 +30,9 @@ public class TowerdefenseRoom extends InstanceContainer {
this.player.setAllowFlying(true); this.player.setAllowFlying(true);
this.player.getInventory().setItemStack(0, ItemStack.of(Material.ARMOR_STAND)); this.player.getInventory().setItemStack(0, ItemStack.of(Material.ARMOR_STAND));
setGenerator(new MazeGenerator()); this.setGenerator(new MazeGenerator());
BatchUtil.loadAndApplyBatch(this.game.getMazeBatch(), this, () -> {}); BatchUtil.loadAndApplyBatch(this.game.getMazeBatch(), this, () -> {
});
} }
public void startWave(List<EntityType> entities) { public void startWave(List<EntityType> entities) {
@@ -37,7 +41,7 @@ public class TowerdefenseRoom extends InstanceContainer {
MinecraftServer.getSchedulerManager().scheduleTask(() -> { MinecraftServer.getSchedulerManager().scheduleTask(() -> {
this.addEntity(new EntityCreature(entityType)); this.addEntity(new EntityCreature(entityType));
return TaskSchedule.stop(); return TaskSchedule.stop();
}, TaskSchedule.millis(800L*counter)); }, TaskSchedule.millis(800L * counter));
counter++; counter++;
} }
} }
@@ -45,14 +49,14 @@ public class TowerdefenseRoom extends InstanceContainer {
private void addEntity(EntityCreature entity) { private void addEntity(EntityCreature entity) {
entity.setInstance(this, this.game.getMazePath().getFirst()); entity.setInstance(this, this.game.getMazePath().getFirst());
entity.getAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(0.15); 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) { private void changeEntityGoal(EntityCreature entity, int positionIndex) {
if(positionIndex == this.game.getMazePath().size()-1) { if(positionIndex == this.game.getMazePath().size() - 1) {
return; 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), YELLOW(Material.YELLOW_WOOL, 500, 1500),
GREEN(Material.GREEN_WOOL, 2000, 5000); GREEN(Material.GREEN_WOOL, 2000, 5000);
private static final Random rnd = new Random();
public final ItemStack item; public final ItemStack item;
private final int minDuration; private final int minDuration;
private final int maxDuration; private final int maxDuration;
private static final Random rnd = new Random();
LightPhase(Material material, int minDuration, int maxDuration) { LightPhase(Material material, int minDuration, int maxDuration) {
this.item = ItemStack.of(material); this.item = ItemStack.of(material);
@@ -23,7 +23,7 @@ enum LightPhase {
} }
public TaskSchedule taskScheduleRandomDuration() { 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; package eu.mhsl.minenet.minigames.instance.game.stateless.types.trafficlightrace;
import de.articdive.jnoise.JNoise; 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.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.score.FirstWinsScore; import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.BatchUtil; 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.util.CommonProperties;
import eu.mhsl.minenet.minigames.world.BlockPallet; import eu.mhsl.minenet.minigames.world.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator; import eu.mhsl.minenet.minigames.world.generator.terrain.SquarePlateTerrainGenerator;
@@ -26,56 +26,55 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer; import java.util.function.Consumer;
class TrafficLightRace extends StatelessGame { class TrafficLightRace extends StatelessGame {
private LightPhase phase = LightPhase.RED;
private int phaseCounter = 0;
private final int width; private final int width;
private final int length; private final int length;
private final int preRun = 10; private final int preRun = 10;
private final int afterRun = 10; private final int afterRun = 10;
private final List<Pos> trafficLights = new ArrayList<>(); private final List<Pos> trafficLights = new ArrayList<>();
private LightPhase phase = LightPhase.RED;
private int phaseCounter = 0;
public TrafficLightRace(int width, int length) { public TrafficLightRace(int width, int length) {
super(Dimension.THE_END.key, "Ampelrennen", new FirstWinsScore()); super(Dimension.THE_END.key, "Ampelrennen", new FirstWinsScore());
this.width = width; this.width = width;
this.length = length; this.length = length;
setGenerator( this.setGenerator(
new SquarePlateTerrainGenerator(width, length + preRun + afterRun) new SquarePlateTerrainGenerator(width, length + this.preRun + this.afterRun)
.setPlateHeight(50) .setPlateHeight(50)
.setGenerateBorders(true) .setGenerateBorders(true)
); );
} }
@Override @Override
protected void onLoad(@NotNull CompletableFuture<Void> callback) { protected void onLoad(@NotNull CompletableFuture<Void> callback) {
final JNoise slowBatches = JNoise.newBuilder() final JNoise slowBatches = JNoise.newBuilder()
.fastSimplex() .fastSimplex()
.setSeed(rnd.nextLong()) .setSeed(this.rnd.nextLong())
.setFrequency(0.1) .setFrequency(0.1)
.build(); .build();
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for (int x = 0; x <= width; x++) { for(int x = 0; x <= this.width; x++) {
for (int z = 0; z <= preRun; z++) { for(int z = 0; z <= this.preRun; z++) {
batch.setBlock(x, 50, z, BlockPallet.GROUND.rnd()); 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()); 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, 50, z, BlockPallet.GROUND.rnd());
} }
batch.setBlock(x, 51, preRun-1, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest)); batch.setBlock(x, 51, this.preRun - 1, Block.OAK_FENCE.withProperties(CommonProperties.fenceEastWest));
batch.setBlock(x, 50, preRun + length, Block.GOLD_BLOCK); 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) -> { Consumer<TrafficLightsInput> generateTrafficLight = (input) -> {
batch.setBlock(input.x, 51, input.z, Block.ANVIL); 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); 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(x, 60, input.z, Block.SMOOTH_STONE_SLAB);
} }
batch.setBlock(input.x-2, 59, input.z, Block.STONE_BRICK_WALL); batch.setBlock(input.x - 2, 59, input.z, Block.STONE_BRICK_WALL);
trafficLights.add(new Pos(input.x-2, 58, input.z)); this.trafficLights.add(new Pos(input.x - 2, 58, input.z));
trafficLights.add(new Pos(input.x-2, 57, 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); batch.setBlock(input.x + 2, 59, input.z, Block.STONE_BRICK_WALL);
trafficLights.add(new Pos(input.x+2, 58, input.z)); this.trafficLights.add(new Pos(input.x + 2, 58, input.z));
trafficLights.add(new Pos(input.x+2, 57, 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); batch.setBlock(trafficLight, Block.WHITE_WOOL);
} }
}; };
for (int count = 0; count <= this.rnd.nextInt(1, 2); count++) { 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(0, this.rnd.nextInt(this.preRun + 10, this.length + this.preRun - 10)));
generateTrafficLight.accept(new TrafficLightsInput(width, this.rnd.nextInt(preRun + 10, length + preRun - 10))); generateTrafficLight.accept(new TrafficLightsInput(this.width, this.rnd.nextInt(this.preRun + 10, this.length + this.preRun - 10)));
} }
if(width > 30) { if(this.width > 30) {
for (int count = 0; count <= this.rnd.nextInt(1, 2); count++) { for(int count = 0; count <= this.rnd.nextInt(1, 2); count++) {
generateTrafficLight.accept(new TrafficLightsInput(width/2, this.rnd.nextInt(preRun, length + preRun))); 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(0, this.length + this.preRun));
generateTrafficLight.accept(new TrafficLightsInput(width, length + preRun)); generateTrafficLight.accept(new TrafficLightsInput(this.width, this.length + this.preRun));
BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null)); BatchUtil.loadAndApplyBatch(batch, this, () -> callback.complete(null));
} }
@@ -121,50 +120,51 @@ class TrafficLightRace extends StatelessGame {
@Override @Override
protected void onStart() { protected void onStart() {
AbsoluteBlockBatch batch = new AbsoluteBlockBatch(); AbsoluteBlockBatch batch = new AbsoluteBlockBatch();
for(int x = 0; x <= width; x++) { for(int x = 0; x <= this.width; x++) {
batch.setBlock(x, 51, preRun-1, Block.AIR); 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(); if(!super.isRunning) return TaskSchedule.stop();
phaseCounter++; this.phaseCounter++;
if(phaseCounter >= 3) phaseCounter = 0; if(this.phaseCounter >= 3) this.phaseCounter = 0;
if(phaseCounter == 0) phase = LightPhase.RED; if(this.phaseCounter == 0) this.phase = LightPhase.RED;
if(phaseCounter == 1) phase = LightPhase.GREEN; if(this.phaseCounter == 1) this.phase = LightPhase.GREEN;
if(phaseCounter == 2) phase = LightPhase.YELLOW; if(this.phaseCounter == 2) this.phase = LightPhase.YELLOW;
getPlayers().forEach(player -> { this.getPlayers().forEach(player -> {
for(int i = 0; i < 9; i++) { for(int i = 0; i < 9; i++) {
player.getInventory().setItemStack(i, phase.item); player.getInventory().setItemStack(i, this.phase.item);
} }
}); });
AbsoluteBlockBatch changeLightsBatch = new AbsoluteBlockBatch(); AbsoluteBlockBatch changeLightsBatch = new AbsoluteBlockBatch();
for (Pos trafficLight : trafficLights) { for(Pos trafficLight : this.trafficLights) {
changeLightsBatch.setBlock(trafficLight, phase.item.material().block()); 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); }, ExecutionType.TICK_END);
} }
@Override @Override
protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) { protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
if(isBeforeBeginning) return; if(this.isBeforeBeginning) return;
if(getScore().hasResult(playerMoveEvent.getPlayer())) 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().setVelocity(new Vec(0, 8, -15));
playerMoveEvent.getPlayer().playSound(Sound.sound(SoundEvent.ENTITY_BLAZE_SHOOT, Sound.Source.PLAYER, 1f, 1f)); playerMoveEvent.getPlayer().playSound(Sound.sound(SoundEvent.ENTITY_BLAZE_SHOOT, Sound.Source.PLAYER, 1f, 1f));
} }
if(playerMoveEvent.getNewPosition().z() > preRun+length) { if(playerMoveEvent.getNewPosition().z() > this.preRun + this.length) {
getScore().insertResult(playerMoveEvent.getPlayer()); this.getScore().insertResult(playerMoveEvent.getPlayer());
playerMoveEvent.getPlayer().getInventory().clear(); playerMoveEvent.getPlayer().getInventory().clear();
playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR); playerMoveEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
} }
@@ -172,6 +172,6 @@ class TrafficLightRace extends StatelessGame {
@Override @Override
public Pos getSpawn() { 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; 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.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.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.Option;
import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption; import eu.mhsl.minenet.minigames.instance.game.stateless.config.common.NumericOption;
import eu.mhsl.minenet.minigames.instance.room.Room; import eu.mhsl.minenet.minigames.instance.room.Room;
@@ -25,8 +25,8 @@ public class TrafficLightRaceFactory implements GameFactory {
@Override @Override
public ConfigManager configuration() { public ConfigManager configuration() {
return new ConfigManager() return new ConfigManager()
.addOption(new NumericOption("width", Material.OAK_FENCE, TranslatedComponent.byId("game_TrafficlightRace#width"), 20, 30, 40)) .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("length", Material.BLACK_CONCRETE_POWDER, TranslatedComponent.byId("game_TrafficlightRace#length"), 50, 80, 100, 120, 150));
} }
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,25 +19,26 @@ import java.util.List;
public class MinigameSelectInventory extends InteractableInventory { public class MinigameSelectInventory extends InteractableInventory {
final private Room room; final private Room room;
final private Player p; final private Player p;
public MinigameSelectInventory(Room room, Player p) { public MinigameSelectInventory(Room room, Player p) {
super(InventoryType.CHEST_6_ROW, TranslatedComponent.assemble("room#invTitle", p)); super(InventoryType.CHEST_6_ROW, TranslatedComponent.assemble("room#invTitle", p));
this.room = room; this.room = room;
this.p = p; this.p = p;
InventoryItemAlignment itemAlignment = new InventoryItemAlignment(GameType.values().length, 1); InventoryItemAlignment itemAlignment = new InventoryItemAlignment(GameType.values().length, 1);
for (GameType type : GameType.values()) { for(GameType type : GameType.values()) {
setClickableItem( this.setClickableItem(
ItemStack.builder(type.getIcon()) ItemStack.builder(type.getIcon())
.customName(type.getTitle().getAssembled(p)) .customName(type.getTitle().getAssembled(p))
.lore(type.getDescription().addWrap().getWrappedAssembled(p)) .lore(type.getDescription().addWrap().getWrappedAssembled(p))
.build(), .build(),
itemAlignment.next().get(), itemAlignment.next().get(),
itemClick -> drawGames(type) itemClick -> this.drawGames(type)
); );
} }
for(int i = 9; i <= 17; i++) { 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) { private void drawGames(GameType type) {
for(int i = 18; i <= 53; i++) { for(int i = 18; i <= 53; i++) {
setDummyItem(Material.AIR, i); this.setDummyItem(Material.AIR, i);
} }
int offset = 18; int offset = 18;
List<GameList> games = Arrays.stream(GameList.values()).filter(gameList -> gameList.getType().equals(type)).toList(); List<GameList> games = Arrays.stream(GameList.values()).filter(gameList -> gameList.getType().equals(type)).toList();
InventoryItemAlignment itemAlignment = new InventoryItemAlignment(games.size(), 4); InventoryItemAlignment itemAlignment = new InventoryItemAlignment(games.size(), 4);
for (GameList game : games) { for(GameList game : games) {
GameFactory gameFactory = game.getFactory(); GameFactory gameFactory = game.getFactory();
setClickableItem( this.setClickableItem(
ItemStack.builder(gameFactory.symbol()) ItemStack.builder(gameFactory.symbol())
.customName(gameFactory.name().getAssembled(p)) .customName(gameFactory.name().getAssembled(this.p))
.lore(gameFactory.description().addWrap().getWrappedAssembled(p)) .lore(gameFactory.description().addWrap().getWrappedAssembled(this.p))
.build(), .build(),
offset + itemAlignment.next().get(), offset + itemAlignment.next().get(),
itemClick -> itemClick.getPlayer().openInventory(new GameConfigurationInventory(room, itemClick.getPlayer(), gameFactory)) 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 class Transfer extends MineNetInstance implements Spawnable {
public Transfer() { public Transfer() {
super(Dimension.THE_END.key); super(Dimension.THE_END.key);
eventNode().addListener(PlayerMoveEvent.class, CommonEventHandles::cancel); this.eventNode().addListener(PlayerMoveEvent.class, CommonEventHandles::cancel);
setBlock(0, 0, 0, Block.BARRIER); this.setBlock(0, 0, 0, Block.BARRIER);
} }
@Override @Override

View File

@@ -14,17 +14,17 @@ public class Lang {
} }
public void addEntry(String key, String value) { public void addEntry(String key, String value) {
entries.put(key, value); this.entries.put(key, value);
} }
public String getEntry(String key) { 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!"); Logger.getLogger("localisation").warning(s + " is not known by translation files!");
return new DummyLang().getEntry(s); return new DummyLang().getEntry(s);
}); });
} }
public String getLangId() { 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.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger; import java.util.logging.Logger;
public class Languages { public class Languages {
private static Languages instance; public static final String defaultLanguage = "de_de";
private static final Logger logger = Logger.getLogger("translation"); private static final Logger logger = Logger.getLogger("translation");
private static Languages instance;
private final Map<String, Lang> languages = new HashMap<>(); private final Map<String, Lang> languages = new HashMap<>();
public static final String defaultLanguage = "de_de"; private Languages() {
this.readAll();
}
public static Languages getInstance() { public static Languages getInstance() {
if(instance == null) instance = new Languages(); if(instance == null) instance = new Languages();
return instance; return instance;
} }
private Languages() { public Lang getLanguage(Player p) {
readAll(); 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) { 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() { private void readAll() {
File locales = new File(Resource.LOCALES.getPath().toString()); 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) { if(files.length == 0) {
logger.warning("Failed to find any Language-files!"); logger.warning("Failed to find any Language-files!");
@@ -66,20 +68,22 @@ public class Languages {
index++; index++;
if(langId.endsWith("map")) continue; if(langId.endsWith("map")) continue;
languages.computeIfAbsent(langId, Lang::new); this.languages.computeIfAbsent(langId, Lang::new);
Lang lang = languages.get(langId); Lang lang = this.languages.get(langId);
langColumn.put(index, lang); langColumn.put(index, lang);
languages.put(langId, lang); this.languages.put(langId, lang);
} }
} else if(columns[0].startsWith("ns:")) { } 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]; namespace = columns[0].split(":")[1];
} else { } else {
// file contents // 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; int index = 0;
String mapId = ""; String mapId = "";
for(String translation : columns) { 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()); logger.warning("Exception while parsing lang-files: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }

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