Compare commits

...

No commits in common. "master-1.8" and "master-1.18" have entirely different histories.

77 changed files with 5729 additions and 4421 deletions

11
.gitignore vendored
View File

@ -1,3 +1,8 @@
deps *
target !.gitignore
.vscode !src
!src/*
!src/**
!deps
!deps/*.jar
!pom.xml

BIN
deps/server.jar vendored Normal file

Binary file not shown.

48
pom.xml
View File

@ -12,23 +12,45 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
</properties> </properties>
<repositories>
<repository>
<id>minecraft-libraries</id>
<name>Minecraft Libraries</name>
<url>https://libraries.minecraft.net</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.spigotmc</groupId>
<artifactId>junit</artifactId> <artifactId>spigot-api</artifactId>
<version>4.11</version> <version>1.18.1-R0.1-SNAPSHOT</version>
<scope>test</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>spigot</groupId>
<artifactId>bukkit</artifactId> <artifactId>server</artifactId>
<version>1.0</version> <version>1.0</version>
<scope>system</scope> <scope>system</scope>
<systemPath>${basedir}/deps/bukkit.jar</systemPath> <systemPath>${basedir}/deps/server.jar</systemPath>
</dependency>
<dependency>
<groupId>com.mojang</groupId>
<artifactId>brigadier</artifactId>
<version>1.0.18</version>
</dependency>
<dependency>
<groupId>com.mojang</groupId>
<artifactId>datafixerupper</artifactId>
<version>1.0.20</version>
</dependency> </dependency>
</dependencies> </dependencies>
@ -73,5 +95,13 @@
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
<resources>
<resource>
<directory>src</directory>
<includes>
<include>**/*.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>

View File

@ -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

View File

@ -2,293 +2,254 @@ package me.topchetoeu.bedwars;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.OfflinePlayer; import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import me.topchetoeu.bedwars.commandUtility.Command; import me.topchetoeu.bedwars.commands.Command;
import me.topchetoeu.bedwars.commandUtility.CommandExecutor;
import me.topchetoeu.bedwars.commandUtility.CommandExecutors;
import me.topchetoeu.bedwars.engine.BedwarsPlayer; import me.topchetoeu.bedwars.engine.BedwarsPlayer;
import me.topchetoeu.bedwars.engine.Config; import me.topchetoeu.bedwars.engine.Config;
import me.topchetoeu.bedwars.engine.Game; import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
import me.topchetoeu.bedwars.engine.TeamColor; import me.topchetoeu.bedwars.engine.TeamColor;
import me.topchetoeu.bedwars.messaging.MessageParser;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.ChatColor;
public class Commands { public class Commands {
private static File confFile = new File(Main.getInstance().getDataFolder(), "config.yml"); private static File confFile = new File(Main.getInstance().getDataFolder(), "config.yml");
@SuppressWarnings("deprecation") @SuppressWarnings("unchecked")
public static CommandExecutor kill = (CommandSender sender, Command cmd, String alias, String[] args) -> { public static Command kill(Command cmd) {
if (Game.isStarted()) { return cmd.player("players", false).setRecursive(true).setExecutor((sender, _cmd, args) -> {
for (String arg : args) { if (Game.isStarted()) {
OfflinePlayer p = Bukkit.getOfflinePlayer(arg); for (Player p : (List<Player>)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 MessageUtility.parser("commands.not-in-game").variable("player", p.getDisplayName()).parse();
}
return null;
}
else return MessageUtility.parser("commands.game-not-started").parse();
});
}
@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<Player>)args.get("players")) {
BedwarsPlayer bwp = Game.instance.getPlayer(p);
if (bwp != null) {
bwp.revive();
Bukkit.broadcastMessage("Player " + p.getName() + " revived!");
return null;
}
else return MessageUtility.parser("commands.not-in-game").variable("player", p.getDisplayName()).parse();
}
return null;
}
else return MessageUtility.parser("commands.game-not-started").parse();
});
}
public static Command start(Command cmd) {
return cmd.setExecutor((sender, _cmd, args) -> {
if (!Game.isStarted()) {
Game.start();
MessageUtility.parser("commands.start.success").send(sender);
return null;
}
else return MessageUtility.parser("commands.start.game-started").parse();
});
}
public static Command stop(Command cmd) {
return cmd.setExecutor((sender, _cmd, args) -> {
if (Game.isStarted()) {
Game.stop();
MessageUtility.parser("commands.stop.success").send(sender);
return null;
}
else return MessageUtility.parser("commands.start.game-not-started").parse();
});
}
if (p != null) { private static Command basesArg() {
BedwarsPlayer bwp = Game.instance.getPlayer(p); return Command.createCollection("team", () -> Config.instance.getColors()
.stream()
if (bwp != null) { .collect(Collectors.toMap(
bwp.kill(bwp.getPlayer().getName() + " definitely died with no admin intervention."); TeamColor::getName,
} v -> v
else sender.sendMessage("Player is not in game!"); )), false
} );
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);
if (p != null) { public static Command baseAdd(Command cmd) {
BedwarsPlayer bwp = Game.instance.getPlayer(p); 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 (bwp != null) { if (!Game.isStarted()) {
bwp.revive(); String name = args.get("name").toString().toLowerCase();
Bukkit.broadcastMessage("Player " + p.getName() + " revived!"); Material wool = (Material)args.get("wool");
} org.bukkit.ChatColor bukkitChatColor = (org.bukkit.ChatColor)args.get("color");
else sender.sendMessage("Player is not in game!"); int r = (int)args.get("red"),
} g = (int)args.get("green"),
else sender.sendMessage("Player doesn't exist!"); b = (int)args.get("blue");
}
}
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 == 3 && args[2].length() == 1) {
if (!Game.isStarted()) {
if (Utility.isParsable(args[1])) {
String name = args[0];
int woolId = Integer.parseInt(args[1]);
char chatId = args[2].charAt(0);
if (woolId >= 0 && woolId < 16) {
if (Config.instance.getColor(name.toLowerCase()) == null) {
Config.instance.getColors().add(new TeamColor(name.toLowerCase(), woolId, chatId));
Config.instance.save(confFile);
sender.sendMessage("New base was created!");
}
else sender.sendMessage("Base with this name already exists!");
}
else sender.sendMessage("woolId must be a valid number between 0 and 15!");
} else sender.sendMessage("woolId must be a valid number between 0 and 15!");
}
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 <name> <woolId> <chatId>");
};
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 <name>");
};
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<TeamColor> colors = Config.instance.getColors();
if (colors.size() != 0) {
sender.sendMessage("Bases:");
for (TeamColor color : colors) {
sender.sendMessage("§" + color.getColorId() + 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<Team> 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;
Location loc = p.getLocation(); ChatColor chatColor = Utility.bukkitToBungeeColor(bukkitChatColor);
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;
Location loc = p.getLocation(); if (Config.instance.getColor(name.toLowerCase()) == null) {
if (aligned) { Config.instance.getColors().add(new TeamColor(name, wool, Color.fromRGB(r, g, b), chatColor));
loc.setX(loc.getBlockX() + 0.5); Config.instance.save(confFile);
loc.setZ(loc.getBlockZ() + 0.5); MessageUtility.parser("commands.base-add.success").variable("base", name).send(sender);
} return null;
}
Config.instance.getEmeraldGenerators().add(loc); else return MessageUtility.parser("commands.base-add.already-exists").variable("base", name).parse();
Config.instance.save(confFile); }
else return MessageUtility.parser("commands.base-add.game-started").parse();
p.sendMessage("§aGenerator added!"); });
} }
else sender.sendMessage("§4Only a player may execute this command.");
}; public static Command baseRemove(Command cmd) {
return cmd
public static CommandExecutor _default = CommandExecutors.message("For help do /bw help"); .addChild(basesArg())
.setExecutor((sender, _cmd, args) -> {
TeamColor color = (TeamColor)args.get("team");
Config.instance.getColors().remove(color);
Config.instance.save(confFile);
MessageUtility.parser("commands.base-remove").variable("base", color.getColorName()).send(sender);
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);
MessageUtility.parser("commands.base-spawn").variable("base", color.getColorName()).send(sender);
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);
MessageUtility.parser("commands.base-generator").variable("base", color.getColorName()).send(sender);
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);
MessageUtility.parser("commands.base-bed").variable("base", color.getColorName()).send(sender);
return null;
});
// );
}
public static Command baseList(Command cmd) {
return cmd
.setExecutor((sender, _cmd, args) -> {
List<TeamColor> colors = Config.instance.getColors();
if (colors.size() != 0) {
MessageUtility.parser("commands.base-list.title").variable("count", colors.size()).send(sender);
for (TeamColor color : colors) {
MessageParser parser = MessageUtility.parser("commands.base-list.not-fully-specified");
if (color.isFullySpecified()) parser = MessageUtility.parser("commands.base-list.fully-specified");
parser
.variable("name", color.getColorName())
.variable("woolId", color.getWoolMaterial().getKey())
.variable("colorRed", color.getColor().getRed())
.variable("colorGreen", color.getColor().getGreen())
.variable("colorBlue", color.getColor().getBlue())
.send(sender);
}
}
else MessageUtility.parser("commands.base-list.no-bases").send(sender);
return null;
});
}
@SuppressWarnings("unchecked")
public static Command breakBed(Command cmd) {
return cmd
.addChild(basesArg()).setRecursive(true)
.setExecutor((sender, _cmd, args) -> {
if (!Game.isStarted()) return MessageUtility.parser("commands.game-not-started").parse();
List<TeamColor> colors = (List<TeamColor>)args.get("team");
ArrayList<Team> teams = new ArrayList<>();
for (TeamColor color : colors) {
Team team = Game.instance.getTeam(color);
if (team == null) {
return MessageUtility.parser("commands.break-bed.not-in-game").variable("team", color.getColorName()).parse();
}
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);
MessageUtility.parser("commands.generator-create.diamond").send(sender);
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);
MessageUtility.parser("commands.generator-create.emerald").send(sender);
return null;
});
}
public static Command clearGens(Command cmd) {
return cmd.setExecutor((sender, _cmd, args) -> {
Config.instance.getEmeraldGenerators().clear();
Config.instance.save(confFile);
MessageUtility.parser("commands.generator-create.clear").send(sender);
return null;
});
}
} }

View File

@ -3,91 +3,91 @@ package me.topchetoeu.bedwars;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class InventoryUtility { public class InventoryUtility {
public static boolean itemEquals(ItemStack a, ItemStack b, boolean ignoreAmount) { public static boolean itemEquals(ItemStack a, ItemStack b, boolean ignoreAmount) {
if (a == null && b == null) return true; if (a == null && b == null) return true;
if (a == null || b == null) return false; if (a == null || b == null) return false;
if (ignoreAmount) { if (ignoreAmount) {
a = a.clone(); a = a.clone();
a.setAmount(1); a.setAmount(1);
b = b.clone(); b = b.clone();
b.setAmount(1); b.setAmount(1);
return a.equals(b); return a.equals(b);
} }
else return a.equals(b); else return a.equals(b);
} }
public static ItemStack giveItem(ItemStack[] inv, ItemStack _item) { public static ItemStack giveItem(ItemStack[] inv, ItemStack _item) {
ItemStack item = _item.clone(); ItemStack item = _item.clone();
int remaining = item.getAmount(); int remaining = item.getAmount();
int maxStackSize = item.getMaxStackSize(); int maxStackSize = item.getMaxStackSize();
for (int i = 0; i < 36; i++) { for (int i = 0; i < 36; i++) {
if (itemEquals(inv[i], item, true)) { if (itemEquals(inv[i], item, true)) {
if (inv[i].getAmount() < maxStackSize) { if (inv[i].getAmount() < maxStackSize) {
int newCount = remaining + inv[i].getAmount(); int newCount = remaining + inv[i].getAmount();
if (newCount > maxStackSize) { if (newCount > maxStackSize) {
inv[i].setAmount(maxStackSize); inv[i].setAmount(maxStackSize);
remaining = newCount - maxStackSize; remaining = newCount - maxStackSize;
} }
else { else {
inv[i].setAmount(newCount); inv[i].setAmount(newCount);
return null; return null;
} }
} }
} }
} }
item.setAmount(remaining); item.setAmount(remaining);
for (int i = 0; i < 36; i++) { for (int i = 0; i < 36; i++) {
if (inv[i] == null) { if (inv[i] == null) {
inv[i] = item; inv[i] = item;
return null; return null;
} }
} }
return item; return item;
} }
public static boolean hasItem(ItemStack[] inv, ItemStack item) { public static boolean hasItem(ItemStack[] inv, ItemStack item) {
int n = 0; int n = 0;
for (int i = 0; i < inv.length; i++) { for (int i = 0; i < inv.length; i++) {
if (inv[i] != null) { if (inv[i] != null) {
if (itemEquals(inv[i], (item), true)) { if (itemEquals(inv[i], (item), true)) {
n += inv[i].getAmount(); n += inv[i].getAmount();
if (n >= item.getAmount()) { if (n >= item.getAmount()) {
return true; return true;
} }
} }
} }
} }
return false; return false;
} }
public static ItemStack takeItems(ItemStack[] inv, ItemStack item) { public static ItemStack takeItems(ItemStack[] inv, ItemStack item) {
item = item.clone(); item = item.clone();
for (int i = 0; i < inv.length; i++) { for (int i = 0; i < inv.length; i++) {
if (inv[i] != null) { if (inv[i] != null) {
if (itemEquals(inv[i], (item), true)) { if (itemEquals(inv[i], (item), true)) {
int amount = inv[i].getAmount(); int amount = inv[i].getAmount();
if (item.getAmount() > amount) { if (item.getAmount() > amount) {
item.setAmount(item.getAmount() - amount); item.setAmount(item.getAmount() - amount);
inv[i] = null; inv[i] = null;
} }
else if (item.getAmount() == amount) { else if (item.getAmount() == amount) {
inv[i] = null; inv[i] = null;
return null; return null;
} }
else if (item.getAmount() < amount) { else if (item.getAmount() < amount) {
inv[i].setAmount(inv[i].getAmount() - item.getAmount()); inv[i].setAmount(inv[i].getAmount() - item.getAmount());
return null; return null;
} }
} }
} }
} }
return item; return item;
} }
} }

View File

@ -1,18 +1,12 @@
package me.topchetoeu.bedwars; package me.topchetoeu.bedwars;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -20,12 +14,12 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import me.topchetoeu.bedwars.commandUtility.Command; import me.topchetoeu.bedwars.commands.Command;
import me.topchetoeu.bedwars.commandUtility.CommandExecutors; import me.topchetoeu.bedwars.commands.CommandExecutors;
import me.topchetoeu.bedwars.engine.AttackCooldownEradicator;
import me.topchetoeu.bedwars.engine.Config; import me.topchetoeu.bedwars.engine.Config;
import me.topchetoeu.bedwars.engine.Game; import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.trader.Favourites; import me.topchetoeu.bedwars.engine.trader.Favourites;
@ -42,274 +36,216 @@ import me.topchetoeu.bedwars.engine.trader.upgrades.FatigueTeamUpgrade;
import me.topchetoeu.bedwars.engine.trader.upgrades.HealTeamUpgrade; import me.topchetoeu.bedwars.engine.trader.upgrades.HealTeamUpgrade;
import me.topchetoeu.bedwars.engine.trader.upgrades.ProtectionTeamUpgrade; import me.topchetoeu.bedwars.engine.trader.upgrades.ProtectionTeamUpgrade;
import me.topchetoeu.bedwars.engine.trader.upgrades.SharpnessTeamUpgrade; import me.topchetoeu.bedwars.engine.trader.upgrades.SharpnessTeamUpgrade;
import me.topchetoeu.bedwars.messaging.MessageUtility;
// TODO add permissions
public class Main extends JavaPlugin implements Listener { public class Main extends JavaPlugin implements Listener {
private static Main instance; private static Main instance;
private int playerCount; private int playerCount;
public static Main getInstance() { public static Main getInstance() {
return instance; return instance;
} }
private File confFile = new File(getDataFolder(), "config.yml"); // private File confFile = new File(getDataFolder(), "config.yml");
private int getGameSize() { private int getGameSize() {
return Config.instance.getTeamSize() * Config.instance.getColors().size(); return Config.instance.getTeamSize() * Config.instance.getColors().size();
} }
int timer = 0; int timer = 0;
BukkitTask timerTask = null; BukkitTask timerTask = null;
private void stopTimer() { private void stopTimer() {
if (timerTask == null) return; if (timerTask == null) return;
Utility.broadcastTitle("Not enough players!", null, 10, 40, 5); Utility.broadcastTitle(
timerTask.cancel(); MessageUtility.parser("pre-game.not-enough-players.title").parse(),
timerTask = null; MessageUtility.parser("pre-game.not-enough-players.subtitle").parse(),
} 10, 40, 5
private void startTimer() { );
if (timerTask != null) return; timerTask.cancel();
timerTask = null;
timerTask = Bukkit.getScheduler().runTaskTimer(this, () -> { }
if (Game.isStarted()) { private void startTimer() {
stopTimer(); if (timerTask != null) return;
return;
} timerTask = Bukkit.getScheduler().runTaskTimer(this, () -> {
if (timer % 30 == 0 || timer == 15 || timer == 10) if (Game.isStarted()) {
Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 10, 40, 5); stopTimer();
else if (timer <= 5) return;
Utility.broadcastTitle("Starting in " + timer + " seconds!", null, 0, 20, 0); }
timer--; if (timer % 30 == 0 || timer == 15 || timer == 10) {
if (timer <= 0) { Utility.broadcastTitle(
Game.start(); MessageUtility.parser("pre-game.starting.title").variable("time", timer).parse(),
timerTask.cancel(); MessageUtility.parser("pre-game.starting.subtitle").variable("time", timer).parse(),
timerTask = null; 10, 40, 5
} );
}, 0, 20); }
} else if (timer <= 5) {
public void updateTimer() { Utility.broadcastTitle(
// TODO make timing configurable MessageUtility.parser("pre-game.starting.title").variable("time", timer).parse(),
if (!Game.isStarted()) { MessageUtility.parser("pre-game.starting.subtitle").variable("time", timer).parse(),
if (playerCount <= 1 || playerCount <= getGameSize() / 4) { 0, 21, 0
Utility.broadcastTitle("Not enough players", "Waiting for more...", 0, 100, 0); );
stopTimer(); }
} timer--;
else if (playerCount <= getGameSize() / 2) { if (timer <= 0) {
timer = 60; Game.start();
startTimer(); timerTask.cancel();
} timerTask = null;
else if (playerCount <= getGameSize() - 1) { }
timer = 60; }, 0, 20);
startTimer(); }
} public void updateTimer() {
else { // TODO make timing configurable
timer = 15; if (!Game.isStarted()) {
startTimer(); if (playerCount <= 1 || playerCount <= getGameSize() / 4) {
} stopTimer();
} }
} else if (playerCount <= getGameSize() / 2) {
timer = 60;
@EventHandler startTimer();
private void onJoin(PlayerJoinEvent e) { }
playerCount++; else if (playerCount <= getGameSize() - 1) {
e.getPlayer().setGameMode(GameMode.SPECTATOR); timer = 60;
updateTimer(); startTimer();
} }
@EventHandler else {
private void onLeave(PlayerQuitEvent e) { timer = 15;
playerCount--; startTimer();
updateTimer(); }
} }
}
@EventHandler
private void onFoodLost(FoodLevelChangeEvent e) { @EventHandler
e.setCancelled(true); private void onJoin(PlayerJoinEvent e) {
} playerCount++;
e.getPlayer().setGameMode(GameMode.SPECTATOR);
@SuppressWarnings("deprecation") updateTimer();
@Override }
public void onEnable() { @EventHandler
playerCount = Bukkit.getServer().getOnlinePlayers().size(); private void onLeave(PlayerQuitEvent e) {
try { playerCount--;
instance = this; updateTimer();
getDataFolder().mkdir(); }
File conf = new File(getDataFolder(), "config.yml");
if (!conf.exists()) @EventHandler
try { private void onFoodLost(FoodLevelChangeEvent e) {
YamlConfiguration.loadConfiguration( e.setCancelled(true);
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"));
BlindnessTeamUpgrade.init(this); @Override
FatigueTeamUpgrade.init(this); public void onEnable() {
HealTeamUpgrade.init(this); playerCount = Bukkit.getServer().getOnlinePlayers().size();
EfficiencyTeamUpgrade.init(); try {
ProtectionTeamUpgrade.init(); instance = this;
SharpnessTeamUpgrade.init(); getDataFolder().mkdir();
TeamUpgradeRanks.init(this, sectionsConf); File conf = new File(getDataFolder(), "config.yml");
if (!conf.exists())
ItemDealType.init(); conf.createNewFile();
RankedDealType.init(this, sectionsConf); Config.load(conf);
EnforcedRankedDealType.init(); File defaultFavourites = new File(getDataFolder(), "default-favourites.yml");
RankedUpgradeDealType.init();
Sections.init(new File(getDataFolder(), "sections.yml")); MessageUtility.load(new File(getDataFolder(), "messages.yml"));
Favourites.instance = new Favourites(favsDir, defaultFavs);
if (!defaultFavourites.exists())
updateTimer(); defaultFavourites.createNewFile();
getServer().getWorlds().get(0).getEntitiesByClass(Villager.class).forEach(v -> { File favsDir = new File(getDataFolder(), "favourites");
net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) v).getHandle();
nmsEntity.b(true); // Disables its AI try {
}); Traders.instance = new Traders(new File(getDataFolder(), "traders.txt"));
} catch (IOException e) {
Command cmd = new Command("bedwars", "bw").setExecutor(Commands._default); e.printStackTrace();
cmd }
.attachCommand(new Command("help")
.setExecutor(CommandExecutors.help(cmd)) AttackCooldownEradicator.init(this);
.setHelpMessage("Shows help for the command")
) YamlConfiguration sectionsConf = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "sections.yml"));
.attachCommand(new Command("start")
.setExecutor(Commands.start) BlindnessTeamUpgrade.init(this);
.setHelpMessage("Starts the game") FatigueTeamUpgrade.init(this);
) HealTeamUpgrade.init(this);
.attachCommand(new Command("stop") EfficiencyTeamUpgrade.init();
.setExecutor(Commands.stop) ProtectionTeamUpgrade.init();
.setHelpMessage("Stops the game, noone wins") SharpnessTeamUpgrade.init();
) TeamUpgradeRanks.init(this, sectionsConf);
.attachCommand(new Command("respawn", "revive")
.setExecutor(Commands.revive) ItemDealType.init();
.setHelpMessage("Respawns a spectator, if he has a bed, he is immediatly respawned")) RankedDealType.init(this, sectionsConf);
.attachCommand(new Command("breakbed", "eliminateteam") EnforcedRankedDealType.init();
.setExecutor(Commands.breakBed) RankedUpgradeDealType.init();
.setHelpMessage("Destoys the bed of a team") Sections.init(new File(getDataFolder(), "sections.yml"));
) Favourites.instance = new Favourites(favsDir, defaultFavourites);
.attachCommand(new Command("eliminate")
.setHelpMessage("Eliminates a player") updateTimer();
)
.attachCommand(new Command("kill") getServer().getWorlds().get(0).getEntitiesByClass(Villager.class).forEach(v -> {
.setExecutor(Commands.kill) v.setAI(false);
.setHelpMessage("Kills a player") });
)
.attachCommand(new Command("killteam") Command cmd = Command.createLiteral("bedwars", "bw").permission("bedwars");
.setHelpMessage("Kills all players of a team")
) cmd.literal("help").permission("bedwars.help").setExecutor(CommandExecutors.help()).string("args", false).setRecursive(true).setExecutor(CommandExecutors.help());
.attachCommand(new Command("villagertools", "villager", "trader") Commands.start(cmd.literal("start")).permission("bedwars.control.start");
.setExecutor((sender, _cmd, alias, args) -> { Commands.stop(cmd.literal("stop")).permission("bedwars.control.stop");
if (args.length == 0) {
if (sender instanceof Player) { Commands.kill(cmd.literal("kill")).permission("bedwars.cheat.kill");
Player p = (Player)sender; Commands.revive(cmd.literal("revive")).permission("bedwars.cheat.revive");
p.getInventory().addItem(Utility.namedItem(new ItemStack(Material.MONSTER_EGG), "§rTrader spawner")); Command config = cmd.literal("configuration", "config", "conf").permission("bedwars.conf");
p.getInventory().addItem(Utility.namedItem(new ItemStack(Material.STICK), "§rTrader eradicator")); Command base = config.literal("base").permission("bedwars.conf.bases");
} Command generator = config.literal("generator", "gen").permission("bedwars.conf.generators");
}
}) Commands.baseAdd(base.literal("add")).permission("bedwars.config.bases.add");
.setHelpMessage("Gives you tools to manage traders") Commands.baseRemove(base.literal("remove")).permission("bedwars.config.bases.remove");
) Commands.baseSetSpawn(base.literal("setspawn", "spawn")).permission("bedwars.config.bases.setspawn");
.attachCommand(new Command("config", "conf", "settings") Commands.baseSetGenerator(base.literal("setgenerator", "generator", "gen")).permission("bedwars.config.bases.setgenerator");
.setExecutor(Commands._default) Commands.baseSetBed(base.literal("setbed", "bed")).permission("bedwars.config.bases.setbed");
.setHelpMessage("Command for configuring the map") Commands.baseList(base.literal("list", "l")).permission("bedwars.config.bases.list");
.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") Commands.createDiamondGen(generator.literal("diamond")).permission("bedwars.config.generators.diamond");
) Commands.createEmeraldGen(generator.literal("emerald", "em")).permission("bedwars.config.generators.emerald");
.attachCommand(new Command("base", "b") Commands.clearGens(generator.literal("clear")).permission("bedwars.config.generators.clear");
.setExecutor(Commands._default)
.setHelpMessage("Command for configuring separate bases") Commands.breakBed(cmd.literal("breakbed", "cheat", "bedishonest", "abusepowers")).permission("bedwars.config.cheat.breakbed");
.attachCommand(new Command("new", "add", "create", "c") cmd.literal("villagertools", "villagers", "traders")
.setExecutor(Commands.baseAdd) .setHelpMessage("Gives you tools to manage traders")
.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'") .permission("bedwars.villagertools")
) .setExecutor((sender, _cmd, args) -> {
.attachCommand(new Command("remove", "delete", "del", "d") if (sender instanceof Player) {
.setExecutor(Commands.baseRemove) Player p = (Player)sender;
.setHelpMessage("Removes a base with the selected name") Traders.instance.give(p);
) return null;
.attachCommand(new Command("setbed", "bed", "b") }
.setExecutor(Commands.baseSetBed) else return MessageUtility.parser("commands.for-players").parse();
.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") cmd.register(this);
.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("respawn", "revive")
) // .setExecutor(Commands.revive)
.attachCommand(new Command("setspawn", "spawn", "s") // .setHelpMessage("Respawns a spectator, if he has a bed, he is immediately respawned"))
.setExecutor(Commands.baseSetSpawn) // .attachCommand(new Command("breakbed", "eliminateteam")
.setHelpMessage("Sets the location where players of the team will respawn") // .setExecutor(Commands.breakBed)
) // .setHelpMessage("Destroys the bed of a team")
.attachCommand(new Command("list", "l") // )
.setExecutor(Commands.baseList) // .attachCommand(new Command("eliminate")
.setHelpMessage("Lists all bases") // .setHelpMessage("Eliminates a player")
) // )
) // .attachCommand(new Command("killteam")
.attachCommand(new Command("generator", "gen", "g") // .setHelpMessage("Kills all players of a team")
.setExecutor(Commands._default) // )
.setHelpMessage("Command for configuring the global generators") //
.attachCommand(new Command("diamond", "d") // .register(this);
.setExecutor(Commands.createDiamondGen)
.setHelpMessage("Creates a diamond generator in (approximately) your position") getServer().getPluginManager().registerEvents(this, this);
) }
.attachCommand(new Command("emerald", "e") catch (Throwable t) {
.setExecutor(Commands.createEmeraldGen) getLogger().log(Level.SEVERE, "Failed to initialize. Config files are probably to blame", t);
.setHelpMessage("Creates a emerald generator in (approximately) your position") 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.");
) }
.attachCommand(new Command("remove", "delete", "del", "r") }
.setHelpMessage("Deletes all generators within 5 block of your position") public void onDisable() {
) if (Game.isStarted()) Game.instance.close();
) }
)
.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();
}
} }

View File

@ -4,175 +4,240 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Optional; import java.util.Optional;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.Bed;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import net.minecraft.server.v1_8_R3.ChatComponentText; import net.md_5.bungee.api.ChatColor;
import net.minecraft.server.v1_8_R3.EntityPlayer; import net.md_5.bungee.api.chat.BaseComponent;
import net.minecraft.server.v1_8_R3.IChatBaseComponent; import net.md_5.bungee.api.chat.ComponentBuilder;
import net.minecraft.server.v1_8_R3.PacketPlayOutTitle; import net.md_5.bungee.api.chat.TranslatableComponent;
import net.minecraft.server.v1_8_R3.PacketPlayOutTitle.EnumTitleAction;
public class Utility { public class Utility {
public static void sendTitle(Player p, BaseComponent[] title, BaseComponent[] subtitle, int fadeIn, int duration, int fadeout) {
String _title = title == null ? null : BaseComponent.toLegacyText(title);
String _subtitle = subtitle == null ? null : BaseComponent.toLegacyText(subtitle);
p.sendTitle(_title, _subtitle, fadeIn, duration, fadeout);
}
public static void broadcastTitle(BaseComponent[] title, BaseComponent[] 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 BaseComponent[] getItemName(Material item) {
return getItemName(new ItemStack(item));
}
public static BaseComponent[] getItemName(ItemStack item) {
if (item.getItemMeta().getDisplayName() != null && !item.getItemMeta().getDisplayName().isEmpty())
return new ComponentBuilder().appendLegacy(item.getItemMeta().getDisplayName()).create();
return new ComponentBuilder()
.append(new TranslatableComponent(CraftItemStack.asNMSCopy(item).n()))
.reset()
.create();
}
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<String, Object> 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<String>)map.get("lore"));
if (map.containsKey("enchants")) {
for(Entry<String, Integer> entry : ((Map<String, Integer>)map.get("enchants")).entrySet()) {
Enchantment e = Enchantment.getByName(entry.getKey().toUpperCase());
meta.addEnchant(e, entry.getValue(), true);
}
}
if (map.containsKey("potion")) {
Map<String, Object> potionMap = (Map<String, Object>)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<String, Object> mapifyConfig(ConfigurationSection config) {
Map<String, Object> 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;
}
private static IChatBaseComponent getText(String text) { public static boolean isBed(Block meta) {
return new ChatComponentText(text); return meta.getBlockData() instanceof Bed;
} }
public static boolean isWool(Block meta) {
public static void sendTitle(Player p, String title, String subtitle, int fadein, int duration, int fadeout) { return meta.getType().getKey().getKey().endsWith("_wool");
EntityPlayer handle = ((CraftPlayer)p).getHandle(); }
public static boolean isWool(Material meta) {
handle.playerConnection.sendPacket(new PacketPlayOutTitle( return meta.getKey().getKey().endsWith("_wool");
EnumTitleAction.TIMES, null, fadein, duration, fadeout }
)); public static boolean isTool(Material type) {
if (subtitle == null) { return type == Material.SHEARS ||
subtitle = ""; type.getKey().getKey().endsWith("_pickaxe") ||
} type.getKey().getKey().endsWith("_shovel") ||
if (title == null) { type.getKey().getKey().endsWith("_axe");
title = ""; }
} public static boolean isArmor(Material type) {
handle.playerConnection.sendPacket(new PacketPlayOutTitle( return
EnumTitleAction.SUBTITLE, getText(subtitle) type.getKey().getKey().endsWith("_helmet") ||
)); type.getKey().getKey().endsWith("_chestplate") ||
handle.playerConnection.sendPacket(new PacketPlayOutTitle( type.getKey().getKey().endsWith("_leggings") ||
EnumTitleAction.TITLE, getText(title) type.getKey().getKey().endsWith("_boots");
)); }
} public static boolean isWeapon(Material type) {
public static void broadcastTitle(String title, String subtitle, int fadein, int duration, int fadeout) { return
Bukkit.getOnlinePlayers().forEach(v -> sendTitle(v, title, subtitle, fadein, duration, fadeout)); type.getKey().getKey().endsWith("_sword") ||
} type.getKey().getKey().endsWith("_axe");
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) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(new ItemStack(item));
return nmsStack.getItem().a(nmsStack);
}
public static String getItemName(ItemStack item) {
if (item.getItemMeta().hasDisplayName()) return item.getItemMeta().getDisplayName();
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
return nmsStack.getItem().a(nmsStack);
}
@SuppressWarnings("unchecked")
public static ItemStack deserializeItemStack(Map<String, Object> map) {
String id = ((String)map.get("id")).toUpperCase();
int amount = map.containsKey("amount") ? (Integer)map.get("amount") : 1;
short damage = (short)(map.containsKey("damage") ? (Integer)map.get("damage") : 0);
ItemStack item = new ItemStack(Material.getMaterial(id), amount, damage);
ItemMeta meta = item.getItemMeta();
if (map.containsKey("displayName")) meta.setDisplayName((String)map.get("displayName"));
if (map.containsKey("lore")) meta.setLore((ArrayList<String>)map.get("lore"));
if (map.containsKey("enchants")) {
for(Entry<String, Integer> entry : ((Map<String, Integer>)map.get("enchants")).entrySet()) {
Enchantment e = Enchantment.getByName(entry.getKey().toUpperCase());
meta.addEnchant(e, entry.getValue(), true);
}
}
if (map.containsKey("potion")) {
Map<String, Object> potionMap = (Map<String, Object>)map.get("potion");
String name = (String)potionMap.get("id");
int level = (Integer)potionMap.get("level");
int duration = (Integer)potionMap.get("duration");
boolean splash = potionMap.containsKey("splash") && (boolean)potionMap.get("splash");
PotionEffectType effectType = PotionEffectType.getByName(name.toUpperCase());
PotionMeta potionMeta = (PotionMeta)meta;
potionMeta.addCustomEffect(new PotionEffect(
effectType,
duration, level, false
), false);
Potion pot = new Potion(PotionType.getByEffect(effectType), 1);
if (splash) pot = pot.splash();
pot.apply(item);
meta = potionMeta;
}
item.setItemMeta(meta);
return item;
}
public static Map<String, Object> mapifyConfig(ConfigurationSection config) {
Map<String, Object> 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 Optional<PotionEffect> getPotionEffect(Collection<PotionEffect> p, PotionEffectType type) {
return p.stream().filter(v -> v.getType().equals(type)).findFirst(); public static Optional<PotionEffect> getPotionEffect(Collection<PotionEffect> p, PotionEffectType type) {
} return p.stream().filter(v -> v.getType().equals(type)).findFirst();
public static Optional<PotionEffect> getPotionEffect(LivingEntity p, PotionEffectType type) { }
return getPotionEffect(p.getActivePotionEffects(), type); public static Optional<PotionEffect> 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); public static void applyPotionEffect(LivingEntity p, PotionEffect e) {
PotionEffect eff = getPotionEffect(p, e.getType()).orElse(null);
if (eff == null) p.addPotionEffect(e);
else { if (eff == null) p.addPotionEffect(e);
p.removePotionEffect(e.getType()); else {
p.addPotionEffect(e); p.removePotionEffect(e.getType());
} p.addPotionEffect(e);
} }
}
@Deprecated(since = "Don't forget to remove these")
public static void debugMsg(Object obj) { @Deprecated(since = "Don't forget to remove these")
if (obj == null) obj = "null"; public static void debugMsg(Object obj) {
Bukkit.getServer().broadcastMessage(obj.toString()); 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) { @Deprecated(since = "Don't forget to remove these")
if (obj == null) obj = "null"; public static void debugMsg(CommandSender p, Object obj) {
p.sendMessage(obj.toString()); 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;
}
}
} }

