diff --git a/pom.xml b/pom.xml
index 16330be..113197d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -12,10 +12,18 @@
UTF-8
- 1.8
- 1.8
+ 17
+ 17
+
+
+ minecraft-libraries
+ Minecraft Libraries
+ https://libraries.minecraft.net
+
+
+
junit
@@ -44,6 +52,11 @@
system
${basedir}/deps/datafixerupper.jar
+
+ com.mojang
+ brigadier
+ 1.0.18
+
@@ -87,5 +100,13 @@
+
+
+ src
+
+ **/*.yml
+
+
+
diff --git a/src/default-favourites.yml b/src/default-favourites.yml
new file mode 100644
index 0000000..aa8e1f4
--- /dev/null
+++ b/src/default-favourites.yml
@@ -0,0 +1,72 @@
+'26':
+ deal: 5
+ section: 4
+'25':
+ deal: 11
+ section: 4
+'24':
+ deal: 8
+ section: 2
+'23':
+ deal: 7
+ section: 2
+'22':
+ deal: 4
+ section: 2
+'21':
+ deal: 2
+ section: 0
+'19':
+ deal: 9
+ section: 4
+'18':
+ deal: 4
+ section: 4
+'17':
+ deal: 2
+ section: 2
+'16':
+ deal: 2
+ section: 3
+'15':
+ deal: 2
+ section: 1
+'14':
+ deal: 1
+ section: 0
+'12':
+ deal: 8
+ section: 4
+'11':
+ deal: 3
+ section: 4
+'10':
+ deal: 1
+ section: 2
+'9':
+ deal: 1
+ section: 3
+'8':
+ deal: 1
+ section: 1
+'7':
+ deal: 4
+ section: 0
+'5':
+ deal: 7
+ section: 4
+'4':
+ deal: 0
+ section: 4
+'3':
+ deal: 0
+ section: 2
+'2':
+ deal: 0
+ section: 3
+'1':
+ deal: 0
+ section: 1
+'0':
+ deal: 0
+ section: 0
diff --git a/src/main/java/me/topchetoeu/bedwars/Commands.java b/src/main/java/me/topchetoeu/bedwars/Commands.java
index 49aac5b..0bf3856 100644
--- a/src/main/java/me/topchetoeu/bedwars/Commands.java
+++ b/src/main/java/me/topchetoeu/bedwars/Commands.java
@@ -2,306 +2,245 @@ package me.topchetoeu.bedwars;
import java.io.File;
import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
-import org.bukkit.OfflinePlayer;
-import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.topchetoeu.bedwars.commandUtility.Command;
-import me.topchetoeu.bedwars.commandUtility.CommandExecutor;
-import me.topchetoeu.bedwars.commandUtility.CommandExecutors;
import me.topchetoeu.bedwars.engine.BedwarsPlayer;
import me.topchetoeu.bedwars.engine.Config;
import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.Team;
import me.topchetoeu.bedwars.engine.TeamColor;
+import net.md_5.bungee.api.ChatColor;
+import net.md_5.bungee.api.chat.ComponentBuilder;
public class Commands {
- private static File confFile = new File(Main.getInstance().getDataFolder(), "config.yml");
-
- @SuppressWarnings("deprecation")
- public static CommandExecutor kill = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (Game.isStarted()) {
- for (String arg : args) {
- OfflinePlayer p = Bukkit.getOfflinePlayer(arg);
+ private static File confFile = new File(Main.getInstance().getDataFolder(), "config.yml");
+
+ @SuppressWarnings("unchecked")
+ public static Command kill(Command cmd) {
+ return cmd.player("players", false).setRecursive(true).setExecutor((sender, _cmd, args) -> {
+ if (Game.isStarted()) {
+ for (Player p : (List)args.get("players")) {
+ BedwarsPlayer bwp = Game.instance.getPlayer(p);
+ if (bwp != null) {
+ bwp.kill(bwp.getPlayer().getName() + " definitely died with no admin intervention.");
+ }
+ else return "Player is not in game!";
+ }
+ return null;
+ }
+ else return "The game isn't started yet";
+ });
+ }
+ @SuppressWarnings("unchecked")
+ public static Command revive(Command cmd) {
+ return cmd.player("players", false).setRecursive(true).setExecutor((sender, _cmd, args) -> {
+ if (Game.isStarted()) {
+ for (Player p : (List)args.get("players")) {
+ BedwarsPlayer bwp = Game.instance.getPlayer(p);
+ if (bwp != null) {
+ bwp.revive();
+ Bukkit.broadcastMessage("Player " + p.getName() + " revived!");
+ return null;
+ }
+ else return "Player is not in game!";
+ }
+ return null;
+ }
+ else return "The game isn't started yet";
+ });
+ }
+
+ public static Command start(Command cmd) {
+ return cmd.setExecutor((sender, _cmd, args) -> {
+ if (!Game.isStarted()) {
+ Game.start();
+ sender.sendMessage("Started the game!");
+ return null;
+ }
+ else return "The game is already started";
+ });
+ }
+ public static Command stop(Command cmd) {
+ return cmd.setExecutor((sender, _cmd, args) -> {
+ if (Game.isStarted()) {
+ Game.stop();
+ sender.sendMessage("Stopped the game!");
+ return null;
+ }
+ else return "The game is not started";
+ });
+ }
- if (p != null) {
- BedwarsPlayer bwp = Game.instance.getPlayer(p);
-
- if (bwp != null) {
- bwp.kill(bwp.getPlayer().getName() + " definitely died with no admin intervention.");
- }
- else sender.sendMessage("Player is not in game!");
- }
- else sender.sendMessage("Player doesn't exist!");
- }
- }
- else sender.sendMessage("The game isn't started yet");
- };
- @SuppressWarnings("deprecation")
- public static CommandExecutor revive = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (Game.isStarted()) {
- for (String arg : args) {
- OfflinePlayer p = Bukkit.getOfflinePlayer(arg);
+ private static Command basesArg() {
+ return Command.createCollection("team", () -> Config.instance.getColors()
+ .stream()
+ .collect(Collectors.toMap(
+ TeamColor::getName,
+ v -> v
+ )), false
+ );
+ }
- if (p != null) {
- BedwarsPlayer bwp = Game.instance.getPlayer(p);
-
- if (bwp != null) {
- bwp.revive();
- Bukkit.broadcastMessage("Player " + p.getName() + " revived!");
- }
- else sender.sendMessage("Player is not in game!");
- }
- else sender.sendMessage("Player doesn't exist!");
- }
- }
- else sender.sendMessage("The game isn't started yet");
- };
-
- public static CommandExecutor start = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length == 0) {
- if (!Game.isStarted()) {
- Game.start();
- sender.sendMessage("Started the game!");
- }
- else sender.sendMessage("The game is already started");
- }
- else sender.sendMessage("Invalid command syntax. No parameters required!");
- };
- public static CommandExecutor stop = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length == 0) {
- if (Game.isStarted()) {
- Game.stop();
- }
- else sender.sendMessage("The game is not started");
- }
- else sender.sendMessage("Invalid command syntax. No parameters required!");
- };
-
- public static CommandExecutor baseAdd = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length == 6 && args[5].length() == 1) {
- if (!Game.isStarted()) {
- if (Utility.isParsable(args[2])) {
- if (Utility.isParsable(args[3])) {
- if (Utility.isParsable(args[4])) {
+ public static Command baseAdd(Command cmd) {
+ return cmd.string("name", false)._int("red")._int("green")._int("blue")._enum("color", org.bukkit.ChatColor.class, true)._enum("wool", Material.class, true)
+ .setExecutor((sender, _cmd, args) -> {
+ if (!Game.isStarted()) {
+ String name = args.get("name").toString().toLowerCase();
+ Material wool = (Material)args.get("wool");
+ org.bukkit.ChatColor bukkitChatColor = (org.bukkit.ChatColor)args.get("color");
+ int r = (int)args.get("red"),
+ g = (int)args.get("green"),
+ b = (int)args.get("blue");
- String name = args[0];
- Material wool = Material.getMaterial(args[1].toString());
- char chatId = args[5].charAt(0);
- if (wool != null) {
- if (Config.instance.getColor(name.toLowerCase()) == null) {
- Config.instance.getColors().add(new TeamColor(name.toLowerCase(), wool,
- Color.fromRGB(
- Integer.parseInt(args[2]),
- Integer.parseInt(args[3]),
- Integer.parseInt(args[4])
- ),
- chatId
- ));
- Config.instance.save(confFile);
- sender.sendMessage("New base was created!");
- }
- else sender.sendMessage("Base with this name already exists!");
- }
- else sender.sendMessage("The material '" + args[1] + " was not found!");
- } else sender.sendMessage("blue must be a valid number between 0 and 255!");
- } else sender.sendMessage("green must be a valid number between 0 and 255!");
- } else sender.sendMessage("red must be a valid number between 0 and 255!");
- }
- else sender.sendMessage("Can't make modifications to the map while a game is ongoing!");
- }
- else sender.sendMessage("Invalid command syntax. Syntax: /bw conf base new ");
- };
-
- public static CommandExecutor baseRemove = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length == 1) {
- TeamColor color = Config.instance.getColor(args[0]);
- if (color != null) {
- Config.instance.getColors().remove(color);
- Config.instance.save(confFile);
- sender.sendMessage("Base removed!");
- }
- else sender.sendMessage("Base doesn't exist!");
- }
- else sender.sendMessage("Invalid syntax! Syntax: /bw conf base del ");
- };
- public static CommandExecutor baseSetSpawn = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- boolean aligned = args.length == 2 && args[1].equals("aligned");
-
- if (args.length == 1 || aligned) {
- if (sender instanceof Player) {
- Player p = (Player)sender;
-
- TeamColor color = Config.instance.getColor(args[0]);
- if (color != null) {
- Location loc = p.getLocation();
- if (aligned) {
- loc.setX(loc.getBlockX() + 0.5);
- loc.setZ(loc.getBlockZ() + 0.5);
- }
- color.setSpawnLocation(loc);
- Config.instance.save(confFile);
- sender.sendMessage("Base spawn set to your current location");
- }
- else sender.sendMessage("Base doesn't exist!");
-
- }
- else sender.sendMessage("This commands is for players only!");
- }
- else sender.sendMessage("Invalid syntax! Syntax: /bw conf base spawn [aligned]");
- };
- public static CommandExecutor baseSetGenerator = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- boolean aligned = args.length == 2 && args[1].equals("aligned");
-
- if (args.length == 1 || aligned) {
- if (sender instanceof Player) {
- Player p = (Player)sender;
-
- TeamColor color = Config.instance.getColor(args[0]);
- if (color != null) {
- Location loc = p.getLocation();
- if (aligned) {
- loc.setX(loc.getBlockX() + 0.5);
- loc.setZ(loc.getBlockZ() + 0.5);
- }
- color.setGeneratorLocation(loc);
- Config.instance.save(confFile);
- sender.sendMessage("Base generator set to your current location");
- }
- else sender.sendMessage("Base doesn't exist!");
-
- }
- else sender.sendMessage("This commands is for players only!");
- }
- else sender.sendMessage("Invalid syntax! Syntax: /bw conf base gen [aligned]");
- };
- public static CommandExecutor baseSetBed = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- boolean aligned = args.length == 2 && args[1].equals("aligned");
-
- if (args.length == 1 || aligned) {
- if (sender instanceof Player) {
- Player p = (Player)sender;
-
- TeamColor color = Config.instance.getColor(args[0]);
- if (color != null) {
- Location loc = p.getLocation();
- if (aligned) {
- loc.setX(loc.getBlockX() + 0.5);
- loc.setZ(loc.getBlockZ() + 0.5);
- }
- color.setBedLocation(loc);
- Config.instance.save(confFile);
- sender.sendMessage("Base bed set to your current location");
- }
- else sender.sendMessage("Base doesn't exist!");
-
- }
- else sender.sendMessage("This commands is for players only!");
- }
- else sender.sendMessage("Invalid syntax! Syntax: /bw conf base bed [aligned]");
- };
- public static CommandExecutor baseList = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length == 0) {
- ArrayList colors = Config.instance.getColors();
-
- if (colors.size() != 0) {
- sender.sendMessage("Bases:");
- for (TeamColor color : colors) {
- sender.sendMessage("§" + color.getChatColor() + color.getName() + "§r" + (
- color.isFullySpecified() ? "" : " (not fully specified)"
- ));
- }
- }
- else sender.sendMessage("No bases found.");
- }
- else sender.sendMessage("Invalid syntax! No parameters required");
- };
-
- public static CommandExecutor breakBed = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (!Game.isStarted()) {
- sender.sendMessage("§4A game hasn't been started yet.");
- return;
- }
-
- ArrayList teams = new ArrayList<>();
-
- for (String arg : args) {
- TeamColor color = Config.instance.getColor(arg);
-
- if (color == null) {
- sender.sendMessage(String.format("§4The team color §l§4%s§r§4 doesn't exist.", arg));
- return;
- }
-
- Team team = Game.instance.getTeam(color);
-
- if (team == null) {
- sender.sendMessage(String.format("§6The team color §l§4%s§r§4 isn't in the game.", arg));
- }
-
- teams.add(team);
- }
-
- for (Team team : teams) {
- if (!team.destroyBed(null))
- sender.sendMessage(String.format("§4The %s's bed is already destroyed.", team.getTeamColor().getName()));
-
- }
- };
-
- public static CommandExecutor createDiamondGen = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length > 1) {
- sender.sendMessage("§4Invalid syntax!§r Syntax: /bw config gen diamond [aligned]");
- return;
- }
-
- boolean aligned = args.length == 1 && args[0] == "aligned";
-
- if (sender instanceof Player) {
- Player p = (Player)sender;
+ ChatColor chatColor = Utility.bukkitToBungeeColor(bukkitChatColor);
- Location loc = p.getLocation();
- if (aligned) {
- loc.setX(loc.getBlockX() + 0.5);
- loc.setZ(loc.getBlockZ() + 0.5);
- }
-
- Config.instance.getDiamondGenerators().add(loc);
- Config.instance.save(confFile);
-
- p.sendMessage("§aGenerator added!");
- }
- else sender.sendMessage("§4Only a player may execute this command.");
- };
- public static CommandExecutor createEmeraldGen = (CommandSender sender, Command cmd, String alias, String[] args) -> {
- if (args.length > 1) {
- sender.sendMessage("§4Invalid syntax!§r Syntax: /bw config gen emerald [aligned]");
- return;
- }
-
- boolean aligned = args.length == 1 && args[0] == "aligned";
-
- if (sender instanceof Player) {
- Player p = (Player)sender;
+ if (Config.instance.getColor(name.toLowerCase()) == null) {
+ Config.instance.getColors().add(new TeamColor(name, wool, Color.fromRGB(r, g, b), chatColor));
+ Config.instance.save(confFile);
+ sender.sendMessage("New base was created!");
+ return null;
+ }
+ else return "Base with this name already exists!";
+ }
+ else return "Can't make modifications to the map while a game is ongoing!";
+ });
+ }
- Location loc = p.getLocation();
- if (aligned) {
- loc.setX(loc.getBlockX() + 0.5);
- loc.setZ(loc.getBlockZ() + 0.5);
- }
-
- Config.instance.getEmeraldGenerators().add(loc);
- Config.instance.save(confFile);
-
- p.sendMessage("§aGenerator added!");
- }
- else sender.sendMessage("§4Only a player may execute this command.");
- };
-
- public static CommandExecutor _default = CommandExecutors.message("For help do /bw help");
+ public static Command baseRemove(Command cmd) {
+ return cmd
+ .addChild(basesArg())
+ .setExecutor((sender, _cmd, args) -> {
+ TeamColor color = (TeamColor)args.get("team");
+ Config.instance.getColors().remove(color);
+ Config.instance.save(confFile);
+ sender.sendMessage("Base removed!");
+ return null;
+ });
+ }
+ public static Command baseSetSpawn(Command cmd) {
+ return cmd
+ .addChild(basesArg())
+ .location("location")
+ .setExecutor((sender, _cmd, args) -> {
+ TeamColor color = (TeamColor)args.get("team");
+ Location loc = (Location)args.get("location");
+
+ color.setSpawnLocation(loc);
+ Config.instance.save(confFile);
+ sender.sendMessage("Base spawn set");
+
+ return null;
+ });
+ }
+ public static Command baseSetGenerator(Command cmd) {
+ return cmd
+ .addChild(basesArg())
+ .location("location")
+ .setExecutor((sender, _cmd, args) -> {
+ TeamColor color = (TeamColor)args.get("team");
+ Location loc = (Location)args.get("location");
+
+ color.setGeneratorLocation(loc);
+ Config.instance.save(confFile);
+ sender.sendMessage("Base generator set");
+
+ return null;
+ });
+ }
+ public static Command baseSetBed(Command cmd) {
+ return cmd
+ .addChild(basesArg())
+ .location("location")
+ .setExecutor((sender, _cmd, args) -> {
+ TeamColor color = (TeamColor)args.get("team");
+ Location loc = (Location)args.get("location");
+
+ color.setBedLocation(loc);
+ Config.instance.save(confFile);
+ sender.sendMessage("Base bed set");
+
+ return null;
+ });
+ // );
+ }
+ public static Command baseList(Command cmd) {
+ return cmd
+ .setExecutor((sender, _cmd, args) -> {
+ List colors = Config.instance.getColors();
+
+ if (colors.size() != 0) {
+ sender.sendMessage("Bases:");
+ for (TeamColor color : colors) {
+ ComponentBuilder cb = new ComponentBuilder().append(color.getName()).color(color.getChatColor());
+ if (!color.isFullySpecified()) cb.append(" (not fully specified)").reset().italic(true);
+ sender.spigot().sendMessage(cb.create());
+ }
+ }
+ else sender.sendMessage("No bases found.");
+
+ return null;
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Command breakBed(Command cmd) {
+ return cmd
+ .addChild(basesArg()).setRecursive(true)
+ .setExecutor((sender, _cmd, args) -> {
+ if (!Game.isStarted()) return "A game hasn't been started yet.";
+
+ List colors = (List)args.get("team");
+ ArrayList teams = new ArrayList<>();
+ for (TeamColor color : colors) {
+ Team team = Game.instance.getTeam(color);
+
+ if (team == null) {
+ return "The team color %s isn't in the game.".formatted(color.getName());
+ }
+
+ teams.add(team);
+ }
+
+ for (Team team : teams) {
+ team.destroyBed(null);
+ }
+
+ return null;
+ });
+ }
+
+ public static Command createDiamondGen(Command cmd) {
+ return cmd.location("location").setExecutor((sender, _cmd, args) -> {
+ Location loc = (Location)args.get("location");
+ Config.instance.getDiamondGenerators().add(loc);
+ Config.instance.save(confFile);
+ sender.sendMessage("§aGenerator added!");
+ return null;
+ });
+ }
+ public static Command createEmeraldGen(Command cmd) {
+ return cmd.location("location").setExecutor((sender, _cmd, args) -> {
+ Location loc = (Location)args.get("location");
+ Config.instance.getEmeraldGenerators().add(loc);
+ Config.instance.save(confFile);
+ sender.sendMessage("§aGenerator added!");
+ return null;
+ });
+ }
+ public static Command clearGens(Command cmd) {
+ return cmd.setExecutor((sender, _cmd, args) -> {
+ Config.instance.getEmeraldGenerators().clear();
+ Config.instance.save(confFile);
+ sender.sendMessage("§aGenerators cleared!");
+ return null;
+ });
+ }
}
diff --git a/src/main/java/me/topchetoeu/bedwars/InventoryUtility.java b/src/main/java/me/topchetoeu/bedwars/InventoryUtility.java
index e096ef3..00406eb 100644
--- a/src/main/java/me/topchetoeu/bedwars/InventoryUtility.java
+++ b/src/main/java/me/topchetoeu/bedwars/InventoryUtility.java
@@ -3,91 +3,91 @@ package me.topchetoeu.bedwars;
import org.bukkit.inventory.ItemStack;
public class InventoryUtility {
- public static boolean itemEquals(ItemStack a, ItemStack b, boolean ignoreAmount) {
- if (a == null && b == null) return true;
- if (a == null || b == null) return false;
-
- if (ignoreAmount) {
- a = a.clone();
- a.setAmount(1);
- b = b.clone();
- b.setAmount(1);
-
- return a.equals(b);
- }
- else return a.equals(b);
- }
- public static ItemStack giveItem(ItemStack[] inv, ItemStack _item) {
- ItemStack item = _item.clone();
- int remaining = item.getAmount();
- int maxStackSize = item.getMaxStackSize();
-
- for (int i = 0; i < 36; i++) {
- if (itemEquals(inv[i], item, true)) {
- if (inv[i].getAmount() < maxStackSize) {
- int newCount = remaining + inv[i].getAmount();
- if (newCount > maxStackSize) {
- inv[i].setAmount(maxStackSize);
- remaining = newCount - maxStackSize;
- }
- else {
- inv[i].setAmount(newCount);
- return null;
- }
- }
- }
- }
-
- item.setAmount(remaining);
-
- for (int i = 0; i < 36; i++) {
- if (inv[i] == null) {
- inv[i] = item;
- return null;
- }
- }
-
- return item;
- }
- public static boolean hasItem(ItemStack[] inv, ItemStack item) {
- int n = 0;
-
- for (int i = 0; i < inv.length; i++) {
- if (inv[i] != null) {
- if (itemEquals(inv[i], (item), true)) {
- n += inv[i].getAmount();
- if (n >= item.getAmount()) {
- return true;
- }
- }
- }
- }
-
- return false;
- }
- public static ItemStack takeItems(ItemStack[] inv, ItemStack item) {
- item = item.clone();
-
- for (int i = 0; i < inv.length; i++) {
- if (inv[i] != null) {
- if (itemEquals(inv[i], (item), true)) {
- int amount = inv[i].getAmount();
- if (item.getAmount() > amount) {
- item.setAmount(item.getAmount() - amount);
- inv[i] = null;
- }
- else if (item.getAmount() == amount) {
- inv[i] = null;
- return null;
- }
- else if (item.getAmount() < amount) {
- inv[i].setAmount(inv[i].getAmount() - item.getAmount());
- return null;
- }
- }
- }
- }
-
- return item;
- }
+ public static boolean itemEquals(ItemStack a, ItemStack b, boolean ignoreAmount) {
+ if (a == null && b == null) return true;
+ if (a == null || b == null) return false;
+
+ if (ignoreAmount) {
+ a = a.clone();
+ a.setAmount(1);
+ b = b.clone();
+ b.setAmount(1);
+
+ return a.equals(b);
+ }
+ else return a.equals(b);
+ }
+ public static ItemStack giveItem(ItemStack[] inv, ItemStack _item) {
+ ItemStack item = _item.clone();
+ int remaining = item.getAmount();
+ int maxStackSize = item.getMaxStackSize();
+
+ for (int i = 0; i < 36; i++) {
+ if (itemEquals(inv[i], item, true)) {
+ if (inv[i].getAmount() < maxStackSize) {
+ int newCount = remaining + inv[i].getAmount();
+ if (newCount > maxStackSize) {
+ inv[i].setAmount(maxStackSize);
+ remaining = newCount - maxStackSize;
+ }
+ else {
+ inv[i].setAmount(newCount);
+ return null;
+ }
+ }
+ }
+ }
+
+ item.setAmount(remaining);
+
+ for (int i = 0; i < 36; i++) {
+ if (inv[i] == null) {
+ inv[i] = item;
+ return null;
+ }
+ }
+
+ return item;
+ }
+ public static boolean hasItem(ItemStack[] inv, ItemStack item) {
+ int n = 0;
+
+ for (int i = 0; i < inv.length; i++) {
+ if (inv[i] != null) {
+ if (itemEquals(inv[i], (item), true)) {
+ n += inv[i].getAmount();
+ if (n >= item.getAmount()) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+ public static ItemStack takeItems(ItemStack[] inv, ItemStack item) {
+ item = item.clone();
+
+ for (int i = 0; i < inv.length; i++) {
+ if (inv[i] != null) {
+ if (itemEquals(inv[i], (item), true)) {
+ int amount = inv[i].getAmount();
+ if (item.getAmount() > amount) {
+ item.setAmount(item.getAmount() - amount);
+ inv[i] = null;
+ }
+ else if (item.getAmount() == amount) {
+ inv[i] = null;
+ return null;
+ }
+ else if (item.getAmount() < amount) {
+ inv[i].setAmount(inv[i].getAmount() - item.getAmount());
+ return null;
+ }
+ }
+ }
+ }
+
+ return item;
+ }
}
diff --git a/src/main/java/me/topchetoeu/bedwars/Main.java b/src/main/java/me/topchetoeu/bedwars/Main.java
index 0bd7b58..dc8b651 100644
--- a/src/main/java/me/topchetoeu/bedwars/Main.java
+++ b/src/main/java/me/topchetoeu/bedwars/Main.java
@@ -1,26 +1,18 @@
package me.topchetoeu.bedwars;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
-import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.entity.ArmorStand;
-import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
-import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
@@ -46,270 +38,194 @@ import me.topchetoeu.bedwars.engine.trader.upgrades.SharpnessTeamUpgrade;
// TODO add permissions
public class Main extends JavaPlugin implements Listener {
-
-
- private static Main instance;
- private int playerCount;
- public static Main getInstance() {
- return instance;
- }
-
- private File confFile = new File(getDataFolder(), "config.yml");
- private int getGameSize() {
- return Config.instance.getTeamSize() * Config.instance.getColors().size();
- }
-
- int timer = 0;
- BukkitTask timerTask = null;
-
- private void stopTimer() {
- if (timerTask == null) return;
- Utility.broadcastTitle("Not enough players!", null, 10, 40, 5);
- timerTask.cancel();
- timerTask = null;
- }
- private void startTimer() {
- if (timerTask != null) return;
-
- timerTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
- if (Game.isStarted()) {
- stopTimer();
- return;
- }
- if (timer % 30 == 0 || timer == 15 || timer == 10)
- Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 10, 40, 5);
- else if (timer <= 5)
- Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 0, 20, 0);
- timer--;
- if (timer <= 0) {
- Game.start();
- timerTask.cancel();
- timerTask = null;
- }
- }, 0, 20);
- }
- public void updateTimer() {
- // TODO make timing configurable
- if (!Game.isStarted()) {
- if (playerCount <= 1 || playerCount <= getGameSize() / 4) {
- Utility.broadcastTitle("Not enough players", "Waiting for more...", 0, 100, 0);
- stopTimer();
- }
- else if (playerCount <= getGameSize() / 2) {
- timer = 60;
- startTimer();
- }
- else if (playerCount <= getGameSize() - 1) {
- timer = 60;
- startTimer();
- }
- else {
- timer = 15;
- startTimer();
- }
- }
- }
-
- @EventHandler
- private void onJoin(PlayerJoinEvent e) {
- playerCount++;
- e.getPlayer().setGameMode(GameMode.SPECTATOR);
- updateTimer();
- }
- @EventHandler
- private void onLeave(PlayerQuitEvent e) {
- playerCount--;
- updateTimer();
- }
-
- @EventHandler
- private void onFoodLost(FoodLevelChangeEvent e) {
- e.setCancelled(true);
- }
-
- @Override
- public void onEnable() {
- playerCount = Bukkit.getServer().getOnlinePlayers().size();
- try {
- instance = this;
- getDataFolder().mkdir();
- File conf = new File(getDataFolder(), "config.yml");
- if (!conf.exists())
- try {
- YamlConfiguration.loadConfiguration(
- new InputStreamReader(
- getClass()
- .getClassLoader()
- .getResourceAsStream("config.yml")
- )
- ).save(confFile);
- }
- catch (IOException e) { /* Everything is fine */ }
-
- // Deprecation warnings are for beginners
- Config.load(conf);
- File defaultFavs = new File(getDataFolder(), "default-favourites.yml");
-
- if (!defaultFavs.exists()) {
- try {
- OutputStream w = new FileOutputStream(defaultFavs);
- InputStream r = getClass()
- .getClassLoader()
- .getResourceAsStream("default-favourites.yml");
-
- w.write(r.readAllBytes());
-
- w.close();
- r.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- File favsDir = new File(getDataFolder(), "favourites");
-
- try {
- Traders.instance = new Traders(new File(getDataFolder(), "traders.txt"));
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- YamlConfiguration sectionsConf = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "sections.yml"));
+
+
+ private static Main instance;
+ private int playerCount;
+ public static Main getInstance() {
+ return instance;
+ }
+
+ // private File confFile = new File(getDataFolder(), "config.yml");
+ private int getGameSize() {
+ return Config.instance.getTeamSize() * Config.instance.getColors().size();
+ }
+
+ int timer = 0;
+ BukkitTask timerTask = null;
+
+ private void stopTimer() {
+ if (timerTask == null) return;
+ Utility.broadcastTitle("Not enough players!", null, 10, 40, 5);
+ timerTask.cancel();
+ timerTask = null;
+ }
+ private void startTimer() {
+ if (timerTask != null) return;
+
+ timerTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
+ if (Game.isStarted()) {
+ stopTimer();
+ return;
+ }
+ if (timer % 30 == 0 || timer == 15 || timer == 10)
+ Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 10, 40, 5);
+ else if (timer <= 5)
+ Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 0, 20, 0);
+ timer--;
+ if (timer <= 0) {
+ Game.start();
+ timerTask.cancel();
+ timerTask = null;
+ }
+ }, 0, 20);
+ }
+ public void updateTimer() {
+ // TODO make timing configurable
+ if (!Game.isStarted()) {
+ if (playerCount <= 1 || playerCount <= getGameSize() / 4) {
+ Utility.broadcastTitle("Not enough players", "Waiting for more...", 0, 100, 0);
+ stopTimer();
+ }
+ else if (playerCount <= getGameSize() / 2) {
+ timer = 60;
+ startTimer();
+ }
+ else if (playerCount <= getGameSize() - 1) {
+ timer = 60;
+ startTimer();
+ }
+ else {
+ timer = 15;
+ startTimer();
+ }
+ }
+ }
+
+ @EventHandler
+ private void onJoin(PlayerJoinEvent e) {
+ playerCount++;
+ e.getPlayer().setGameMode(GameMode.SPECTATOR);
+ updateTimer();
+ }
+ @EventHandler
+ private void onLeave(PlayerQuitEvent e) {
+ playerCount--;
+ updateTimer();
+ }
+
+ @EventHandler
+ private void onFoodLost(FoodLevelChangeEvent e) {
+ e.setCancelled(true);
+ }
- BlindnessTeamUpgrade.init(this);
- FatigueTeamUpgrade.init(this);
- HealTeamUpgrade.init(this);
- EfficiencyTeamUpgrade.init();
- ProtectionTeamUpgrade.init();
- SharpnessTeamUpgrade.init();
- TeamUpgradeRanks.init(this, sectionsConf);
-
- ItemDealType.init();
- RankedDealType.init(this, sectionsConf);
- EnforcedRankedDealType.init();
- RankedUpgradeDealType.init();
- Sections.init(new File(getDataFolder(), "sections.yml"));
- Favourites.instance = new Favourites(favsDir, defaultFavs);
-
- updateTimer();
-
- getServer().getWorlds().get(0).getEntitiesByClass(Villager.class).forEach(v -> {
- v.setAI(false);
- });
-
- Command cmd = new Command("bedwars", "bw").setExecutor(Commands._default);
- cmd
- .attachCommand(new Command("help")
- .setExecutor(CommandExecutors.help(cmd))
- .setHelpMessage("Shows help for the command")
- )
- .attachCommand(new Command("start")
- .setExecutor(Commands.start)
- .setHelpMessage("Starts the game")
- )
- .attachCommand(new Command("stop")
- .setExecutor(Commands.stop)
- .setHelpMessage("Stops the game, noone wins")
- )
- .attachCommand(new Command("respawn", "revive")
- .setExecutor(Commands.revive)
- .setHelpMessage("Respawns a spectator, if he has a bed, he is immediatly respawned"))
- .attachCommand(new Command("breakbed", "eliminateteam")
- .setExecutor(Commands.breakBed)
- .setHelpMessage("Destoys the bed of a team")
- )
- .attachCommand(new Command("eliminate")
- .setHelpMessage("Eliminates a player")
- )
- .attachCommand(new Command("kill")
- .setExecutor(Commands.kill)
- .setHelpMessage("Kills a player")
- )
- .attachCommand(new Command("killteam")
- .setHelpMessage("Kills all players of a team")
- )
- .attachCommand(new Command("villagertools", "villager", "trader")
- .setExecutor((sender, _cmd, alias, args) -> {
- if (args.length == 0) {
- if (sender instanceof Player) {
- Player p = (Player)sender;
-
- p.getInventory().addItem(Utility.namedItem(new ItemStack(Material.VILLAGER_SPAWN_EGG), "§rTrader spawner"));
- p.getInventory().addItem(Utility.namedItem(new ItemStack(Material.STICK), "§rTrader eradicator"));
- }
- }
- })
- .setHelpMessage("Gives you tools to manage traders")
- )
- .attachCommand(new Command("config", "conf", "settings")
- .setExecutor(Commands._default)
- .setHelpMessage("Command for configuring the map")
- .attachCommand(new Command("spawn")
- .setHelpMessage("Sets the spawn at which the platform is going to be spawned, and where spectators are going to be spawned")
- )
- .attachCommand(new Command("base", "b")
- .setExecutor(Commands._default)
- .setHelpMessage("Command for configuring separate bases")
- .attachCommand(new Command("new", "add", "create", "c")
- .setExecutor(Commands.baseAdd)
- .setHelpMessage("Creates a base with a color, chat id and a wool id. NOTE: for chat id, do the following: if in chat the color you want is &2, specify just '2'")
- )
- .attachCommand(new Command("remove", "delete", "del", "d")
- .setExecutor(Commands.baseRemove)
- .setHelpMessage("Removes a base with the selected name")
- )
- .attachCommand(new Command("setbed", "bed", "b")
- .setExecutor(Commands.baseSetBed)
- .setHelpMessage("Sets the location of the bed. Any broken bed within 5 blocks of the specified location will trigger the breaking of the team's bed")
- )
- .attachCommand(new Command("setgenerator", "generator", "setgen", "gen", "g")
- .setExecutor(Commands.baseSetGenerator)
- .setHelpMessage("Sets the location of the generator. Anyone within 2 blocks of it will pick up the produced items")
- )
- .attachCommand(new Command("setspawn", "spawn", "s")
- .setExecutor(Commands.baseSetSpawn)
- .setHelpMessage("Sets the location where players of the team will respawn")
- )
- .attachCommand(new Command("list", "l")
- .setExecutor(Commands.baseList)
- .setHelpMessage("Lists all bases")
- )
- )
- .attachCommand(new Command("generator", "gen", "g")
- .setExecutor(Commands._default)
- .setHelpMessage("Command for configuring the global generators")
- .attachCommand(new Command("diamond", "d")
- .setExecutor(Commands.createDiamondGen)
- .setHelpMessage("Creates a diamond generator in (approximately) your position")
- )
- .attachCommand(new Command("emerald", "e")
- .setExecutor(Commands.createEmeraldGen)
- .setHelpMessage("Creates a emerald generator in (approximately) your position")
- )
- .attachCommand(new Command("remove", "delete", "del", "r")
- .setHelpMessage("Deletes all generators within 5 block of your position")
- )
- )
- )
- .attachCommand(new Command("diemydarling")
- .setExecutor((a, b, c, d) -> {
- Bukkit.getWorld("world")
- .getEntities()
- .stream()
- .filter(v -> v instanceof ArmorStand)
- .forEach(v -> v.remove());
- })
- )
- .register(this);
-
- getServer().getPluginManager().registerEvents(this, this);
- }
- catch (Throwable t) {
- getLogger().log(Level.SEVERE, "Failed to initialize. Config files are probably to blame", t);
- getServer().broadcastMessage("§4The bedwars plugin failed to initialize. Many, if not all parts of the plugin won't work. Check console for details and stack trace.");
- }
- }
- public void onDisable() {
- if (Game.isStarted()) Game.instance.close();
- }
+ @Override
+ public void onEnable() {
+ playerCount = Bukkit.getServer().getOnlinePlayers().size();
+ try {
+ instance = this;
+ getDataFolder().mkdir();
+ File conf = new File(getDataFolder(), "config.yml");
+ if (!conf.exists())
+ conf.createNewFile();
+ Config.load(conf);
+ File defaultFavs = new File(getDataFolder(), "default-favourites.yml");
+
+ if (!defaultFavs.exists())
+ defaultFavs.createNewFile();
+
+ File favsDir = new File(getDataFolder(), "favourites");
+
+ try {
+ Traders.instance = new Traders(new File(getDataFolder(), "traders.txt"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ YamlConfiguration sectionsConf = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "sections.yml"));
+
+ BlindnessTeamUpgrade.init(this);
+ FatigueTeamUpgrade.init(this);
+ HealTeamUpgrade.init(this);
+ EfficiencyTeamUpgrade.init();
+ ProtectionTeamUpgrade.init();
+ SharpnessTeamUpgrade.init();
+ TeamUpgradeRanks.init(this, sectionsConf);
+
+ ItemDealType.init();
+ RankedDealType.init(this, sectionsConf);
+ EnforcedRankedDealType.init();
+ RankedUpgradeDealType.init();
+ Sections.init(new File(getDataFolder(), "sections.yml"));
+ Favourites.instance = new Favourites(favsDir, defaultFavs);
+
+ updateTimer();
+
+ getServer().getWorlds().get(0).getEntitiesByClass(Villager.class).forEach(v -> {
+ v.setAI(false);
+ });
+
+ Command cmd = Command.createLiteral("bedwars", "bw");
+
+ cmd.literal("help").setExecutor(CommandExecutors.help()).string("args", false).setRecursive(true).setExecutor(CommandExecutors.help());
+ Commands.start(cmd.literal("start"));
+ Commands.stop(cmd.literal("stop"));
+
+ Commands.kill(cmd.literal("kill"));
+ Commands.revive(cmd.literal("revive"));
+
+ Command config = cmd.literal("configuration", "config", "conf");
+ Command base = config.literal("base");
+ Command generator = config.literal("generator", "gen");
+
+ Commands.baseAdd(base.literal("add"));
+ Commands.baseRemove(base.literal("remove"));
+ Commands.baseSetSpawn(base.literal("setspawn", "spawn"));
+ Commands.baseSetGenerator(base.literal("setgenerator", "generator", "gen"));
+ Commands.baseSetBed(base.literal("setbed", "bed"));
+ Commands.baseList(base.literal("list", "l"));
+
+ Commands.createDiamondGen(generator.literal("diamond"));
+ Commands.createEmeraldGen(generator.literal("emerald", "em"));
+ Commands.clearGens(generator.literal("emerald", "em"));
+
+ Commands.breakBed(cmd.literal("breakbed", "cheat", "bedishonest", "abusepowers"));
+
+ cmd.register(this);
+ // .attachCommand(new Command("respawn", "revive")
+ // .setExecutor(Commands.revive)
+ // .setHelpMessage("Respawns a spectator, if he has a bed, he is immediatly respawned"))
+ // .attachCommand(new Command("breakbed", "eliminateteam")
+ // .setExecutor(Commands.breakBed)
+ // .setHelpMessage("Destoys the bed of a team")
+ // )
+ // .attachCommand(new Command("eliminate")
+ // .setHelpMessage("Eliminates a player")
+ // )
+ // .attachCommand(new Command("killteam")
+ // .setHelpMessage("Kills all players of a team")
+ // )
+ // .attachCommand(new Command("villagertools", "villager", "trader")
+ // .setExecutor((sender, _cmd, alias, args) -> {
+ // if (args.length == 0) {
+ // if (sender instanceof Player) {
+ // Player p = (Player)sender;
+ // Traders.instance.give(p);
+ // }
+ // }
+ // })
+ // .setHelpMessage("Gives you tools to manage traders")
+ // )
+ // .register(this);
+
+ getServer().getPluginManager().registerEvents(this, this);
+ }
+ catch (Throwable t) {
+ getLogger().log(Level.SEVERE, "Failed to initialize. Config files are probably to blame", t);
+ getServer().broadcastMessage("§4The bedwars plugin failed to initialize. Many, if not all parts of the plugin won't work. Check console for details and stack trace.");
+ }
+ }
+ public void onDisable() {
+ if (Game.isStarted()) Game.instance.close();
+ }
}
diff --git a/src/main/java/me/topchetoeu/bedwars/Utility.java b/src/main/java/me/topchetoeu/bedwars/Utility.java
index 8ed101a..6f9826a 100644
--- a/src/main/java/me/topchetoeu/bedwars/Utility.java
+++ b/src/main/java/me/topchetoeu/bedwars/Utility.java
@@ -24,159 +24,211 @@ import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
-public class Utility {
- public static void sendTitle(Player p, String title, String subtitle, int fadeIn, int duration, int fadeout) {
- p.sendTitle(title, subtitle, fadeIn, duration, fadeout);
- }
- public static void broadcastTitle(String title, String subtitle, int fadeIn, int duration, int fadeout) {
- Bukkit.getOnlinePlayers().forEach(v -> sendTitle(v, title, subtitle, fadeIn, duration, fadeout));
- }
- public static boolean isParsable(String val) {
- try {
- Integer.parseInt(val);
- } catch (NumberFormatException e) {
- return false;
- }
-
- return true;
- }
-
- public static ItemStack namedItem(ItemStack i, String name) {
- ItemMeta meta = i.getItemMeta();
- meta.setDisplayName(name);
- i.setItemMeta(meta);
- return i;
- }
- public static ItemStack copyNamedItem(ItemStack i, String name) {
- i = new ItemStack(i);
- ItemMeta meta = i.getItemMeta();
- meta.setDisplayName(name);
- i.setItemMeta(meta);
- return i;
- }
- public static String getItemName(Material item) {
- return CraftItemStack.asNMSCopy(new ItemStack(item)).n();
- }
- public static String getItemName(ItemStack item) {
- if (item.getItemMeta().hasDisplayName()) return item.getItemMeta().getDisplayName();
- return CraftItemStack.asNMSCopy(item).n();
- }
- public static void takeOne(Player p, EquipmentSlot e) {
- ItemStack i = p.getInventory().getItem(e);
- if (i.getAmount() == 0) p.getInventory().setItem(e, i);
- else {
- i.setAmount(i.getAmount() - 1);
- p.getInventory().setItem(e, i);
- }
- }
-
- @SuppressWarnings({ "unchecked", "deprecation" })
- public static ItemStack deserializeItemStack(Map map) {
- String id = ((String)map.get("id")).toUpperCase();
- int amount = map.containsKey("amount") ? (Integer)map.get("amount") : 1;
-
- ItemStack item = new ItemStack(Material.getMaterial(id), amount);
-
- ItemMeta meta = item.getItemMeta();
- if (map.containsKey("displayName")) meta.setDisplayName((String)map.get("displayName"));
-
- if (map.containsKey("lore")) meta.setLore((ArrayList)map.get("lore"));
-
- if (map.containsKey("enchants")) {
- for(Entry entry : ((Map)map.get("enchants")).entrySet()) {
- Enchantment e = Enchantment.getByName(entry.getKey().toUpperCase());
-
- meta.addEnchant(e, entry.getValue(), true);
- }
- }
- if (map.containsKey("potion")) {
- Map potionMap = (Map)map.get("potion");
- String name = (String)potionMap.get("id");
- int level = (Integer)potionMap.get("level");
- int duration = (Integer)potionMap.get("duration");
-
- PotionEffectType effectType = PotionEffectType.getByName(name.toUpperCase());
-
- PotionMeta potionMeta = (PotionMeta)meta;
- potionMeta.addCustomEffect(new PotionEffect(
- effectType,
- duration, level, false
- ), false);
- potionMeta.setColor(effectType.getColor());
-
- meta = potionMeta;
- }
-
- item.setItemMeta(meta);
-
- return item;
- }
- public static Map mapifyConfig(ConfigurationSection config) {
- Map map = config.getValues(false);
- for (String key : map.keySet()) {
- Object val = map.get(key);
- if (val instanceof ConfigurationSection) {
- map.put(key, mapifyConfig((ConfigurationSection)val));
- }
- }
-
- return map;
- }
+import net.md_5.bungee.api.ChatColor;
+import net.md_5.bungee.api.chat.TranslatableComponent;
- public static boolean isBed(Block meta) {
- return meta.getBlockData() instanceof Bed;
- }
- public static boolean isWool(Block meta) {
- return meta.getType().getKey().getKey().endsWith("WOOL");
- }
- public static boolean isWool(Material meta) {
- return meta.getKey().getKey().endsWith("WOOL");
- }
+public class Utility {
+ public static void sendTitle(Player p, String title, String subtitle, int fadeIn, int duration, int fadeout) {
+ p.sendTitle(title, subtitle, fadeIn, duration, fadeout);
+ }
+ public static void broadcastTitle(String title, String subtitle, int fadeIn, int duration, int fadeout) {
+ Bukkit.getOnlinePlayers().forEach(v -> sendTitle(v, title, subtitle, fadeIn, duration, fadeout));
+ }
+ public static boolean isParsable(String val) {
+ try {
+ Integer.parseInt(val);
+ } catch (NumberFormatException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public static ItemStack namedItem(ItemStack i, String name) {
+ ItemMeta meta = i.getItemMeta();
+ meta.setDisplayName(name);
+ i.setItemMeta(meta);
+ return i;
+ }
+ public static ItemStack copyNamedItem(ItemStack i, String name) {
+ i = new ItemStack(i);
+ ItemMeta meta = i.getItemMeta();
+ meta.setDisplayName(name);
+ i.setItemMeta(meta);
+ return i;
+ }
+ public static TranslatableComponent getItemName(Material item) {
+ return new TranslatableComponent(CraftItemStack.asNMSCopy(new ItemStack(item)).n());
+ }
+ public static TranslatableComponent getItemName(ItemStack item) {
+ return new TranslatableComponent(CraftItemStack.asNMSCopy(new ItemStack(item)).n());
+ }
+ public static void takeOne(Player p, EquipmentSlot e) {
+ ItemStack i = p.getInventory().getItem(e);
+ if (i.getAmount() == 0) p.getInventory().setItem(e, i);
+ else {
+ i.setAmount(i.getAmount() - 1);
+ p.getInventory().setItem(e, i);
+ }
+ }
+
+ @SuppressWarnings({ "unchecked", "deprecation" })
+ public static ItemStack deserializeItemStack(Map map) {
+ String id = ((String)map.get("id")).toUpperCase();
+ int amount = map.containsKey("amount") ? (Integer)map.get("amount") : 1;
+
+ ItemStack item = new ItemStack(Material.getMaterial(id), amount);
+
+ ItemMeta meta = item.getItemMeta();
+ if (map.containsKey("displayName")) meta.setDisplayName((String)map.get("displayName"));
+
+ if (map.containsKey("lore")) meta.setLore((ArrayList)map.get("lore"));
+
+ if (map.containsKey("enchants")) {
+ for(Entry entry : ((Map)map.get("enchants")).entrySet()) {
+ Enchantment e = Enchantment.getByName(entry.getKey().toUpperCase());
+
+ meta.addEnchant(e, entry.getValue(), true);
+ }
+ }
+ if (map.containsKey("potion")) {
+ Map potionMap = (Map)map.get("potion");
+ String name = (String)potionMap.get("id");
+ int level = (Integer)potionMap.get("level");
+ int duration = (Integer)potionMap.get("duration");
+
+ PotionEffectType effectType = PotionEffectType.getByName(name.toUpperCase());
+
+ PotionMeta potionMeta = (PotionMeta)meta;
+ potionMeta.addCustomEffect(new PotionEffect(
+ effectType,
+ duration, level, false
+ ), false);
+ potionMeta.setColor(effectType.getColor());
+
+ meta = potionMeta;
+ }
+
+ item.setItemMeta(meta);
+
+ return item;
+ }
+ public static Map mapifyConfig(ConfigurationSection config) {
+ Map map = config.getValues(false);
+ for (String key : map.keySet()) {
+ Object val = map.get(key);
+ if (val instanceof ConfigurationSection) {
+ map.put(key, mapifyConfig((ConfigurationSection)val));
+ }
+ }
+
+ return map;
+ }
+
+ public static boolean isBed(Block meta) {
+ return meta.getBlockData() instanceof Bed;
+ }
+ public static boolean isWool(Block meta) {
+ return meta.getType().getKey().getKey().endsWith("WOOL");
+ }
+ public static boolean isWool(Material meta) {
+ return meta.getKey().getKey().endsWith("WOOL");
+ }
public static boolean isTool(Material type) {
- return type == Material.SHEARS ||
- type.getKey().getKey().endsWith("PICKAXE") ||
- type.getKey().getKey().endsWith("SHOVEL") ||
- type.getKey().getKey().endsWith("AXE");
+ return type == Material.SHEARS ||
+ type.getKey().getKey().endsWith("PICKAXE") ||
+ type.getKey().getKey().endsWith("SHOVEL") ||
+ type.getKey().getKey().endsWith("AXE");
}
public static boolean isArmor(Material type) {
- return
- type.getKey().getKey().endsWith("HELMET") ||
- type.getKey().getKey().endsWith("CHESTPLATE") ||
- type.getKey().getKey().endsWith("LEGGINGS") ||
- type.getKey().getKey().endsWith("BOOTS");
+ return
+ type.getKey().getKey().endsWith("HELMET") ||
+ type.getKey().getKey().endsWith("CHESTPLATE") ||
+ type.getKey().getKey().endsWith("LEGGINGS") ||
+ type.getKey().getKey().endsWith("BOOTS");
}
public static boolean isWeapon(Material type) {
- return
- type.getKey().getKey().endsWith("SWORD") ||
- type.getKey().getKey().endsWith("AXE");
+ return
+ type.getKey().getKey().endsWith("SWORD") ||
+ type.getKey().getKey().endsWith("AXE");
}
- public static Optional getPotionEffect(Collection p, PotionEffectType type) {
- return p.stream().filter(v -> v.getType().equals(type)).findFirst();
- }
- public static Optional getPotionEffect(LivingEntity p, PotionEffectType type) {
- return getPotionEffect(p.getActivePotionEffects(), type);
- }
-
- public static void applyPotionEffect(LivingEntity p, PotionEffect e) {
- PotionEffect eff = getPotionEffect(p, e.getType()).orElse(null);
-
- if (eff == null) p.addPotionEffect(e);
- else {
- p.removePotionEffect(e.getType());
- p.addPotionEffect(e);
- }
- }
-
- @Deprecated(since = "Don't forget to remove these")
- public static void debugMsg(Object obj) {
- if (obj == null) obj = "null";
- Bukkit.getServer().broadcastMessage(obj.toString());
- }
- @Deprecated(since = "Don't forget to remove these")
- public static void debugMsg(CommandSender p, Object obj) {
- if (obj == null) obj = "null";
- p.sendMessage(obj.toString());
- }
+ public static Optional getPotionEffect(Collection p, PotionEffectType type) {
+ return p.stream().filter(v -> v.getType().equals(type)).findFirst();
+ }
+ public static Optional getPotionEffect(LivingEntity p, PotionEffectType type) {
+ return getPotionEffect(p.getActivePotionEffects(), type);
+ }
+
+ public static void applyPotionEffect(LivingEntity p, PotionEffect e) {
+ PotionEffect eff = getPotionEffect(p, e.getType()).orElse(null);
+
+ if (eff == null) p.addPotionEffect(e);
+ else {
+ p.removePotionEffect(e.getType());
+ p.addPotionEffect(e);
+ }
+ }
+
+ @Deprecated(since = "Don't forget to remove these")
+ public static void debugMsg(Object obj) {
+ if (obj == null) obj = "null";
+ Bukkit.getServer().broadcastMessage(obj.toString());
+ }
+ @Deprecated(since = "Don't forget to remove these")
+ public static void debugMsg(CommandSender p, Object obj) {
+ if (obj == null) obj = "null";
+ p.sendMessage(obj.toString());
+ }
+ public static ChatColor bukkitToBungeeColor(org.bukkit.ChatColor bukkitChatColor) {
+ switch (bukkitChatColor) {
+ case RED:
+ return ChatColor.RED;
+ case AQUA:
+ return ChatColor.AQUA;
+ case BLACK:
+ return ChatColor.BLACK;
+ case BLUE:
+ return ChatColor.BLUE;
+ case BOLD:
+ return ChatColor.BOLD;
+ case DARK_AQUA:
+ return ChatColor.DARK_AQUA;
+ case DARK_BLUE:
+ return ChatColor.DARK_BLUE;
+ case DARK_GRAY:
+ return ChatColor.DARK_GRAY;
+ case DARK_GREEN:
+ return ChatColor.DARK_GREEN;
+ case DARK_PURPLE:
+ return ChatColor.DARK_PURPLE;
+ case DARK_RED:
+ return ChatColor.DARK_RED;
+ case GOLD:
+ return ChatColor.GOLD;
+ case GRAY:
+ return ChatColor.GRAY;
+ case GREEN:
+ return ChatColor.GREEN;
+ case ITALIC:
+ return ChatColor.ITALIC;
+ case LIGHT_PURPLE:
+ return ChatColor.LIGHT_PURPLE;
+ case MAGIC:
+ return ChatColor.MAGIC;
+ case RESET:
+ return ChatColor.RESET;
+ case STRIKETHROUGH:
+ return ChatColor.STRIKETHROUGH;
+ case UNDERLINE:
+ return ChatColor.UNDERLINE;
+ case WHITE:
+ return ChatColor.WHITE;
+ case YELLOW:
+ return ChatColor.YELLOW;
+ default:
+ return null;
+ }
+ }
}
diff --git a/src/main/java/me/topchetoeu/bedwars/commandUtility/Command.java b/src/main/java/me/topchetoeu/bedwars/commandUtility/Command.java
index 7353c11..0a59f9f 100644
--- a/src/main/java/me/topchetoeu/bedwars/commandUtility/Command.java
+++ b/src/main/java/me/topchetoeu/bedwars/commandUtility/Command.java
@@ -1,146 +1,322 @@
package me.topchetoeu.bedwars.commandUtility;
-import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
-public class Command {
- private String[] aliases;
- private String name;
- private String helpMessage;
- private CommandExecutor fallbackExecutor;
- private HashSet attachedCommands = new HashSet<>();
-
- private JavaPlugin parent = null;
-
- public String[] getAliases() {
- return aliases;
- }
-
- public String getName() {
- return name;
- }
-
- public String getHelpMessage() {
- return helpMessage;
- }
- public Command setHelpMessage(String val) {
- helpMessage = val;
- return this;
- }
-
- public CommandExecutor getFallbackExecutor() {
- return fallbackExecutor;
- }
- public Command setExecutor(CommandExecutor val) {
- fallbackExecutor = val;
- return this;
- }
-
- public Command attachCommand(Command cmd) {
- if (cmd == null) throw new RuntimeException("cmd is null");
- attachedCommands.add(cmd);
- return this;
- }
- public Command detachCommand(Command cmd) {
- if (cmd == null) throw new RuntimeException("cmd is null");
- attachedCommands.remove(cmd);
- return this;
- }
- public boolean commandAttached(Command cmd) {
- if (cmd == null) return false;
- return attachedCommands.contains(cmd);
- }
- public Command[] getAttachedCommands() {
- return attachedCommands.toArray(Command[]::new);
- }
-
- public void execute(CommandSender sender, String alias, String[] args) {
- Command cmd;
- if (args.length == 0) cmd = null;
- else cmd = getAttachedCommand(args[0]);
-
- String[] newArgs;
- if (args.length <= 1) newArgs = new String[0];
- else {
- newArgs = new String[args.length - 1];
- System.arraycopy(args, 1, newArgs, 0, args.length - 1);
- }
-
- if (cmd != null)
- cmd.execute(sender, args[0], newArgs);
- else if (fallbackExecutor != null) fallbackExecutor.execute(
- sender, this,
- alias, args
- );
- else sender.sendMessage("This command doesn't do anything :(");
- }
-
- public Command register(JavaPlugin pl) {
- if (pl == parent) throw new IllegalArgumentException("The command is already attached to the given plugin");
- if (pl == null) throw new RuntimeException("pl is null");
- parent = pl;
- pl.getCommand(name).setAliases(Arrays.asList(aliases));
- pl.getCommand(name).setExecutor(new org.bukkit.command.CommandExecutor() {
-
- @Override
- public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String alias, String[] args) {
- execute(sender, alias, args);
- return true;
- }
- });
-
- return this;
- }
-
- public Command getAttachedCommand(String alias) {
- String newAlias = alias.toLowerCase();
- for (Command command : attachedCommands) {
- if (command.name.equals(newAlias) || Arrays.stream(command.aliases).anyMatch(v -> v.equals(newAlias)))
- return command;
- }
- return null;
- }
+import me.topchetoeu.bedwars.commandUtility.args.ArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.ArgParserRes;
+import me.topchetoeu.bedwars.commandUtility.args.CollectionArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.CollectionProvider;
+import me.topchetoeu.bedwars.commandUtility.args.EnumArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.IntArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.LiteralArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.LocationArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.PlayerArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.StringArgParser;
+import me.topchetoeu.bedwars.commandUtility.args.Suggestions;
+import net.md_5.bungee.api.ChatColor;
+import net.md_5.bungee.api.chat.ComponentBuilder;
- public Command(String name, String alias) {
- this.name = name;
- this.aliases = new String[] { alias };
- }
- public Command(String name, String... aliases) {
- this.name = name;
- this.aliases = aliases;
- }
- public Command(String name, CommandExecutor executor, String... aliases) {
- this.name = name;
- this.aliases = aliases;
- this.fallbackExecutor = executor;
- }
- public Command(String name, String alias, Command... commands) {
- this.name = name;
- this.aliases = new String[] { alias };
-
- for (Command cmd : commands) {
- attachCommand(cmd);
- }
- }
- public Command(String name, String[] aliases, Command... commands) {
- this.name = name;
- this.aliases = aliases;
-
- for (Command cmd : commands) {
- attachCommand(cmd);
- }
- }
- public Command(String name, String[] aliases, CommandExecutor executor, Command... commands) {
- this.name = name;
- this.aliases = aliases;
- fallbackExecutor = executor;
-
- for (Command cmd : commands) {
- attachCommand(cmd);
- }
- }
-
+public class Command {
+ private String name;
+ private String helpMessage;
+ private CommandExecutor executor;
+ private HashSet children = new HashSet<>();
+ private ArgParser parser;
+ private boolean recursive = false;
+
+ private Set parents = new HashSet<>();
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean attachedToAnyPlugin() {
+ return parents.size() > 0;
+ }
+ public Set getParentPlugins() {
+ return Collections.unmodifiableSet(parents);
+ }
+
+ public ArgParser getParser() {
+ return parser;
+ }
+
+ public String getHelpMessage() {
+ return helpMessage;
+ }
+ public Command setHelpMessage(String val) {
+ helpMessage = val;
+ return this;
+ }
+
+ public CommandExecutor getExecutor() {
+ return executor;
+ }
+ public Command setExecutor(CommandExecutor val) {
+ executor = val;
+ return this;
+ }
+
+ public Command addChild(Command cmd) {
+ if (cmd == null) throw new RuntimeException("cmd is null");
+ children.add(cmd);
+ return cmd;
+ }
+ public Command removeChild(Command cmd) {
+ if (cmd == null) throw new RuntimeException("cmd is null");
+ children.remove(cmd);
+ return this;
+ }
+ public boolean hasChild(Command cmd) {
+ if (cmd == null) return false;
+ return children.contains(cmd);
+ }
+ public Set getChildren() {
+ return Collections.unmodifiableSet(children);
+ }
+
+ public Command setRecursive(boolean val) {
+ recursive = val;
+ return this;
+ }
+ public boolean isRecursive() {
+ return recursive;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void execute(CommandSender sender, String[] _args) {
+ Command toExecute = this;
+
+ Hashtable newArgs = new Hashtable<>();
+
+ List args = new ArrayList<>();
+ Collections.addAll(args, _args);
+
+ String err = null;
+
+ while (args.size() > 0) {
+ Command newCmd = null;
+ Set children = toExecute.getChildren();
+ if (toExecute.isRecursive()) children = Collections.singleton(toExecute);
+ for (Command cmd : children) {
+ ArgParser parser = cmd.getParser();
+ ArgParserRes res = parser.parse(sender, args);
+
+ if (res.hasError()) err = res.getError();
+ else if (res.hasSucceeded()) {
+ for (int i = 0; i < res.getTakenCount(); i++) {
+ if (args.size() == 0) break;
+ args.remove(0);
+ }
+
+ if (res.hasResult()) {
+ if (cmd.recursive) {
+ if (!newArgs.containsKey(cmd.name)) newArgs.put(cmd.name, new ArrayList<>());
+ ((List