View File

@ -1,147 +0,0 @@
package me.topchetoeu.bedwars.commandUtility;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.commons.lang.NullArgumentException;
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<Command> 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 NullArgumentException("cmd");
attachedCommands.add(cmd);
return this;
}
public Command detachCommand(Command cmd) {
if (cmd == null) throw new NullArgumentException("cmd");
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 NullArgumentException("pl");
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;
}
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);
}
}
}

View File

@ -1,7 +0,0 @@
package me.topchetoeu.bedwars.commandUtility;
import org.bukkit.command.CommandSender;
public interface CommandExecutor {
void execute(CommandSender sender, Command cmd, String alias, String[] args);
}

View File

@ -1,62 +0,0 @@
package me.topchetoeu.bedwars.commandUtility;
import org.bukkit.command.CommandSender;
public class CommandExecutors {
private static String join(String[] arr, String separator) {
if (arr.length == 0) return "";
if (arr.length == 1) return arr[0];
String res = arr[0];
for (int i = 1; i < arr.length; i++) {
res += separator + arr[i];
}
return res;
}
public static CommandExecutor help(Command mainCmd) {
return new CommandExecutor() {
@Override
public void execute(CommandSender sender, Command cmd, String alias, String[] args) {
Command currCmd = mainCmd;
String path = "/" + mainCmd.getName();
for (String arg : args) {
currCmd = currCmd.getAttachedCommand(arg);
if (currCmd == null) {
String msg = "Help can't be provided for the command.";
sender.sendMessage(msg);
return;
}
path += " " + currCmd.getName();
}
sender.sendMessage(path + ": " + (currCmd.getHelpMessage() == null ?
"no help provided" :
currCmd.getHelpMessage())
);
if (currCmd.getAliases().length != 0)
sender.sendMessage("Aliases: " + join(currCmd.getAliases(), ", "));
if (currCmd.getAttachedCommands().length > 0) {
sender.sendMessage("Commands: ");
for (Command subCmd : currCmd.getAttachedCommands()) {
sender.sendMessage(path + " " + subCmd.getName() + ": " + subCmd.getHelpMessage());
}
}
}
};
}
public static CommandExecutor message(String msg) {
return new CommandExecutor() {
@Override
public void execute(CommandSender sender, Command cmd, String alias, String[] args) {
sender.sendMessage(msg);
}
};
}
}

View File

@ -0,0 +1,341 @@
package me.topchetoeu.bedwars.commands;
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;
import me.topchetoeu.bedwars.commands.args.ArgParser;
import me.topchetoeu.bedwars.commands.args.ArgParserRes;
import me.topchetoeu.bedwars.commands.args.CollectionArgParser;
import me.topchetoeu.bedwars.commands.args.CollectionProvider;
import me.topchetoeu.bedwars.commands.args.EnumArgParser;
import me.topchetoeu.bedwars.commands.args.IntArgParser;
import me.topchetoeu.bedwars.commands.args.LiteralArgParser;
import me.topchetoeu.bedwars.commands.args.LocationArgParser;
import me.topchetoeu.bedwars.commands.args.PlayerArgParser;
import me.topchetoeu.bedwars.commands.args.StringArgParser;
import me.topchetoeu.bedwars.commands.args.Suggestions;
import me.topchetoeu.bedwars.permissions.Permissions;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class Command {
private String name;
private String helpMessage;
private CommandExecutor executor;
private HashSet<Command> children = new HashSet<>();
private ArgParser parser;
private boolean recursive = false;
private String requiredPermission = null;
private Set<JavaPlugin> parents = new HashSet<>();
public String getName() {
return name;
}
public boolean attachedToAnyPlugin() {
return parents.size() > 0;
}
public Set<JavaPlugin> 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 String getRequiredPermission() {
return requiredPermission;
}
public Command permission(String wildcard) {
requiredPermission = wildcard;
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<Command> 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<String, Object> newArgs = new Hashtable<>();
List<String> args = new ArrayList<>();
Collections.addAll(args, _args);
String err = null;
while (args.size() > 0) {
Command newCmd = null;
Set<Command> 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<Object>)newArgs.get(cmd.name)).add(res.getResult());
}
else newArgs.put(cmd.name, res.getResult());
}
newCmd = cmd;
if (cmd.requiredPermission != null) {
if (!Permissions.hasPermission(sender, cmd.requiredPermission))
err = "You don't have enough permissions to do that.";
}
break;
}
}
if (newCmd == null) {
toExecute = null;
break;
}
toExecute = newCmd;
if (err != null) break;
}
if (err == null) {
if (toExecute == null) err = "Invalid command syntax.";
else if (toExecute.getExecutor() == null) err = "Incomplete command.";
}
if (err != null) sender.spigot().sendMessage(new ComponentBuilder()
.append("Error: ")
.color(ChatColor.DARK_RED)
.append(err)
.color(ChatColor.RED)
.create()
);
else {
if (toExecute.isRecursive() && !newArgs.containsKey(toExecute.name)) newArgs.put(toExecute.name, new ArrayList<>());
BaseComponent[] _err = toExecute.getExecutor().execute(sender, this, newArgs);
if (_err != null && _err.length > 0) sender.spigot().sendMessage(new ComponentBuilder()
.append("Error: ")
.color(ChatColor.DARK_RED)
.append(err)
.reset()
.create()
);
}
}
public List<String> tabComplete(CommandSender sender, String[] _args) {
Command toComplete = this;
List<String> args = new ArrayList<>();
Collections.addAll(args, _args);
int index = 1;
while (args.size() > 0) {
boolean found = false;
index++;
for (Command cmd : toComplete.children) {
ArgParser parser = cmd.getParser();
ArgParserRes res = parser.parse(sender, args);
if (res.hasSucceeded()) {
for (int i = 0; i < res.getTakenCount(); i++) {
if (args.size() == 0) break;
args.remove(0);
}
toComplete = cmd;
found = true;
break;
}
}
if (!found) break;
}
if (args.size() == 0) return null;
Suggestions suggestions = new Suggestions();
for (Command cmd : toComplete.children) {
cmd.getParser().addCompleteSuggestions(sender, args, suggestions);
}
if (suggestions.hasError() && !suggestions.getSuggestions().contains(args.get(0))) {
sender.spigot().sendMessage(new ComponentBuilder()
.append("Error (argument %d): ".formatted(index + 1))
.color(ChatColor.DARK_RED)
.append(suggestions.getError())
.color(ChatColor.RED)
.create()
);
return null;
}
else {
List<String> _suggestions = new ArrayList<>(suggestions.getSuggestions());
return _suggestions;
}
}
public Command register(JavaPlugin pl) {
if (!(parser instanceof LiteralArgParser))
throw new IllegalArgumentException("Only a command with a literal parser may be registered.");
if (parents.contains(pl)) throw new IllegalArgumentException("The command is already attached to the given plugin");
if (pl == null) throw new RuntimeException("pl is null");
parents.add(pl);
LiteralArgParser parser = (LiteralArgParser)this.parser;
String name = parser.getLiteral();
pl.getCommand(name).setAliases(parser.getAliases());
pl.getCommand(name).setExecutor((sender, cmd, alias, args) -> {
execute(sender, args);
return true;
});
pl.getCommand(name).setTabCompleter((sender, cmd, alias, args) -> {
return tabComplete(sender, args);
});
return this;
}
public Command(String name, ArgParser parser) {
this.name = name;
this.parser = parser;
}
public Command literal(String name) {
Command cmd = createLiteral(name);
addChild(cmd);
return cmd;
}
public Command literal(String name, String ...aliases) {
Command cmd = createLiteral(name, aliases);
addChild(cmd);
return cmd;
}
public Command location(String name) {
Command cmd = createLocation(name);
addChild(cmd);
return cmd;
}
public Command _enum(String name, Class<? extends Enum<?>> enumType, boolean caseInsensitive) {
Command cmd = createEnum(name, enumType, caseInsensitive);
addChild(cmd);
return cmd;
}
public Command player(String name, boolean caseInsensitive) {
Command cmd = createPlayer(name, caseInsensitive);
addChild(cmd);
return cmd;
}
public Command string(String name, boolean greedy) {
Command cmd = createString(name, greedy);
addChild(cmd);
return cmd;
}
public Command _int(String name) {
Command cmd = createInt(name);
addChild(cmd);
return cmd;
}
public Command collection(String name, SimpleCollectionQuery query, boolean caseInsensitive) {
Command cmd = createCollection(name, query, caseInsensitive);
addChild(cmd);
return cmd;
}
public Command collection(String name, CollectionProvider provider, boolean caseInsensitive) {
Command cmd = createCollection(name, provider, caseInsensitive);
addChild(cmd);
return cmd;
}
public static Command createCollection(String name, SimpleCollectionQuery query, boolean caseInsensitive) {
return new Command(name, new CollectionArgParser(
() -> query.get().stream().collect(Collectors.toMap(v->v, v->v)),
caseInsensitive)
);
}
public static Command createCollection(String name, CollectionProvider provider, boolean caseInsensitive) {
return new Command(name, new CollectionArgParser(provider, caseInsensitive));
}
public static Command createPlayer(String name, boolean caseInsensitive) {
return new Command(name, new PlayerArgParser(caseInsensitive));
}
public static Command createEnum(String name, Class<? extends Enum<?>> enumType, boolean caseInsensitive) {
return new Command(name, new EnumArgParser(enumType, caseInsensitive));
}
public static Command createString(String name, boolean greedy) {
return new Command(name, new StringArgParser(greedy));
}
public static Command createInt(String name) {
return new Command(name, new IntArgParser());
}
public static Command createLocation(String name) {
return new Command(name, new LocationArgParser());
}
public static Command createLiteral(String lit) {
return new Command(lit, new LiteralArgParser(lit));
}
public static Command createLiteral(String lit, String ...aliases) {
return new Command(lit, new LiteralArgParser(lit, aliases));
}
public interface SimpleCollectionQuery {
Collection<String> get();
}
}

View File

@ -0,0 +1,11 @@
package me.topchetoeu.bedwars.commands;
import java.util.Map;
import org.bukkit.command.CommandSender;
import net.md_5.bungee.api.chat.BaseComponent;
public interface CommandExecutor {
BaseComponent[] execute(CommandSender sender, Command cmd, Map<String, Object> args);
}

View File

@ -0,0 +1,96 @@
package me.topchetoeu.bedwars.commands;
import java.util.ArrayList;
import java.util.List;
import me.topchetoeu.bedwars.commands.args.LiteralArgParser;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class CommandExecutors {
// private static List<String> getSyntaxes(Command cmd) {
// ArrayList<String> syntaxes = new ArrayList<>();
// for (Command child : cmd.getChildren()) {
// ArgParser parser = child.getParser();
// if (parser instanceof LiteralArgParser) {
// }
// }
// return null;
// }
@SuppressWarnings("unchecked")
public static CommandExecutor help() {
return (sender, cmd, _args) -> {
List<String> args = (List<String>)_args.get("args");
if (args == null) args = new ArrayList<>();
String path = "/" + cmd.getName();
Command currCmd = cmd;
while (args.size() > 0) {
Command next = null;
for (Command child : currCmd.getChildren()) {
if (child.getParser() instanceof LiteralArgParser && child.getParser().parse(sender, args).hasSucceeded()) {
next = child;
break;
}
}
if (next == null) break;
currCmd = next;
path += " " + args.get(0);
args.remove(0);
}
cmd = currCmd;
LiteralArgParser cmdParser = (LiteralArgParser)cmd.getParser();
sender.spigot().sendMessage(new ComponentBuilder()
.append("Help for %s: ".formatted(path))
.bold(true)
.create()
);
if (cmd.getHelpMessage() != null) sender.spigot().sendMessage(new ComponentBuilder()
.append(" " + cmd.getHelpMessage())
.create()
);
sender.spigot().sendMessage(new ComponentBuilder()
.append(" Aliases: ")
.bold(true)
.append(String.join(", ", cmdParser.getAliases()))
.bold(false)
.create()
);
sender.spigot().sendMessage(new ComponentBuilder()
.append(" Subcommands: ")
.bold(true)
.create()
);
for (Command child : currCmd.getChildren()) {
if (child.getParser() instanceof LiteralArgParser) {
sender.spigot().sendMessage(new ComponentBuilder()
.append(" %s: ".formatted(((LiteralArgParser)child.getParser()).getLiteral()))
.bold(true)
.append(child.getHelpMessage() != null ? child.getHelpMessage() : "No help provided.")
.bold(false)
.create()
);
}
}
return null;
};
}
public static CommandExecutor message(String msg) {
return (sender, cmd, args) -> {
sender.sendMessage(msg);
return null;
};
}
}

View File

@ -0,0 +1,10 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.List;
import org.bukkit.command.CommandSender;
public interface ArgParser {
ArgParserRes parse(CommandSender sender, List<String> remainingArgs);
void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions suggestions);
}

View File

@ -0,0 +1,71 @@
package me.topchetoeu.bedwars.commands.args;
public class ArgParserRes {
private int takenCount;
private Object res;
private boolean failed;
private String error;
public int getTakenCount() {
return takenCount;
}
public Object getResult() {
return res;
}
public String getError() {
return error;
}
public boolean takenAny() {
return takenCount > 0;
}
public boolean hasResult() {
return res != null;
}
public boolean hasFailed() {
return failed;
}
public boolean hasSucceeded() {
return !failed;
}
public boolean hasError() {
return error != null && !error.isEmpty();
}
private ArgParserRes(int takenCount, Object res, String error, boolean failed) {
this.takenCount = takenCount;
this.res = res;
this.failed = failed;
this.error = error;
}
public static ArgParserRes error(String error) {
if (error == null || error.isEmpty()) error = "An error ocurred while paring the arguments";
return new ArgParserRes(0, null, error, true);
}
public static ArgParserRes fail() {
return new ArgParserRes(0, null, null, true);
}
public static ArgParserRes takenNone() {
return takenNone(null);
}
public static ArgParserRes takenOne() {
return takenOne(null);
}
public static ArgParserRes takenMany(int count) {
return takenMany(count, null);
}
public static ArgParserRes takenNone(Object res) {
return new ArgParserRes(0, res, null, false);
}
public static ArgParserRes takenOne(Object res) {
return new ArgParserRes(1, res, null, false);
}
public static ArgParserRes takenMany(int count, Object res) {
if (count < 1) return takenNone(res);
return new ArgParserRes(count, res, null, false);
}
}

View File

@ -0,0 +1,61 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.List;
import java.util.Map;
import org.bukkit.command.CommandSender;
public class CollectionArgParser implements ArgParser {
private final boolean caseInsensitive;
private final CollectionProvider provider;
public boolean isCaseInsensitive() {
return caseInsensitive;
}
public boolean isCaseSensitive() {
return !caseInsensitive;
}
public CollectionProvider getProvider() {
return provider;
}
@Override
public ArgParserRes parse(CommandSender sender, List<String> remainingArgs) {
String arg = remainingArgs.get(0);
Map<String, Object> map = provider.get();
if (caseInsensitive) arg = arg.toLowerCase();
if (map.containsKey(arg)) return ArgParserRes.takenOne(map.get(arg));
else return ArgParserRes.error("Unknown element '" + arg + "'.");
}
public CollectionArgParser addElement(String element, Object parsesTo) {
if (caseInsensitive) element = element.toLowerCase();
Map<String, Object> map = provider.get();
map.put(element, parsesTo);
return this;
}
public CollectionArgParser addElements(Map<String, Object> parseTable) {
for (Map.Entry<String, Object> a : parseTable.entrySet()) {
if (caseInsensitive) addElement(a.getKey().toLowerCase(), a.getValue());
else addElement(a.getKey(), a.getValue());
}
return this;
}
@Override
public void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions suggestions) {
String arg;
if (caseInsensitive) arg = args.get(0).toLowerCase();
else arg = args.get(0);
Map<String, Object> map = provider.get();
List<String> _suggestions = map.keySet().stream().filter(v -> v.startsWith(arg)).toList();
suggestions.addSuggestions(_suggestions);
if (_suggestions.size() == 0) suggestions.error("Unknown element '" + arg + "'.");
}
public CollectionArgParser(CollectionProvider provider, boolean caseInsensitive) {
this.provider = provider;
this.caseInsensitive = caseInsensitive;
}
}

View File

@ -0,0 +1,7 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.Map;
public interface CollectionProvider {
Map<String, Object> get();
}

View File

@ -0,0 +1,24 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.Hashtable;
import java.util.Map;
public class EnumArgParser extends StaticCollectionArgParser {
private static Map<String, Object> getCol(Class<? extends Enum<?>> enumType, boolean caseInsensitive) {
Map<String, Object> map = new Hashtable<>();
if (enumType.getEnumConstants() != null) {
for (Enum<?> c : enumType.getEnumConstants()) {
if (caseInsensitive) map.put(c.name().toLowerCase(), c);
else map.put(c.name(), c);
}
}
return map;
}
public EnumArgParser(Class<? extends Enum<?>> enumType, boolean caseInsensitive) {
super(getCol(enumType, caseInsensitive), caseInsensitive);
}
}

View File

@ -0,0 +1,22 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.List;
import org.bukkit.command.CommandSender;
public class IntArgParser implements ArgParser {
@Override
public ArgParserRes parse(CommandSender sender, List<String> remainingArgs) {
try {
return ArgParserRes.takenOne(Integer.parseInt(remainingArgs.get(0)));
}
catch (NumberFormatException e) {
return ArgParserRes.error("Invalid number format.");
}
}
@Override
public void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions suggestions) {
suggestions.addSuggestion("0");
}
}

View File

@ -0,0 +1,46 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
public class LiteralArgParser implements ArgParser {
private final String literal;
private final List<String> aliases = new ArrayList<>();
public String getLiteral() {
return literal;
}
public List<String> getAliases() {
return Collections.unmodifiableList(aliases);
}
@Override
public ArgParserRes parse(CommandSender sender, List<String> remainingArgs) {
if (!remainingArgs.get(0).equals(literal) && !aliases.contains(remainingArgs.get(0))) return ArgParserRes.fail();
else return ArgParserRes.takenOne();
}
@Override
public void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions elements) {
String arg = args.get(0);
elements.addSuggestions(aliases.stream().filter(v -> v.startsWith(arg)));
if (literal.startsWith(arg)) elements.addSuggestion(literal);
}
public LiteralArgParser(String lit) {
this.literal = lit;
}
public LiteralArgParser(String lit, String ...aliases) {
this.literal = lit;
Collections.addAll(this.aliases, aliases);
}
public LiteralArgParser(String lit, Collection<String> aliases) {
this.literal = lit;
this.aliases.addAll(aliases);
}
}

View File

@ -0,0 +1,103 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.LivingEntity;
public class LocationArgParser implements ArgParser {
@Override
public ArgParserRes parse(CommandSender sender, List<String> remainingArgs) {
if (remainingArgs.size() < 3) return ArgParserRes.fail();
else {
Location loc = null;
if (sender instanceof LivingEntity) loc = ((LivingEntity)sender).getLocation();
else if (sender instanceof BlockCommandSender) loc = ((BlockCommandSender)sender).getBlock().getLocation();
else return ArgParserRes.error("Coordinates may not be specified by a non-located command sender.");
String rawX = remainingArgs.get(0),
rawY = remainingArgs.get(1),
rawZ = remainingArgs.get(2);
boolean relX = false, relY = false, relZ = false;
if (rawX.startsWith("~")) {
relX = true;
rawX = rawX.substring(1);
if (rawX.isEmpty()) rawX = "0";
}
if (rawY.startsWith("~")) {
relY = true;
rawY = rawY.substring(1);
if (rawY.isEmpty()) rawY = "0";
}
if (rawZ.startsWith("~")) {
relZ = true;
rawZ = rawZ.substring(1);
if (rawZ.isEmpty()) rawZ = "0";
}
double x, y, z;
try {
x = Double.parseDouble(rawX);
y = Double.parseDouble(rawY);
z = Double.parseDouble(rawZ);
} catch(NumberFormatException e) {
return ArgParserRes.error("Invalid number format.");
}
if (relX) x += loc.getX();
if (relY) y += loc.getY();
if (relZ) z += loc.getZ();
return ArgParserRes.takenMany(3, new Location(loc.getWorld(), x, y, z));
}
}
private void addSuggestions(String arg, Double curr, Suggestions suggestions) {
if (arg.isEmpty()) {
suggestions.addSuggestions("~", curr.toString(), Double.toString(Math.floor(curr)), Double.toString(Math.floor(curr) + 0.5));
}
else if (arg.startsWith("~")) {
arg = arg.substring(1);
suggestions.addSuggestions("~" + arg, "~" + ".5");
}
else suggestions.addSuggestion(arg);
if (arg.length() > 0) {
try {
Double.parseDouble(arg);
}
catch (NumberFormatException e) {
suggestions.error("Number is in an invalid format.");
}
}
}
@Override
public void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions suggestions) {
Location loc = null;
if (sender instanceof LivingEntity) loc = ((LivingEntity)sender).getLocation();
else if (sender instanceof BlockCommandSender) loc = ((BlockCommandSender)sender).getBlock().getLocation();
else {
suggestions.error("Only located command senders may use locations.");
return;
}
double curr = loc.getZ();
if (args.size() < 3) curr = loc.getY();
if (args.size() < 2) curr = loc.getX();
String arg = args.get(args.size() - 1);
addSuggestions(arg, curr, suggestions);
}
public LocationArgParser() {
}
}

View File

@ -0,0 +1,13 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class PlayerArgParser extends CollectionArgParser {
public PlayerArgParser(boolean caseInsensitive) {
super(() -> Bukkit.getOnlinePlayers().stream().collect(Collectors.toMap(Player::getName, v->v)), caseInsensitive);
}
}

View File

@ -0,0 +1,17 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.Collections;
import java.util.Map;
public class StaticCollectionArgParser extends CollectionArgParser {
private Map<String, Object> map;
public Map<String, Object> getMap() {
return Collections.unmodifiableMap(map);
}
public StaticCollectionArgParser(Map<String, Object> map, boolean caseInsensitive) {
super(() -> map, caseInsensitive);
this.map = map;
}
}

View File

@ -0,0 +1,27 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.List;
import org.bukkit.command.CommandSender;
public class StringArgParser implements ArgParser {
private final boolean greeedy;
public boolean isGreedy() {
return greeedy;
}
@Override
public ArgParserRes parse(CommandSender sender, List<String> remainingArgs) {
if (greeedy) return ArgParserRes.takenMany(remainingArgs.size(), String.join(" ", remainingArgs));
else return ArgParserRes.takenOne(remainingArgs.get(0));
}
@Override
public void addCompleteSuggestions(CommandSender sender, List<String> args, Suggestions suggestions) {
}
public StringArgParser(boolean greedy) {
greeedy = greedy;
}
}

View File

@ -0,0 +1,49 @@
package me.topchetoeu.bedwars.commands.args;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
public class Suggestions {
private final List<String> suggestions = new ArrayList<>();
private String error = null;
public boolean addSuggestion(String suggestion) {
return suggestions.add(suggestion);
}
public void addSuggestions(Collection<String> suggestions) {
for (String suggestion : suggestions) addSuggestion(suggestion);
}
public void addSuggestions(String ...suggestions) {
Collections.addAll(this.suggestions, suggestions);
}
public void addSuggestions(Stream<String> suggestions) {
this.suggestions.addAll(suggestions.toList());
}
public boolean hasSuggestion(String suggestion) {
return suggestions.contains(suggestion);
}
public List<String> getSuggestions() {
return Collections.unmodifiableList(suggestions);
}
public void error(String error) {
if (error == null || error.trim().isEmpty()) return;
this.error = error;
}
public boolean hasError() {
return error != null;
}
public String getError() {
return error;
}
public Suggestions(List<String> suggestions) {
this.suggestions.addAll(suggestions);
}
public Suggestions() {
}
}

View File

@ -0,0 +1,31 @@
package me.topchetoeu.bedwars.engine;
import org.bukkit.Bukkit;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class AttackCooldownEradicator implements Listener{
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(PlayerJoinEvent e){
setAttackSpeed(e.getPlayer(), 32);
}
private void setAttackSpeed(Player player, double attackSpeed){
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_ATTACK_SPEED);
attribute.setBaseValue(attackSpeed);
player.saveData();
}
public static AttackCooldownEradicator init(JavaPlugin pl) {
AttackCooldownEradicator instance = new AttackCooldownEradicator();
Bukkit.getPluginManager().registerEvents(instance, pl);
return instance;
}
}

View File

@ -1,20 +1,27 @@
package me.topchetoeu.bedwars.engine; package me.topchetoeu.bedwars.engine;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import com.mojang.datafixers.util.Pair;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.attribute.Attribute;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.attribute.AttributeInstance;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType; import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType;
import net.minecraft.server.v1_8_R3.EntityPlayer; import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityEquipment; import net.minecraft.network.protocol.game.PacketPlayOutEntityEquipment;
import net.minecraft.world.entity.EnumItemSlot;
import org.bukkit.entity.Explosive; import org.bukkit.entity.Explosive;
import org.bukkit.entity.Fireball; import org.bukkit.entity.Fireball;
@ -32,7 +39,7 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
@ -46,448 +53,468 @@ import me.topchetoeu.bedwars.InventoryUtility;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
public class BedwarsPlayer implements Listener, AutoCloseable { public class BedwarsPlayer implements Listener, AutoCloseable {
private OfflinePlayer player; private OfflinePlayer player;
private Team team; private Team team;
private boolean dead = true; private boolean dead = true;
private boolean deathPending = false; private boolean deathPending = false;
private boolean revivalPending = false; private boolean revivalPending = false;
private boolean spectator = false; private boolean spectator = false;
private Map<String, String> deathMessages; private Map<String, String> deathMessages;
private float revivalTimer = 0; private float revivalTimer = 0;
private int offenceTimer = 0; private int offenceTimer = 0;
private BukkitTask offenceTask = null; private BukkitTask offenceTask = null;
private BukkitTask invisTask = null; private BukkitTask invisTask = null;
private BukkitTask reviveTask = null; private BukkitTask reviveTask = null;
private int kills; private int kills;
private int finalKills; private int finalKills;
private int beds; private int beds;
private int deaths; private int deaths;
private boolean invisible = false; private boolean invisible = false;
private OfflinePlayer offender = null; private OfflinePlayer offender = null;
private void updateInvisibility(Player p) { private void updateInvisibility(Player p) {
net.minecraft.server.v1_8_R3.ItemStack helmetItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getHelmet()); net.minecraft.world.item.ItemStack helmetItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getHelmet());
net.minecraft.server.v1_8_R3.ItemStack chestplateItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getChestplate()); net.minecraft.world.item.ItemStack chestplateItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getChestplate());
net.minecraft.server.v1_8_R3.ItemStack leggingsItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getLeggings()); net.minecraft.world.item.ItemStack leggingsItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getLeggings());
net.minecraft.server.v1_8_R3.ItemStack bootsItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getBoots()); net.minecraft.world.item.ItemStack bootsItem = CraftItemStack.asNMSCopy(getOnlinePlayer().getInventory().getBoots());
if (invisible) {
helmetItem = chestplateItem = leggingsItem = bootsItem = null;
}
int id = getOnlinePlayer().getEntityId(); if (invisible) {
PacketPlayOutEntityEquipment helmet = new PacketPlayOutEntityEquipment(id, 1, helmetItem); helmetItem = chestplateItem = leggingsItem = bootsItem = null;
PacketPlayOutEntityEquipment chestplate = new PacketPlayOutEntityEquipment(id, 2, chestplateItem); }
PacketPlayOutEntityEquipment leggings = new PacketPlayOutEntityEquipment(id, 3, leggingsItem);
PacketPlayOutEntityEquipment boots = new PacketPlayOutEntityEquipment(id, 4, bootsItem);
EntityPlayer handle = ((CraftPlayer)p).getHandle();
handle.playerConnection.sendPacket(helmet);
handle.playerConnection.sendPacket(chestplate);
handle.playerConnection.sendPacket(leggings);
handle.playerConnection.sendPacket(boots);
}
private void updateInvisiblity() {
for (Player player : Bukkit.getOnlinePlayers()) {
if (Game.inGame(player) && !team.hasPlayer(player)) {
updateInvisibility(player);
}
}
}
private void removeInvis() {
invisible = false;
updateInvisiblity();
if (isOnline()) getOnlinePlayer().removePotionEffect(PotionEffectType.INVISIBILITY);
if (invisTask != null) {
invisTask.cancel();
invisTask = null;
}
}
public OfflinePlayer getPlayer() {
return player;
}
public Player getOnlinePlayer() {
if (player.isOnline()) return player.getPlayer();
else return null;
}
public Team getTeam() {
return team;
}
public boolean isDead() {
return dead;
}
public boolean isSpectator() {
return spectator;
}
public boolean isOnline() {
return player.isOnline();
}
public int getRegularKills() {
return kills;
}
public int getFinalKills() {
return finalKills;
}
public int getKills() {
return kills + finalKills;
}
public int getBeds() {
return beds;
}
public int getDeaths() {
return deaths;
}
public float getRevivalTimer() {
return revivalTimer;
}
public float increaseRevivalTimer(float amount) {
return revivalTimer += amount;
}
public void resetRevivalTimer() {
revivalTimer = 0;
}
public void kill(String deathMsg) {
if (dead) return;
if (player.isOnline()) {
Bukkit.getServer().broadcastMessage(deathMsg);
BedwarsPlayer bwOffender = null;
if (offender != null && Game.isStarted() && Game.instance.isPlaying(offender)) {
bwOffender = Game.instance.getPlayer(offender);
if (offender.isOnline()) {
Player p = offender.getPlayer();
ItemStack[] inv = p.getInventory().getContents();
getOnlinePlayer().getInventory().forEach(i -> {
if (i != null) {
if (i.getType() == Material.IRON_INGOT ||
i.getType() == Material.GOLD_INGOT ||
i.getType() == Material.EMERALD ||
i.getType() == Material.DIAMOND) {
InventoryUtility.giveItem(inv, i);
}
}
});
p.getInventory().setContents(inv);
p.updateInventory();
}
}
for(PotionEffect effect : getOnlinePlayer().getActivePotionEffects())
{
getOnlinePlayer().removePotionEffect(effect.getType());
}
if (team.hasBed()) {
dead = true;
removeInvis();
getOnlinePlayer().setGameMode(GameMode.SPECTATOR);
getOnlinePlayer().setHealth(20);
RankedDealType.getDefinedRanks().values().forEach((v) -> {
v.onDeath(getOnlinePlayer());
});
revivalTimer = 5;
reviveTask = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
if (!player.isOnline()) {
dead = false;
revivalTimer = 0;
deathPending = true;
reviveTask.cancel();
reviveTask = null;
}
Utility.sendTitle(player.getPlayer(),
"You died!",
String.format("Respawning in %.2f", revivalTimer),
0, 4, 5
);
revivalTimer -= 0.1;
if (revivalTimer <= 0) {
revive();
}
}, 0, 2);
offender = null;
if (bwOffender != null) bwOffender.kills++;
}
else {
eliminate();
if (bwOffender != null) bwOffender.finalKills++;
}
ScoreboardManager.updateAll();
}
else deathPending = true;
}
public void revive() {
if (!dead) return;
dead = false;
spectator = false;
if (reviveTask != null) {
reviveTask.cancel();
reviveTask = null;
revivalTimer = 0;
}
if (player.isOnline()) {
player.getPlayer().setGameMode(GameMode.SURVIVAL);
player.getPlayer().teleport(team.getTeamColor().getSpawnLocation());
player.getPlayer().getInventory().clear();
player.getPlayer().setHealth(20);
WoodenSword.update(this, player.getPlayer().getInventory());
RankedDealType.getDefinedRanks().values().forEach((v) -> {
v.refreshInv(getOnlinePlayer());
});
RankedDealType.refreshPlayer(getOnlinePlayer());
}
else revivalPending = true;
}
@SuppressWarnings("deprecation")
public void eliminate() {
if (spectator) return;
if (!dead) {
// TODO make some more spectator features
player.getPlayer().setGameMode(GameMode.SPECTATOR);
player.getPlayer().setHealth(20);
dead = true;
}
Bukkit.getServer().broadcastMessage(String.format("%s was eliminated.", player.getName()));
if (team.decreaseRemainingPlayers() > 0) {
// TODO fix these messages
// Also, this deprecation is just fine :)
player.getPlayer().sendTitle("You are dead", "You can only spectate your more intelligent friends");
}
else
Bukkit.getServer().broadcastMessage(String.format("Team %s was eliminated.", team.getTeamColor().getName()));
if (team.getPlayersCount() == 1) {
player.getPlayer().sendTitle("You were eliminated!", "Now you can spectate");
}
else
player.getPlayer().sendTitle("Your team was eliminated", "Your team fucked up bad time :(");
spectator = true;
}
public void close() {
if (reviveTask != null) {
reviveTask.cancel();
}
offenceTask.cancel();
List<Pair<EnumItemSlot, net.minecraft.world.item.ItemStack>> items = new ArrayList<>();
if (isOnline()) {
for(PotionEffect effect : getOnlinePlayer().getActivePotionEffects()) { items.add(new Pair<EnumItemSlot,net.minecraft.world.item.ItemStack>(EnumItemSlot.c, helmetItem));
getOnlinePlayer().removePotionEffect(effect.getType()); items.add(new Pair<EnumItemSlot,net.minecraft.world.item.ItemStack>(EnumItemSlot.d, chestplateItem));
} items.add(new Pair<EnumItemSlot,net.minecraft.world.item.ItemStack>(EnumItemSlot.e, leggingsItem));
getOnlinePlayer().setGameMode(GameMode.SPECTATOR); items.add(new Pair<EnumItemSlot,net.minecraft.world.item.ItemStack>(EnumItemSlot.f, bootsItem));
getOnlinePlayer().getInventory().clear();
getOnlinePlayer().getEnderChest().clear(); int id = getOnlinePlayer().getEntityId();
}
PacketPlayOutEntityEquipment packet = new PacketPlayOutEntityEquipment(id, items);
HandlerList.unregisterAll(this);
((CraftPlayer)p).getHandle().b.a(packet);
offenceTask = null; }
reviveTask = null;
team = null; private void updateInvisiblity() {
player = null; for (Player player : Bukkit.getOnlinePlayers()) {
deathMessages = null; if (Game.inGame(player) && !team.hasPlayer(player)) {
} updateInvisibility(player);
}
@EventHandler }
private void onLogout(PlayerQuitEvent e) { }
if (equals(e.getPlayer())) { private void removeInvis() {
if (!team.hasBed() ) { invisible = false;
eliminate(); updateInvisiblity();
} if (isOnline()) getOnlinePlayer().removePotionEffect(PotionEffectType.INVISIBILITY);
else if (!dead) deathPending = true; if (invisTask != null) {
} invisTask.cancel();
} invisTask = null;
@EventHandler }
private void onLogin(PlayerJoinEvent e) { }
if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) {
player = e.getPlayer(); public OfflinePlayer getPlayer() {
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> { return player;
if (deathPending) { }
if (!revivalPending) kill(DeathMessage.getMsg(player, offender, deathMessages, "generic")); public Player getOnlinePlayer() {
else revivalPending = false; if (player.isOnline()) return player.getPlayer();
deathPending = false; else return null;
} }
if (revivalPending) { public Team getTeam() {
if (!deathPending) revive(); return team;
revivalPending = false; }
}
ScoreboardManager.update(e.getPlayer()); public boolean isDead() {
}, 3); return dead;
} }
public boolean isSpectator() {
updateInvisiblity(); return spectator;
} }
@EventHandler public boolean isOnline() {
private void onEntityDamageEntity(EntityDamageByEntityEvent e) { return player.isOnline();
if (e.getEntity() instanceof Player) { }
Player p = (Player)e.getEntity();
if (equals(p)) { public int getRegularKills() {
if (e.getDamager() instanceof Player) { return kills;
offender = (OfflinePlayer)e.getDamager(); }
} public int getFinalKills() {
if (e.getDamager() instanceof Projectile) { return finalKills;
Projectile projectile = (Projectile)e.getDamager(); }
if (projectile.getShooter() instanceof Player) { public int getKills() {
OfflinePlayer shooter = (OfflinePlayer)projectile.getShooter(); return kills + finalKills;
if (equals(shooter) && e.getDamager() instanceof Fireball) e.setDamage(0); }
offender = shooter; public int getBeds() {
} return beds;
} }
if (e.getDamager() instanceof Explosive) { public int getDeaths() {
e.setDamage(e.getDamage() / 3); return deaths;
if (e.getFinalDamage() >= p.getHealth()) { }
e.setDamage(0);
kill(DeathMessage.getMessage(e.getCause(), player, offender, deathMessages));
} public float getRevivalTimer() {
} return revivalTimer;
}
if (offender != null) offenceTimer = 15; public float increaseRevivalTimer(float amount) {
} return revivalTimer += amount;
} }
} public void resetRevivalTimer() {
@EventHandler revivalTimer = 0;
private void onDamage(EntityDamageEvent e) { }
if (e.getEntity() instanceof Player) { public void kill(String deathMsg) {
Player p = (Player)e.getEntity(); if (dead) return;
if (equals(p)) { if (player.isOnline()) {
if (e.getCause() == DamageCause.ENTITY_EXPLOSION) { Bukkit.getServer().broadcastMessage(deathMsg);
return; BedwarsPlayer bwOffender = null;
} if (offender != null && Game.isStarted() && Game.instance.isPlaying(offender)) {
if (e.getFinalDamage() >= p.getHealth()) { bwOffender = Game.instance.getPlayer(offender);
e.setDamage(0); if (offender.isOnline()) {
kill(DeathMessage.getMessage(e.getCause(), player, offender, deathMessages)); Player p = offender.getPlayer();
}
} ItemStack[] inv = p.getInventory().getContents();
}
} getOnlinePlayer().getInventory().forEach(i -> {
@EventHandler if (i != null) {
private void onTeleport(PlayerTeleportEvent e) { if (i.getType() == Material.IRON_INGOT ||
Player player = e.getPlayer(); i.getType() == Material.GOLD_INGOT ||
i.getType() == Material.EMERALD ||
i.getType() == Material.DIAMOND) {
InventoryUtility.giveItem(inv, i);
}
}
});
p.getInventory().setContents(inv);
p.updateInventory();
}
}
for(PotionEffect effect : getOnlinePlayer().getActivePotionEffects())
{
getOnlinePlayer().removePotionEffect(effect.getType());
}
if (team.hasBed()) {
dead = true;
removeInvis();
getOnlinePlayer().setGameMode(GameMode.SPECTATOR);
getOnlinePlayer().setHealth(20);
RankedDealType.getDefinedRanks().values().forEach((v) -> {
v.onDeath(getOnlinePlayer());
});
revivalTimer = 5;
reviveTask = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
if (!player.isOnline()) {
dead = false;
revivalTimer = 0;
deathPending = true;
reviveTask.cancel();
reviveTask = null;
}
Utility.sendTitle(player.getPlayer(),
MessageUtility.parser("player.died.title").parse(),
MessageUtility.parser("player.died.subtitle").variable("time", "%.2f".formatted(revivalTimer)).parse(),
0, 4, 5
);
revivalTimer -= 0.1;
if (revivalTimer <= 0) {
revive();
}
}, 0, 2);
offender = null;
if (bwOffender != null) bwOffender.kills++;
}
else {
eliminate();
if (bwOffender != null) bwOffender.finalKills++;
}
ScoreboardManager.updateAll();
}
else deathPending = true;
}
public void revive() {
if (!dead) return;
dead = false;
spectator = false;
if (reviveTask != null) {
reviveTask.cancel();
reviveTask = null;
revivalTimer = 0;
}
if (player.isOnline()) {
player.getPlayer().setGameMode(GameMode.SURVIVAL);
player.getPlayer().teleport(team.getTeamColor().getSpawnLocation());
player.getPlayer().getInventory().clear();
player.getPlayer().setHealth(20);
WoodenSword.update(this, player.getPlayer().getInventory());
RankedDealType.getDefinedRanks().values().forEach((v) -> {
v.refreshInv(getOnlinePlayer());
});
RankedDealType.refreshPlayer(getOnlinePlayer());
}
else revivalPending = true;
}
public void eliminate() {
if (spectator) return;
if (!dead) {
// TODO make some more spectator features
player.getPlayer().setGameMode(GameMode.SPECTATOR);
player.getPlayer().setHealth(20);
dead = true;
}
Bukkit.getServer().broadcastMessage(String.format("%s was eliminated.", player.getName()));
if (team.decreaseRemainingPlayers() > 0) {
Utility.sendTitle(
getOnlinePlayer(),
MessageUtility.parser("player.solo.eliminated.title").parse(),
MessageUtility.parser("player.solo.eliminated.subtitle").parse(),
5, 40, 10
);
}
else
Bukkit.getServer().broadcastMessage(String.format("Team %s was eliminated.", team.getTeamColor().getName()));
if (team.getPlayersCount() == 1) {
Utility.sendTitle(
getOnlinePlayer(),
MessageUtility.parser("player.solo.eliminated.title").parse(),
MessageUtility.parser("player.solo.eliminated.subtitle").parse(),
5, 40, 10
);
}
else
Utility.sendTitle(
getOnlinePlayer(),
MessageUtility.parser("player.team.eliminated.title").parse(),
MessageUtility.parser("player.team.eliminated.subtitle").parse(),
5, 40, 10
);
spectator = true;
}
public void close() {
if (reviveTask != null) {
reviveTask.cancel();
}
offenceTask.cancel();
if (isOnline()) {
for(PotionEffect effect : getOnlinePlayer().getActivePotionEffects()) {
getOnlinePlayer().removePotionEffect(effect.getType());
}
getOnlinePlayer().setGameMode(GameMode.SPECTATOR);
getOnlinePlayer().getInventory().clear();
getOnlinePlayer().getEnderChest().clear();
}
HandlerList.unregisterAll(this);
offenceTask = null;
reviveTask = null;
team = null;
player = null;
deathMessages = null;
}
@EventHandler
private void onLogout(PlayerQuitEvent e) {
if (equals(e.getPlayer())) {
if (!team.hasBed() ) {
eliminate();
}
else if (!dead) deathPending = true;
}
}
@EventHandler
private void onLogin(PlayerJoinEvent e) {
if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) {
player = e.getPlayer();
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> {
if (deathPending) {
if (!revivalPending) kill(DeathMessage.getMsg(player, offender, deathMessages, "generic"));
else revivalPending = false;
deathPending = false;
}
if (revivalPending) {
if (!deathPending) revive();
revivalPending = false;
}
ScoreboardManager.update(e.getPlayer());
}, 3);
}
updateInvisiblity();
}
@EventHandler
private void onEntityDamageEntity(EntityDamageByEntityEvent e) {
if (e.getEntity() instanceof Player) {
Player p = (Player)e.getEntity();
if (equals(p)) {
AttributeInstance attribute = p.getAttribute(Attribute.GENERIC_ATTACK_SPEED);
attribute.setBaseValue(16);
p.saveData();
if (e.getDamager() instanceof Player) {
offender = (OfflinePlayer)e.getDamager();
}
if (e.getDamager() instanceof Projectile) {
Projectile projectile = (Projectile)e.getDamager();
if (projectile.getShooter() instanceof Player) {
OfflinePlayer shooter = (OfflinePlayer)projectile.getShooter();
if (equals(shooter) && e.getDamager() instanceof Fireball) e.setDamage(0);
offender = shooter;
}
}
if (e.getDamager() instanceof Explosive) {
e.setDamage(e.getDamage() / 3);
if (e.getFinalDamage() >= p.getHealth()) {
e.setDamage(0);
kill(DeathMessage.getMessage(e.getCause(), player, offender, deathMessages));
}
}
if (offender != null) offenceTimer = 15;
}
}
}
@EventHandler
private void onDamage(EntityDamageEvent e) {
if (e.getEntity() instanceof Player) {
Player p = (Player)e.getEntity();
if (equals(p)) {
if (e.getCause() == DamageCause.ENTITY_EXPLOSION) {
return;
}
if (e.getFinalDamage() >= p.getHealth()) {
e.setDamage(0);
kill(DeathMessage.getMessage(e.getCause(), player, offender, deathMessages));
}
}
}
}
@EventHandler
private void onTeleport(PlayerTeleportEvent e) {
Player player = e.getPlayer();
if (e.getCause() == TeleportCause.ENDER_PEARL) { if (e.getCause() == TeleportCause.ENDER_PEARL) {
e.setCancelled(true); e.setCancelled(true);
player.teleport(e.getTo()); player.teleport(e.getTo());
} }
} }
private void onInvisExpire() { private void onInvisExpire() {
removeInvis(); removeInvis();
} }
@EventHandler @EventHandler
private void onMove(PlayerMoveEvent e) { private void onMove(PlayerMoveEvent e) {
if (e.getPlayer() instanceof Player) { if (e.getPlayer() instanceof Player) {
if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) { if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) {
if (e.getTo().getY() < 40) { if (e.getTo().getY() < 40) {
e.setTo(e.getTo().add(0, 100, 0)); e.setTo(e.getTo().add(0, 100, 0));
e.getPlayer().playSound(e.getTo(), Sound.HURT_FLESH, 1, 1); e.getPlayer().playSound(e.getTo(), Sound.ENTITY_PLAYER_HURT, 1, 1);
kill(DeathMessage.getMessage(DamageCause.VOID, player, offender, deathMessages)); kill(DeathMessage.getMessage(DamageCause.VOID, player, offender, deathMessages));
} }
} }
} }
} }
@EventHandler @EventHandler
private void onThrow(PlayerDropItemEvent e) { private void onThrow(PlayerDropItemEvent e) {
if (equals(e.getPlayer())) { if (equals(e.getPlayer())) {
if (e.getItemDrop().getItemStack().getType() == Material.WOOD_SWORD) e.setCancelled(true); if (e.getItemDrop().getItemStack().getType() == Material.WOODEN_SWORD) e.setCancelled(true);
else WoodenSword.update(this, e.getPlayer().getInventory()); else WoodenSword.update(this, e.getPlayer().getInventory());
} }
} }
@EventHandler @EventHandler
private void onPickup(PlayerPickupItemEvent e) { private void onPickup(EntityPickupItemEvent e) {
if (WoodenSword.isOtherSword(e.getItem().getItemStack().getType())) if (e.getEntity() instanceof Player) {
e.getPlayer().getInventory().remove(Material.WOOD_SWORD); Player p = (Player)e.getEntity();
} if (WoodenSword.isOtherSword(e.getItem().getItemStack().getType()))
@EventHandler p.getInventory().remove(Material.WOODEN_SWORD);
private void onConsume(PlayerItemConsumeEvent e) { }
if (e.getPlayer() instanceof Player) { }
if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) { @EventHandler
if (e.getItem().getItemMeta() instanceof PotionMeta) { private void onConsume(PlayerItemConsumeEvent e) {
PotionMeta meta = (PotionMeta)e.getItem().getItemMeta(); if (e.getPlayer() instanceof Player) {
if (e.getPlayer().getUniqueId().equals(player.getUniqueId())) {
meta.getCustomEffects().forEach(eff -> { if (e.getItem().getItemMeta() instanceof PotionMeta) {
Utility.applyPotionEffect(getOnlinePlayer(), eff); PotionMeta meta = (PotionMeta)e.getItem().getItemMeta();
if (eff.getType().equals(PotionEffectType.INVISIBILITY)) { meta.getCustomEffects().forEach(eff -> {
Utility.applyPotionEffect(getOnlinePlayer(), eff);
if (invisible) {
invisTask.cancel(); if (eff.getType().equals(PotionEffectType.INVISIBILITY)) {
}
if (invisible) {
invisTask = Bukkit.getScheduler().runTaskLater(Main.getInstance(), invisTask.cancel();
() -> onInvisExpire(), }
eff.getDuration()
); invisTask = Bukkit.getScheduler().runTaskLater(Main.getInstance(),
invisible = true; () -> onInvisExpire(),
updateInvisiblity(); eff.getDuration()
} );
}); invisible = true;
updateInvisiblity();
e.getPlayer().getInventory().setItemInHand(null); }
e.setCancelled(true); });
}
} e.getItem().setType(Material.AIR);
} e.setCancelled(true);
} }
}
}
}
@EventHandler @EventHandler
private void onInventory(InventoryClickEvent e) { private void onInventory(InventoryClickEvent e) {
if (e.getCursor() != null && e.getCursor().getType() == Material.WOOD_SWORD) { if (e.getCursor() != null && e.getCursor().getType() == Material.WOODEN_SWORD) {
if (e.getClickedInventory() != e.getWhoClicked().getInventory()) e.setCancelled(true); if (e.getClickedInventory() != e.getWhoClicked().getInventory()) e.setCancelled(true);
} }
else if (e.getCurrentItem() != null && e.getCurrentItem().getType() == Material.WOOD_SWORD) { else if (e.getCurrentItem() != null && e.getCurrentItem().getType() == Material.WOODEN_SWORD) {
if (e.getClick() == ClickType.SHIFT_LEFT || e.getClick() == ClickType.SHIFT_RIGHT) e.setCancelled(true); if (e.getClick() == ClickType.SHIFT_LEFT || e.getClick() == ClickType.SHIFT_RIGHT) e.setCancelled(true);
} }
} }
public OfflinePlayer getOffender() { public OfflinePlayer getOffender() {
return offender; return offender;
} }
public BedwarsPlayer(OfflinePlayer p, Team t) { public BedwarsPlayer(OfflinePlayer p, Team t) {
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
team = t; team = t;
player = p; player = p;
deathMessages = DeathMessage.getMessages(p); deathMessages = DeathMessage.getMessages(p);
offenceTask = Bukkit.getServer().getScheduler().runTaskTimer(Main.getInstance(), () -> { offenceTask = Bukkit.getServer().getScheduler().runTaskTimer(Main.getInstance(), () -> {
if (offenceTimer > 0) { if (offenceTimer > 0) {
offenceTimer--; offenceTimer--;
if (offenceTimer == 0) offender = null; if (offenceTimer == 0) offender = null;
} }
}, 0, 20); }, 0, 20);
if (p.isOnline()) { if (p.isOnline()) {
dead = true; dead = true;
revive(); revive();
} }
else { else {
dead = false; dead = false;
kill(DeathMessage.getMsg(p, null, deathMessages, "generic")); kill(DeathMessage.getMsg(p, null, deathMessages, "generic"));
} }
} }
public boolean equals(UUID p) { public boolean equals(UUID p) {
if (p == null) return false; if (p == null) return false;
return player.getUniqueId().equals(p); return player.getUniqueId().equals(p);
} }
public boolean equals(OfflinePlayer p) { public boolean equals(OfflinePlayer p) {
if (p == null) return false; if (p == null) return false;
return player.getUniqueId().equals(p.getUniqueId()); return player.getUniqueId().equals(p.getUniqueId());
} }
} }

View File

@ -6,7 +6,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.configuration.Configuration; import org.bukkit.configuration.Configuration;
@ -14,133 +13,129 @@ import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
public class Config { public class Config {
public static Config instance; public static Config instance;
private int perTeam = 0; private int perTeam = 0;
private Location respawnLocation; private Location respawnLocation;
private ArrayList<TeamColor> colors; private List<TeamColor> colors;
private ArrayList<Location> diamondGenerators; private List<Location> diamondGenerators;
private ArrayList<Location> emeraldGenerators; private List<Location> emeraldGenerators;
public Location getRespawnLocation() { public Location getRespawnLocation() {
return respawnLocation; return respawnLocation;
} }
public void setRespawnLocation(Location loc) { public void setRespawnLocation(Location loc) {
respawnLocation = loc; respawnLocation = loc;
} }
public int getTeamSize() { public int getTeamSize() {
return perTeam; return perTeam;
} }
public void setTeamSize(int size) { public void setTeamSize(int size) {
perTeam = size; perTeam = size;
} }
public ArrayList<TeamColor> getColors() { public List<TeamColor> getColors() {
return colors; return colors;
} }
public TeamColor getColor(String name) { public TeamColor getColor(String name) {
return Config.instance.getColors() return getColors()
.stream() .stream()
.filter(v -> v.getName().equals(name.toLowerCase())) .filter(v -> v.getName().equals(name.toLowerCase()))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
} }
public ArrayList<Location> getDiamondGenerators() { public List<Location> getDiamondGenerators() {
return diamondGenerators; return diamondGenerators;
} }
public Location getClosestDiamondGenerator(Location loc) { public Location getClosestDiamondGenerator(Location loc) {
if (diamondGenerators.size() == 0) return null; if (diamondGenerators.size() == 0) return null;
Location closest = null; Location closest = null;
double smallestDist = diamondGenerators.get(0).distance(loc); double smallestDist = diamondGenerators.get(0).distance(loc);
for (int i = 0; i < diamondGenerators.size(); i++) { for (int i = 0; i < diamondGenerators.size(); i++) {
Location el = diamondGenerators.get(i); Location el = diamondGenerators.get(i);
double dist = el.distance(loc); double dist = el.distance(loc);
if (dist < smallestDist) { if (dist < smallestDist) {
closest = el; closest = el;
smallestDist = dist; smallestDist = dist;
} }
} }
return closest; return closest;
} }
public List<Location> getDiamondGeneratorsInRadius(double radius, Location loc) { public List<Location> getDiamondGeneratorsInRadius(double radius, Location loc) {
return diamondGenerators.stream() return diamondGenerators.stream()
.filter(v -> v.distance(loc) <= radius) .filter(v -> v.distance(loc) <= radius)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public ArrayList<Location> getEmeraldGenerators() { public List<Location> getEmeraldGenerators() {
return emeraldGenerators; return emeraldGenerators;
} }
public Location getClosestEmeraldGenerator(Location loc) { public Location getClosestEmeraldGenerator(Location loc) {
if (diamondGenerators.size() == 0) return null; if (diamondGenerators.size() == 0) return null;
Location closest = null; Location closest = null;
double smallestDist = emeraldGenerators.get(0).distance(loc); double smallestDist = emeraldGenerators.get(0).distance(loc);
for (int i = 0; i < emeraldGenerators.size(); i++) { for (int i = 0; i < emeraldGenerators.size(); i++) {
Location el = emeraldGenerators.get(i); Location el = emeraldGenerators.get(i);
double dist = el.distance(loc); double dist = el.distance(loc);
if (dist < smallestDist) { if (dist < smallestDist) {
closest = el; closest = el;
smallestDist = dist; smallestDist = dist;
} }
} }
return closest; return closest;
} }
public List<Location> getEmeraldGeneratorsInRadius(double radius, Location loc) { public List<Location> getEmeraldGeneratorsInRadius(double radius, Location loc) {
return emeraldGenerators.stream() return emeraldGenerators.stream()
.filter(v -> v.distance(loc) <= radius) .filter(v -> v.distance(loc) <= radius)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private static ArrayList<?> toList(Stream<?> s) { @SuppressWarnings("unchecked")
return new ArrayList<>(s.collect(Collectors.toList())); public static void load(File confFile) {
} Configuration conf = YamlConfiguration.loadConfiguration(confFile);
@SuppressWarnings("unchecked") Config c = new Config();
public static void load(File confFile) {
Configuration conf = YamlConfiguration.loadConfiguration(confFile); c.perTeam = conf.getInt("perTeam");
if (conf.get("respawnLocation") != null) c.respawnLocation = Location.deserialize(conf.getConfigurationSection("respawnLocation").getValues(false));
Config c = new Config(); c.colors = new ArrayList<>(conf
.getMapList("colors")
c.perTeam = conf.getInt("perTeam"); .stream()
if (conf.get("respawnLocation") != null) c.respawnLocation = Location.deserialize(conf.getConfigurationSection("respawnLocation").getValues(false)); .map(v -> TeamColor.deserialize((Map<String, Object>)v))
c.colors = (ArrayList<TeamColor>)toList(conf .toList());
.getMapList("colors") c.diamondGenerators = new ArrayList<>(conf
.stream() .getMapList("diamondGenerators")
.map(v -> TeamColor.deserialize((Map<String, Object>)v)) .stream()
); .map(v -> Location.deserialize((Map<String, Object>)v))
c.diamondGenerators = (ArrayList<Location>)toList(conf .toList())
.getMapList("diamondGenerators") ;
.stream() c.emeraldGenerators = new ArrayList<>(conf
.map(v -> Location.deserialize((Map<String, Object>)v)) .getMapList("emeraldGenerators")
); .stream()
c.emeraldGenerators = (ArrayList<Location>)toList(conf .map(v -> Location.deserialize((Map<String, Object>)v))
.getMapList("emeraldGenerators") .toList());
.stream()
.map(v -> Location.deserialize((Map<String, Object>)v)) instance = c;
); }
instance = c;
}
public void save(File confFile) { public void save(File confFile) {
FileConfiguration conf = YamlConfiguration.loadConfiguration(confFile); FileConfiguration conf = YamlConfiguration.loadConfiguration(confFile);
conf.set("perTeam", perTeam); conf.set("perTeam", perTeam);
conf.set("colors", toList(colors.stream().map(v -> v.serialize()))); conf.set("colors", colors.stream().map(v -> v.serialize()).toList());
conf.set("diamondGenerators", toList(diamondGenerators.stream().map(v -> v.serialize()))); conf.set("diamondGenerators", diamondGenerators.stream().map(v -> v.serialize()).toList());
conf.set("emeraldGenerators", toList(emeraldGenerators.stream().map(v -> v.serialize()))); conf.set("emeraldGenerators", emeraldGenerators.stream().map(v -> v.serialize()).toList());
try { try {
conf.save(confFile); conf.save(confFile);
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
e.printStackTrace(); }
} }
}
} }

View File

@ -11,58 +11,58 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
public class DeathMessage { public class DeathMessage {
public static String getMsg(OfflinePlayer offended, OfflinePlayer offender, Map<String, String> messages, String msg) { public static String getMsg(OfflinePlayer offended, OfflinePlayer offender, Map<String, String> messages, String msg) {
return String.format(messages.get(msg), offended.getName(), offender == null ? "" : offender.getName()); return String.format(messages.get(msg), offended.getName(), offender == null ? "" : offender.getName());
} }
public static String getMessage(DamageCause cause, OfflinePlayer offended, OfflinePlayer offender, Map<String, String> messages) { public static String getMessage(DamageCause cause, OfflinePlayer offended, OfflinePlayer offender, Map<String, String> messages) {
String name = "generic"; String name = "generic";
switch (cause) { switch (cause) {
case BLOCK_EXPLOSION: case BLOCK_EXPLOSION:
case ENTITY_EXPLOSION: case ENTITY_EXPLOSION:
name = "explosion"; name = "explosion";
break; break;
case DROWNING: case DROWNING:
name = "drowned"; name = "drowned";
break; break;
case FALL: case FALL:
name = "fall"; name = "fall";
break; break;
case FIRE: case FIRE:
name = "fire"; name = "fire";
break; break;
case LAVA: case LAVA:
name = "lava"; name = "lava";
break; break;
case MAGIC: case MAGIC:
name = "magic"; name = "magic";
break; break;
case POISON: case POISON:
name = "poison"; name = "poison";
break; break;
case PROJECTILE: case PROJECTILE:
name = "projectile"; name = "projectile";
break; break;
case VOID: case VOID:
name = "void"; name = "void";
break; break;
default: default:
name = "generic"; name = "generic";
break; break;
} }
if (offender == null) return getMsg(offended, offender, messages, name); if (offender == null) return getMsg(offended, offender, messages, name);
else if (offender == offended) return getMsg(offended, offender, messages, name + "-suicide"); else if (offender == offended) return getMsg(offended, offender, messages, name + "-suicide");
else return getMsg(offended, offender, messages, name + "-byPlayer"); else return getMsg(offended, offender, messages, name + "-byPlayer");
} }
public static Map<String, String> getMessages(OfflinePlayer player) { public static Map<String, String> getMessages(OfflinePlayer player) {
return YamlConfiguration return YamlConfiguration
.loadConfiguration(new File(Main.getInstance().getDataFolder(), "death-messages.yml")) .loadConfiguration(new File(Main.getInstance().getDataFolder(), "death-messages.yml"))
.getValues(true) .getValues(true)
.entrySet() .entrySet()
.stream() .stream()
.collect(Collectors.toMap(v -> v.getKey(), v -> (String)v.getValue())); .collect(Collectors.toMap(v -> v.getKey(), v -> (String)v.getValue()));
} }
} }

View File

@ -44,407 +44,410 @@ import org.bukkit.util.Vector;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType; import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
public class Game implements Listener, AutoCloseable { public class Game implements Listener, AutoCloseable {
public static Game instance = null; public static Game instance = null;
private static Deque<Location> placedBlocks = new ArrayDeque<>(); private static Deque<Location> placedBlocks = new ArrayDeque<>();
private static HashSet<SavedBlock> brokenBlocks = new HashSet<>(); private static HashSet<SavedBlock> brokenBlocks = new HashSet<>();
// private static int onlineCount; // private static int onlineCount;
public static boolean inGame(OfflinePlayer p) { public static boolean inGame(OfflinePlayer p) {
return isStarted() && instance.isPlaying(p); return isStarted() && instance.isPlaying(p);
} }
public static void start() { public static void start() {
Game.instance = new Game( Game.instance = new Game(
new ArrayList<TeamColor>(Config.instance.getColors().stream().filter(v -> v.isFullySpecified()).collect(Collectors.toList())), new ArrayList<TeamColor>(Config.instance.getColors().stream().filter(v -> v.isFullySpecified()).collect(Collectors.toList())),
Config.instance.getTeamSize(), Config.instance.getTeamSize(),
new ArrayList<OfflinePlayer>(Bukkit.getOnlinePlayers()) new ArrayList<OfflinePlayer>(Bukkit.getOnlinePlayers())
); );
Bukkit.getOnlinePlayers().forEach(p -> { Bukkit.getOnlinePlayers().forEach(p -> {
RankedDealType.getDefinedRanks().values().forEach(v -> v.refreshInv(p.getPlayer())); RankedDealType.getDefinedRanks().values().forEach(v -> v.refreshInv(p.getPlayer()));
}); });
ScoreboardManager.updateAll(); ScoreboardManager.updateAll();
} }
public static void stop() { public static void stop() {
Game.instance.close(); Game.instance.close();
Game.instance = null; Game.instance = null;
Main.getInstance().updateTimer(); Main.getInstance().updateTimer();
ScoreboardManager.updateAll(); ScoreboardManager.updateAll();
} }
public static void stop(boolean immediatly) { public static void stop(boolean immediately) {
if (immediatly) stop(); if (immediately) stop();
else Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> stop(), 20 * 5); else Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> stop(), 20 * 5);
} }
public static boolean isStarted() { public static boolean isStarted() {
return instance != null; return instance != null;
} }
private ArrayList<Team> teams = new ArrayList<>(); private ArrayList<Team> teams = new ArrayList<>();
private ArrayList<Generator> diamondGens = new ArrayList<>(); private ArrayList<Generator> diamondGens = new ArrayList<>();
private ArrayList<Generator> emeraldGens = new ArrayList<>(); private ArrayList<Generator> emeraldGens = new ArrayList<>();
public List<Generator> getDiamondGenerators() { public List<Generator> getDiamondGenerators() {
return Collections.unmodifiableList(diamondGens); return Collections.unmodifiableList(diamondGens);
} }
public List<Generator> getEmeraldGenerators() { public List<Generator> getEmeraldGenerators() {
return Collections.unmodifiableList(emeraldGens); return Collections.unmodifiableList(emeraldGens);
} }
public void teamifyItem(Player player, ItemStack item, boolean colour, boolean enchant) { public void teamifyItem(Player player, ItemStack item, boolean colour, boolean enchant) {
Team t = getTeam(player); Team t = getTeam(player);
if (t != null) t.teamifyItem(item, colour, enchant); if (t != null) t.teamifyItem(item, colour, enchant);
} }
public void win(TeamColor color) { public void win(TeamColor color) {
getTeam(color).sendTitle("You won!", "", 0, 20 * 5, 0); getTeam(color).sendTitle(
getTeam(color).sendTilteToOthers(color.getColorName() + " won!", "You lost :(", 0, 20 * 5, 0); MessageUtility.parser("player.won.title").parse(),
stop(false); MessageUtility.parser("player.won.subtitle").parse(),
} 0, 20 * 5, 0
);
public void breakBlock(Block block) { getTeam(color).sendTitleToOthers(
SavedBlock bl = new SavedBlock(block.getLocation(), block.getState().getData(), block.getState().getType()); MessageUtility.parser("player.lost.title").variable("team", color.getColorName()).parse(),
brokenBlocks.add(bl); MessageUtility.parser("player.lost.subtitle").variable("team", color.getColorName()).parse(),
block.setType(Material.AIR, false); 0, 20 * 5, 0
} );
public void registerBrokenBlock(Location block) { stop(false);
placedBlocks.remove(block); }
}
public void registerPlacedBlock(Location block) { public void breakBlock(Block block) {
placedBlocks.push(block); SavedBlock bl = new SavedBlock(block.getLocation(), block.getState().getBlockData(), block.getState().getType());
} brokenBlocks.add(bl);
block.setType(Material.AIR, false);
public boolean allowPlace(Location loc) { }
for (Generator gen : Generator.getGenerators()) { public void registerBrokenBlock(Location block) {
if (gen.getLocation().distance(loc) < 5) return false; placedBlocks.remove(block);
} }
return true; public void registerPlacedBlock(Location block) {
} placedBlocks.push(block);
public boolean allowBreak(Location loc) { }
if (!isStarted()) return true;
return placedBlocks.contains(loc) || loc.getWorld().getBlockAt(loc).getType() == Material.BED_BLOCK; public boolean allowPlace(Location loc) {
} for (Generator gen : Generator.getGenerators()) {
if (gen.getLocation().distance(loc) < 5) return false;
public ArrayList<Team> getTeams() { }
return teams; return true;
} }
public List<Team> getAliveTeams() { public boolean allowBreak(Location loc) {
return teams.stream().filter(v -> !v.isEliminated()).collect(Collectors.toList()); if (!isStarted()) return true;
} return placedBlocks.contains(loc) || Utility.isBed(loc.getWorld().getBlockAt(loc));
public Team getTeam(TeamColor color) { }
return teams
.stream() public ArrayList<Team> getTeams() {
.filter(v -> v.getTeamColor() == color) return teams;
.findFirst() }
.orElse(null); public List<Team> getAliveTeams() {
} return teams.stream().filter(v -> !v.isEliminated()).collect(Collectors.toList());
public Team getTeam(OfflinePlayer player) { }
return teams public Team getTeam(TeamColor color) {
.stream() return teams
.filter(v -> v.getPlayers().stream().anyMatch(p -> p.equals(player))) .stream()
.findFirst() .filter(v -> v.getTeamColor() == color)
.orElse(null); .findFirst()
} .orElse(null);
public ArrayList<BedwarsPlayer> getPlayers() { }
ArrayList<BedwarsPlayer> res = new ArrayList<>(); public Team getTeam(OfflinePlayer player) {
return teams
for (Team team : teams) { .stream()
res.addAll(team.getPlayers()); .filter(v -> v.getPlayers().stream().anyMatch(p -> p.equals(player)))
} .findFirst()
.orElse(null);
return res; }
} public ArrayList<BedwarsPlayer> getPlayers() {
public BedwarsPlayer getPlayer(OfflinePlayer player) { ArrayList<BedwarsPlayer> res = new ArrayList<>();
Optional<BedwarsPlayer> _p = getPlayers()
.stream() for (Team team : teams) {
.filter(v -> v.getPlayer().getUniqueId().equals(player.getUniqueId())) res.addAll(team.getPlayers());
.findFirst(); }
if (_p.isPresent()) return _p.get(); return res;
else return null; }
} public BedwarsPlayer getPlayer(OfflinePlayer player) {
Optional<BedwarsPlayer> _p = getPlayers()
.stream()
.filter(v -> v.getPlayer().getUniqueId().equals(player.getUniqueId()))
.findFirst();
if (_p.isPresent()) return _p.get();
else return null;
}
public boolean isPlaying(OfflinePlayer p) { public boolean isPlaying(OfflinePlayer p) {
return getPlayer(p) != null; return getPlayer(p) != null;
} }
@SuppressWarnings("deprecation") public void close() {
public void close() { for (Team team : teams) {
for (Team team : teams) { team.close();
team.close(); }
} for (World w : Bukkit.getWorlds()) {
for (World w : Bukkit.getWorlds()) { for (Entity e : w.getEntities()) {
for (Entity e : w.getEntities()) { if (!(e instanceof Player))
if (!(e instanceof Player)) if (!(e instanceof Villager))
if (!(e instanceof Villager)) if (!(e instanceof ArmorStand))
if (!(e instanceof ArmorStand)) e.remove();
e.remove(); }
} }
}
for (Generator gen: diamondGens) {
for (Generator gen: diamondGens) { gen.close();
gen.close(); gen.getLabel().close();
gen.getLabel().close(); }
} for (Generator gen: emeraldGens) {
for (Generator gen: emeraldGens) { gen.close();
gen.close(); gen.getLabel().close();
gen.getLabel().close(); }
}
RankedDealType.resetPlayerTiers();
RankedDealType.resetPlayerTiers();
HandlerList.unregisterAll(this);
HandlerList.unregisterAll(this);
for (Location placedBlock : placedBlocks) {
for (Location placedBlock : placedBlocks) { placedBlock.getBlock().setType(Material.AIR);
placedBlock.getBlock().setType(Material.AIR); }
} for (SavedBlock brokenBlock : brokenBlocks) {
for (SavedBlock brokenBlock : brokenBlocks) { brokenBlock.loc.getBlock().setType(brokenBlock.type, false);
brokenBlock.loc.getBlock().setType(brokenBlock.type, false); brokenBlock.loc.getBlock().setBlockData(brokenBlock.meta, false);
brokenBlock.loc.getBlock().setData(brokenBlock.meta.getData(), false); }
}
placedBlocks.clear();
placedBlocks.clear(); brokenBlocks.clear();
brokenBlocks.clear();
teams = null;
teams = null; }
}
@EventHandler
@EventHandler private void onLogout(PlayerQuitEvent e) {
private void onLogout(PlayerQuitEvent e) { if (isPlaying(e.getPlayer())) {
if (isPlaying(e.getPlayer())) { e.setQuitMessage(e.getPlayer().getName() + " logged out.");
e.setQuitMessage(e.getPlayer().getName() + " logged out."); }
} }
} @EventHandler
@EventHandler private void onLogin(PlayerJoinEvent e) {
private void onLogin(PlayerJoinEvent e) { if(!isPlaying(e.getPlayer())) {
if(!isPlaying(e.getPlayer())) { e.getPlayer().setGameMode(GameMode.SPECTATOR);
e.getPlayer().setGameMode(GameMode.SPECTATOR); e.getPlayer().teleport(Bukkit.getServer().getWorlds().get(0).getSpawnLocation());
e.getPlayer().teleport(Bukkit.getServer().getWorlds().get(0).getSpawnLocation()); Utility.sendTitle(
Utility.sendTitle(e.getPlayer(), "You are now spectating", null, 5, 35, 10); e.getPlayer(),
} MessageUtility.parser("player.midgame-spectator.title").parse(),
else MessageUtility.parser("player.midgame-spectator.subtitle").parse(),
e.setJoinMessage(e.getPlayer().getName() + " reconnected."); 5, 35, 10
} );
@EventHandler }
private void onInventoryClick(InventoryClickEvent e) { else
if (isStarted() && isPlaying((Player)e.getWhoClicked())) { e.setJoinMessage(BaseComponent.toLegacyText(MessageUtility.parser("player.reconnected").variable("name", e.getPlayer().getDisplayName()).parse()));
if (e.getClickedInventory() instanceof CraftingInventory) e.setCancelled(true); }
} @EventHandler
} private void onInventoryClick(InventoryClickEvent e) {
@EventHandler if (isStarted() && isPlaying((Player)e.getWhoClicked())) {
private void onItemDamage(PlayerItemDamageEvent e) { if (e.getClickedInventory() instanceof CraftingInventory) e.setCancelled(true);
e.setCancelled(true); }
} }
@EventHandler
private void onItemDamage(PlayerItemDamageEvent e) {
e.setCancelled(true);
}
private static boolean isExceptional(Material mat) { private static boolean isExceptional(Material mat) {
return mat == Material.LONG_GRASS || mat == Material.YELLOW_FLOWER || mat == Material.RED_ROSE; return !mat.isSolid();
} }
@EventHandler @EventHandler
private boolean onBlockBreak(Block b) { private boolean onBlockBreak(Block b) {
if (isExceptional(b.getType())) { if (isExceptional(b.getType())) {
b.getDrops().forEach(v -> b.getWorld().dropItemNaturally(b.getLocation().add(0.5, 0.5, 0.5), v)); b.getDrops().forEach(v -> b.getWorld().dropItemNaturally(b.getLocation().add(0.5, 0.5, 0.5), v));
breakBlock(b); breakBlock(b);
} }
else if (b.getType() == Material.BED_BLOCK) { else if (Utility.isBed(b)) {
return false; return false;
} }
else if (allowBreak(b.getLocation())) { else if (allowBreak(b.getLocation())) {
registerBrokenBlock(b.getLocation()); registerBrokenBlock(b.getLocation());
b.breakNaturally(); b.breakNaturally();
} }
else { else {
return false; return false;
} }
return true; return true;
} }
@EventHandler @EventHandler
private void onBlockBreak(BlockBreakEvent e) { private void onBlockBreak(BlockBreakEvent e) {
e.setCancelled(true); e.setCancelled(true);
onBlockBreak(e.getBlock()); onBlockBreak(e.getBlock());
} }
@SuppressWarnings("incomplete-switch") @SuppressWarnings("incomplete-switch")
@EventHandler @EventHandler
private void onBlockPlace(PlayerBucketEmptyEvent e) { private void onBlockPlace(PlayerBucketEmptyEvent e) {
Location loc = e.getBlockClicked().getLocation(); Location loc = e.getBlockClicked().getLocation();
switch (e.getBlockFace()) { switch (e.getBlockFace()) {
case UP: case UP:
loc.add(0, 1, 0); loc.add(0, 1, 0);
break; break;
case DOWN: case DOWN:
loc.add(0, -1, 0); loc.add(0, -1, 0);
break; break;
case EAST: case EAST:
loc.add(1, 0, 0); loc.add(1, 0, 0);
break; break;
case WEST: case WEST:
loc.add(-1, 0, 0); loc.add(-1, 0, 0);
break; break;
case NORTH: case NORTH:
loc.add(0, 0, -1); loc.add(0, 0, -1);
break; break;
case SOUTH: case SOUTH:
loc.add(0, 0, 1); loc.add(0, 0, 1);
break; break;
} }
if (!allowPlace(loc)) { if (!allowPlace(loc)) {
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
if (loc.getBlock().getType() != Material.AIR) { if (loc.getBlock().getType() != Material.AIR) {
if (!allowBreak(loc)) e.setCancelled(true); if (!allowBreak(loc)) e.setCancelled(true);
} }
else registerPlacedBlock(loc); else registerPlacedBlock(loc);
} }
@EventHandler @EventHandler
@SuppressWarnings("incomplete-switch") @SuppressWarnings("incomplete-switch")
private void onBlockPlace(BlockPlaceEvent e) { private void onBlockPlace(BlockPlaceEvent e) {
if (e.getBlock().getType() == Material.TNT) { if (e.getBlock().getType() == Material.TNT) {
e.setCancelled(true); e.setCancelled(true);
ItemStack i = e.getPlayer().getItemInHand(); Utility.takeOne(e.getPlayer(), e.getHand());
if (i.getAmount() == 0) e.getPlayer().setItemInHand(null); e.getBlock().getWorld().spawnEntity(e.getBlock().getLocation().add(.5, 0, .5), EntityType.PRIMED_TNT).setVelocity(new Vector(0, 0, 0));
else { }
i.setAmount(i.getAmount() - 1); else {
e.getPlayer().setItemInHand(i); switch (e.getBlockReplacedState().getType()) {
} case WATER:
e.getBlock().getWorld().spawnEntity(e.getBlock().getLocation().add(.5, 0, .5), EntityType.PRIMED_TNT).setVelocity(new Vector(0, 0, 0)); case LAVA:
} if (!allowBreak(e.getBlock().getLocation())) e.setCancelled(true);
else { return;
switch (e.getBlockReplacedState().getType()) { case AIR:
case WATER: if (!allowPlace(e.getBlock().getLocation())) {
case STATIONARY_WATER: e.setCancelled(true);
case LAVA: return;
case STATIONARY_LAVA: }
if (!allowBreak(e.getBlock().getLocation())) e.setCancelled(true); break;
return; case GRASS:
case AIR: case TALL_GRASS:
if (!allowPlace(e.getBlock().getLocation())) { break;
e.setCancelled(true); }
return;
} if (!e.isCancelled()) {
break; registerPlacedBlock(e.getBlock().getLocation());
case GRASS: }
case LONG_GRASS: }
break; }
} @EventHandler
private void onWaterPassTrough(BlockFromToEvent e) {
if (!e.isCancelled()) { e.setCancelled(true);
registerPlacedBlock(e.getBlock().getLocation()); }
} @EventHandler
} private void onEntityExplode(EntityExplodeEvent e) {
} e.setCancelled(true);
@EventHandler for (Block b : e.blockList()) {
private void onWaterPassTrough(BlockFromToEvent e) { if (b.getType() != Material.GLASS) {
e.setCancelled(true); onBlockBreak(b);
} }
@EventHandler }
private void onEntityExplode(EntityExplodeEvent e) {
e.setCancelled(true); for (Player p : Bukkit.getOnlinePlayers()) {
for (Block b : e.blockList()) { p.playSound(e.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1, 1);
if (b.getType() != Material.GLASS) { }
onBlockBreak(b); }
} @EventHandler
} private void onUse(PlayerInteractEvent e) {
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
for (Player p : Bukkit.getOnlinePlayers()) { if (e.getItem() == null) return;
p.playSound(e.getLocation(), Sound.EXPLODE, 1, 1); if (e.getItem().getType() == Material.FIRE_CHARGE) {
}
} Utility.takeOne(e.getPlayer(), e.getHand());
@EventHandler
private void onUse(PlayerInteractEvent e) { Location loc = e.getPlayer().getEyeLocation();
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (e.getItem() == null) return; Fireball fireball = (Fireball)e.getPlayer().getWorld().spawnEntity(
if (e.getItem().getType() == Material.FIREBALL) { loc.add(loc.getDirection().multiply(.5)),
EntityType.FIREBALL
ItemStack i = e.getPlayer().getItemInHand(); );
if (i.getAmount() == 0) e.getPlayer().setItemInHand(null);
else { fireball.getLocation().add(fireball.getDirection().multiply(10));
i.setAmount(i.getAmount() - 1); fireball.setShooter(e.getPlayer());
e.getPlayer().setItemInHand(i); fireball.setYield(3);
} e.setCancelled(true);
}
Location loc = e.getPlayer().getEyeLocation(); }
}
Fireball fireball = (Fireball)e.getPlayer().getWorld().spawnEntity(
loc.add(loc.getDirection().multiply(.5)), public Game(ArrayList<TeamColor> colors, int perTeam, ArrayList<OfflinePlayer> players) {
EntityType.FIREBALL Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
); int spectatorsCount = players.size() - perTeam * colors.size();
ArrayList<OfflinePlayer> spectators = new ArrayList<OfflinePlayer>();
fireball.getLocation().add(fireball.getDirection().multiply(10));
fireball.setShooter(e.getPlayer()); if (spectatorsCount > 0) {
fireball.setYield(3); for (int i = 0; i < spectatorsCount; i++) {
e.setCancelled(true); OfflinePlayer removed = players.remove((int)(Math.random() * players.size()));
} spectators.add(removed);
} if (removed.isOnline()) {
} removed.getPlayer().setGameMode(GameMode.SPECTATOR);
removed.getPlayer().teleport(new Location(removed.getPlayer().getLocation().getWorld(), 0, 80, 0));
public Game(ArrayList<TeamColor> colors, int perTeam, ArrayList<OfflinePlayer> players) { }
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); if (removed.isOnline()) MessageUtility.parser("player.will-be-spectator").send(removed.getPlayer());
int spectatorsCount = players.size() - perTeam * colors.size(); }
ArrayList<OfflinePlayer> spectators = new ArrayList<OfflinePlayer>(); }
if (spectatorsCount > 0) {
for (int i = 0; i < spectatorsCount; i++) {
OfflinePlayer removed = players.remove((int)(Math.random() * players.size()));
spectators.add(removed);
if (removed.isOnline()) {
removed.getPlayer().setGameMode(GameMode.SPECTATOR);
removed.getPlayer().teleport(Config.instance.getRespawnLocation());
}
if (removed.isOnline()) removed.getPlayer().sendMessage("You will be a spectator");
}
}
this.teams = new ArrayList<>(); this.teams = new ArrayList<>();
if (colors.size() != 0) { if (colors.size() != 0) {
int colorI = 0; int colorI = 0;
for (TeamColor color : colors) { for (TeamColor color : colors) {
this.teams.add(new Team(color)); this.teams.add(new Team(color));
} }
while (!players.isEmpty()) { while (!players.isEmpty()) {
Team currTeam = this.teams.get(colorI); Team currTeam = this.teams.get(colorI);
OfflinePlayer p; OfflinePlayer p;
currTeam.addPlayer(p = players.remove((int)(Math.random() * players.size()))); currTeam.addPlayer(p = players.remove((int)(Math.random() * players.size())));
if (p.isOnline()) { if (p.isOnline()) {
// onlineCount++; // onlineCount++;
} }
if (currTeam.getPlayersCount() == perTeam) { if (currTeam.getPlayersCount() == perTeam) {
colorI++; colorI++;
} }
} }
} }
// TODO: Make times configurable // TODO: Make times configurable
for (Location loc : Config.instance.getDiamondGenerators()) { for (Location loc : Config.instance.getDiamondGenerators()) {
GeneratorLabel label = new GeneratorLabel("§cDiamond Generator", loc.clone().add(0, 1, 0)); GeneratorLabel label = new GeneratorLabel(TextComponent.fromLegacyText("§cDiamond Generator"), loc.clone().add(0, 1, 0));
Generator gen = new Generator(loc, 4, label); Generator gen = new Generator(loc, 4, label);
gen.addItem(Material.DIAMOND, 600); gen.addItem(Material.DIAMOND, 600);
diamondGens.add(gen); diamondGens.add(gen);
} }
for (Location loc : Config.instance.getEmeraldGenerators()) { for (Location loc : Config.instance.getEmeraldGenerators()) {
GeneratorLabel label = new GeneratorLabel("§cEmerald Generator", loc.clone().add(0, 1, 0)); GeneratorLabel label = new GeneratorLabel(TextComponent.fromLegacyText("§cEmerald Generator"), loc.clone().add(0, 1, 0));
Generator gen = new Generator(loc, 2, label); Generator gen = new Generator(loc, 2, label);
gen.addItem(Material.EMERALD, 1200); gen.addItem(Material.EMERALD, 1200);
emeraldGens.add(gen); emeraldGens.add(gen);
} }
} }
} }

View File

@ -17,7 +17,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.ItemMergeEvent; import org.bukkit.event.entity.ItemMergeEvent;
import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@ -25,122 +25,124 @@ import org.bukkit.util.Vector;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
public class Generator implements AutoCloseable, Listener { public class Generator implements AutoCloseable, Listener {
private class _Item implements AutoCloseable { private class _Item implements AutoCloseable {
private BukkitTask task; private BukkitTask task;
private BukkitTask timerTask; private BukkitTask timerTask;
private Generator parentInstance; private Generator parentInstance;
private int timer = 0; private int timer = 0;
public void close() { public void close() {
task.cancel(); task.cancel();
timerTask.cancel(); timerTask.cancel();
timerTask = null; timerTask = null;
task = null; task = null;
} }
public _Item(int interval, Material type, Generator gen) { public _Item(int interval, Material type, Generator gen) {
parentInstance = gen; parentInstance = gen;
timer = interval; timer = interval;
this.task = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> { this.task = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
Item i = location.getWorld().dropItem(location, new ItemStack(type, 1)); Item i = location.getWorld().dropItem(location, new ItemStack(type, 1));
i.setVelocity(new Vector(0, 0, 0)); i.setVelocity(new Vector(0, 0, 0));
parentInstance.generatedItems.add(i.getUniqueId()); parentInstance.generatedItems.add(i.getUniqueId());
if (parentInstance.generatedItems.size() > parentInstance.maxItems) { if (parentInstance.generatedItems.size() > parentInstance.maxItems) {
if (parentInstance.generatedItems.size() != 0) { if (parentInstance.generatedItems.size() != 0) {
UUID removed = parentInstance.generatedItems.stream().findFirst().get(); UUID removed = parentInstance.generatedItems.stream().findFirst().get();
Bukkit.getServer().getWorlds() Bukkit.getServer().getWorlds()
.stream() .stream()
.flatMap(v -> v.getEntities().stream()) .flatMap(v -> v.getEntities().stream())
.filter(v -> v.getUniqueId().equals(removed)) .filter(v -> v.getUniqueId().equals(removed))
.findFirst() .findFirst()
.ifPresent(v -> v.remove()); .ifPresent(v -> v.remove());
parentInstance.generatedItems.remove(removed); parentInstance.generatedItems.remove(removed);
} }
} }
}, interval, interval); }, interval, interval);
this.timerTask = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> { this.timerTask = Bukkit.getScheduler().runTaskTimer(Main.getInstance(), () -> {
timer--; timer--;
if (timer == 0) timer = interval; if (timer == 0) timer = interval;
if (parentInstance.label != null) parentInstance.label.setRemaining(type, timer / 20f); if (parentInstance.label != null) parentInstance.label.setRemaining(type, timer / 20f);
}, 0, 1); }, 0, 1);
} }
} }
private static HashSet<Generator> generators = new HashSet<>(); private static HashSet<Generator> generators = new HashSet<>();
private HashSet<UUID> generatedItems = new HashSet<>(); private HashSet<UUID> generatedItems = new HashSet<>();
private Hashtable<Material, _Item> itemGenerators = new Hashtable<>(); private Hashtable<Material, _Item> itemGenerators = new Hashtable<>();
private Location location; private Location location;
private int maxItems; private int maxItems;
private GeneratorLabel label; private GeneratorLabel label;
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
public void addItem(Material type, int interval) { public void addItem(Material type, int interval) {
if (itemGenerators.contains(type)) removeItem(type); if (itemGenerators.contains(type)) removeItem(type);
itemGenerators.put(type, new _Item(interval, type, this)); itemGenerators.put(type, new _Item(interval, type, this));
} }
public void removeItem(Material type) { public void removeItem(Material type) {
itemGenerators.remove(type).close(); itemGenerators.remove(type).close();
} }
public GeneratorLabel getLabel() { public GeneratorLabel getLabel() {
return label; return label;
} }
@EventHandler @EventHandler
private void onItemMerge(ItemMergeEvent e) { private void onItemMerge(ItemMergeEvent e) {
if (generatedItems.contains(e.getEntity().getUniqueId()) || generatedItems.contains(e.getTarget().getUniqueId())) if (generatedItems.contains(e.getEntity().getUniqueId()) || generatedItems.contains(e.getTarget().getUniqueId()))
e.setCancelled(true); e.setCancelled(true);
} }
@EventHandler @EventHandler
private void onPickup(PlayerPickupItemEvent e) { private void onPickup(EntityPickupItemEvent e) {
if (generatedItems.contains(e.getItem().getUniqueId())) { if (e.getEntity() instanceof Player) {
e.setCancelled(true); if (generatedItems.contains(e.getItem().getUniqueId())) {
e.setCancelled(true);
for (BedwarsPlayer bwp : Game.instance.getPlayers()) {
if (bwp.isOnline()) { for (BedwarsPlayer bwp : Game.instance.getPlayers()) {
Player p = bwp.getOnlinePlayer(); if (bwp.isOnline()) {
Player p = bwp.getOnlinePlayer();
if (p.getLocation().distance(e.getItem().getLocation()) < 2) {
p.playSound(e.getItem().getLocation(), Sound.ITEM_PICKUP, .5f, 2); if (p.getLocation().distance(e.getItem().getLocation()) < 2) {
p.getInventory().addItem(e.getItem().getItemStack()); p.playSound(e.getItem().getLocation(), Sound.ENTITY_ITEM_PICKUP, .5f, 2);
} p.getInventory().addItem(e.getItem().getItemStack());
} }
} }
generatedItems.remove(e.getItem().getUniqueId()); }
e.getItem().remove(); generatedItems.remove(e.getItem().getUniqueId());
} e.getItem().remove();
} }
}
public void close() { }
for (Material m : new ArrayList<>(itemGenerators.keySet())) {
removeItem(m); public void close() {
} for (Material m : new ArrayList<>(itemGenerators.keySet())) {
HandlerList.unregisterAll(this); removeItem(m);
}
itemGenerators = null; HandlerList.unregisterAll(this);
generatedItems = null;
} itemGenerators = null;
generatedItems = null;
public static Set<Generator> getGenerators() { }
return Collections.unmodifiableSet(generators);
} public static Set<Generator> getGenerators() {
return Collections.unmodifiableSet(generators);
public Generator(Location loc, int maxItems, GeneratorLabel label) { }
this.location = loc;
this.maxItems = maxItems; public Generator(Location loc, int maxItems, GeneratorLabel label) {
this.label = label; this.location = loc;
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); this.maxItems = maxItems;
this.label = label;
generators.add(this); Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
}
generators.add(this);
}
} }

View File

@ -7,40 +7,42 @@ import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class GeneratorLabel { public class GeneratorLabel {
private HoverLabel label; private HoverLabel label;
private String firstLine; private BaseComponent[] firstLine;
private Hashtable<Material, Float> remainingTimes = new Hashtable<>(); private Hashtable<Material, Float> remainingTimes = new Hashtable<>();
public void close() { public void close() {
label.close(); label.close();
} }
public void setRemaining(Material item, float remainingSeconds) { public void setRemaining(Material item, float remainingSeconds) {
remainingTimes.put(item, remainingSeconds); remainingTimes.put(item, remainingSeconds);
update(); update();
} }
public float getRemaining(Material item) { public float getRemaining(Material item) {
return remainingTimes.get(item); return remainingTimes.get(item);
} }
public void update() { public void update() {
ArrayList<String> lines = new ArrayList<>(); ArrayList<BaseComponent[]> lines = new ArrayList<>();
lines.add(firstLine); lines.add(firstLine);
lines.add(null); lines.add(null);
for (Material item : remainingTimes.keySet()) { for (Material item : remainingTimes.keySet()) {
lines.add(String.format("%s in %.2f seconds", Utility.getItemName(item), remainingTimes.get(item))); lines.add(new ComponentBuilder().append(Utility.getItemName(item)).append(" in %.2f seconds".formatted(remainingTimes.get(item))).create());
} }
label.setData(lines); label.setData(lines);
} }
public GeneratorLabel(String firstLine, Location loc) { public GeneratorLabel(BaseComponent[] firstLine, Location loc) {
this.firstLine = firstLine; this.firstLine = firstLine;
label = new HoverLabel(loc, new ArrayList<String>()); label = new HoverLabel(loc, new ArrayList<BaseComponent[]>());
} }
} }

View File

@ -9,99 +9,101 @@ import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import net.md_5.bungee.api.chat.BaseComponent;
public class HoverLabel { public class HoverLabel {
private List<String> data; private List<BaseComponent[]> data;
private List<ArmorStand> armorStands; private List<ArmorStand> armorStands;
private Location loc; private Location loc;
private ArmorStand generateArmorStand(Location loc, String name) { private ArmorStand generateArmorStand(Location loc, BaseComponent[] name) {
if (name == null || name.equals("")) return null; if (name == null || name.length == 0) return null;
ArmorStand as = (ArmorStand)loc.getWorld().spawnEntity(loc, EntityType.ARMOR_STAND); ArmorStand as = (ArmorStand)loc.getWorld().spawnEntity(loc, EntityType.ARMOR_STAND);
as.setGravity(false); as.setGravity(false);
as.setVisible(false); as.setVisible(false);
as.setCustomName(name); as.setCustomName(BaseComponent.toLegacyText(name));
as.setCustomNameVisible(true); as.setCustomNameVisible(true);
return as; return as;
} }
@EventHandler @EventHandler
private void damage(EntityDamageEvent e) { private void damage(EntityDamageEvent e) {
if (e.getEntity() instanceof ArmorStand) { if (e.getEntity() instanceof ArmorStand) {
ArmorStand as = (ArmorStand)e.getEntity(); ArmorStand as = (ArmorStand)e.getEntity();
if (armorStands.contains(as)) { if (armorStands.contains(as)) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }
public void close() { public void close() {
for (ArmorStand as : armorStands) { for (ArmorStand as : armorStands) {
if (as != null) as.remove(); if (as != null) as.remove();
} }
} }
public void setLocation(Location loc) { public void setLocation(Location loc) {
this.loc = loc; this.loc = loc;
for(ArmorStand as : armorStands) { for(ArmorStand as : armorStands) {
if (as != null) as.teleport(loc); if (as != null) as.teleport(loc);
loc = loc.add(0, -0.25, 0); loc = loc.add(0, -0.25, 0);
} }
} }
public Location getLocation() { public Location getLocation() {
return loc; return loc;
} }
private Location replaceData(List<String> data, int n) { private Location replaceData(List<BaseComponent[]> data, int n) {
Location loc = this.loc.clone(); Location loc = this.loc.clone();
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
String line = data.get(i); BaseComponent[] line = data.get(i);
if (line == null || line.equals("")) { if (line == null || line.length == 0) {
if (armorStands.get(i) != null) armorStands.get(i).remove(); if (armorStands.get(i) != null) armorStands.get(i).remove();
armorStands.set(i, null); armorStands.set(i, null);
} }
else { else {
if (armorStands.get(i) == null) armorStands.set(i, generateArmorStand(loc, line)); if (armorStands.get(i) == null) armorStands.set(i, generateArmorStand(loc, line));
else armorStands.get(i).setCustomName(line); else armorStands.get(i).setCustomName(BaseComponent.toLegacyText(line));
} }
loc.add(0, -0.25, 0); loc.add(0, -0.25, 0);
} }
return loc; return loc;
} }
public void setData(List<String> data) { public void setData(List<BaseComponent[]> data) {
if (data.size() > this.data.size()) { if (data.size() > this.data.size()) {
Location loc = replaceData(data, this.data.size()); Location loc = replaceData(data, this.data.size());
for (int i = this.data.size(); i < data.size(); i++) { for (int i = this.data.size(); i < data.size(); i++) {
armorStands.add(generateArmorStand(loc, data.get(i))); armorStands.add(generateArmorStand(loc, data.get(i)));
loc.add(0, -0.25, 0); loc.add(0, -0.25, 0);
} }
} }
else if (data.size() == this.data.size()) { else if (data.size() == this.data.size()) {
replaceData(data, data.size()); replaceData(data, data.size());
} }
else { else {
replaceData(data, data.size()); replaceData(data, data.size());
for (int i = data.size(); i < this.data.size(); i++) { for (int i = data.size(); i < this.data.size(); i++) {
ArmorStand curr = armorStands.get(data.size()); ArmorStand curr = armorStands.get(data.size());
if (curr != null) curr.remove(); if (curr != null) curr.remove();
armorStands.remove(data.size()); armorStands.remove(data.size());
} }
} }
this.data = data; this.data = data;
} }
public List<String> getData() { public List<BaseComponent[]> getData() {
return data; return data;
} }
public HoverLabel(Location loc, List<String> data) { public HoverLabel(Location loc, List<BaseComponent[]> data) {
this.loc = loc; this.loc = loc;
this.data = new ArrayList<String>(); this.data = new ArrayList<BaseComponent[]>();
this.armorStands = new ArrayList<ArmorStand>(); this.armorStands = new ArrayList<ArmorStand>();
setData(data); setData(data);
} }
} }

View File

@ -2,16 +2,16 @@ package me.topchetoeu.bedwars.engine;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.material.MaterialData; import org.bukkit.block.data.BlockData;
public class SavedBlock { public class SavedBlock {
public Location loc; public Location loc;
public MaterialData meta; public BlockData meta;
public Material type; public Material type;
public SavedBlock(Location l, MaterialData m, Material t) { public SavedBlock(Location l, BlockData m, Material t) {
loc = l; loc = l;
meta = m; meta = m;
type = t; type = t;
} }
} }

View File

@ -12,68 +12,69 @@ import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Scoreboard;
public class ScoreboardManager { import net.md_5.bungee.api.chat.BaseComponent;
private static Hashtable<UUID, Scoreboard> scoreboards = new Hashtable<>();
private static List<String> getLines(Player p) {
if (!Game.isStarted()) return new ArrayList<>();
return Game.instance
.getTeams()
.stream()
.map(v -> {
String teamCounter = "§a✔";
if (v.getRemainingPlayers() == 0) teamCounter = "§4✖";
else if (!v.hasBed()) teamCounter = Integer.toString(v.getRemainingPlayers());
String newStr = String.format(" %s§r: %s", v.getTeamColor().getColorName(), teamCounter);
if (v.hasPlayer(p)) {
newStr = (newStr + "§r (you)").replaceAll("§([0-9a-z])", "§$1§l");
}
return newStr;
})
.collect(Collectors.toList());
}
public static Scoreboard getScoreboard(Player p) {
Scoreboard scoreboard = scoreboards.get(p.getUniqueId());
if (scoreboard == null) {
scoreboards.put(p.getUniqueId(), Bukkit.getScoreboardManager().getNewScoreboard());
scoreboard = scoreboards.get(p.getUniqueId());
p.setScoreboard(scoreboard);
Objective objective = scoreboard.registerNewObjective("bedwars", "dummy");
objective.setDisplayName(" §4§lBedwars ");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
}
return scoreboard;
}
public static void update(Player p) {
Scoreboard scoreboard = getScoreboard(p);
List<String> lines = getLines(p);
for (String entry : scoreboard.getEntries()) {
scoreboard.resetScores(entry);
}
for (int i = 0; i < lines.size(); i++) {
scoreboard.getObjective("bedwars").getScore(lines.get(lines.size() - 1 - i)).setScore(i);
}
}
public static void updateAll() {
updateAll(false);
}
public static void updateAll(boolean supressTeamCheck) {
Bukkit.getServer().getOnlinePlayers().forEach(v -> update(v));
if (Game.isStarted() && Game.instance.getAliveTeams().size() == 1) { public class ScoreboardManager {
Game.instance.win(Game.instance.getAliveTeams().get(0).getTeamColor()); private static Hashtable<UUID, Scoreboard> scoreboards = new Hashtable<>();
}
} private static List<String> getLines(Player p) {
if (!Game.isStarted()) return new ArrayList<>();
return Game.instance
.getTeams()
.stream()
.map(v -> {
String teamCounter = "§a✔";
if (v.getRemainingPlayers() == 0) teamCounter = "§4✖";
else if (!v.hasBed()) teamCounter = Integer.toString(v.getRemainingPlayers());
String newStr = String.format(" %s§r: %s", BaseComponent.toLegacyText(v.getTeamColor().getColorName()), teamCounter);
if (v.hasPlayer(p)) {
newStr = (newStr + "§r (you)").replaceAll("§([0-9a-z])", "§$1§l");
}
return newStr;
})
.collect(Collectors.toList());
}
public static Scoreboard getScoreboard(Player p) {
Scoreboard scoreboard = scoreboards.get(p.getUniqueId());
if (scoreboard == null) {
scoreboards.put(p.getUniqueId(), Bukkit.getScoreboardManager().getNewScoreboard());
scoreboard = scoreboards.get(p.getUniqueId());
p.setScoreboard(scoreboard);
Objective objective = scoreboard.registerNewObjective("bedwars", "dummy", " §4§lBedwars ");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
}
return scoreboard;
}
public static void update(Player p) {
Scoreboard scoreboard = getScoreboard(p);
List<String> lines = getLines(p);
for (String entry : scoreboard.getEntries()) {
scoreboard.resetScores(entry);
}
for (int i = 0; i < lines.size(); i++) {
scoreboard.getObjective("bedwars").getScore(lines.get(lines.size() - 1 - i)).setScore(i);
}
}
public static void updateAll() {
updateAll(false);
}
public static void updateAll(boolean supressTeamCheck) {
Bukkit.getServer().getOnlinePlayers().forEach(v -> update(v));
if (Game.isStarted() && Game.instance.getAliveTeams().size() == 1) {
Game.instance.win(Game.instance.getAliveTeams().get(0).getTeamColor());
}
}
} }

View File

@ -9,7 +9,6 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -28,228 +27,233 @@ import org.bukkit.inventory.meta.LeatherArmorMeta;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade; import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.chat.BaseComponent;
public class Team implements Listener, AutoCloseable { public class Team implements Listener, AutoCloseable {
private TeamColor color; private TeamColor color;
private ArrayList<BedwarsPlayer> players = new ArrayList<>(); private ArrayList<BedwarsPlayer> players = new ArrayList<>();
private Hashtable<String, TeamUpgrade> upgrades = new Hashtable<>(); private Hashtable<String, TeamUpgrade> upgrades = new Hashtable<>();
private Generator generator; private Generator generator;
private boolean bed = true; private boolean bed = true;
private int playersCount; private int playersCount;
private int remainingPlayers; private int remainingPlayers;
public boolean hasBed() { public boolean hasBed() {
return bed; return bed;
} }
public boolean destroyBed(OfflinePlayer player) { public boolean destroyBed(OfflinePlayer player) {
if (!bed) return false; if (!bed) return false;
World world = Bukkit.getWorlds().get(0); World world = Bukkit.getWorlds().get(0);
for (int x = -5; x < 5; x++) { for (int x = -5; x < 5; x++) {
for (int y = -5; y < 5; y++) { for (int y = -5; y < 5; y++) {
for (int z = -5; z < 5; z++) { for (int z = -5; z < 5; z++) {
Block block = new Location( Block block = new Location(
world, world,
color.getBedLocation().getBlockX() + x, color.getBedLocation().getBlockX() + x,
color.getBedLocation().getBlockY() + y, color.getBedLocation().getBlockY() + y,
color.getBedLocation().getBlockZ() + z color.getBedLocation().getBlockZ() + z
).getBlock(); ).getBlock();
if (block.getType() == Material.BED_BLOCK) { if (Utility.isBed(block)) {
Game.instance.breakBlock(block); Game.instance.breakBlock(block);
} }
} }
} }
} }
bed = false; bed = false;
for (BedwarsPlayer bwp : players) { for (BedwarsPlayer bwp : players) {
if (bwp.isOnline()) { if (bwp.isOnline()) {
Player p = bwp.getOnlinePlayer(); Player p = bwp.getOnlinePlayer();
String msg = color.getColorName() + "§r's bed was destroyed"; MessageUtility.parser("team.bed-broken.notification")
if (player != null) msg += " by " + player.getName(); .variable("team", getTeamColor().getColorName())
msg += "."; .variable("player", p == null ? "a very strong wind current" : p.getDisplayName())
Bukkit.broadcastMessage(msg); .broadcast();
Utility.sendTitle(p, "Bed destroyed!", "You will no longer respawn!", 5, 35, 10); Utility.sendTitle(p,
p.playSound(p.getLocation(), Sound.EXPLODE, 1, 1); MessageUtility.parser("team.bed-broken.title").parse(),
} MessageUtility.parser("team.bed-broken.subtitle").parse(),
} 5, 35, 10
);
ScoreboardManager.updateAll(); p.playSound(p.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1, 1);
}
return true; }
}
ScoreboardManager.updateAll();
public int decreaseRemainingPlayers() {
return --remainingPlayers; return true;
} }
public int getRemainingPlayers() {
return remainingPlayers; public int decreaseRemainingPlayers() {
} return --remainingPlayers;
public int getPlayersCount() { }
return playersCount; public int getRemainingPlayers() {
} return remainingPlayers;
public void resetRemainingPlayers() { }
remainingPlayers = playersCount; public int getPlayersCount() {
} return playersCount;
}
public void resetRemainingPlayers() {
remainingPlayers = playersCount;
}
public void removeUpgrade(Class<? extends TeamUpgrade> type) { public void removeUpgrade(Class<? extends TeamUpgrade> type) {
upgrades.keySet().removeIf(k -> { upgrades.keySet().removeIf(k -> {
TeamUpgrade v = upgrades.get(k); TeamUpgrade v = upgrades.get(k);
return v.getClass().equals(type); return v.getClass().equals(type);
}); });
} }
public void addUpgrade(TeamUpgrade upgrade) { public void addUpgrade(TeamUpgrade upgrade) {
upgrades.put(upgrade.getName(), upgrade); upgrades.put(upgrade.getName(), upgrade);
} }
public void updateUpgrades() { public void updateUpgrades() {
upgrades.values().forEach(v -> v.updateTeam(this)); upgrades.values().forEach(v -> v.updateTeam(this));
} }
public Collection<TeamUpgrade> getUpgrades() { public Collection<TeamUpgrade> getUpgrades() {
return upgrades.values(); return upgrades.values();
} }
public boolean hasUpgrade(TeamUpgrade upgrade) { public boolean hasUpgrade(TeamUpgrade upgrade) {
return upgrades.contains(upgrade); return upgrades.contains(upgrade);
} }
public TeamColor getTeamColor() { public TeamColor getTeamColor() {
return color; return color;
} }
public List<BedwarsPlayer> getPlayers() { public List<BedwarsPlayer> getPlayers() {
return Collections.unmodifiableList(players); return Collections.unmodifiableList(players);
} }
public void removePlayer(BedwarsPlayer p) { public void removePlayer(BedwarsPlayer p) {
if (players.remove(p)) { if (players.remove(p)) {
playersCount--; playersCount--;
if (!p.isSpectator()) remainingPlayers--; if (!p.isSpectator()) remainingPlayers--;
} }
} }
public void addPlayer(BedwarsPlayer p) { public void addPlayer(BedwarsPlayer p) {
if (players.add(p)) { if (players.add(p)) {
playersCount++; playersCount++;
if (!p.isSpectator()) remainingPlayers++; if (!p.isSpectator()) remainingPlayers++;
} }
} }
public void addPlayer(OfflinePlayer p) { public void addPlayer(OfflinePlayer p) {
if (!hasPlayer(p)) { if (!hasPlayer(p)) {
players.add(new BedwarsPlayer(p, this)); players.add(new BedwarsPlayer(p, this));
playersCount++; playersCount++;
if (bed) remainingPlayers++; if (bed) remainingPlayers++;
} }
} }
public boolean hasPlayer(BedwarsPlayer p) { public boolean hasPlayer(BedwarsPlayer p) {
return hasPlayer(p.getPlayer()); return hasPlayer(p.getPlayer());
} }
public boolean hasPlayer(OfflinePlayer p) { public boolean hasPlayer(OfflinePlayer p) {
return players return players
.stream() .stream()
.filter(v -> v.getPlayer().getUniqueId().equals(p.getUniqueId())) .filter(v -> v.getPlayer().getUniqueId().equals(p.getUniqueId()))
.findFirst() .findFirst()
.isPresent(); .isPresent();
} }
public boolean isEliminated() { public boolean isEliminated() {
return remainingPlayers == 0; return remainingPlayers == 0;
} }
@Override @Override
public void close() { public void close() {
generator.close(); generator.close();
for (BedwarsPlayer bwp : players) { for (BedwarsPlayer bwp : players) {
bwp.close(); bwp.close();
} }
HandlerList.unregisterAll(this); HandlerList.unregisterAll(this);
players = null; players = null;
generator = null; generator = null;
} }
@EventHandler @EventHandler
private void onBlockBreak(BlockBreakEvent e) { private void onBlockBreak(BlockBreakEvent e) {
if (e.getBlock().getType() == Material.BED_BLOCK) { if (Utility.isBed(e.getBlock())) {
if (e.getBlock().getLocation().distance(color.getBedLocation()) < 5) { if (e.getBlock().getLocation().distance(color.getBedLocation()) < 5) {
if (hasPlayer(e.getPlayer())) { if (hasPlayer(e.getPlayer())) {
e.setCancelled(true); e.setCancelled(true);
if (getPlayersCount() == 1) { if (getPlayersCount() == 1) {
e.getPlayer().sendMessage("§4You may not destroy your bed."); MessageUtility.parser("player.solo.break-own-bed").send(e.getPlayer());
} }
else { else {
e.getPlayer().sendMessage("§4You may not destroy your team's bed."); MessageUtility.parser("player.team.break-own-bed").send(e.getPlayer());
} }
} }
else { else {
if (bed) { if (bed) {
e.setCancelled(true); e.setCancelled(true);
destroyBed(e.getPlayer()); destroyBed(e.getPlayer());
} }
} }
} }
} }
} }
public void sendMessage(String msg) { public void sendMessage(BaseComponent[] msg) {
for (BedwarsPlayer bwp : players) { for (BedwarsPlayer bwp : players) {
if (bwp.isOnline()) bwp.getOnlinePlayer().sendMessage(msg); if (bwp.isOnline()) bwp.getOnlinePlayer().spigot().sendMessage(msg);
} }
} }
public void sendTitle(String title, String subtitle, int fadein, int duration, int fadeout) { public void sendTitle(BaseComponent[] title, BaseComponent[] subtitle, int fadein, int duration, int fadeout) {
for (BedwarsPlayer bwp : players) { for (BedwarsPlayer bwp : players) {
if (bwp.isOnline()) Utility.sendTitle(bwp.getOnlinePlayer(), title, subtitle, fadein, duration, fadeout); if (bwp.isOnline()) Utility.sendTitle(bwp.getOnlinePlayer(), title, subtitle, fadein, duration, fadeout);
} }
} }
public void sendTilteToOthers(String title, String subtitle, int fadein, int duration, int fadeout) { public void sendTitleToOthers(BaseComponent[] title, BaseComponent[] subtitle, int fadein, int duration, int fadeout) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) { for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (players.stream().noneMatch(v -> v.getPlayer().getUniqueId().equals(p.getUniqueId()))) if (players.stream().noneMatch(v -> v.getPlayer().getUniqueId().equals(p.getUniqueId())))
Utility.sendTitle(p, title, subtitle, fadein, duration, fadeout); Utility.sendTitle(p, title, subtitle, fadein, duration, fadeout);
} }
} }
@SuppressWarnings("deprecation") public ItemStack teamifyItem(ItemStack stack, boolean colour, boolean upgrades) {
public ItemStack teamifyItem(ItemStack stack, boolean colour, boolean upgrades) { if (colour) {
if (colour) { if (Utility.isWool(stack.getType())) stack.setType(color.getWoolMaterial());
if (stack.getType() == Material.WOOL) stack.setDurability((short)color.getWoolId()); else {
else { ItemMeta meta = stack.getItemMeta();
ItemMeta meta = stack.getItemMeta();
if (meta instanceof LeatherArmorMeta) {
if (meta instanceof LeatherArmorMeta) { LeatherArmorMeta armour = (LeatherArmorMeta)meta;
LeatherArmorMeta armour = (LeatherArmorMeta)meta; armour.setColor(color.getColor());
armour.setColor(DyeColor.getByData((byte)color.getWoolId()).getColor()); stack.setItemMeta(armour);
stack.setItemMeta(armour); }
} }
} }
}
if (upgrades) {
if (upgrades) { this.upgrades.values().forEach(v -> {
this.upgrades.values().forEach(v -> { v.upgradeItem(stack);
v.upgradeItem(stack); });
}); }
}
return stack;
return stack; }
}
public Team(TeamColor color, Player... players) {
public Team(TeamColor color, Player... players) { this.players.addAll(Arrays.asList(players)
this.players.addAll(Arrays.asList(players) .stream()
.stream() .map(v -> new BedwarsPlayer(v, this))
.map(v -> new BedwarsPlayer(v, this)) .collect(Collectors.toList())
.collect(Collectors.toList()) );
); this.color = color;
this.color = color; this.playersCount = this.remainingPlayers = players.length;
this.playersCount = this.remainingPlayers = players.length;
this.generator = new Generator(color.getGeneratorLocation(), 48, null);
this.generator = new Generator(color.getGeneratorLocation(), 48, null); this.generator.addItem(Material.IRON_INGOT, 20);
this.generator.addItem(Material.IRON_INGOT, 20); this.generator.addItem(Material.GOLD_INGOT, 80);
this.generator.addItem(Material.GOLD_INGOT, 80);
Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); }
}
} }

View File

@ -3,85 +3,100 @@ package me.topchetoeu.bedwars.engine;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Map; import java.util.Map;
import org.bukkit.Color;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.ConfigurationSerializable;
public class TeamColor implements ConfigurationSerializable { import me.topchetoeu.bedwars.Utility;
private String name; import net.md_5.bungee.api.ChatColor;
private int woolId; import net.md_5.bungee.api.chat.BaseComponent;
private char colorId; import net.md_5.bungee.api.chat.ComponentBuilder;
private Location bed = null;
private Location spawnLocation = null;
private Location generatorLocation = null;
public String getName() {
return name;
}
public String getColorName() {
return String.format("§%c%s%s", colorId, name.substring(0, 1).toUpperCase(), name.substring(1));
}
public int getWoolId() {
return woolId;
}
public char getColorId() {
return colorId;
}
public Location getBedLocation() {
return bed;
}
public void setBedLocation(Location loc) {
bed = loc;
}
public Location getSpawnLocation() { public class TeamColor implements ConfigurationSerializable {
return spawnLocation; private String name;
} private Material wool;
public void setSpawnLocation(Location loc) { private ChatColor chatColor;
spawnLocation = loc; private Color color;
} private Location bed = null;
private Location spawnLocation = null;
public Location getGeneratorLocation() { private Location generatorLocation = null;
return generatorLocation;
} public String getName() {
public void setGeneratorLocation(Location loc) { return name;
generatorLocation = loc; }
} public BaseComponent[] getColorName() {
return new ComponentBuilder().append(name).color(chatColor).create();
public boolean isFullySpecified() { }
return bed != null && spawnLocation != null && generatorLocation != null; public Material getWoolMaterial() {
} return wool;
}
public TeamColor(String name, int woolId, char colorId) { public Color getColor() {
this.name = name; return color;
this.woolId = woolId; }
this.colorId = colorId; public ChatColor getChatColor() {
} return chatColor;
@Override }
public Map<String, Object> serialize() {
Map<String, Object> map = new Hashtable<>(); public Location getBedLocation() {
return bed;
map.put("name", name); }
map.put("woolId", woolId); public void setBedLocation(Location loc) {
map.put("colorId", colorId); bed = loc;
if (bed != null) map.put("bed", bed.serialize()); }
if (generatorLocation != null) map.put("generator", generatorLocation.serialize());
if (spawnLocation != null) map.put("spawn", spawnLocation.serialize()); public Location getSpawnLocation() {
return spawnLocation;
return map; }
} public void setSpawnLocation(Location loc) {
@SuppressWarnings("unchecked") spawnLocation = loc;
public static TeamColor deserialize(Map<String, Object> map) { }
TeamColor color = new TeamColor(
(String)map.get("name"), public Location getGeneratorLocation() {
(int)map.get("woolId"), return generatorLocation;
((String)map.get("colorId")).charAt(0) }
); public void setGeneratorLocation(Location loc) {
generatorLocation = loc;
if (map.containsKey("bed")) color.setBedLocation(Location.deserialize((Map<String, Object>) map.get("bed"))); }
if (map.containsKey("generator")) color.setGeneratorLocation(Location.deserialize((Map<String, Object>) map.get("generator")));
if (map.containsKey("spawn"))color.setSpawnLocation(Location.deserialize((Map<String, Object>) map.get("spawn"))); public boolean isFullySpecified() {
return bed != null && spawnLocation != null && generatorLocation != null;
return color; }
}
public TeamColor(String name, Material wool, Color color, ChatColor colorId) {
this.name = name;
this.wool = wool;
this.color = color;
this.chatColor = colorId;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = new Hashtable<>();
map.put("name", name);
map.put("wool", wool.getKey().getKey().toLowerCase());
map.put("color", color.serialize());
map.put("chatColor", chatColor.getName());
if (bed != null) map.put("bed", bed.serialize());
if (generatorLocation != null) map.put("generator", generatorLocation.serialize());
if (spawnLocation != null) map.put("spawn", spawnLocation.serialize());
return map;
}
@SuppressWarnings({ "unchecked" })
public static TeamColor deserialize(Map<String, Object> map) {
TeamColor color = new TeamColor(
map.get("name").toString(),
Material.getMaterial(map.get("wool").toString().toUpperCase()),
Color.deserialize((Map<String, Object>)map.get("color")),
Utility.bukkitToBungeeColor(org.bukkit.ChatColor.valueOf(map.get("chatColor").toString().toUpperCase()))
);
if (map.containsKey("bed")) color.setBedLocation(Location.deserialize((Map<String, Object>) map.get("bed")));
if (map.containsKey("generator")) color.setGeneratorLocation(Location.deserialize((Map<String, Object>) map.get("generator")));
if (map.containsKey("spawn"))color.setSpawnLocation(Location.deserialize((Map<String, Object>) map.get("spawn")));
return color;
}
} }

View File

@ -5,22 +5,22 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class WoodenSword { public class WoodenSword {
public static boolean isOtherSword(Material mat) { public static boolean isOtherSword(Material mat) {
return mat == Material.IRON_SWORD || return mat == Material.IRON_SWORD ||
mat == Material.DIAMOND_SWORD || mat == Material.DIAMOND_SWORD ||
mat == Material.STONE_SWORD || mat == Material.STONE_SWORD ||
mat == Material.STONE_SWORD; mat == Material.STONE_SWORD;
} }
public static boolean hasOtherSword(Inventory inv) { public static boolean hasOtherSword(Inventory inv) {
return inv.contains(Material.IRON_SWORD) || return inv.contains(Material.IRON_SWORD) ||
inv.contains(Material.DIAMOND_SWORD) || inv.contains(Material.DIAMOND_SWORD) ||
inv.contains(Material.STONE_SWORD) || inv.contains(Material.STONE_SWORD) ||
inv.contains(Material.STONE_SWORD); inv.contains(Material.STONE_SWORD);
} }
public static void update(BedwarsPlayer p, Inventory inv) { public static void update(BedwarsPlayer p, Inventory inv) {
if (hasOtherSword(inv)) if (hasOtherSword(inv))
inv.remove(Material.WOOD_SWORD); inv.remove(Material.WOODEN_SWORD);
else if (!inv.contains(Material.WOOD_SWORD)) else if (!inv.contains(Material.WOODEN_SWORD))
inv.addItem(p.getTeam().teamifyItem(new ItemStack(Material.WOOD_SWORD, 1), true, true)); inv.addItem(p.getTeam().teamifyItem(new ItemStack(Material.WOODEN_SWORD, 1), true, true));
} }
} }

View File

@ -4,12 +4,14 @@ import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import net.md_5.bungee.api.chat.BaseComponent;
public interface Deal { public interface Deal {
public ItemStack getDealItem(Player p); public ItemStack getDealItem(Player p);
public String getDealName(Player p); public BaseComponent[] getDealName(Player p);
public Material getPriceType(Player p); public Material getPriceType(Player p);
public int getPrice(Player p); public int getPrice(Player p);
public boolean alreadyBought(Player p); public boolean alreadyBought(Player p);
public void commence(Player p); public void commence(Player p);
} }

View File

@ -3,24 +3,24 @@ package me.topchetoeu.bedwars.engine.trader;
import java.util.List; import java.util.List;
public class DealPtr { public class DealPtr {
private int sectionN; private int sectionN;
private int dealN; private int dealN;
public int getSectionN() { public int getSectionN() {
return sectionN; return sectionN;
} }
public int getDealN() { public int getDealN() {
return dealN; return dealN;
} }
public Deal getDeal(List<Section> sections) { public Deal getDeal(List<Section> sections) {
if (sections.size() <= sectionN) return null; if (sections.size() <= sectionN) return null;
if (sections.get(sectionN).getDeals().size() <= dealN) return null; if (sections.get(sectionN).getDeals().size() <= dealN) return null;
return sections.get(sectionN).getDeal(dealN); return sections.get(sectionN).getDeal(dealN);
} }
public DealPtr(int sectionN, int dealN) { public DealPtr(int sectionN, int dealN) {
this.sectionN = sectionN; this.sectionN = sectionN;
this.dealN = dealN; this.dealN = dealN;
} }
} }

View File

@ -3,6 +3,6 @@ package me.topchetoeu.bedwars.engine.trader;
import java.util.Map; import java.util.Map;
public interface DealType { public interface DealType {
public Deal parse(Map<String, Object> map); public Deal parse(Map<String, Object> map);
public String getId(); public String getId();
} }

View File

@ -3,18 +3,18 @@ package me.topchetoeu.bedwars.engine.trader;
import java.util.Hashtable; import java.util.Hashtable;
public class DealTypes { public class DealTypes {
private static Hashtable<String, DealType> dealTypes = new Hashtable<>(); private static Hashtable<String, DealType> dealTypes = new Hashtable<>();
private DealTypes() { private DealTypes() {
} }
public static boolean register(DealType type) { public static boolean register(DealType type) {
if (dealTypes.contains(type.getId())) return false; if (dealTypes.contains(type.getId())) return false;
dealTypes.put(type.getId(), type); dealTypes.put(type.getId(), type);
return true; return true;
} }
public static DealType get(String id) { public static DealType get(String id) {
return dealTypes.get(id); return dealTypes.get(id);
} }
} }

View File

@ -10,72 +10,72 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
public class Favourites { public class Favourites {
public static Favourites instance; public static Favourites instance;
private File directory; private File directory;
private Map<Integer, DealPtr> defaults; private Map<Integer, DealPtr> defaults;
private YamlConfiguration serialize(Map<Integer, DealPtr> favs) { private YamlConfiguration serialize(Map<Integer, DealPtr> favs) {
YamlConfiguration config = new YamlConfiguration(); YamlConfiguration config = new YamlConfiguration();
for (int n : favs.keySet()) { for (int n : favs.keySet()) {
Map<String, Object> map = new Hashtable<>(); Map<String, Object> map = new Hashtable<>();
map.put("section", favs.get(n).getSectionN()); map.put("section", favs.get(n).getSectionN());
map.put("deal", favs.get(n).getDealN()); map.put("deal", favs.get(n).getDealN());
config.set(Integer.toString(n), map); config.set(Integer.toString(n), map);
} }
return config; return config;
} }
private Map<Integer, DealPtr> deserialize(YamlConfiguration config) { private Map<Integer, DealPtr> deserialize(YamlConfiguration config) {
Map<Integer, DealPtr> favs = new Hashtable<>(); Map<Integer, DealPtr> favs = new Hashtable<>();
for (String s : config.getKeys(false)) { for (String s : config.getKeys(false)) {
int n = Integer.parseInt(s); int n = Integer.parseInt(s);
ConfigurationSection section = config.getConfigurationSection(s); ConfigurationSection section = config.getConfigurationSection(s);
int dealN, sectN; int dealN, sectN;
dealN = section.getInt("deal"); dealN = section.getInt("deal");
sectN = section.getInt("section"); sectN = section.getInt("section");
DealPtr deal = new DealPtr(sectN, dealN); DealPtr deal = new DealPtr(sectN, dealN);
favs.put(n, deal); favs.put(n, deal);
} }
return favs; return favs;
} }
public Map<Integer, DealPtr> getFavourites(OfflinePlayer p) { public Map<Integer, DealPtr> getFavourites(OfflinePlayer p) {
File file = new File(directory, p.getUniqueId().toString() + ".yml"); File file = new File(directory, p.getUniqueId().toString() + ".yml");
if (file.exists() && file.canRead()) return deserialize(YamlConfiguration.loadConfiguration(file)); if (file.exists() && file.canRead()) return deserialize(YamlConfiguration.loadConfiguration(file));
else { else {
try { try {
serialize(defaults).save(file); serialize(defaults).save(file);
} catch (IOException e) { /* everythings fine */ } } catch (IOException e) { /* everythings fine */ }
return defaults; return defaults;
} }
} }
public void updateFavourites(OfflinePlayer p, Map<Integer, DealPtr> newFavs) { public void updateFavourites(OfflinePlayer p, Map<Integer, DealPtr> newFavs) {
try { try {
serialize(newFavs).save(new File(directory, p.getUniqueId().toString() + ".yml")); serialize(newFavs).save(new File(directory, p.getUniqueId().toString() + ".yml"));
} catch (IOException e) { } catch (IOException e) {
p.getPlayer().sendMessage(e.getMessage()); p.getPlayer().sendMessage(e.getMessage());
} }
} }
public Favourites(File directory, Map<Integer, DealPtr> defaults) { public Favourites(File directory, Map<Integer, DealPtr> defaults) {
directory.mkdir(); directory.mkdir();
this.directory = directory; this.directory = directory;
this.defaults = defaults; this.defaults = defaults;
} }
public Favourites(File directory, File defaults) { public Favourites(File directory, File defaults) {
directory.mkdir(); directory.mkdir();
this.directory = directory; this.directory = directory;
this.defaults = deserialize(YamlConfiguration.loadConfiguration(defaults)); this.defaults = deserialize(YamlConfiguration.loadConfiguration(defaults));
} }
} }

View File

@ -7,42 +7,42 @@ import java.util.stream.Collectors;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class Section { public class Section {
private ArrayList<Deal> items = new ArrayList<>(); private ArrayList<Deal> items = new ArrayList<>();
private ItemStack icon; private ItemStack icon;
public Deal getDeal(int i) { public Deal getDeal(int i) {
if (i < 0 || i >= items.size()) return null; if (i < 0 || i >= items.size()) return null;
return items.get(i); return items.get(i);
} }
public Section addDeal(Deal d) { public Section addDeal(Deal d) {
items.add(d); items.add(d);
return this; return this;
} }
public void removeDeal(Deal d) { public void removeDeal(Deal d) {
items.remove(d); items.remove(d);
} }
public List<Deal> getDealPage(int size, int n) { public List<Deal> getDealPage(int size, int n) {
return items.stream().skip(size * n).limit(size).collect(Collectors.toList()); return items.stream().skip(size * n).limit(size).collect(Collectors.toList());
} }
public List<Deal> getDeals() { public List<Deal> getDeals() {
return new ArrayList<>(items); return new ArrayList<>(items);
} }
public ItemStack getIcon() { public ItemStack getIcon() {
return icon; return icon;
} }
public void setIcon(ItemStack item) { public void setIcon(ItemStack item) {
icon = item; icon = item;
} }
public Section(ItemStack icon) { public Section(ItemStack icon) {
this.items = new ArrayList<>(); this.items = new ArrayList<>();
this.icon = icon; this.icon = icon;
} }
public Section(ItemStack icon, List<Deal> deals) { public Section(ItemStack icon, List<Deal> deals) {
this.items = new ArrayList<>(deals); this.items = new ArrayList<>(deals);
this.icon = icon; this.icon = icon;
} }
} }

View File

@ -12,39 +12,39 @@ import me.topchetoeu.bedwars.Utility;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class Sections { public class Sections {
public static File SECTIONS_FILE; public static File SECTIONS_FILE;
private static List<Section> sections; private static List<Section> sections;
private static Deal deserializeDeal(Map<String, Object> raw) { private static Deal deserializeDeal(Map<String, Object> raw) {
String type = (String)raw.get("type"); String type = (String)raw.get("type");
DealType dealType = DealTypes.get(type); DealType dealType = DealTypes.get(type);
if (dealType == null) throw new RuntimeException(String.format("Deal type %s is not recognised.", type)); if (dealType == null) throw new RuntimeException(String.format("Deal type %s is not recognised.", type));
return dealType.parse(raw); return dealType.parse(raw);
} }
private static Section deserializeSection(Map<String, Object> raw) { private static Section deserializeSection(Map<String, Object> raw) {
List<Deal> deals = ((List<Map<?, ?>>)raw.get("deals")) List<Deal> deals = ((List<Map<?, ?>>)raw.get("deals"))
.stream() .stream()
.map(v -> deserializeDeal((Map<String, Object>)v)) .map(v -> deserializeDeal((Map<String, Object>)v))
.collect(Collectors.toList()); .collect(Collectors.toList());
ItemStack icon = Utility.deserializeItemStack((Map<String, Object>)raw.get("iconItem")); ItemStack icon = Utility.deserializeItemStack((Map<String, Object>)raw.get("iconItem"));
return new Section(icon, deals); return new Section(icon, deals);
} }
public static List<Section> getSections() { public static List<Section> getSections() {
return sections; return sections;
} }
public static void init(File sectionsFile) { public static void init(File sectionsFile) {
SECTIONS_FILE = sectionsFile; SECTIONS_FILE = sectionsFile;
sections = YamlConfiguration sections = YamlConfiguration
.loadConfiguration(SECTIONS_FILE) .loadConfiguration(SECTIONS_FILE)
.getMapList("sections") .getMapList("sections")
.stream() .stream()
.map(v -> deserializeSection((Map<String, Object>)v)) .map(v -> deserializeSection((Map<String, Object>)v))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }

View File

@ -23,319 +23,334 @@ import me.topchetoeu.bedwars.InventoryUtility;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.trader.dealTypes.ItemDeal; import me.topchetoeu.bedwars.engine.trader.dealTypes.ItemDeal;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
// Very bad code. // Very bad code.
public class TraderGUI implements Listener { public class TraderGUI implements Listener {
private List<Section> sections; private List<Section> sections;
private Inventory inventory = null; private Inventory inventory = null;
private Player player; private Player player;
private int currSectionN = -1; private int currSectionN = -1;
private Map<Integer, DealPtr> favourites; private Map<Integer, DealPtr> favourites;
private int currFavourite = -1; private int currFavourite = -1;
private int sectionsOffset = 0; private int sectionsOffset = 0;
private boolean sectionsOverflow = false; private boolean sectionsOverflow = false;
public Inventory getInventory() { public Inventory getInventory() {
return inventory; return inventory;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public ItemStack generateDealItem(Deal d, boolean addFavouriteLore) { public ItemStack generateDealItem(Deal d, boolean addFavouriteLore) {
String name = "§r" + d.getDealName(player); ComponentBuilder cb = new ComponentBuilder().append(d.getDealName(player));
if (d.alreadyBought(player)) name += " §4(already unlocked)"; if (d.alreadyBought(player)) cb.append("(already unlocked)").color(ChatColor.DARK_RED);
else name += String.format(" (%dx %s)", else cb
d.getPrice(player), .append(" (%dx ".formatted(d.getPrice(player)))
Utility.getItemName(d.getPriceType(player)) .reset()
); .append(BaseComponent.toLegacyText(Utility.getItemName(d.getPriceType(player)))).color(ChatColor.DARK_RED)
.append(")")
.reset();
ItemStack item = Utility.copyNamedItem(d.getDealItem(player), name); ItemStack item = Utility.copyNamedItem(d.getDealItem(player), BaseComponent.toLegacyText(cb.create()));
if (addFavouriteLore) { if (addFavouriteLore) {
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
lore.add("§rShift + Left click to set slot"); lore.add("§rShift + Left click to set slot");
lore.add("§rShift + Right click to reset"); lore.add("§rShift + Right click to reset");
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
if (meta.getLore() != null) lore.addAll(meta.getLore()); if (meta.getLore() != null) lore.addAll(meta.getLore());
meta.setLore(lore); meta.setLore(lore);
item.setItemMeta(meta); item.setItemMeta(meta);
} }
return item; return item;
} }
public void setSectionOffset(int n) { public void setSectionOffset(int n) {
sectionsOffset = n; sectionsOffset = n;
ItemStack[] invC = inventory.getContents(); ItemStack[] invC = inventory.getContents();
ItemStack blackGlassPanes = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)15); ItemStack blackGlassPanes = new ItemStack(Material.BLACK_STAINED_GLASS_PANE, 1);
ItemMeta meta = blackGlassPanes.getItemMeta(); ItemMeta meta = blackGlassPanes.getItemMeta();
meta.setDisplayName(" "); meta.setDisplayName(" ");
blackGlassPanes.setItemMeta(meta); blackGlassPanes.setItemMeta(meta);
for (int i = 1; i < 8; i++) { for (int i = 1; i < 8; i++) {
invC[i] = blackGlassPanes; invC[i] = blackGlassPanes;
} }
if (sectionsOffset == 0) if (sectionsOffset == 0)
invC[1 - sectionsOffset] = Utility.namedItem(new ItemStack(Material.NETHER_STAR), "§rFavourites"); invC[1 - sectionsOffset] = Utility.namedItem(new ItemStack(Material.NETHER_STAR), "§rFavourites");
for (int i = 0; i < sections.size(); i++) { for (int i = 0; i < sections.size(); i++) {
Section sec = sections.get(i); Section sec = sections.get(i);
int index = i + 2 - sectionsOffset; int index = i + 2 - sectionsOffset;
if (index > 0 && index < 8) invC[index] = sec.getIcon(); if (index > 0 && index < 8) invC[index] = sec.getIcon();
} }
inventory.setContents(invC); inventory.setContents(invC);
} }
public void selectSection(int n) { public void selectSection(int n) {
if (n == -1) if (n == -1)
selectFavourite(); selectFavourite();
else { else {
if (n < 0 || n >= sections.size()) return; if (n < 0 || n >= sections.size()) return;
Section sec = sections.get(n); Section sec = sections.get(n);
ItemStack[] contents = inventory.getContents(); ItemStack[] contents = inventory.getContents();
for (int x = 1; x < 8; x++) { for (int x = 1; x < 8; x++) {
for (int y = 1; y < 5; y++) { for (int y = 1; y < 5; y++) {
contents[x + y * 9] = null; contents[x + y * 9] = null;
} }
} }
for (int i = 0; i < sec.getDeals().size(); i++) { for (int i = 0; i < sec.getDeals().size(); i++) {
Deal d = sec.getDeal(i); Deal d = sec.getDeal(i);
contents[i % 7 + i / 7 * 9 + 10] = generateDealItem(d, false); contents[i % 7 + i / 7 * 9 + 10] = generateDealItem(d, false);
} }
inventory.setContents(contents); inventory.setContents(contents);
} }
player.playSound(player.getLocation(), Sound.CLICK, 1, 1); player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
currSectionN = n; currSectionN = n;
} }
public void selectFavourite() { public void selectFavourite() {
ItemStack[] contents = inventory.getContents(); ItemStack[] contents = inventory.getContents();
ItemStack empty = Utility.namedItem(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)8), "§rEmpty slot"); ItemStack empty = Utility.namedItem(new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1), "§rEmpty slot");
ItemMeta meta = empty.getItemMeta(); ItemMeta meta = empty.getItemMeta();
List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
lore.add("§rShift + Left click to set slot"); lore.add("§rShift + Left click to set slot");
meta.setLore(lore); meta.setLore(lore);
empty.setItemMeta(meta); empty.setItemMeta(meta);
for (int x = 1; x < 8; x++) { for (int x = 1; x < 8; x++) {
for (int y = 1; y < 5; y++) { for (int y = 1; y < 5; y++) {
contents[x + y * 9] = empty; contents[x + y * 9] = empty;
} }
} }
for (Integer n : favourites.keySet()) { for (Integer n : favourites.keySet()) {
Deal d = favourites.get(n).getDeal(sections); Deal d = favourites.get(n).getDeal(sections);
if (d != null) contents[n % 7 + n / 7 * 9 + 10] = generateDealItem(d, true); if (d != null) contents[n % 7 + n / 7 * 9 + 10] = generateDealItem(d, true);
} }
inventory.setContents(contents); inventory.setContents(contents);
currSectionN = -1; currSectionN = -1;
} }
public void updateSection() { public void updateSection() {
selectSection(currSectionN); selectSection(currSectionN);
} }
public void trade(Deal deal) { public void trade(Deal deal) {
if (deal.alreadyBought(player)) { if (deal.alreadyBought(player)) {
player.sendMessage("You already own this."); MessageUtility.parser("trade.already-unlocked").variable("name", deal.getDealName(player)).send(player);
player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1, 1); player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
} }
else { else {
ItemStack[] inv = player.getInventory().getContents(); ItemStack[] inv = player.getInventory().getContents();
ItemStack price = new ItemStack(deal.getPriceType(player), deal.getPrice(player)); ItemStack price = new ItemStack(deal.getPriceType(player), deal.getPrice(player));
if (deal instanceof ItemDeal && !((ItemDeal)deal).isImplemented()) { if (deal instanceof ItemDeal && !((ItemDeal)deal).isImplemented()) {
deal.commence(player); deal.commence(player);
} }
else { else {
if (InventoryUtility.hasItem(inv, price)) { if (InventoryUtility.hasItem(inv, price)) {
InventoryUtility.takeItems(inv, price); InventoryUtility.takeItems(inv, price);
player.getInventory().setContents(inv); player.getInventory().setContents(inv);
deal.commence(player); MessageUtility.parser("trade.purchase")
updateSection(); .variable("name", deal.getDealName(player))
if (player.getInventory().contains(Material.STONE_SWORD) || .variable("price", deal.getPrice(player))
player.getInventory().contains(Material.IRON_SWORD) || .variable("priceType", Utility.getItemName(deal.getPriceType(player)))
player.getInventory().contains(Material.DIAMOND_SWORD)) { .send(player);
if (player.getInventory().contains(Material.WOOD_SWORD)) { deal.commence(player);
player.getInventory().remove(Material.WOOD_SWORD); updateSection();
} if (player.getInventory().contains(Material.STONE_SWORD) ||
} player.getInventory().contains(Material.IRON_SWORD) ||
player.playSound(player.getLocation(), Sound.VILLAGER_YES, 1, 1); player.getInventory().contains(Material.DIAMOND_SWORD)) {
} if (player.getInventory().contains(Material.WOODEN_SWORD)) {
else { player.getInventory().remove(Material.WOODEN_SWORD);
player.sendMessage(String.format("You don't have enough %ss!", Utility.getItemName(deal.getPriceType(player)).toLowerCase())); }
player.playSound(player.getLocation(), Sound.VILLAGER_NO, 1, 1); }
} player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_YES, 1, 1);
} }
} else {
} MessageUtility.parser("trade.not-enough-resources")
.variable("name", deal.getDealName(player))
private void generateInventory(Inventory inv) { .variable("price", deal.getPrice(player))
ItemStack blackGlassPanes = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)15); .variable("priceType", Utility.getItemName(deal.getPriceType(player)))
ItemMeta meta = blackGlassPanes.getItemMeta(); .send(player);
meta.setDisplayName(" "); player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
blackGlassPanes.setItemMeta(meta); }
}
ItemStack[] invC = inv.getContents(); }
}
for (int i = 0; i < 6; i++) {
invC[i * 9] = blackGlassPanes; private void generateInventory(Inventory inv) {
invC[i * 9 + 8] = blackGlassPanes; ItemStack blackGlassPanes = new ItemStack(Material.BLACK_STAINED_GLASS_PANE, 1);
} ItemMeta meta = blackGlassPanes.getItemMeta();
for (int i = 0; i < 9; i++) { meta.setDisplayName(" ");
invC[i] = blackGlassPanes; blackGlassPanes.setItemMeta(meta);
invC[i + 45] = blackGlassPanes;
} ItemStack[] invC = inv.getContents();
if (sectionsOverflow) { for (int i = 0; i < 6; i++) {
invC[0] = Utility.namedItem(new ItemStack(Material.ARROW), "§rBack"); invC[i * 9] = blackGlassPanes;
invC[8] = Utility.namedItem(new ItemStack(Material.ARROW), "§rForward"); invC[i * 9 + 8] = blackGlassPanes;
} }
for (int i = 0; i < 9; i++) {
inv.setContents(invC); invC[i] = blackGlassPanes;
invC[i + 45] = blackGlassPanes;
ItemStack exitItem = new ItemStack(Material.BARRIER); }
meta = exitItem.getItemMeta();
meta.setDisplayName("§rExit"); if (sectionsOverflow) {
exitItem.setItemMeta(meta); invC[0] = Utility.namedItem(new ItemStack(Material.ARROW), "§rBack");
inv.setItem(49, exitItem); invC[8] = Utility.namedItem(new ItemStack(Material.ARROW), "§rForward");
}
setSectionOffset(0);
} inv.setContents(invC);
public Inventory open() { ItemStack exitItem = new ItemStack(Material.BARRIER);
inventory = Bukkit.createInventory(null, 54, "Trader"); meta = exitItem.getItemMeta();
generateInventory(inventory); meta.setDisplayName("§rExit");
selectFavourite(); exitItem.setItemMeta(meta);
inv.setItem(49, exitItem);
inventory = player.openInventory(inventory).getTopInventory();
setSectionOffset(0);
return inventory; }
}
public void dispose() { public Inventory open() {
HandlerList.unregisterAll(this); inventory = Bukkit.createInventory(null, 54, "Trader");
sections = null; generateInventory(inventory);
inventory = null; selectFavourite();
}
inventory = player.openInventory(inventory).getTopInventory();
private void setFavourite(DealPtr d) {
if (currFavourite < 0) return; return inventory;
if (d == null && favourites.containsKey(currFavourite)) { }
favourites.remove(currFavourite); public void dispose() {
Favourites.instance.updateFavourites(player, favourites); HandlerList.unregisterAll(this);
player.playSound(player.getLocation(), Sound.GHAST_FIREBALL, 1, 1); sections = null;
} inventory = null;
else { }
favourites.put(currFavourite, d);
Favourites.instance.updateFavourites(player, favourites); private void setFavourite(DealPtr d) {
player.playSound(player.getLocation(), Sound.ORB_PICKUP, 1, 1); if (currFavourite < 0) return;
} if (d == null && favourites.containsKey(currFavourite)) {
favourites.remove(currFavourite);
currFavourite = -1; Favourites.instance.updateFavourites(player, favourites);
selectFavourite(); player.playSound(player.getLocation(), Sound.ENTITY_GHAST_SHOOT, 1, 1);
} }
else {
@EventHandler favourites.put(currFavourite, d);
private void onInventoryClick(InventoryClickEvent e) { Favourites.instance.updateFavourites(player, favourites);
if ((Object)inventory == (Object)e.getInventory()) { player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1, 1);
e.setCancelled(true); }
if (e.getClickedInventory() == e.getInventory()) {
if (e.getClick() != ClickType.LEFT && e.getClick() != ClickType.SHIFT_LEFT && e.getClick() != ClickType.SHIFT_RIGHT) return; currFavourite = -1;
int slot = e.getSlot(); selectFavourite();
}
if (slot == 0 && sectionsOffset > 0) {
setSectionOffset(sectionsOffset - 1); @EventHandler
return; private void onInventoryClick(InventoryClickEvent e) {
} if ((Object)inventory == (Object)e.getInventory()) {
if (slot == 8 && sectionsOffset < sections.size() - 6) { e.setCancelled(true);
setSectionOffset(sectionsOffset + 1); if (e.getClickedInventory() == e.getInventory()) {
return; if (e.getClick() != ClickType.LEFT && e.getClick() != ClickType.SHIFT_LEFT && e.getClick() != ClickType.SHIFT_RIGHT) return;
} int slot = e.getSlot();
if (slot % 9 == 8 || slot % 9 == 0) { if (slot == 0 && sectionsOffset > 0) {
if (currFavourite >= 0) setFavourite(null); setSectionOffset(sectionsOffset - 1);
return; return;
} }
if (slot == 8 && sectionsOffset < sections.size() - 6) {
setSectionOffset(sectionsOffset + 1);
return;
}
if (slot % 9 == 8 || slot % 9 == 0) {
if (currFavourite >= 0) setFavourite(null);
return;
}
if (slot == 49) { if (slot == 49) {
player.closeInventory(); player.closeInventory();
player.playSound(player.getLocation(), Sound.CLICK, 1, 1); player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
return; return;
} }
else if (slot < 9) selectSection(slot - 2 + sectionsOffset); // Section else if (slot < 9) selectSection(slot - 2 + sectionsOffset); // Section
else if (slot / 9 == 5) { else if (slot / 9 == 5) {
if (currFavourite >= 0) setFavourite(null); if (currFavourite >= 0) setFavourite(null);
} }
else { else {
int x = slot % 9 - 1; int x = slot % 9 - 1;
int y = slot / 9 - 1; int y = slot / 9 - 1;
int n = x + y * 7; int n = x + y * 7;
Deal d = null; Deal d = null;
if (currSectionN >= 0) { if (currSectionN >= 0) {
Section s = sections.get(currSectionN); Section s = sections.get(currSectionN);
d = s.getDeal(n); d = s.getDeal(n);
} }
else if (favourites.containsKey(n)) { else if (favourites.containsKey(n)) {
d = favourites.get(n).getDeal(sections); d = favourites.get(n).getDeal(sections);
} }
if (currSectionN < 0) { if (currSectionN < 0) {
if (e.getClick() == ClickType.SHIFT_LEFT) { if (e.getClick() == ClickType.SHIFT_LEFT) {
player.playSound(player.getLocation(), Sound.CLICK, 1, 1); player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
currFavourite = n; return; currFavourite = n; return;
} }
else if (e.getClick() == ClickType.SHIFT_RIGHT) { else if (e.getClick() == ClickType.SHIFT_RIGHT) {
currFavourite = n; currFavourite = n;
setFavourite(null); setFavourite(null);
return; return;
} }
} }
if (d != null) { if (d != null) {
if (currFavourite < 0) trade(d); if (currFavourite < 0) trade(d);
else { else {
if (currSectionN < 0) setFavourite(favourites.get(n)); if (currSectionN < 0) setFavourite(favourites.get(n));
else setFavourite(new DealPtr(currSectionN, n)); else setFavourite(new DealPtr(currSectionN, n));
} }
} }
} }
} }
} }
} }
@EventHandler @EventHandler
private void onInventoryClose(InventoryCloseEvent e) { private void onInventoryClose(InventoryCloseEvent e) {
if (e.getInventory() == inventory) { if (e.getInventory() == inventory) {
dispose(); dispose();
} }
} }
public TraderGUI(File favsDir, Player p) { public TraderGUI(File favouritesDir, Player p) {
this.sections = Sections.getSections(); this.sections = Sections.getSections();
this.player = p; this.player = p;
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
this.favourites = Favourites.instance.getFavourites(p); this.favourites = Favourites.instance.getFavourites(p);
this.sectionsOverflow = sections.size() + 1 > 7; this.sectionsOverflow = sections.size() + 1 > 7;
} }
} }

View File

@ -1,9 +1,11 @@
package me.topchetoeu.bedwars.engine.trader; package me.topchetoeu.bedwars.engine.trader;
import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -14,7 +16,6 @@ import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Villager; import org.bukkit.entity.Villager;
@ -27,156 +28,149 @@ import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.google.common.io.Files;
import me.topchetoeu.bedwars.Main; import me.topchetoeu.bedwars.Main;
import net.minecraft.server.v1_8_R3.NBTTagCompound; import me.topchetoeu.bedwars.Utility;
public class Traders implements Listener { public class Traders implements Listener {
public static Traders instance = null; public static Traders instance = null;
private List<UUID> villagers = new ArrayList<>(); private List<UUID> villagers = new ArrayList<>();
private File file; private File file;
private void write() {
BufferedWriter writer;
try {
writer = Files.newWriter(file, Charset.defaultCharset());
for (UUID uuid : villagers) {
writer.write(uuid.toString() + "\n");
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Villager summonVillager(Location loc) {
Villager vil = (Villager)loc.getWorld().spawnEntity(loc, EntityType.VILLAGER);
net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) vil).getHandle();
NBTTagCompound tag = nmsEntity.getNBTTag();
if (tag == null) {
tag = new NBTTagCompound();
}
nmsEntity.c(tag);
tag.setInt("NoAI", 1);
nmsEntity.f(tag);
nmsEntity.b(true);
villagers.add(vil.getUniqueId());
write();
return vil;
}
@EventHandler
private void onEntityInteract(PlayerInteractEntityEvent e) {
if (e.getRightClicked() instanceof Villager) {
Villager v = (Villager)e.getRightClicked();
if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) {
e.setCancelled(true);
File favsDir = new File(Main.getInstance().getDataFolder(), "favourites"); private final ItemStack eradicator, spawner;
new TraderGUI(favsDir, e.getPlayer()).open(); private void write() {
} try {
} OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
}
@EventHandler for (UUID uuid : villagers) {
private void onUse(PlayerInteractEvent e) { writer.write(uuid.toString() + "\n");
if (e.getAction() == Action.RIGHT_CLICK_BLOCK && }
e.hasItem() && writer.close();
e.getItem().hasItemMeta() && } catch (IOException e) {
e.getItem().getItemMeta().hasDisplayName() && e.printStackTrace();
e.getItem().getItemMeta().getDisplayName() == "§rTrader spawner") { }
if (e.getItem().getType() == Material.MONSTER_EGG) { }
int yaw = (int)e.getPlayer().getLocation().getYaw() - 45;
if (yaw < 0) yaw += 360; public void give(Player p) {
p.getInventory().addItem(eradicator, spawner);
yaw = yaw / 90 * 90; }
yaw -= 90;
public Villager summonVillager(Location loc) {
Villager vil = (Villager)loc.getWorld().spawnEntity(loc, EntityType.VILLAGER);
Location loc = new Location(
e.getClickedBlock().getLocation().getWorld(), vil.setAI(false);
e.getClickedBlock().getLocation().getBlockX() + .5, villagers.add(vil.getUniqueId());
e.getClickedBlock().getLocation().getBlockY(),
e.getClickedBlock().getLocation().getBlockZ() + .5, write();
yaw, 0
); return vil;
}
if (e.getBlockFace() == BlockFace.DOWN) loc.setY(loc.getY() - 2);
if (e.getBlockFace() == BlockFace.UP) loc.setY(loc.getY() + 1); @EventHandler
if (e.getBlockFace() == BlockFace.SOUTH) loc.setZ(loc.getZ() + 1); private void onEntityInteract(PlayerInteractEntityEvent e) {
if (e.getBlockFace() == BlockFace.NORTH) loc.setZ(loc.getZ() - 1); if (e.getRightClicked() instanceof Villager) {
if (e.getBlockFace() == BlockFace.EAST) loc.setX(loc.getX() + 1); Villager v = (Villager)e.getRightClicked();
if (e.getBlockFace() == BlockFace.WEST) loc.setX(loc.getX() - 1);
if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) {
summonVillager(loc); e.setCancelled(true);
e.getPlayer().sendMessage("Trader spawned!"); File favsDir = new File(Main.getInstance().getDataFolder(), "favourites");
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.VILLAGER_YES, 1, 1);
} new TraderGUI(favsDir, e.getPlayer()).open();
} }
} }
@EventHandler }
private void onEntityDamage(EntityDamageEvent e) { @EventHandler
if (e.getEntity() instanceof Villager) { private void onUse(PlayerInteractEvent e) {
Villager v = (Villager)e.getEntity(); if (e.getAction() == Action.RIGHT_CLICK_BLOCK &&
e.hasItem() &&
if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) { spawner.getItemMeta().equals(e.getItem().getItemMeta())) {
e.setCancelled(true); if (e.getItem().getType() == Material.VILLAGER_SPAWN_EGG) {
} int yaw = (int)e.getPlayer().getLocation().getYaw() - 45;
} if (yaw < 0) yaw += 360;
}
@EventHandler yaw = yaw / 90 * 90;
private void onEntityDamageEntity(EntityDamageByEntityEvent e) { yaw -= 90;
if (e.getDamager() instanceof Player) {
Player p = (Player)e.getDamager();
Location loc = new Location(
if (e.getEntity() instanceof Villager) { e.getClickedBlock().getLocation().getWorld(),
Villager v = (Villager)e.getEntity(); e.getClickedBlock().getLocation().getBlockX() + .5,
e.getClickedBlock().getLocation().getBlockY(),
if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) { e.getClickedBlock().getLocation().getBlockZ() + .5,
e.setCancelled(true); yaw, 0
);
ItemStack hand = p.getInventory().getItemInHand();
if (e.getBlockFace() == BlockFace.DOWN) loc.setY(loc.getY() - 2);
if (hand != null && if (e.getBlockFace() == BlockFace.UP) loc.setY(loc.getY() + 1);
hand.hasItemMeta() && if (e.getBlockFace() == BlockFace.SOUTH) loc.setZ(loc.getZ() + 1);
hand.getItemMeta().hasDisplayName() && if (e.getBlockFace() == BlockFace.NORTH) loc.setZ(loc.getZ() - 1);
hand.getItemMeta().getDisplayName().equals("§rTrader eradicator")) { if (e.getBlockFace() == BlockFace.EAST) loc.setX(loc.getX() + 1);
if (hand.getType() == Material.STICK) { if (e.getBlockFace() == BlockFace.WEST) loc.setX(loc.getX() - 1);
villagers.remove(v.getUniqueId());
write(); summonVillager(loc);
v.remove();
p.playSound(p.getLocation(), Sound.VILLAGER_DEATH, 1, 1); e.getPlayer().sendMessage("Trader spawned!");
p.sendMessage("Trader removed!"); e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_YES, 1, 1);
}
} e.setCancelled(true);
} }
} }
} }
} @EventHandler
private void onEntityDamage(EntityDamageEvent e) {
if (e.getEntity() instanceof Villager) {
Villager v = (Villager)e.getEntity();
public Traders(File tradersFile) throws IOException {
if (!tradersFile.exists()) tradersFile.createNewFile(); if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) {
villagers = Files.readLines(tradersFile, Charset.defaultCharset()) e.setCancelled(true);
.stream() }
.map(v -> UUID.fromString(v)) }
.collect(Collectors.toList()); }
@EventHandler
file = tradersFile; private void onEntityDamageEntity(EntityDamageByEntityEvent e) {
if (e.getDamager() instanceof Player) {
Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); Player p = (Player)e.getDamager();
}
if (e.getEntity() instanceof Villager) {
Villager v = (Villager)e.getEntity();
if (villagers.stream().anyMatch(_v -> _v.equals(v.getUniqueId()))) {
e.setCancelled(true);
ItemStack hand = p.getInventory().getItemInMainHand();
if (hand != null &&
hand.hasItemMeta() &&
eradicator.getItemMeta().equals(hand.getItemMeta())) {
if (hand.getType() == Material.STICK) {
villagers.remove(v.getUniqueId());
write();
v.remove();
p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_DEATH, 1, 1);
p.sendMessage("Trader removed!");
}
}
}
}
}
}
public Traders(File tradersFile) throws IOException {
if (!tradersFile.exists()) tradersFile.createNewFile();
villagers = Files.readAllLines(Path.of(tradersFile.getAbsolutePath()))
.stream()
.map(v -> UUID.fromString(v))
.collect(Collectors.toList());
file = tradersFile;
spawner = Utility.namedItem(new ItemStack(Material.VILLAGER_SPAWN_EGG), "§rTrader spawner");
eradicator = Utility.namedItem(new ItemStack(Material.STICK), "§rTrader eradicator");
Bukkit.getPluginManager().registerEvents(this, Main.getInstance());
}
} }

View File

@ -1,52 +1,52 @@
package me.topchetoeu.bedwars.engine.trader.dealTypes; package me.topchetoeu.bedwars.engine.trader.dealTypes;
import java.util.Hashtable; import java.util.Hashtable;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.engine.Game; import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.trader.Deal; import me.topchetoeu.bedwars.engine.trader.Deal;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class EnforcedRankedDeal implements Deal { public class EnforcedRankedDeal implements Deal {
private Rank soldRank; private Rank soldRank;
private Hashtable<RankTier, Price> prices; private Hashtable<RankTier, Price> prices;
public Rank getRank() { public Rank getRank() {
return soldRank; return soldRank;
} }
@Override @Override
public ItemStack getDealItem(Player p) { public ItemStack getDealItem(Player p) {
ItemStack icon = soldRank.getNextTier(p).getIcon(); ItemStack icon = soldRank.getNextTier(p).getIcon();
if (Game.isStarted()) Game.instance.teamifyItem(p, icon, true, true); if (Game.isStarted()) Game.instance.teamifyItem(p, icon, true, true);
return icon; return icon;
} }
@Override @Override
public String getDealName(Player p) { public BaseComponent[] getDealName(Player p) {
return soldRank.getNextTier(p).getDisplayName(); return new ComponentBuilder().append(soldRank.getNextTier(p).getDisplayName()).reset().create();
} }
@Override @Override
public Material getPriceType(Player p) { public Material getPriceType(Player p) {
return prices.get(soldRank.getNextTier(p)).getPriceType(); return prices.get(soldRank.getNextTier(p)).getPriceType();
} }
@Override @Override
public int getPrice(Player p) { public int getPrice(Player p) {
return prices.get(soldRank.getNextTier(p)).getPrice(); return prices.get(soldRank.getNextTier(p)).getPrice();
} }
@Override @Override
public boolean alreadyBought(Player p) { public boolean alreadyBought(Player p) {
return soldRank.getNextTier(p) == soldRank.getPlayerTier(p); return soldRank.getNextTier(p) == soldRank.getPlayerTier(p);
} }
@Override @Override
public void commence(Player p) { public void commence(Player p) {
p.sendMessage(String.format("§rYou just purchased %s.", getDealName(p))); soldRank.increasePlayerTier(p, soldRank.getNextTier(p));
soldRank.increasePlayerTier(p, soldRank.getNextTier(p)); }
}
public EnforcedRankedDeal(Rank rank, Hashtable<RankTier, Price> prices) {
public EnforcedRankedDeal(Rank rank, Hashtable<RankTier, Price> prices) { this.soldRank = rank;
this.soldRank = rank; this.prices = prices;
this.prices = prices; }
}
} }

View File

@ -8,28 +8,28 @@ import me.topchetoeu.bedwars.engine.trader.DealType;
import me.topchetoeu.bedwars.engine.trader.DealTypes; import me.topchetoeu.bedwars.engine.trader.DealTypes;
public class EnforcedRankedDealType implements DealType { public class EnforcedRankedDealType implements DealType {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Deal parse(Map<String, Object> map) { public Deal parse(Map<String, Object> map) {
Hashtable<RankTier, Price> prices = new Hashtable<>(); Hashtable<RankTier, Price> prices = new Hashtable<>();
Rank rank = RankedDealType.getDefinedRanks().get((String)map.get("rank")); Rank rank = RankedDealType.getDefinedRanks().get((String)map.get("rank"));
Map<String, Map<String, Object>> pricesMap = (Map<String, Map<String, Object>>)map.get("prices"); Map<String, Map<String, Object>> pricesMap = (Map<String, Map<String, Object>>)map.get("prices");
for (String name : pricesMap.keySet()) { for (String name : pricesMap.keySet()) {
RankTier tier = rank.getTier(name); RankTier tier = rank.getTier(name);
Price price = Price.deserialize(pricesMap.get(name)); Price price = Price.deserialize(pricesMap.get(name));
prices.put(tier, price); prices.put(tier, price);
} }
return new EnforcedRankedDeal(rank, prices); return new EnforcedRankedDeal(rank, prices);
} }
@Override @Override
public String getId() { return "tier_enforced"; } public String getId() { return "tier_enforced"; }
public static void init() { public static void init() {
DealTypes.register(new EnforcedRankedDealType()); DealTypes.register(new EnforcedRankedDealType());
} }
} }

View File

@ -10,65 +10,77 @@ import me.topchetoeu.bedwars.engine.BedwarsPlayer;
import me.topchetoeu.bedwars.engine.Game; import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.WoodenSword; import me.topchetoeu.bedwars.engine.WoodenSword;
import me.topchetoeu.bedwars.engine.trader.Deal; import me.topchetoeu.bedwars.engine.trader.Deal;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class ItemDeal implements Deal { public class ItemDeal implements Deal {
private ItemStack item; private ItemStack item;
private int price; private int price;
private Material priceType; private Material priceType;
private boolean implemented; private boolean implemented;
@Override @Override
public ItemStack getDealItem(Player p) { public ItemStack getDealItem(Player p) {
ItemStack item = this.item; ItemStack item = this.item;
if (Game.isStarted()) Game.instance.teamifyItem(p, item, true, true); if (Game.isStarted()) Game.instance.teamifyItem(p, item, true, true);
return item; return item;
} }
@Override @Override
public String getDealName(Player p) { public BaseComponent[] getDealName(Player p) {
return String.format("§r%dx %s%s", item.getAmount(), Utility.getItemName(item), implemented ? "" : " §4§l(not implemented)§r"); ComponentBuilder builder = new ComponentBuilder()
} .append(Integer.toString(item.getAmount()))
.append("x ")
.append(Utility.getItemName(item));
if (!implemented) builder.append(" (not implemented)").bold(true).color(ChatColor.RED);
return builder.create();
}
@Override @Override
public Material getPriceType(Player p) { public Material getPriceType(Player p) {
return priceType; return priceType;
} }
public boolean isImplemented() { public boolean isImplemented() {
return implemented; return implemented;
} }
@Override @Override
public int getPrice(Player p) { public int getPrice(Player p) {
return price; return price;
} }
@Override @Override
public void commence(Player p) { public void commence(Player p) {
if (!implemented) { if (!implemented) {
p.sendMessage("The item you're trying to buy is not implemented yet."); MessageUtility.parser("player.trade.not-implemented")
return; .variable("name", getDealName(p))
} .variable("price", getPrice(p))
ItemStack item = getDealItem(p); .variable("priceType", getPriceType(p))
p.sendMessage(String.format("You just purchased %s.", getDealName(p))); .send(p);
ItemStack[] contents = p.getInventory().getContents(); return;
InventoryUtility.giveItem(contents, item); }
p.getInventory().setContents(contents); ItemStack item = getDealItem(p);
if (Game.isStarted()) { ItemStack[] contents = p.getInventory().getContents();
BedwarsPlayer bwp = Game.instance.getPlayer(p); InventoryUtility.giveItem(contents, item);
if (bwp != null) WoodenSword.update(bwp, p.getInventory()); p.getInventory().setContents(contents);
} if (Game.isStarted()) {
BedwarsPlayer bwp = Game.instance.getPlayer(p);
} if (bwp != null) WoodenSword.update(bwp, p.getInventory());
}
}
public ItemDeal(ItemStack item, int price, Material priceType, boolean implemented) { public ItemDeal(ItemStack item, int price, Material priceType, boolean implemented) {
this.item = item; this.item = item;
this.price = price; this.price = price;
this.priceType = priceType; this.priceType = priceType;
this.implemented = implemented; this.implemented = implemented;
} }
@Override @Override
public boolean alreadyBought(Player p) { public boolean alreadyBought(Player p) {
return false; return false;
} }
} }

View File

@ -11,24 +11,24 @@ import me.topchetoeu.bedwars.engine.trader.DealType;
import me.topchetoeu.bedwars.engine.trader.DealTypes; import me.topchetoeu.bedwars.engine.trader.DealTypes;
public class ItemDealType implements DealType { public class ItemDealType implements DealType {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Deal parse(Map<String, Object> map) { public Deal parse(Map<String, Object> map) {
boolean implemented = !map.containsKey("implemented") || (boolean)map.get("implemented"); boolean implemented = !map.containsKey("implemented") || (boolean)map.get("implemented");
int price = (Integer)map.get("price"); int price = (Integer)map.get("price");
Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase()); Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase());
ItemStack type = Utility.deserializeItemStack((Map<String, Object>)map.get("item")); ItemStack type = Utility.deserializeItemStack((Map<String, Object>)map.get("item"));
return new ItemDeal(type, price, priceType, implemented); return new ItemDeal(type, price, priceType, implemented);
} }
@Override @Override
public String getId() { public String getId() {
return "item"; return "item";
} }
public static void init() { public static void init() {
DealTypes.register(new ItemDealType()); DealTypes.register(new ItemDealType());
} }
} }

View File

@ -5,31 +5,31 @@ import java.util.Map;
import org.bukkit.Material; import org.bukkit.Material;
public class Price { public class Price {
private int price; private int price;
private Material priceType; private Material priceType;
private String displayName; private String displayName;
public int getPrice() { public int getPrice() {
return price; return price;
} }
public Material getPriceType() { public Material getPriceType() {
return priceType; return priceType;
} }
public String getDisplayName() { public String getDisplayName() {
return displayName; return displayName;
} }
public static Price deserialize(Map<String, Object> map) { public static Price deserialize(Map<String, Object> map) {
int price = (Integer)map.get("price"); int price = (Integer)map.get("price");
Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase()); Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase());
String displayName = (String)map.get("displayName"); String displayName = (String)map.get("displayName");
return new Price(price, priceType, displayName); return new Price(price, priceType, displayName);
} }
public Price(int price, Material priceType, String displayName) { public Price(int price, Material priceType, String displayName) {
this.price = price; this.price = price;
this.priceType = priceType; this.priceType = priceType;
this.displayName = displayName; this.displayName = displayName;
} }
} }

View File

@ -29,231 +29,234 @@ import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType.InventoryBeh
import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType.LoseAction; import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType.LoseAction;
public class Rank implements Listener { public class Rank implements Listener {
private RankTier defaultTier; private RankTier defaultTier;
private LoseAction onLose; private LoseAction onLose;
private InventoryBehaviour inventory; private InventoryBehaviour inventory;
private Map<String, RankTier> nameToTierMap; private Map<String, RankTier> nameToTierMap;
private ArrayList<RankTier> tiers; private ArrayList<RankTier> tiers;
private Hashtable<UUID, RankTier> currentTier = new Hashtable<>(); private Hashtable<UUID, RankTier> currentTier = new Hashtable<>();
public void resetPlayerTiers() { public void resetPlayerTiers() {
for (UUID key : new HashSet<>(currentTier.keySet())) { for (UUID key : new HashSet<>(currentTier.keySet())) {
if (defaultTier == null) currentTier.remove(key); if (defaultTier == null) currentTier.remove(key);
else currentTier.put(key, defaultTier); else currentTier.put(key, defaultTier);
} }
} }
public boolean hasDefaultTier() { public boolean hasDefaultTier() {
return defaultTier != null; return defaultTier != null;
} }
public RankTier getDefaultTier() { public RankTier getDefaultTier() {
return defaultTier; return defaultTier;
} }
public LoseAction getOnLoseAction() { public LoseAction getOnLoseAction() {
return onLose; return onLose;
} }
public InventoryBehaviour getInventoryBehaviour() { public InventoryBehaviour getInventoryBehaviour() {
return inventory; return inventory;
} }
public Collection<RankTier> getTiers() { public Collection<RankTier> getTiers() {
return nameToTierMap.values(); return nameToTierMap.values();
} }
public Set<String> getTierNames() { public Set<String> getTierNames() {
return nameToTierMap.keySet(); return nameToTierMap.keySet();
} }
public RankTier getTier(String name) { public RankTier getTier(String name) {
return nameToTierMap.get(name); return nameToTierMap.get(name);
} }
public boolean containsItem(ItemStack item) { public boolean containsItem(ItemStack item) {
if (item == null) return false; if (item == null) return false;
return tiers.stream() return tiers.stream()
.flatMap(v -> v.getItems() .flatMap(v -> v.getItems()
.stream() .stream()
.filter(_v -> _v instanceof RankTierItemApplier) .filter(_v -> _v instanceof RankTierItemApplier)
.map(_v -> (RankTierItemApplier)_v) .map(_v -> (RankTierItemApplier)_v)
.map(i -> i.getItem()) .map(i -> i.getItem())
) )
.anyMatch(v -> v.getType().equals(item.getType())); .anyMatch(v -> v.getType().equals(item.getType()));
} }
public boolean playerHasOrAboveTier(OfflinePlayer player, RankTier tier) { public boolean playerHasOrAboveTier(OfflinePlayer player, RankTier tier) {
return tiers.indexOf(tier) <= tiers.indexOf(getPlayerTier(player)); return tiers.indexOf(tier) <= tiers.indexOf(getPlayerTier(player));
} }
public RankTier getPlayerTier(OfflinePlayer player) { public RankTier getPlayerTier(OfflinePlayer player) {
return currentTier.get(player.getUniqueId()); return currentTier.get(player.getUniqueId());
} }
public RankTier getNextTier(OfflinePlayer player) { public RankTier getNextTier(OfflinePlayer player) {
int i = tiers.indexOf(getPlayerTier(player)) + 1; int i = tiers.indexOf(getPlayerTier(player)) + 1;
if (i >= tiers.size()) i--; if (i >= tiers.size()) i--;
return tiers.get(i); return tiers.get(i);
} }
public void increasePlayerTier(OfflinePlayer player, RankTier target) { public void increasePlayerTier(OfflinePlayer player, RankTier target) {
int i = tiers.indexOf(getPlayerTier(player)); int i = tiers.indexOf(getPlayerTier(player));
int targetI = tiers.indexOf(target); int targetI = tiers.indexOf(target);
if (targetI <= i) return; if (targetI <= i) return;
if (player.isOnline()) { if (player.isOnline()) {
Player p = player.getPlayer(); Player p = player.getPlayer();
ItemStack[] inv = p.getInventory().getContents(); ItemStack[] inv = p.getInventory().getContents();
i++; i++;
for (; i <= targetI; i++) { for (; i <= targetI; i++) {
tiers.get(i).apply(inv, p, this); tiers.get(i).apply(inv, p, this);
} }
ItemStack[] armor = p.getInventory().getArmorContents();
p.getInventory().setContents(inv); p.getInventory().setContents(inv);
} p.getInventory().setArmorContents(armor);
}
currentTier.put(player.getUniqueId(), target);
} currentTier.put(player.getUniqueId(), target);
}
public void clear(ItemStack[] inv) {
for (int i = 0; i < inv.length; i++) { public void clear(ItemStack[] inv) {
if (inv[i] != null && containsItem(inv[i])) { for (int i = 0; i < inv.length; i++) {
inv[i] = null; if (inv[i] != null && containsItem(inv[i])) {
} inv[i] = null;
} }
} }
}
public void onDeath(Player p) {
RankTier tier = getPlayerTier(p); public void onDeath(Player p) {
RankTier tier = getPlayerTier(p);
if (tier != null) {
currentTier.put(p.getUniqueId(), onLose.getTier(tier)); if (tier != null) {
} currentTier.put(p.getUniqueId(), onLose.getTier(tier));
refreshInv(p); }
} refreshInv(p);
@EventHandler }
private void onRespawn(PlayerRespawnEvent e) { @EventHandler
if (Game.instance.isPlaying(e.getPlayer())) { private void onRespawn(PlayerRespawnEvent e) {
} if (Game.instance.isPlaying(e.getPlayer())) {
} }
@EventHandler }
private void onJoin(PlayerJoinEvent e) { @EventHandler
if (Game.inGame(e.getPlayer())) { private void onJoin(PlayerJoinEvent e) {
if (defaultTier != null) increasePlayerTier(e.getPlayer(), defaultTier); if (Game.inGame(e.getPlayer())) {
refreshInv(e.getPlayer()); if (defaultTier != null) increasePlayerTier(e.getPlayer(), defaultTier);
} refreshInv(e.getPlayer());
} }
}
@EventHandler @EventHandler
private void onDrop(PlayerDropItemEvent e) { private void onDrop(PlayerDropItemEvent e) {
if (containsItem(e.getItemDrop().getItemStack())) { if (containsItem(e.getItemDrop().getItemStack())) {
if (inventory != InventoryBehaviour.FREE) e.setCancelled(true); if (inventory != InventoryBehaviour.FREE) e.setCancelled(true);
} }
} }
@EventHandler @EventHandler
private void onInventory(InventoryClickEvent e) { private void onInventory(InventoryClickEvent e) {
if (Game.isStarted() && Game.instance.isPlaying((Player)e.getWhoClicked())) { if (Game.isStarted() && Game.instance.isPlaying((Player)e.getWhoClicked())) {
if (containsItem(e.getCurrentItem()) || containsItem(e.getCursor())) { if (containsItem(e.getCurrentItem()) || containsItem(e.getCursor())) {
switch (inventory) { switch (inventory) {
case STUCK: case STUCK:
e.setCancelled(true); e.setCancelled(true);
return; return;
case NOENDER: case NOENDER:
if ((e.getClickedInventory() instanceof PlayerInventory)) { if ((e.getClickedInventory() instanceof PlayerInventory)) {
if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) e.setCancelled(true); if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) e.setCancelled(true);
} }
else e.setCancelled(true); else e.setCancelled(true);
case NODROP: case NODROP:
switch (e.getAction()) { switch (e.getAction()) {
case DROP_ALL_CURSOR: case DROP_ALL_CURSOR:
case DROP_ALL_SLOT: case DROP_ALL_SLOT:
case DROP_ONE_CURSOR: case DROP_ONE_CURSOR:
case DROP_ONE_SLOT: case DROP_ONE_SLOT:
e.setCancelled(true); e.setCancelled(true);
default: default:
break; break;
} }
return; return;
case FREE: case FREE:
return; return;
} }
} }
} }
} }
public void refreshInv(Player p) { public void refreshInv(Player p) {
ItemStack[] inv = p.getInventory().getContents(); ItemStack[] inv = p.getInventory().getContents();
clear(inv); clear(inv);
RankTier tier = getPlayerTier(p); RankTier tier = getPlayerTier(p);
if (tier != null) { if (tier != null) {
int max = tiers.indexOf(tier); int max = tiers.indexOf(tier);
for (int i = 0; i <= max; i++) { for (int i = 0; i <= max; i++) {
tiers.get(i).apply(inv, p, this); tiers.get(i).apply(inv, p, this);
} }
} }
p.getInventory().setContents(inv); ItemStack[] armor = p.getInventory().getArmorContents();
p.updateInventory(); p.getInventory().setContents(inv);
} p.getInventory().setArmorContents(armor);
p.updateInventory();
}
@SuppressWarnings("unchecked")
public static Rank deserialize(Plugin pl, Map<String, Object> map) {
List<RankTier> tiers = ((Map<String, Object>)map.get("tiers")) @SuppressWarnings("unchecked")
.entrySet() public static Rank deserialize(Plugin pl, Map<String, Object> map) {
.stream() List<RankTier> tiers = ((Map<String, Object>)map.get("tiers"))
.map(v -> RankTier.deserialize(v.getKey(), (Map<String, Object>)v.getValue())) .entrySet()
.collect(Collectors.toList()); .stream()
.map(v -> RankTier.deserialize(v.getKey(), (Map<String, Object>)v.getValue()))
RankTier defaultTier = map.containsKey("default") ? tiers .collect(Collectors.toList());
.stream()
.filter(v -> v.getName().equals(map.get("default"))) RankTier defaultTier = map.containsKey("default") ? tiers
.findFirst() .stream()
.orElseThrow() : null; .filter(v -> v.getName().equals(map.get("default")))
InventoryBehaviour inventory = InventoryBehaviour.valueOf(((String)map.get("inventory")).toUpperCase()); .findFirst()
.orElseThrow() : null;
return new Rank(pl, tiers, inventory, defaultTier, (String)map.get("onLose")); InventoryBehaviour inventory = InventoryBehaviour.valueOf(((String)map.get("inventory")).toUpperCase());
}
return new Rank(pl, tiers, inventory, defaultTier, (String)map.get("onLose"));
public Rank(Plugin pl, Collection<RankTier> tiers, InventoryBehaviour inventory, RankTier defaultTier, String loseAction) { }
this.tiers = new ArrayList<>(tiers);
this.nameToTierMap = this.tiers.stream().collect(Collectors.toMap(v -> v.getName(), v -> v)); public Rank(Plugin pl, Collection<RankTier> tiers, InventoryBehaviour inventory, RankTier defaultTier, String loseAction) {
this.inventory = inventory; this.tiers = new ArrayList<>(tiers);
this.defaultTier = defaultTier; this.nameToTierMap = this.tiers.stream().collect(Collectors.toMap(v -> v.getName(), v -> v));
this.inventory = inventory;
switch (loseAction) { this.defaultTier = defaultTier;
case "keep":
onLose = currTier -> currTier; switch (loseAction) {
break; case "keep":
case "lower": onLose = currTier -> currTier;
onLose = currTier -> { break;
int i = this.tiers.indexOf(currTier) - 1; case "lower":
if (i < 0) i = 0; onLose = currTier -> {
Bukkit.getServer().broadcastMessage(Integer.toString(i)); int i = this.tiers.indexOf(currTier) - 1;
if (i < 0) i = 0;
return this.tiers.get(i); Bukkit.getServer().broadcastMessage(Integer.toString(i));
};
break; return this.tiers.get(i);
case "lose": };
onLose = currTier -> null; break;
break; case "lose":
default: onLose = currTier -> null;
if (loseAction.startsWith("tier_")) { break;
String tierName = loseAction.substring(5); default:
RankTier tier = nameToTierMap.get(tierName); if (loseAction.startsWith("tier_")) {
onLose = currTier -> tier; String tierName = loseAction.substring(5);
} RankTier tier = nameToTierMap.get(tierName);
else throw new RuntimeException(String.format("The lose action %s was not recognised.", loseAction)); onLose = currTier -> tier;
break; }
} else throw new RuntimeException(String.format("The lose action %s was not recognised.", loseAction));
break;
if (defaultTier != null) { }
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
increasePlayerTier(p, defaultTier); if (defaultTier != null) {
} for (Player p : Bukkit.getServer().getOnlinePlayers()) {
} increasePlayerTier(p, defaultTier);
}
Bukkit.getPluginManager().registerEvents(this, pl); }
}
Bukkit.getPluginManager().registerEvents(this, pl);
}
} }

View File

@ -8,48 +8,50 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class RankTier { public class RankTier {
private String name; private String name;
private ItemStack icon; private ItemStack icon;
private Collection<RankTierItemApplier> items; private Collection<RankTierItemApplier> items;
public String getName() { public String getName() {
return name; return name;
} }
public String getDisplayName() { public BaseComponent[] getDisplayName() {
return Utility.getItemName(icon); return new ComponentBuilder().append(Utility.getItemName(icon)).reset().create();
} }
public ItemStack getIcon() { public ItemStack getIcon() {
return icon; return icon;
} }
public Collection<RankTierItemApplier> getItems() { public Collection<RankTierItemApplier> getItems() {
return items; return items;
} }
public void apply(ItemStack[] inv, Player p, Rank rank) { public void apply(ItemStack[] inv, Player p, Rank rank) {
for (RankTierItemApplier item : items) { for (RankTierItemApplier item : items) {
item.apply(p, inv, rank); item.apply(p, inv, rank);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static RankTier deserialize(String name, Map<String, Object> map) { public static RankTier deserialize(String name, Map<String, Object> map) {
Collection<RankTierItemApplier> items = ((Collection<Map<String, Object>>)map.get("items")) Collection<RankTierItemApplier> items = ((Collection<Map<String, Object>>)map.get("items"))
.stream() .stream()
.map(v -> RankTierItemApplier.deserialize(v)) .map(v -> RankTierItemApplier.deserialize(v))
.collect(Collectors.toList()); .collect(Collectors.toList());
ItemStack icon = null; ItemStack icon = null;
if (map.containsKey("icon")) icon = Utility.deserializeItemStack((Map<String, Object>)map.get("icon")); if (map.containsKey("icon")) icon = Utility.deserializeItemStack((Map<String, Object>)map.get("icon"));
else icon = items.stream().findFirst().orElseThrow().getIcon(); else icon = items.stream().findFirst().orElseThrow().getIcon();
return new RankTier(name, icon, items); return new RankTier(name, icon, items);
} }
public RankTier(String name, ItemStack icon, Collection<RankTierItemApplier> items) { public RankTier(String name, ItemStack icon, Collection<RankTierItemApplier> items) {
this.name = name; this.name = name;
this.icon = icon; this.icon = icon;
this.items = items; this.items = items;
} }
} }

View File

@ -6,19 +6,19 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public interface RankTierApplier { public interface RankTierApplier {
ItemStack getIcon(); ItemStack getIcon();
void apply(Player p, ItemStack[] inv, Rank rank); void apply(Player p, ItemStack[] inv, Rank rank);
public static RankTierApplier deserialize(Map<String, Object> map) { public static RankTierApplier deserialize(Map<String, Object> map) {
if (!map.containsKey("type")) throw new RuntimeException("A type property was expected for a rank tier item."); if (!map.containsKey("type")) throw new RuntimeException("A type property was expected for a rank tier item.");
switch (map.get("type").toString()) { switch (map.get("type").toString()) {
case "item": case "item":
return RankTierItemApplier.deserialize(map); return RankTierItemApplier.deserialize(map);
case "upgrade": case "upgrade":
return null; return null;
default: default:
throw new RuntimeException("Unrecoginsed rank tier item type '" + map.get("type") + "'."); throw new RuntimeException("Unrecoginsed rank tier item type '" + map.get("type") + "'.");
} }
} }
} }

View File

@ -12,61 +12,61 @@ import me.topchetoeu.bedwars.engine.Team;
import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType.ApplyAction; import me.topchetoeu.bedwars.engine.trader.dealTypes.RankedDealType.ApplyAction;
public class RankTierItemApplier implements RankTierApplier { public class RankTierItemApplier implements RankTierApplier {
private ItemStack item; private ItemStack item;
private ApplyAction apply; private ApplyAction apply;
public ItemStack getIcon() { public ItemStack getIcon() {
return item; return item;
} }
public ItemStack getItem() { public ItemStack getItem() {
return item; return item;
} }
public ApplyAction getApplyAction() { public ApplyAction getApplyAction() {
return apply; return apply;
} }
public void apply(Player p, ItemStack[] items, Rank rank) { public void apply(Player p, ItemStack[] items, Rank rank) {
ItemStack item = this.item.clone(); ItemStack item = this.item.clone();
if (Game.isStarted()) { if (Game.isStarted()) {
Team team = Game.instance.getTeam(p); Team team = Game.instance.getTeam(p);
if (team != null) team.teamifyItem(item, true, true); if (team != null) team.teamifyItem(item, true, true);
} }
ItemStack remaining = null; ItemStack remaining = null;
switch (apply) { switch (apply) {
case GIVE: case GIVE:
remaining = InventoryUtility.giveItem(items, item); remaining = InventoryUtility.giveItem(items, item);
break; break;
case REPLACEPREV: case REPLACEPREV:
rank.clear(items); rank.clear(items);
remaining = InventoryUtility.giveItem(items, item); remaining = InventoryUtility.giveItem(items, item);
break; break;
case SLOT_HELMET: case SLOT_HELMET:
p.getInventory().setHelmet(item); p.getInventory().setHelmet(item);
break; break;
case SLOT_CHESTPLATE: case SLOT_CHESTPLATE:
p.getInventory().setChestplate(item); p.getInventory().setChestplate(item);
break; break;
case SLOT_LEGGINGS: case SLOT_LEGGINGS:
p.getInventory().setLeggings(item); p.getInventory().setLeggings(item);
break; break;
case SLOT_BOOTS: case SLOT_BOOTS:
p.getInventory().setBoots(item); p.getInventory().setBoots(item);
break; break;
} }
if (remaining != null) p.getWorld().dropItemNaturally(p.getLocation(), remaining); if (remaining != null) p.getWorld().dropItemNaturally(p.getLocation(), remaining);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static RankTierItemApplier deserialize(Map<String, Object> map) { public static RankTierItemApplier deserialize(Map<String, Object> map) {
ItemStack item = Utility.deserializeItemStack((Map<String, Object>)map.get("item")); ItemStack item = Utility.deserializeItemStack((Map<String, Object>)map.get("item"));
ApplyAction apply = ApplyAction.REPLACEPREV; ApplyAction apply = ApplyAction.REPLACEPREV;
if (map.containsKey("apply")) apply = ApplyAction.valueOf(((String)map.get("apply")).toUpperCase()); if (map.containsKey("apply")) apply = ApplyAction.valueOf(((String)map.get("apply")).toUpperCase());
return new RankTierItemApplier(item, apply); return new RankTierItemApplier(item, apply);
} }
public RankTierItemApplier(ItemStack item, ApplyAction apply) { public RankTierItemApplier(ItemStack item, ApplyAction apply) {
this.item = item; this.item = item;
this.apply = apply; this.apply = apply;
} }
} }

View File

@ -7,53 +7,54 @@ import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.Utility; import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.Game; import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.trader.Deal; import me.topchetoeu.bedwars.engine.trader.Deal;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
public class RankedDeal implements Deal { public class RankedDeal implements Deal {
private Rank soldRank; private Rank soldRank;
private RankTier soldTier; private RankTier soldTier;
private Material priceType; private Material priceType;
private int price; private int price;
public Rank getRank() { public Rank getRank() {
return soldRank; return soldRank;
} }
public RankTier getTier() { public RankTier getTier() {
return soldTier; return soldTier;
} }
@Override @Override
public ItemStack getDealItem(Player p) { public ItemStack getDealItem(Player p) {
ItemStack icon = soldTier.getIcon(); ItemStack icon = soldTier.getIcon();
if (Game.isStarted()) Game.instance.teamifyItem(p, icon, true, true); if (Game.isStarted()) Game.instance.teamifyItem(p, icon, true, true);
return icon; return icon;
} }
@Override @Override
public String getDealName(Player p) { public BaseComponent[] getDealName(Player p) {
return Utility.getItemName(soldTier.getIcon()); return new ComponentBuilder().append(Utility.getItemName(soldTier.getIcon())).reset().create();
} }
@Override @Override
public Material getPriceType(Player p) { public Material getPriceType(Player p) {
return priceType; return priceType;
} }
@Override @Override
public int getPrice(Player p) { public int getPrice(Player p) {
return price; return price;
} }
@Override @Override
public boolean alreadyBought(Player p) { public boolean alreadyBought(Player p) {
return soldRank.playerHasOrAboveTier(p, soldTier); return soldRank.playerHasOrAboveTier(p, soldTier);
} }
@Override @Override
public void commence(Player p) { public void commence(Player p) {
p.sendMessage(String.format("§rYou just purchased %s.", getDealName(p))); soldRank.increasePlayerTier(p, soldTier);
soldRank.increasePlayerTier(p, soldTier); }
}
public RankedDeal(Rank rank, RankTier tier, Material priceType, int price) {
public RankedDeal(Rank rank, RankTier tier, Material priceType, int price) { soldRank = rank;
soldRank = rank; soldTier = tier;
soldTier = tier; this.priceType = priceType;
this.priceType = priceType; this.price = price;
this.price = price; }
}
} }

View File

@ -15,69 +15,69 @@ import me.topchetoeu.bedwars.engine.trader.DealType;
import me.topchetoeu.bedwars.engine.trader.DealTypes; import me.topchetoeu.bedwars.engine.trader.DealTypes;
public class RankedDealType implements DealType { public class RankedDealType implements DealType {
private static Hashtable<String, Rank> definedRanks = new Hashtable<>(); private static Hashtable<String, Rank> definedRanks = new Hashtable<>();
@Override @Override
public Deal parse(Map<String, Object> map) { public Deal parse(Map<String, Object> map) {
Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase()); Material priceType = Material.getMaterial(((String)map.get("priceType")).toUpperCase());
int price = (Integer)map.get("price"); int price = (Integer)map.get("price");
Rank rank = definedRanks.get((String)map.get("rank")); Rank rank = definedRanks.get((String)map.get("rank"));
RankTier tier = rank.getTier((String)map.get("tier")); RankTier tier = rank.getTier((String)map.get("tier"));
return new RankedDeal(rank, tier, priceType, price); return new RankedDeal(rank, tier, priceType, price);
} }
@Override @Override
public String getId() { return "tier"; } public String getId() { return "tier"; }
public interface LoseAction { public interface LoseAction {
RankTier getTier(RankTier curr); RankTier getTier(RankTier curr);
} }
public enum InventoryBehaviour { public enum InventoryBehaviour {
FREE, FREE,
NODROP, NODROP,
NOENDER, NOENDER,
STUCK, STUCK,
} }
public enum ApplyAction { public enum ApplyAction {
GIVE, GIVE,
REPLACEPREV, REPLACEPREV,
SLOT_HELMET, SLOT_HELMET,
SLOT_CHESTPLATE, SLOT_CHESTPLATE,
SLOT_LEGGINGS, SLOT_LEGGINGS,
SLOT_BOOTS, SLOT_BOOTS,
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void init(Plugin pl, Configuration config) { public static void init(Plugin pl, Configuration config) {
DealTypes.register(new RankedDealType()); DealTypes.register(new RankedDealType());
Map<String, Object> mapConf = Utility.mapifyConfig(config); Map<String, Object> mapConf = Utility.mapifyConfig(config);
Map<String, Object> ranks = (Map<String, Object>)mapConf.get("ranks"); Map<String, Object> ranks = (Map<String, Object>)mapConf.get("ranks");
if (ranks != null) { if (ranks != null) {
for (String key : ranks.keySet()) { for (String key : ranks.keySet()) {
Map<String, Object> map = (Map<String, Object>)ranks.get(key); Map<String, Object> map = (Map<String, Object>)ranks.get(key);
definedRanks.put(key, Rank.deserialize(pl, map)); definedRanks.put(key, Rank.deserialize(pl, map));
} }
} }
} }
public static void resetPlayerTiers() { public static void resetPlayerTiers() {
for (String key: definedRanks.keySet()) { for (String key: definedRanks.keySet()) {
definedRanks.get(key).resetPlayerTiers(); definedRanks.get(key).resetPlayerTiers();
} }
} }
public static void refreshPlayer(Player p) { public static void refreshPlayer(Player p) {
for (Rank rank : definedRanks.values()) { for (Rank rank : definedRanks.values()) {
rank.refreshInv(p); rank.refreshInv(p);
} }
} }
public static Map<String, Rank> getDefinedRanks() { public static Map<String, Rank> getDefinedRanks() {
return Collections.unmodifiableMap(definedRanks); return Collections.unmodifiableMap(definedRanks);
} }
} }

View File

@ -11,78 +11,85 @@ import me.topchetoeu.bedwars.engine.Game;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
import me.topchetoeu.bedwars.engine.trader.Deal; import me.topchetoeu.bedwars.engine.trader.Deal;
import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade; import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade;
import me.topchetoeu.bedwars.messaging.MessageUtility;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
public class RankedUpgradeDeal implements Deal { public class RankedUpgradeDeal implements Deal {
private TeamUpgradeRank rank; private TeamUpgradeRank rank;
private Hashtable<TeamUpgrade, Price> prices = new Hashtable<>(); private Hashtable<TeamUpgrade, Price> prices = new Hashtable<>();
@Override @Override
public ItemStack getDealItem(Player p) { public ItemStack getDealItem(Player p) {
ItemStack _default = new ItemStack(Material.DIAMOND, 1); ItemStack _default = new ItemStack(Material.DIAMOND, 1);
if (!Game.isStarted()) return _default; if (!Game.isStarted()) return _default;
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return _default; if (t == null) return _default;
TeamUpgrade upgrade = rank.getNextTeamUpgrade(t); TeamUpgrade upgrade = rank.getNextTeamUpgrade(t);
ItemStack icon = rank.getIcon(upgrade); ItemStack icon = rank.getIcon(upgrade);
if (icon == null) return _default; if (icon == null) return _default;
else return icon; else return icon;
} }
@Override @Override
public void commence(Player p) { public void commence(Player p) {
if (!Game.isStarted()) return; if (!Game.isStarted()) return;
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return; if (t == null) return;
TeamUpgrade upgrade = rank.getNextTeamUpgrade(t); TeamUpgrade upgrade = rank.getNextTeamUpgrade(t);
if (upgrade == null) return; if (upgrade == null) return;
upgrade.addToTeam(t); upgrade.addToTeam(t);
upgrade.updateTeam(t); upgrade.updateTeam(t);
t.sendMessage(p.getName() + "§r purchased " + upgrade.getDisplayName() + "§r!"); MessageUtility.parser("team.upgrade-purchased")
} .variable("player", p.getDisplayName())
.variable("upgrade", getDealName(p))
.send(t);
}
@Override @Override
public String getDealName(Player p) { public BaseComponent[] getDealName(Player p) {
if (!Game.isStarted()) return "None"; if (!Game.isStarted()) return new BaseComponent[] { new TextComponent("???") };
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return "None"; if (t == null) return new BaseComponent[] { new TextComponent("???") };
return rank.getNextTeamUpgrade(t).getDisplayName(); return new ComponentBuilder().reset().append(rank.getNextTeamUpgrade(t).getDisplayName()).create();
} }
@Override @Override
public Material getPriceType(Player p) { public Material getPriceType(Player p) {
if (!Game.isStarted()) return Material.DIAMOND; if (!Game.isStarted()) return Material.DIAMOND;
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return Material.DIAMOND; if (t == null) return Material.DIAMOND;
TeamUpgrade upgrade = rank.getNextTeamUpgrade(t); TeamUpgrade upgrade = rank.getNextTeamUpgrade(t);
Price price = prices.get(upgrade); Price price = prices.get(upgrade);
return price.getPriceType(); return price.getPriceType();
} }
@Override @Override
public int getPrice(Player p) { public int getPrice(Player p) {
if (!Game.isStarted()) return 128; if (!Game.isStarted()) return 128;
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return 128; if (t == null) return 128;
TeamUpgrade upgrade = rank.getNextTeamUpgrade(t); TeamUpgrade upgrade = rank.getNextTeamUpgrade(t);
Price price = prices.get(upgrade); Price price = prices.get(upgrade);
return price.getPrice(); return price.getPrice();
} }
@Override @Override
public boolean alreadyBought(Player p) { public boolean alreadyBought(Player p) {
if (!Game.isStarted()) return false; if (!Game.isStarted()) return false;
Team t = Game.instance.getTeam(p); Team t = Game.instance.getTeam(p);
if (t == null) return false; if (t == null) return false;
return rank.isTeamAlreadyHighest(t); return rank.isTeamAlreadyHighest(t);
} }
public RankedUpgradeDeal(TeamUpgradeRank rank, Map<TeamUpgrade, Price> prices) { public RankedUpgradeDeal(TeamUpgradeRank rank, Map<TeamUpgrade, Price> prices) {
this.prices = new Hashtable<>(prices); this.prices = new Hashtable<>(prices);
this.rank = rank; this.rank = rank;
} }
} }

View File

@ -10,31 +10,31 @@ import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade;
public class RankedUpgradeDealType implements DealType { public class RankedUpgradeDealType implements DealType {
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Deal parse(Map<String, Object> map) { public Deal parse(Map<String, Object> map) {
Hashtable<TeamUpgrade, Price> prices = new Hashtable<>(); Hashtable<TeamUpgrade, Price> prices = new Hashtable<>();
TeamUpgradeRank rank = TeamUpgradeRanks.get((String)map.get("rank")); TeamUpgradeRank rank = TeamUpgradeRanks.get((String)map.get("rank"));
Map<String, Object> pricesMap = (Map<String, Object>)map.get("prices"); Map<String, Object> pricesMap = (Map<String, Object>)map.get("prices");
for (String name : pricesMap.keySet()) { for (String name : pricesMap.keySet()) {
TeamUpgrade tier = rank.get(name); TeamUpgrade tier = rank.get(name);
Price price = Price.deserialize((Map<String, Object>)pricesMap.get(name)); Price price = Price.deserialize((Map<String, Object>)pricesMap.get(name));
prices.put(tier, price); prices.put(tier, price);
} }
return new RankedUpgradeDeal(rank, prices); return new RankedUpgradeDeal(rank, prices);
} }
@Override @Override
public String getId() { public String getId() {
return "upgrade"; return "upgrade";
} }
public static void init() { public static void init() {
DealTypes.register(new RankedUpgradeDealType()); DealTypes.register(new RankedUpgradeDealType());
} }
} }

View File

@ -14,72 +14,72 @@ import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrade;
import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrades; import me.topchetoeu.bedwars.engine.trader.upgrades.TeamUpgrades;
public class TeamUpgradeRank { public class TeamUpgradeRank {
private ArrayList<TeamUpgrade> upgrades = new ArrayList<>(); private ArrayList<TeamUpgrade> upgrades = new ArrayList<>();
private ArrayList<ItemStack> items = new ArrayList<>(); private ArrayList<ItemStack> items = new ArrayList<>();
private String name; private String name;
public Collection<TeamUpgrade> getUpgrades() { public Collection<TeamUpgrade> getUpgrades() {
return Collections.unmodifiableCollection(upgrades); return Collections.unmodifiableCollection(upgrades);
} }
public String getName() { public String getName() {
return name; return name;
} }
public ItemStack getIcon(TeamUpgrade upgrade) { public ItemStack getIcon(TeamUpgrade upgrade) {
int index = upgrades.indexOf(upgrade); int index = upgrades.indexOf(upgrade);
if (index < 0) return null; if (index < 0) return null;
else return items.get(index); else return items.get(index);
} }
public TeamUpgrade getTeamUpgrade(Team t) { public TeamUpgrade getTeamUpgrade(Team t) {
for (int i = upgrades.size() - 1; i >= 0; i--) { for (int i = upgrades.size() - 1; i >= 0; i--) {
TeamUpgrade upgrade = upgrades.get(i); TeamUpgrade upgrade = upgrades.get(i);
if (t.getUpgrades().contains(upgrade)) return upgrade; if (t.getUpgrades().contains(upgrade)) return upgrade;
} }
return null; return null;
} }
public TeamUpgrade getNextTeamUpgrade(Team t) { public TeamUpgrade getNextTeamUpgrade(Team t) {
if (upgrades.size() == 1) if (upgrades.size() == 1)
return upgrades.get(0); return upgrades.get(0);
for (int i = upgrades.size() - 2; i >= 0; i--) { for (int i = upgrades.size() - 2; i >= 0; i--) {
TeamUpgrade upgrade = upgrades.get(i); TeamUpgrade upgrade = upgrades.get(i);
if (t.getUpgrades().contains(upgrade)) { if (t.getUpgrades().contains(upgrade)) {
return upgrades.get(i + 1); return upgrades.get(i + 1);
} }
} }
return upgrades.get(0); return upgrades.get(0);
} }
public boolean isTeamAlreadyHighest(Team t) { public boolean isTeamAlreadyHighest(Team t) {
return t.getUpgrades().contains(upgrades.get(upgrades.size() - 1)); return t.getUpgrades().contains(upgrades.get(upgrades.size() - 1));
} }
public TeamUpgrade get(String name) { public TeamUpgrade get(String name) {
return upgrades return upgrades
.stream() .stream()
.filter(v -> v.getName().equals(name)) .filter(v -> v.getName().equals(name))
.findAny() .findAny()
.orElse(null); .orElse(null);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static TeamUpgradeRank deserialize(Plugin pl, Collection<Object> list) { public static TeamUpgradeRank deserialize(Plugin pl, Collection<Object> list) {
TeamUpgradeRank rank = new TeamUpgradeRank(); TeamUpgradeRank rank = new TeamUpgradeRank();
for (Object obj : list) { for (Object obj : list) {
Map<String, Object> map = (Map<String, Object>)obj; Map<String, Object> map = (Map<String, Object>)obj;
if (!map.containsKey("name")) throw new RuntimeException("Expected name property in upgrade rank definition."); if (!map.containsKey("name")) throw new RuntimeException("Expected name property in upgrade rank definition.");
if (!map.containsKey("item")) throw new RuntimeException("Expected item property in upgrade rank definition."); if (!map.containsKey("item")) throw new RuntimeException("Expected item property in upgrade rank definition.");
String name = map.get("name").toString(); String name = map.get("name").toString();
TeamUpgrade upgrade = TeamUpgrades.get(name); TeamUpgrade upgrade = TeamUpgrades.get(name);
ItemStack item = Utility.deserializeItemStack((Map<String, Object>)map.get("item")); ItemStack item = Utility.deserializeItemStack((Map<String, Object>)map.get("item"));
rank.items.add(item); rank.items.add(item);
rank.upgrades.add(upgrade); rank.upgrades.add(upgrade);
} }
return rank; return rank;
} }
} }

View File

@ -12,29 +12,29 @@ import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.trader.DealTypes; import me.topchetoeu.bedwars.engine.trader.DealTypes;
public class TeamUpgradeRanks { public class TeamUpgradeRanks {
private static HashMap<String, TeamUpgradeRank> ranks = new HashMap<>(); private static HashMap<String, TeamUpgradeRank> ranks = new HashMap<>();
public static Collection<TeamUpgradeRank> getAll() { public static Collection<TeamUpgradeRank> getAll() {
return Collections.unmodifiableCollection(ranks.values()); return Collections.unmodifiableCollection(ranks.values());
} }
public static TeamUpgradeRank get(String name) { public static TeamUpgradeRank get(String name) {
return ranks.get(name); return ranks.get(name);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void init(Plugin pl, Configuration config) { public static void init(Plugin pl, Configuration config) {
DealTypes.register(new RankedDealType()); DealTypes.register(new RankedDealType());
Map<String, Object> mapConf = Utility.mapifyConfig(config); Map<String, Object> mapConf = Utility.mapifyConfig(config);
Map<String, Collection<Object>> rawRanks = (Map<String, Collection<Object>>)mapConf.get("upgrades"); Map<String, Collection<Object>> rawRanks = (Map<String, Collection<Object>>)mapConf.get("upgrades");
ranks.clear(); ranks.clear();
if (rawRanks != null) { if (rawRanks != null) {
for (String key : rawRanks.keySet()) { for (String key : rawRanks.keySet()) {
Collection<Object> map = (Collection<Object>)rawRanks.get(key); Collection<Object> map = (Collection<Object>)rawRanks.get(key);
ranks.put(key, TeamUpgradeRank.deserialize(pl, map)); ranks.put(key, TeamUpgradeRank.deserialize(pl, map));
} }
} }
} }
} }

View File

@ -13,49 +13,49 @@ import me.topchetoeu.bedwars.engine.Team;
public class BlindnessTeamUpgrade implements TeamUpgrade { public class BlindnessTeamUpgrade implements TeamUpgrade {
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.addUpgrade(this); team.addUpgrade(this);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
} }
@Override @Override
public String getName() { public String getName() {
return "blindness"; return "blindness";
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Blindness"; return "Blindness";
} }
public BlindnessTeamUpgrade(Plugin pl) { public BlindnessTeamUpgrade(Plugin pl) {
Bukkit.getScheduler().runTaskTimer(pl, () -> { Bukkit.getScheduler().runTaskTimer(pl, () -> {
if (!Game.isStarted()) return; if (!Game.isStarted()) return;
for (BedwarsPlayer bwp : Game.instance.getPlayers()) { for (BedwarsPlayer bwp : Game.instance.getPlayers()) {
if (!bwp.isOnline()) continue; if (!bwp.isOnline()) continue;
Player p = bwp.getOnlinePlayer(); Player p = bwp.getOnlinePlayer();
for (Team t : Game.instance.getTeams()) { for (Team t : Game.instance.getTeams()) {
if (!t.hasUpgrade(this)) continue; if (!t.hasUpgrade(this)) continue;
if (t.hasPlayer(bwp)) continue; if (t.hasPlayer(bwp)) continue;
if (p.getLocation().distance(t.getTeamColor().getBedLocation()) < 7.5) { if (p.getLocation().distance(t.getTeamColor().getBedLocation()) < 7.5) {
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 200, 1, true, false)); p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 200, 1, true, false));
t.removeUpgrade(getClass()); t.removeUpgrade(getClass());
} }
} }
} }
}, 0, 20); }, 0, 20);
} }
public static void init(Plugin pl) { public static void init(Plugin pl) {
TeamUpgrades.register(new BlindnessTeamUpgrade(pl)); TeamUpgrades.register(new BlindnessTeamUpgrade(pl));
} }
} }

View File

@ -1,79 +1,77 @@
package me.topchetoeu.bedwars.engine.trader.upgrades; package me.topchetoeu.bedwars.engine.trader.upgrades;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
import net.minecraft.server.v1_8_R3.ItemTool;
public class EfficiencyTeamUpgrade implements TeamUpgrade { public class EfficiencyTeamUpgrade implements TeamUpgrade {
private int level; private int level;
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.removeUpgrade(getClass()); team.removeUpgrade(getClass());
team.addUpgrade(this); team.addUpgrade(this);
updateTeam(team); updateTeam(team);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
team.getPlayers().forEach(ofp -> { team.getPlayers().forEach(ofp -> {
if (ofp.isOnline()) { if (ofp.isOnline()) {
Player p = ofp.getOnlinePlayer(); Player p = ofp.getOnlinePlayer();
ItemStack[] inv = p.getInventory().getContents(); ItemStack[] inv = p.getInventory().getContents();
ItemStack[] armorInv = p.getInventory().getArmorContents(); ItemStack[] armorInv = p.getInventory().getArmorContents();
for (ItemStack i : inv) { for (ItemStack i : inv) {
upgradeItem(i); upgradeItem(i);
} }
for (ItemStack i : armorInv) { for (ItemStack i : armorInv) {
upgradeItem(i); upgradeItem(i);
} }
p.getInventory().setContents(inv); p.getInventory().setContents(inv);
p.getInventory().setArmorContents(armorInv); p.getInventory().setArmorContents(armorInv);
p.updateInventory(); p.updateInventory();
} }
}); });
} }
@Override @Override
public String getName() { public String getName() {
return "efficiency-" + level; return "efficiency-" + level;
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Efficiency " + level; return "Efficiency " + level;
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
if (item == null) return; if (item == null) return;
net.minecraft.server.v1_8_R3.Item nmsItem = CraftItemStack.asNMSCopy(item).getItem();
if (nmsItem instanceof ItemTool) { if (Utility.isTool(item.getType())) {
item.addEnchantment(Enchantment.DIG_SPEED, level); item.addEnchantment(Enchantment.DIG_SPEED, level);
} }
} }
public EfficiencyTeamUpgrade(int level) { public EfficiencyTeamUpgrade(int level) {
this.level = level; this.level = level;
} }
public static void init() { public static void init() {
TeamUpgrades.register(new EfficiencyTeamUpgrade(1)); TeamUpgrades.register(new EfficiencyTeamUpgrade(1));
TeamUpgrades.register(new EfficiencyTeamUpgrade(2)); TeamUpgrades.register(new EfficiencyTeamUpgrade(2));
TeamUpgrades.register(new EfficiencyTeamUpgrade(3)); TeamUpgrades.register(new EfficiencyTeamUpgrade(3));
TeamUpgrades.register(new EfficiencyTeamUpgrade(4)); TeamUpgrades.register(new EfficiencyTeamUpgrade(4));
TeamUpgrades.register(new EfficiencyTeamUpgrade(5)); TeamUpgrades.register(new EfficiencyTeamUpgrade(5));
} }
@Override @Override
public String toString() { public String toString() {
// TODO Auto-generated method stub return getName();
return getName(); }
}
} }

View File

@ -13,49 +13,49 @@ import me.topchetoeu.bedwars.engine.Team;
public class FatigueTeamUpgrade implements TeamUpgrade { public class FatigueTeamUpgrade implements TeamUpgrade {
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.addUpgrade(this); team.addUpgrade(this);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
} }
@Override @Override
public String getName() { public String getName() {
return "fatigue"; return "fatigue";
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Mining Fatigue"; return "Mining Fatigue";
} }
public FatigueTeamUpgrade(Plugin pl) { public FatigueTeamUpgrade(Plugin pl) {
Bukkit.getScheduler().runTaskTimer(pl, () -> { Bukkit.getScheduler().runTaskTimer(pl, () -> {
if (!Game.isStarted()) return; if (!Game.isStarted()) return;
for (BedwarsPlayer bwp : Game.instance.getPlayers()) { for (BedwarsPlayer bwp : Game.instance.getPlayers()) {
if (!bwp.isOnline()) continue; if (!bwp.isOnline()) continue;
Player p = bwp.getOnlinePlayer(); Player p = bwp.getOnlinePlayer();
for (Team t : Game.instance.getTeams()) { for (Team t : Game.instance.getTeams()) {
if (!t.hasUpgrade(this)) continue; if (!t.hasUpgrade(this)) continue;
if (t.hasPlayer(bwp)) continue; if (t.hasPlayer(bwp)) continue;
if (p.getLocation().distance(t.getTeamColor().getBedLocation()) < 7.5) { if (p.getLocation().distance(t.getTeamColor().getBedLocation()) < 7.5) {
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 200, 1, true, false)); p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 200, 1, true, false));
t.removeUpgrade(getClass()); t.removeUpgrade(getClass());
} }
} }
} }
}, 0, 20); }, 0, 20);
} }
public static void init(Plugin pl) { public static void init(Plugin pl) {
TeamUpgrades.register(new FatigueTeamUpgrade(pl)); TeamUpgrades.register(new FatigueTeamUpgrade(pl));
} }
} }

View File

@ -13,47 +13,47 @@ import me.topchetoeu.bedwars.engine.Team;
public class HealTeamUpgrade implements TeamUpgrade { public class HealTeamUpgrade implements TeamUpgrade {
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.addUpgrade(this); team.addUpgrade(this);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
} }
@Override @Override
public String getName() { public String getName() {
return "heal"; return "heal";
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Healing"; return "Healing";
} }
public HealTeamUpgrade(Plugin pl) { public HealTeamUpgrade(Plugin pl) {
Bukkit.getScheduler().runTaskTimer(pl, () -> { Bukkit.getScheduler().runTaskTimer(pl, () -> {
if (!Game.isStarted()) return; if (!Game.isStarted()) return;
for (Team t : Game.instance.getTeams()) { for (Team t : Game.instance.getTeams()) {
if (!t.hasUpgrade(this)) continue; if (!t.hasUpgrade(this)) continue;
for (BedwarsPlayer bwp : t.getPlayers()) { for (BedwarsPlayer bwp : t.getPlayers()) {
if (bwp.isOnline()) { if (bwp.isOnline()) {
Player p = bwp.getOnlinePlayer(); Player p = bwp.getOnlinePlayer();
if (p.getLocation().distance(t.getTeamColor().getSpawnLocation()) < 20) if (p.getLocation().distance(t.getTeamColor().getSpawnLocation()) < 20)
p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 20, 1, true, false)); p.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 20, 1, true, false));
} }
} }
} }
}, 0, 20); }, 0, 20);
} }
public static void init(Plugin pl) { public static void init(Plugin pl) {
TeamUpgrades.register(new HealTeamUpgrade(pl)); TeamUpgrades.register(new HealTeamUpgrade(pl));
} }
} }

View File

@ -1,77 +1,75 @@
package me.topchetoeu.bedwars.engine.trader.upgrades; package me.topchetoeu.bedwars.engine.trader.upgrades;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
import net.minecraft.server.v1_8_R3.ItemArmor;
public class ProtectionTeamUpgrade implements TeamUpgrade { public class ProtectionTeamUpgrade implements TeamUpgrade {
private int level; private int level;
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.removeUpgrade(getClass()); team.removeUpgrade(getClass());
team.addUpgrade(this); team.addUpgrade(this);
updateTeam(team); updateTeam(team);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
team.getPlayers().forEach(ofp -> { team.getPlayers().forEach(ofp -> {
if (ofp.isOnline()) { if (ofp.isOnline()) {
Player p = ofp.getOnlinePlayer(); Player p = ofp.getOnlinePlayer();
ItemStack[] inv = p.getInventory().getContents(); ItemStack[] inv = p.getInventory().getContents();
ItemStack[] armorInv = p.getInventory().getArmorContents(); ItemStack[] armorInv = p.getInventory().getArmorContents();
for (ItemStack i : inv) { for (ItemStack i : inv) {
upgradeItem(i); upgradeItem(i);
} }
for (ItemStack i : armorInv) { for (ItemStack i : armorInv) {
upgradeItem(i); upgradeItem(i);
} }
p.getInventory().setContents(inv); p.getInventory().setContents(inv);
p.getInventory().setArmorContents(armorInv); p.getInventory().setArmorContents(armorInv);
p.updateInventory(); p.updateInventory();
} }
}); });
} }
@Override @Override
public String getName() { public String getName() {
return "protection-" + level; return "protection-" + level;
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Protection " + level; return "Protection " + level;
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
if (item == null) return; if (item == null) return;
if (CraftItemStack.asNMSCopy(item).getItem() instanceof ItemArmor) { if (Utility.isArmor(item.getType())) {
item.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, level); item.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, level);
} }
} }
public ProtectionTeamUpgrade(int level) { public ProtectionTeamUpgrade(int level) {
this.level = level; this.level = level;
} }
public static void init() { public static void init() {
TeamUpgrades.register(new ProtectionTeamUpgrade(1)); TeamUpgrades.register(new ProtectionTeamUpgrade(1));
TeamUpgrades.register(new ProtectionTeamUpgrade(2)); TeamUpgrades.register(new ProtectionTeamUpgrade(2));
TeamUpgrades.register(new ProtectionTeamUpgrade(3)); TeamUpgrades.register(new ProtectionTeamUpgrade(3));
TeamUpgrades.register(new ProtectionTeamUpgrade(4)); TeamUpgrades.register(new ProtectionTeamUpgrade(4));
} }
@Override @Override
public String toString() { public String toString() {
// TODO Auto-generated method stub return getName();
return getName(); }
}
} }

View File

@ -1,77 +1,73 @@
package me.topchetoeu.bedwars.engine.trader.upgrades; package me.topchetoeu.bedwars.engine.trader.upgrades;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.Utility;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
import net.minecraft.server.v1_8_R3.ItemAxe;
import net.minecraft.server.v1_8_R3.ItemSword;
public class SharpnessTeamUpgrade implements TeamUpgrade { public class SharpnessTeamUpgrade implements TeamUpgrade {
private int level; private int level;
@Override @Override
public void addToTeam(Team team) { public void addToTeam(Team team) {
team.removeUpgrade(getClass()); team.removeUpgrade(getClass());
team.addUpgrade(this); team.addUpgrade(this);
updateTeam(team); updateTeam(team);
} }
@Override @Override
public void updateTeam(Team team) { public void updateTeam(Team team) {
team.getPlayers().forEach(ofp -> { team.getPlayers().forEach(ofp -> {
if (ofp.isOnline()) { if (ofp.isOnline()) {
Player p = ofp.getOnlinePlayer(); Player p = ofp.getOnlinePlayer();
ItemStack[] inv = p.getInventory().getContents(); ItemStack[] inv = p.getInventory().getContents();
ItemStack[] armorInv = p.getInventory().getArmorContents(); ItemStack[] armorInv = p.getInventory().getArmorContents();
for (ItemStack i : inv) { for (ItemStack i : inv) {
upgradeItem(i); upgradeItem(i);
} }
for (ItemStack i : armorInv) { for (ItemStack i : armorInv) {
upgradeItem(i); upgradeItem(i);
} }
p.getInventory().setContents(inv); p.getInventory().setContents(inv);
p.getInventory().setArmorContents(armorInv); p.getInventory().setArmorContents(armorInv);
p.updateInventory(); p.updateInventory();
} }
}); });
} }
@Override @Override
public String getName() { public String getName() {
return "sharpness-" + level; return "sharpness-" + level;
} }
@Override @Override
public String getDisplayName() { public String getDisplayName() {
return "Sharpness " + level; return "Sharpness " + level;
} }
@Override @Override
public void upgradeItem(ItemStack item) { public void upgradeItem(ItemStack item) {
if (item == null) return; if (item == null) return;
net.minecraft.server.v1_8_R3.Item nmsItem = CraftItemStack.asNMSCopy(item).getItem(); if (Utility.isWeapon(item.getType())) {
if (nmsItem instanceof ItemSword || nmsItem instanceof ItemAxe) { item.addEnchantment(Enchantment.DAMAGE_ALL, level);
item.addEnchantment(Enchantment.DAMAGE_ALL, level); }
} }
}
public SharpnessTeamUpgrade(int level) {
public SharpnessTeamUpgrade(int level) { this.level = level;
this.level = level; }
}
public static void init() {
public static void init() { TeamUpgrades.register(new SharpnessTeamUpgrade(1));
TeamUpgrades.register(new SharpnessTeamUpgrade(1)); TeamUpgrades.register(new SharpnessTeamUpgrade(2));
TeamUpgrades.register(new SharpnessTeamUpgrade(2)); }
}
@Override
@Override public String toString() {
public String toString() { return getName();
// TODO Auto-generated method stub }
return getName();
}
} }

View File

@ -5,9 +5,9 @@ import org.bukkit.inventory.ItemStack;
import me.topchetoeu.bedwars.engine.Team; import me.topchetoeu.bedwars.engine.Team;
public interface TeamUpgrade { public interface TeamUpgrade {
void addToTeam(Team team); void addToTeam(Team team);
void updateTeam(Team team); void updateTeam(Team team);
void upgradeItem(ItemStack item); void upgradeItem(ItemStack item);
String getName(); String getName();
String getDisplayName(); String getDisplayName();
} }

View File

@ -5,18 +5,18 @@ import java.util.Collections;
import java.util.Hashtable; import java.util.Hashtable;
public class TeamUpgrades { public class TeamUpgrades {
private static Hashtable<String, TeamUpgrade> upgrades = new Hashtable<>(); private static Hashtable<String, TeamUpgrade> upgrades = new Hashtable<>();
public static TeamUpgrade get(String name) { public static TeamUpgrade get(String name) {
return upgrades.get(name); return upgrades.get(name);
} }
public static boolean register(TeamUpgrade upgrade) { public static boolean register(TeamUpgrade upgrade) {
if (upgrades.containsKey(upgrade.getName())) return false; if (upgrades.containsKey(upgrade.getName())) return false;
upgrades.put(upgrade.getName(), upgrade); upgrades.put(upgrade.getName(), upgrade);
return true; return true;
} }
public static Collection<TeamUpgrade> getAll() { public static Collection<TeamUpgrade> getAll() {
return Collections.unmodifiableCollection(upgrades.values()); return Collections.unmodifiableCollection(upgrades.values());
} }
} }

View File

@ -0,0 +1,173 @@
package me.topchetoeu.bedwars.messaging;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import me.topchetoeu.bedwars.engine.Team;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
public class MessageParser {
private class ChatStyle {
public ChatColor color = ChatColor.WHITE;
public final HashSet<ChatColor> styles = new HashSet<>();
@Override
public String toString() {
return color.toString() + String.join("", styles.stream().map(v -> v.toString()).toList());
}
}
private final Hashtable<String, Object> variables = new Hashtable<>();
private final String raw;
private final char colorChar = '&';
public MessageParser variable(String name, Object value) {
variables.put(name, value);
return this;
}
public MessageParser variables(Map<String, Object> map) {
variables.putAll(map);
return this;
}
private ChatStyle getStyle(String str, ChatStyle _default) {
boolean styling = false;
ChatStyle style = new ChatStyle();
style.color = _default.color;
style.styles.addAll(_default.styles);
for (int i = 0; i < str.length(); i++) {
char curr = str.charAt(i);
if (styling) {
switch (curr) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
style.color = ChatColor.getByChar(curr);
style.styles.clear();
style.styles.addAll(_default.styles);
break;
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
style.styles.add(ChatColor.getByChar(curr));
break;
case 'r':
style.styles.clear();
style.styles.addAll(_default.styles);
style.color = _default.color;
break;
default:
break;
}
styling = false;
}
else if (curr == '§') styling = true;
}
return style;
}
private String replaceVariables() {
if (raw.length() < 2) return raw;
String raw = this.raw + ';';
raw = raw.replace(colorChar, '§');
raw = raw.replace("§§", Character.toString(colorChar));
boolean varMode = false;
StringBuilder varName = new StringBuilder();
StringBuilder currText = new StringBuilder();
ChatStyle _default = new ChatStyle();
_default.color = ChatColor.WHITE;
for (int i = 1; i < raw.length(); i++) {
char curr = raw.charAt(i - 1);
char next = raw.charAt(i);
boolean appendChar = false;
if (curr == '{') {
if (next == '{') {
appendChar = true;
i++;
}
else varMode = true;
}
else if (curr == '}') {
if (next == '}') {
appendChar = true;
i++;
}
else {
Object val = variables.get(varName.toString());
String strVal = "undefined";
if (val != null) {
if (val instanceof BaseComponent[]) strVal = BaseComponent.toLegacyText((BaseComponent[])val);
else strVal = val.toString();
}
ChatStyle color = getStyle(currText.toString(), _default);
currText.append(strVal.replace(colorChar, '§').replace("§§", Character.toString(colorChar)));
currText.append(color);
varName.setLength(0);
varMode = false;
}
}
else appendChar = true;
if (appendChar) {
if (varMode) varName.append(curr);
else currText.append(curr);
}
}
return currText.toString();
}
public BaseComponent[] parse() {
if (raw == null) return null;
return TextComponent.fromLegacyText(replaceVariables());
}
public void send(CommandSender sender) {
BaseComponent[] msg = parse();
if (msg == null) msg = new BaseComponent[] { new TextComponent("Missing message from config.") };
sender.spigot().sendMessage(msg);
}
public void send(Team team) {
BaseComponent[] msg = parse();
if (msg == null) msg = new BaseComponent[] { new TextComponent("Missing message from config.") };
team.sendMessage(msg);
}
public void broadcast() {
BaseComponent[] msg = parse();
if (msg == null) msg = new BaseComponent[] { new TextComponent("Missing message from config.") };
Bukkit.spigot().broadcast(msg);
}
public MessageParser(String msg) {
this.raw = msg;
}
}

View File

@ -0,0 +1,25 @@
package me.topchetoeu.bedwars.messaging;
import java.io.File;
import java.io.IOException;
import org.bukkit.configuration.file.YamlConfiguration;
public class MessageUtility {
private static YamlConfiguration config;
private MessageUtility() {
}
public static void load(File file) throws IOException {
config = YamlConfiguration.loadConfiguration(file);
config.save(file);
}
public static MessageParser parser(String path) {
Object obj = config.get(path);
if (obj == null) return new MessageParser(null);
else return new MessageParser(obj.toString());
}
}

View File

@ -0,0 +1,78 @@
package me.topchetoeu.bedwars.permissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class PermissionSegmentWildcard {
private String prefix;
private List<String> remaining;
public String getPrefix() {
return prefix;
}
public List<String> getRemainingSegments() {
return Collections.unmodifiableList(remaining);
}
public boolean isWildcard() {
return remaining != null;
}
public String toString() {
if (isWildcard()) return prefix + "*" + String.join("*", remaining);
else return prefix;
}
public boolean check(String segment) {
if (isWildcard()) {
for (int i = remaining.size() - 1; i >= 0; i--) {
String curr = remaining.get(i);
int index = segment.lastIndexOf(curr);
if (index == -1) return false;
segment = segment.substring(0, index);
}
return !segment.startsWith(prefix);
}
else return segment.equals(prefix);
}
public PermissionSegmentWildcard(String node, boolean isPrefix) {
this.prefix = node;
if (isPrefix) remaining = Collections.emptyList();
}
public PermissionSegmentWildcard(String prefix, String suffix) {
this.prefix = prefix;
this.remaining = Collections.singletonList(suffix);
}
public PermissionSegmentWildcard(String prefix, String ...remaining) {
this.prefix = prefix;
this.remaining = Arrays.asList(remaining);
}
public PermissionSegmentWildcard(String prefix, Collection<String> remaining) {
this.prefix = prefix;
this.remaining = new ArrayList<>(remaining);
}
public static PermissionSegmentWildcard parse(String str) {
if (str.contains("**")) throw new RuntimeException("Recursive wildcards not allowed.");
String[] segments = str.split("\\*");
if (segments.length == 0) return new PermissionSegmentWildcard("", true);
else if (segments.length == 1) return new PermissionSegmentWildcard(segments[0], false);
else {
List<String> remaining = new ArrayList<>();
Collections.addAll(remaining, segments);
remaining.remove(0);
if (remaining.size() == 0) return new PermissionSegmentWildcard(segments[0], true);
if (remaining.get(remaining.size() - 1).isEmpty())
remaining.remove(remaining.size() - 1);
return new PermissionSegmentWildcard(segments[0], remaining);
}
}
}

View File

@ -0,0 +1,84 @@
package me.topchetoeu.bedwars.permissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class PermissionWildcard {
private List<PermissionSegmentWildcard> prefix;
private List<PermissionSegmentWildcard> suffix;
public boolean hasRecursiveWildcard() {
return suffix != null;
}
public PermissionWildcard(boolean isPrefix, Collection<PermissionSegmentWildcard> segments) {
this.prefix = new ArrayList<>(segments);
if (isPrefix) suffix = Collections.emptyList();
}
public PermissionWildcard(boolean isPrefix, PermissionSegmentWildcard ...segments) {
this.prefix = Arrays.asList(segments);
if (isPrefix) suffix = Collections.emptyList();
}
public PermissionWildcard(Collection<PermissionSegmentWildcard> prefix, Collection<PermissionSegmentWildcard> suffix) {
this.prefix = new ArrayList<>(prefix);
this.suffix = new ArrayList<>(suffix);
}
public boolean check(String perm) {
String[] segments = perm.split(".");
if (segments.length < prefix.size()) return false;
if (suffix != null && segments.length < suffix.size()) return false;
int i = 0;
for (; i < prefix.size(); i++) {
if (!prefix.get(i).check(segments[i])) return false;
}
if (hasRecursiveWildcard()) {
int j = 0;
for (i = suffix.size(), j = segments.length; i >= 0; i--, j--) {
if (!prefix.get(i).check(segments[j])) return false;
}
return true;
}
else return i == prefix.size();
}
public String toString() {
String res = String.join(".", prefix.toArray(String[]::new));
if (hasRecursiveWildcard()) {
res += ".**";
if (suffix != null) res += "." + String.join(".", suffix.toArray(String[]::new));
}
return res;
}
public static PermissionWildcard parse(String raw) {
String[] segments = raw.split("\\.");
ArrayList<PermissionSegmentWildcard> prefix = new ArrayList<>();
ArrayList<PermissionSegmentWildcard> suffix = null;
ArrayList<PermissionSegmentWildcard> currList = prefix;
for (String segment : segments) {
if (segment.isEmpty()) throw new RuntimeException("Empty permission segments are not allowed.");
if (segment.equals("**")) {
if (suffix == null) {
currList = suffix = new ArrayList<>();
}
else throw new RuntimeException("Multiple recursive wildcards are not allowed.");
}
else if (segment.contains("**")) throw new RuntimeException("Wildcards must be the only thing in a segment.");
else currList.add(PermissionSegmentWildcard.parse(segment));
}
if (suffix == null) return new PermissionWildcard(false, prefix);
else return new PermissionWildcard(prefix, suffix);
}
}

View File

@ -0,0 +1,32 @@
package me.topchetoeu.bedwars.permissions;
import java.util.Hashtable;
import org.bukkit.permissions.Permissible;
public class Permissions {
private static final Hashtable<String, PermissionWildcard> cache = new Hashtable<>();
private Permissions() {
}
public static void reset() {
cache.clear();
}
public static final PermissionWildcard getCachedOrParse(String rawWildcard) {
cache.clear();
return cache.containsKey(rawWildcard) ? cache.get(rawWildcard) : PermissionWildcard.parse(rawWildcard);
}
public static boolean hasPermission(Permissible permissible, String permission) {
if (permission == null || permission.isEmpty()) return true;
if (permissible == null) return false;
if (permissible.isOp()) return true;
if (permissible.hasPermission(permission)) return true;
return permissible.getEffectivePermissions().stream().anyMatch(v -> {
return getCachedOrParse(v.getPermission()).check(permission);
});
}
}

55
src/plugin.yml Normal file
View File

@ -0,0 +1,55 @@
name: bedwars-plugin
version: 0.7.0
description: A plugin that enables you to make a bedwars game
authors: [ TopchetoEU, SpaceHQ ]
main: me.topchetoeu.bedwars.Main
api-version: 1.18
commands:
bedwars:
description: A command used to control the bedwars plugin
aliases: [ bw, bedwar ]
permissions:
bedwars:
description: Gives access to all bedwars-related commands
children:
bedwars.config: yes
bedwars.cheat: yes
bedwars.control: yes
bedwars.villagertools: yes
bedwars.config:
description: Gives access to all bedwars configuration commands
children:
bedwars.config.bases: yes
bedwars.config.generators: yes
bedwars.config.bases:
description: Gives access to all base-related commands
children:
bedwars.config.bases.add: yes
bedwars.config.bases.remove: yes
bedwars.config.bases.setspawn: yes
bedwars.config.bases.setgenerator: yes
bedwars.config.bases.setbed: yes
bedwars.config.bases.add:
description: Gives access to base add command
bedwars.config.bases.remove:
description: Gives access to base remove command
bedwars.config.bases.setspawn:
description: Gives access to base set spawn command
bedwars.config.bases.setgenerator:
description: Gives access to base set generator command
bedwars.config.bases.setbed:
description: Gives access to base set bed command
bedwars.cheat:
description: Gives access to all features that allow cheating (like killing, eliminating or breaking other's beds)
children:
bedwars.cheat.kill: yes
bedwars.cheat.revive: yes
bedwars.cheat.breakbed: yes
bedwars.cheat.kill:
description: Gives access to the command /bw kill [player]
bedwars.cheat.revive:
description: Gives access to the command /bw revive [player]
bedwars.cheat.breakbed:
description: Gives access to the command /bw breakbed [team]
bedwars.villagertools:
description: Gives access to the command /bw villagertools