diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..469dd55 --- /dev/null +++ b/.classpath @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/.project b/.project new file mode 100644 index 0000000..f710c1c --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + Bases_src2 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/README.md b/README.md index f17d105..7102703 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# Bunkers-by-prestige \ No newline at end of file +Bunkers-by-prestige diff --git a/main/java/com/bizarrealex/aether/Aether.java b/main/java/com/bizarrealex/aether/Aether.java new file mode 100644 index 0000000..e2c4547 --- /dev/null +++ b/main/java/com/bizarrealex/aether/Aether.java @@ -0,0 +1,189 @@ +package com.bizarrealex.aether; + +import com.bizarrealex.aether.event.BoardCreateEvent; +import com.bizarrealex.aether.scoreboard.Board; +import com.bizarrealex.aether.scoreboard.BoardAdapter; +import com.bizarrealex.aether.scoreboard.BoardEntry; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +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.event.player.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.*; + +import static com.bizarrealex.aether.AetherOptions.defaultOptions; + + /** + * TODO: Add documentation to methods, etc + * TODO: Fix inconsistent cooldown scores + * TODO: Finish other board formats + */ + +public class Aether implements Listener { + + @Getter private JavaPlugin plugin; + @Getter private AetherOptions options; + @Getter BoardAdapter adapter; + + public Aether(JavaPlugin plugin, BoardAdapter adapter, AetherOptions options) { + this.options = options; + this.plugin = plugin; + + Bukkit.getPluginManager().registerEvents(this, plugin); + + setAdapter(adapter); + run(); + } + + public Aether(JavaPlugin plugin, BoardAdapter adapter) { + this(plugin, adapter, defaultOptions()); + } + + public Aether(JavaPlugin plugin) { + this(plugin, null, defaultOptions()); + } + + private void run() { + new BukkitRunnable() { + @Override + public void run() { + if (adapter == null) return; + + for (Player player : Bukkit.getOnlinePlayers()) { + Board board = Board.getByPlayer(player); + if (board != null) { + List scores = adapter.getScoreboard(player, board, board.getCooldowns()); + List translatedScores = new ArrayList<>(); + + if (scores == null) { + + if (!board.getEntries().isEmpty()) { + + for (BoardEntry boardEntry : board.getEntries()) { + boardEntry.remove(); + } + + board.getEntries().clear(); + } + + continue; + } + + for (String line : scores) { + translatedScores.add(ChatColor.translateAlternateColorCodes('&', line)); + } + + if (!options.scoreDirectionDown()) { + Collections.reverse(scores); + } + + Scoreboard scoreboard = board.getScoreboard(); + Objective objective = board.getObjective(); + + if (!(objective.getDisplayName().equals(adapter.getTitle(player)))) { + objective.setDisplayName(ChatColor.translateAlternateColorCodes('&', adapter.getTitle(player))); + } + + outer:for (int i = 0; i < scores.size(); i++) { + String text = scores.get(i); + int position; + if (options.scoreDirectionDown()) { + position = 15 - i; + } else { + position = i + 1; + } + + Iterator iterator = new ArrayList<>(board.getEntries()).iterator(); + while (iterator.hasNext()) { + BoardEntry boardEntry = iterator.next(); + Score score = objective.getScore(boardEntry.getKey()); + + if (score != null && boardEntry.getText().equals(ChatColor.translateAlternateColorCodes('&', text))) { + if (score.getScore() == position) { + continue outer; + } + } + } + + int positionToSearch = options.scoreDirectionDown() ? 15 - position : position - 1; + + iterator = board.getEntries().iterator(); + while (iterator.hasNext()) { + BoardEntry boardEntry = iterator.next(); + int entryPosition = scoreboard.getObjective(DisplaySlot.SIDEBAR).getScore(boardEntry.getKey()).getScore(); + + if (!options.scoreDirectionDown()) { + if (entryPosition > scores.size()) { + iterator.remove(); + boardEntry.remove(); + } + } + + } + + BoardEntry entry = board.getByPosition(positionToSearch); + if (entry == null) { + new BoardEntry(board, text).send(position); + } else { + entry.setText(text).setup().send(position); + } + + if (board.getEntries().size() > scores.size()) { + iterator = board.getEntries().iterator(); + while (iterator.hasNext()) { + BoardEntry boardEntry = iterator.next(); + if ((!translatedScores.contains(boardEntry.getText())) || Collections.frequency(board.getBoardEntriesFormatted(), boardEntry.getText()) > 1) { + iterator.remove(); + boardEntry.remove(); + } + } + } + } + + player.setScoreboard(scoreboard); + } + } + } + }.runTaskTimerAsynchronously(plugin, 20L, 2L); + } + + public void setAdapter(BoardAdapter adapter) { + this.adapter = adapter; + for (Player player : Bukkit.getOnlinePlayers()) { + Board board = Board.getByPlayer(player); + + if (board != null) { + Board.getBoards().remove(board); + } + + Bukkit.getPluginManager().callEvent(new BoardCreateEvent(new Board(player, this, options), player)); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoinEvent(PlayerJoinEvent event) { + if (Board.getByPlayer(event.getPlayer()) == null) { + Bukkit.getPluginManager().callEvent(new BoardCreateEvent(new Board(event.getPlayer(), this, options), event.getPlayer())); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerQuitEvent(PlayerQuitEvent event) { + Board board = Board.getByPlayer(event.getPlayer()); + if (board != null) { + Board.getBoards().remove(board); + } + } + +} diff --git a/main/java/com/bizarrealex/aether/AetherOptions.java b/main/java/com/bizarrealex/aether/AetherOptions.java new file mode 100644 index 0000000..9a23dd9 --- /dev/null +++ b/main/java/com/bizarrealex/aether/AetherOptions.java @@ -0,0 +1,21 @@ +package com.bizarrealex.aether; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +@Getter +@Setter +@Accessors(chain = true, fluent = true) +public class AetherOptions { + + static AetherOptions defaultOptions() { + return new AetherOptions() + .hook(true) + .scoreDirectionDown(false); + } + + private boolean hook; + private boolean scoreDirectionDown; + +} diff --git a/main/java/com/bizarrealex/aether/event/BoardCreateEvent.java b/main/java/com/bizarrealex/aether/event/BoardCreateEvent.java new file mode 100644 index 0000000..521d08f --- /dev/null +++ b/main/java/com/bizarrealex/aether/event/BoardCreateEvent.java @@ -0,0 +1,27 @@ +package com.bizarrealex.aether.event; + +import com.bizarrealex.aether.scoreboard.Board; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class BoardCreateEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + @Getter private final Board board; + @Getter private final Player player; + + public BoardCreateEvent(Board board, Player player) { + this.board = board; + this.player = player; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/main/java/com/bizarrealex/aether/example/ExampleBoardAdapter.java b/main/java/com/bizarrealex/aether/example/ExampleBoardAdapter.java new file mode 100644 index 0000000..244899e --- /dev/null +++ b/main/java/com/bizarrealex/aether/example/ExampleBoardAdapter.java @@ -0,0 +1,80 @@ +package com.bizarrealex.aether.example; +import com.bizarrealex.aether.scoreboard.Board; +import com.bizarrealex.aether.scoreboard.BoardAdapter; +import com.bizarrealex.aether.scoreboard.cooldown.BoardCooldown; +import com.bizarrealex.aether.scoreboard.cooldown.BoardFormat; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class ExampleBoardAdapter implements BoardAdapter, Listener { + + public ExampleBoardAdapter(JavaPlugin plugin) { + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + @Override + public String getTitle(Player player) { + return "&6&lAether"; + } + + @Override + public List getScoreboard(Player player, Board board, Set cooldowns) { + List strings = new ArrayList<>(); + strings.add("&7&m-------------------"); + + for (BoardCooldown cooldown : cooldowns) { + if (cooldown.getId().equals("enderpearl")) { + strings.add("&e&lEnderpearl&7:&c " + cooldown.getFormattedString(BoardFormat.SECONDS)); + } + } + + strings.add("&7&m-------------------&r"); + + if (strings.size() == 2) { + return null; + } + + return strings; + } + + @EventHandler + public void onPlayerInteractEvent(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Board board = Board.getByPlayer(player); + if (event.getAction().name().contains("RIGHT")) { + + if (event.getItem() == null) return; + if (event.getItem().getType() != Material.ENDER_PEARL) return; + if (board == null) return; + if (player.getGameMode() == GameMode.CREATIVE) return; + + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + event.setCancelled(true); + return; + } + + BoardCooldown cooldown = board.getCooldown("enderpearl"); + if (cooldown != null) { + event.setCancelled(true); + player.updateInventory(); + player.sendMessage(ChatColor.RED + "You must wait " + cooldown.getFormattedString(BoardFormat.SECONDS) + " seconds before enderpearling again!"); + return; + } + + new BoardCooldown(board, "enderpearl", 16); + } + } + +} diff --git a/main/java/com/bizarrealex/aether/scoreboard/Board.java b/main/java/com/bizarrealex/aether/scoreboard/Board.java new file mode 100644 index 0000000..54d7190 --- /dev/null +++ b/main/java/com/bizarrealex/aether/scoreboard/Board.java @@ -0,0 +1,136 @@ +package com.bizarrealex.aether.scoreboard; + +import com.bizarrealex.aether.Aether; +import com.bizarrealex.aether.AetherOptions; +import com.bizarrealex.aether.scoreboard.cooldown.BoardCooldown; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.*; + +public class Board { + + private static Set boards = new HashSet<>(); + + @Getter private Scoreboard scoreboard; + @Getter private Player player; + @Getter private Objective objective; + @Getter private Set keys; + @Getter private List entries; + private Set cooldowns; + private final Aether aether; + private final AetherOptions options; + + public Board(Player player, Aether aether, AetherOptions options) { + this.player = player; + this.aether = aether; + this.options = options; + this.keys = new HashSet<>(); + this.cooldowns = new HashSet<>(); + this.entries = new ArrayList<>(); + + setup(); + } + + private void setup() { + if (options.hook() && !player.getScoreboard().equals(Bukkit.getScoreboardManager().getMainScoreboard())) { + scoreboard = player.getScoreboard(); + } else { + scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); + } + + objective = scoreboard.registerNewObjective("glaedr_is_shit", "dummy"); + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + + if (aether.getAdapter() != null) { + objective.setDisplayName(ChatColor.translateAlternateColorCodes('&', aether.getAdapter().getTitle(player))); + } else { + objective.setDisplayName("Default Title"); + } + + boards.add(this); + } + + public String getNewKey(BoardEntry entry) { + + for (ChatColor color : ChatColor.values()) { + String colorText = color + "" + ChatColor.WHITE; + + if (entry.getText().length() > 16) { + String sub = entry.getText().substring(0, 16); + colorText = colorText + ChatColor.getLastColors(sub); + } + + if (!keys.contains(colorText)) { + keys.add(colorText); + return colorText; + } + } + + throw new IndexOutOfBoundsException("No more keys available!"); + } + + public List getBoardEntriesFormatted() { + List toReturn = new ArrayList<>(); + + for (BoardEntry entry : new ArrayList<>(entries)) { + toReturn.add(entry.getText()); + } + + return toReturn; + } + + public BoardEntry getByPosition(int position) { + int i = 0; + + for (BoardEntry board : entries) { + if (i == position) { + return board; + } + i++; + } + + return null; + } + + public BoardCooldown getCooldown(String id) { + for (BoardCooldown cooldown : getCooldowns()) { + if (cooldown.getId().equals(id)) { + return cooldown; + } + } + + return null; + } + + public Set getCooldowns() { + Iterator iterator = cooldowns.iterator(); + + while (iterator.hasNext()) { + BoardCooldown cooldown = iterator.next(); + if (System.currentTimeMillis() >= cooldown.getEnd()) { + iterator.remove(); + } + } + + return cooldowns; + } + + public static Board getByPlayer(Player player) { + for (Board board : boards) { + if (board.getPlayer().getName().equals(player.getName())) { + return board; + } + } + return null; + } + + public static Set getBoards() { + return boards; + } +} diff --git a/main/java/com/bizarrealex/aether/scoreboard/BoardAdapter.java b/main/java/com/bizarrealex/aether/scoreboard/BoardAdapter.java new file mode 100644 index 0000000..4d0b3d0 --- /dev/null +++ b/main/java/com/bizarrealex/aether/scoreboard/BoardAdapter.java @@ -0,0 +1,14 @@ +package com.bizarrealex.aether.scoreboard; + +import com.bizarrealex.aether.scoreboard.cooldown.BoardCooldown; +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.Set; + +public interface BoardAdapter { + + String getTitle(Player player); + List getScoreboard(Player player, Board board, Set cooldowns); + +} diff --git a/main/java/com/bizarrealex/aether/scoreboard/BoardEntry.java b/main/java/com/bizarrealex/aether/scoreboard/BoardEntry.java new file mode 100644 index 0000000..74fdbd6 --- /dev/null +++ b/main/java/com/bizarrealex/aether/scoreboard/BoardEntry.java @@ -0,0 +1,88 @@ +package com.bizarrealex.aether.scoreboard; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +@Accessors(chain = true) +public class BoardEntry { + + @Getter private Board board; + @Getter @Setter private String text; + @Getter private String originalText; + @Getter private String key; + @Getter private Team team; + + public BoardEntry(Board board, String text) { + this.board = board; + this.text = text; + this.originalText = text; + this.key = board.getNewKey(this); + + setup(); + } + + public BoardEntry setup() { + Scoreboard scoreboard = board.getScoreboard(); + + text = ChatColor.translateAlternateColorCodes('&', text); + + String teamName = key; + if (teamName.length() > 16) { + teamName = teamName.substring(0, 16); + } + + if (scoreboard.getTeam(teamName) != null) { + team = scoreboard.getTeam(teamName); + } else { + team = scoreboard.registerNewTeam(teamName); + } + + if (!(team.getEntries().contains(key))) { + team.addEntry(key); + } + + if (!(board.getEntries().contains(this))) { + board.getEntries().add(this); + } + + return this; + } + + public BoardEntry send(int position) { + Objective objective = board.getObjective(); + + if (text.length() > 16) { + String first = text.substring(0, 16); + String second = text.substring(16, text.length()); + if (first.endsWith(String.valueOf(ChatColor.COLOR_CHAR))) { + first = first.substring(0, first.length() - 1); + second = ChatColor.COLOR_CHAR + second; + } + String lastColors = ChatColor.getLastColors(first); + second = lastColors + second; + team.setPrefix(first); + team.setSuffix(StringUtils.left(second, 16)); + } else { + team.setSuffix(""); + team.setPrefix(text); + } + + Score score = objective.getScore(key); + score.setScore(position); + + return this; + } + + public void remove() { + board.getKeys().remove(key); + board.getScoreboard().resetScores(key); + } + +} diff --git a/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardCooldown.java b/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardCooldown.java new file mode 100644 index 0000000..4ef0067 --- /dev/null +++ b/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardCooldown.java @@ -0,0 +1,39 @@ +package com.bizarrealex.aether.scoreboard.cooldown; + +import com.bizarrealex.aether.scoreboard.Board; +import lombok.Getter; +import org.apache.commons.lang.time.DurationFormatUtils; + +import java.text.DecimalFormat; + +public class BoardCooldown { + + private static final DecimalFormat SECONDS_FORMATTER = new DecimalFormat("#0.0"); + + @Getter private final Board board; + @Getter private final String id; + @Getter private final double duration; + @Getter private final long end; + + public BoardCooldown(Board board, String id, double duration) { + this.board = board; + this.id = id; + this.duration = duration; + this.end = (long) (System.currentTimeMillis() + (duration * 1000)); + + board.getCooldowns().add(this); + } + + public String getFormattedString(BoardFormat format) { + if (format == null) throw new NullPointerException(); + if (format == BoardFormat.SECONDS) { + return SECONDS_FORMATTER.format(((end - System.currentTimeMillis()) / 1000.0f)); + } else { + return DurationFormatUtils.formatDuration(end - System.currentTimeMillis(), "mm:ss"); + } + } + + public void cancel() { + board.getCooldowns().remove(this); + } +} diff --git a/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardFormat.java b/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardFormat.java new file mode 100644 index 0000000..bda759d --- /dev/null +++ b/main/java/com/bizarrealex/aether/scoreboard/cooldown/BoardFormat.java @@ -0,0 +1,7 @@ +package com.bizarrealex.aether.scoreboard.cooldown; + +public enum BoardFormat { + SECONDS, + MINUTES, + HOURS +} diff --git a/main/java/config.yml b/main/java/config.yml new file mode 100644 index 0000000..72754e1 --- /dev/null +++ b/main/java/config.yml @@ -0,0 +1,6 @@ +koth_faction_name: "Testing" +setup: true +server-name: "bases_1" +map-name: "&6Classic" +scoreboard: + title: "&dVeltPvP &c[Corners]" \ No newline at end of file diff --git a/main/java/me/prestige/bases/Bases.java b/main/java/me/prestige/bases/Bases.java new file mode 100644 index 0000000..ac0769c --- /dev/null +++ b/main/java/me/prestige/bases/Bases.java @@ -0,0 +1,505 @@ +package me.prestige.bases; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +import com.bizarrealex.aether.Aether; +import com.customhcf.base.BasePlugin; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; + +import me.prestige.bases.command.CreateArenaCommand; +import me.prestige.bases.command.ForceStartCommand; +import me.prestige.bases.economy.EconomyCommand; +import me.prestige.bases.economy.EconomyListener; +import me.prestige.bases.economy.EconomyManager; +import me.prestige.bases.economy.EconomyRunnable; +import me.prestige.bases.economy.FlatFileEconomyManager; +import me.prestige.bases.economy.PayCommand; +import me.prestige.bases.economy.VillagerRunnable; +import me.prestige.bases.faction.FactionExecutor; +import me.prestige.bases.faction.FactionManager; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.FlatFileFactionManager; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.event.PlayerJoinFactionEvent; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.struct.Role; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import me.prestige.bases.game.GameManager; +import me.prestige.bases.game.GameState; +import me.prestige.bases.inventory.InventoryHandler; +import me.prestige.bases.kothgame.CaptureZone; +import me.prestige.bases.kothgame.EventExecutor; +import me.prestige.bases.kothgame.faction.CapturableFaction; +import me.prestige.bases.kothgame.faction.KothFaction; +import me.prestige.bases.listener.ChatListener; +import me.prestige.bases.listener.CoreListener; +import me.prestige.bases.listener.DeathListener; +import me.prestige.bases.listener.EntityHandler; +import me.prestige.bases.listener.FactionListener; +import me.prestige.bases.listener.FactionsCoreListener; +import me.prestige.bases.listener.JoinListener; +import me.prestige.bases.listener.LobbyListener; +import me.prestige.bases.listener.NametagListener; +import me.prestige.bases.listener.PlayerStatsListener; +import me.prestige.bases.listener.SkullListener; +import me.prestige.bases.listener.WaitingSnapshotListener; +import me.prestige.bases.listener.WorldListener; +import me.prestige.bases.nms.Nms; +import me.prestige.bases.nms.Villager; +import me.prestige.bases.scoreboard.ScoreboardHandler; +import me.prestige.bases.scoreboard.provider.GameProvider; +import me.prestige.bases.tab.FactionTabManager; +import me.prestige.bases.timer.TimerExecutor; +import me.prestige.bases.timer.TimerManager; +import me.prestige.bases.user.FactionUser; +import me.prestige.bases.user.UserManager; +import net.minecraft.server.v1_7_R4.EntityVillager; +import net.minecraft.util.com.google.gson.Gson; +import redis.clients.jedis.BinaryJedisPubSub; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Tuple; + +public class Bases extends JavaPlugin +{ + + private FactionManager factionManager; + private GameManager gameManager; + private TimerManager timerManager; + private ScoreboardHandler scoreboardHandler; + private InventoryHandler inventoryHandler; + private WorldEditPlugin worldEditPlugin; + private UserManager userManager; + private EconomyManager economyManager; + private EconomyRunnable economyRunnable; + + private String serverName; + private String scoreboardTitle; + private String mapName; + private Aether aether; + private static Bases plugin; + + public static String getRemaining(final long millis, final boolean milliseconds) + { + return getRemaining(millis, milliseconds, true); + } + + public static String getRemaining(final long duration, final boolean milliseconds, final boolean trail) + { + if (milliseconds && duration < TimeUnit.MINUTES.toMillis(1L)) { return (trail ? DateTimeFormats.REMAINING_SECONDS_TRAILING : DateTimeFormats.REMAINING_SECONDS).get().format(duration * 0.001) + 's'; } + return DurationFormatUtils.formatDuration(duration, ((duration >= TimeUnit.HOURS.toMillis(1L)) ? "HH:" : "") + "mm:ss"); + } + + @Override + public void onEnable() + { + getServer().getPluginManager().registerEvents(new NametagListener(), this); + getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + + plugin = this; + aether = new Aether(this, new GameProvider(this)); + if (!new File(getDataFolder(), "config.yml").exists()) + { + saveDefaultConfig(); + } + getConfig().options().copyDefaults(true); + for (Player on : Bukkit.getOnlinePlayers()) + { + on.kickPlayer("Resetting"); + } + this.serverName = getConfig().getString("server-name"); + this.mapName = ChatColor.translateAlternateColorCodes('&', getConfig().getString("map-name")); + + scoreboardTitle = ChatColor.translateAlternateColorCodes('&', getConfig().getString("scoreboard.title")); + System.out.println("Server Name set to " + serverName); + Nms.registerEntity("Villager", 120, EntityVillager.class, Villager.class); + final Plugin wep = Bukkit.getPluginManager().getPlugin("WorldEdit"); + worldEditPlugin = ((wep instanceof WorldEditPlugin && wep.isEnabled()) ? ((WorldEditPlugin) wep) : null); + + loadConfiguations(); + loadCommands(); + loadManagers(); + loadListeners(); + new VillagerRunnable().runTaskTimer(plugin, 1, 1); + economyRunnable = new EconomyRunnable(this); + economyRunnable.runTaskTimerAsynchronously(this, 60, 60); + reserverRedis(); + listenRedis(); + new FactionTabManager(this).init(); + } + + private void loadConfiguations() + { + ConfigurationSerialization.registerClass(CaptureZone.class); + ConfigurationSerialization.registerClass(Claim.class); + ConfigurationSerialization.registerClass(ClaimableFaction.class); + ConfigurationSerialization.registerClass(CapturableFaction.class); + ConfigurationSerialization.registerClass(KothFaction.class); + ConfigurationSerialization.registerClass(Faction.class); + ConfigurationSerialization.registerClass(FactionMember.class); + ConfigurationSerialization.registerClass(ColorFaction.class); + ConfigurationSerialization.registerClass(FactionUser.class); + ConfigurationSerialization.registerClass(ColorFaction.BlueFaction.class); + ConfigurationSerialization.registerClass(ColorFaction.GreenFaction.class); + ConfigurationSerialization.registerClass(ColorFaction.YellowFaction.class); + ConfigurationSerialization.registerClass(ColorFaction.RedFaction.class); + ConfigurationSerialization.registerClass(PlayerFaction.class); + } + + private void loadManagers() + { + factionManager = new FlatFileFactionManager(this); + gameManager = new GameManager(this); + timerManager = new TimerManager(this); + inventoryHandler = new InventoryHandler(this); + scoreboardHandler = new ScoreboardHandler(this); + userManager = new UserManager(this); + economyManager = new FlatFileEconomyManager(this); + } + + private void loadListeners() + { + PluginManager pm = Bukkit.getPluginManager(); + pm.registerEvents(new ChatListener(this), this); + pm.registerEvents(new CoreListener(this), this); + pm.registerEvents(new FactionListener(this), this); + pm.registerEvents(new FactionsCoreListener(this), this); + pm.registerEvents(new JoinListener(this), this); + pm.registerEvents(new WorldListener(this), this); + pm.registerEvents(new DeathListener(this), this); + pm.registerEvents(new EconomyListener(this), this); + pm.registerEvents(new EntityHandler(this), this); + pm.registerEvents(new WaitingSnapshotListener(this), this); + pm.registerEvents(new SkullListener(), this); + pm.registerEvents(new LobbyListener(this), this); + pm.registerEvents(new PlayerStatsListener(this), this); + + } + + private void loadCommands() + { + getCommand("game").setExecutor(new EventExecutor(this)); + getCommand("createarena").setExecutor(new CreateArenaCommand()); + getCommand("faction").setExecutor(new FactionExecutor(this)); + getCommand("forcestart").setExecutor(new ForceStartCommand()); + getCommand("timer").setExecutor(new TimerExecutor(this)); + getCommand("economy").setExecutor(new EconomyCommand(this)); + getCommand("pay").setExecutor(new PayCommand(this)); + final Map> map = getDescription().getCommands(); + for (final Map.Entry> entry : map.entrySet()) + { + final PluginCommand command = getCommand(entry.getKey()); + command.setPermission("command." + entry.getKey()); + command.setPermissionMessage(ChatColor.RED + "You do not have permission for this command."); + } + } + + private void saveData() + { + userManager.saveUserData(); + factionManager.saveFactionData(); + + } + + @Override + public void onDisable() + { + Bukkit.getWorld("world").getEntities().clear(); + saveData(); + if (!gameManager.getGameState().equals(GameState.ENDING)) + { + gameManager.end(null); + } + plugin = null; + } + + public EconomyRunnable getEconomyRunnable() + { + return economyRunnable; + } + + public static Bases getPlugin() + { + return plugin; + } + + public EconomyManager getEconomyManager() + { + return economyManager; + } + + public UserManager getUserManager() + { + return userManager; + } + + public GameManager getGameManager() + { + return gameManager; + } + + public ScoreboardHandler getScoreboardHandler() + { + return scoreboardHandler; + } + + public FactionManager getFactionManager() + { + return factionManager; + } + + public TimerManager getTimerManager() + { + return timerManager; + } + + public InventoryHandler getInventoryHandler() + { + return inventoryHandler; + } + + public WorldEditPlugin getWorldEditPlugin() + { + return worldEditPlugin; + } + + public String getScoreboardTitle() + { + return scoreboardTitle; + } + + public String getMapName() + { + return mapName; + } + + public void listenRedis() + { + + new BukkitRunnable() + { + @Override + public void run() + { + while (getGameManager().getGameState() == GameState.WAITING) + { + try + { + try (Jedis jedis = BasePlugin.getPlugin().getRedis().getResource()) + { + jedis.subscribe(new BinaryJedisPubSub() + { + @Override + public void onMessage(byte[] channel, byte[] message) + { + ByteArrayDataInput input = ByteStreams.newDataInput(message); + String subchannel = input.readUTF(); + if (subchannel.equals("JoinOpenFaction")) + { + int amount = input.readInt(); + ColorFaction working = null; + if (plugin.getFactionManager().getColorFaction("Green").getMembers().size() + amount < 5) + { + working = plugin.getFactionManager().getColorFaction("Green"); + } + else if (plugin.getFactionManager().getColorFaction("Yellow").getMembers().size() + amount < 5) + { + working = plugin.getFactionManager().getColorFaction("Yellow"); + } + else if (plugin.getFactionManager().getColorFaction("Red").getMembers().size() + amount < 5) + { + working = plugin.getFactionManager().getColorFaction("Red"); + } + else if (plugin.getFactionManager().getColorFaction("Blue").getMembers().size() + amount < 5) + { + working = plugin.getFactionManager().getColorFaction("Blue"); + } + else + { + return; + } + if (working == null) { return; } + for (int i = 0; i < amount; i++) + { + String name = input.readUTF(); + UUID uuid = UUID.fromString(input.readUTF()); + if (getFactionManager().getColorFaction(uuid) == working) + { + continue; + } + ensureLeaveFromOthers(uuid, working); + if (working.setMember(uuid, new FactionMember(uuid, ChatChannel.FACTION, Role.MEMBER))) + { + Bukkit.getPluginManager().callEvent(new PlayerJoinFactionEvent(uuid, working, plugin.getFactionManager().getColorFaction(uuid))); + Player player = Bukkit.getPlayer(uuid); + if (player != null) + { + player.sendMessage(net.md_5.bungee.api.ChatColor.YELLOW + "You have joined " + plugin.getFactionManager().getColorFaction(player.getUniqueId()).getDisplayName(player)); + } + } + } + } + } + }, ("bases-" + serverName).getBytes(StandardCharsets.UTF_8)); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + try + { + Thread.sleep(10000); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + } + }.runTaskAsynchronously(this); + } + + public void deleteRedis() + { + new BukkitRunnable() + { + @Override + public void run() + { + deleteSync(); + } + + }.runTaskAsynchronously(this); + } + + public void deleteSync() + { + try (Jedis jedis = BasePlugin.getPlugin().getRedis().getResource()) + { + jedis.set("bases-lock", serverName, "NX", "PX", 20000); + if (jedis.get("bases-lock").equals(serverName)) + { + jedis.del("bases-lock"); + jedis.del("bases-data-" + serverName); + jedis.zrem("bases-lock-queue", serverName); + } + } + } + + public class BasesBeen + { + public int greenCount; + public int blueCount; + public int yellowCount; + public int redCount; + } + + public void reserverRedis() + { + + new BukkitRunnable() + { + @Override + public void run() + { + deleteSync(); + while (getGameManager().getGameState() == GameState.WAITING) + { + try + { + try (Jedis jedis = BasePlugin.getPlugin().getRedis().getResource()) + { + jedis.set("keepalive-" + serverName, String.valueOf(System.currentTimeMillis())); + Double value = jedis.zscore("bases-lock-queue", serverName); + if (value != null) + { + Tuple tuple = jedis.zrangeByScoreWithScores("bases-lock-queue", "-inf", "+inf", 0, 1).iterator().next(); + if (tuple.getElement().equals(serverName)) + { + jedis.setex("bases-lock", 20, serverName); + } + Tuple second = jedis.zrangeByScoreWithScores("bases-lock-queue", "-inf", "+inf", 1, 1).iterator().next(); + if (second.getElement().equals(serverName)) + { + String keepAliveString = jedis.get("keepalive-" + tuple.getElement()); + if (keepAliveString == null || System.currentTimeMillis() - Long.valueOf(keepAliveString) > 15000) + { + jedis.zrem("bases-lock-queue", tuple.getElement()); + System.out.println("Removing a crashed node from the queue: " + tuple.getElement()); + } + } + } + else + { + jedis.zadd("bases-lock-queue", System.currentTimeMillis(), serverName); + } + BasesBeen basesBeen = new BasesBeen(); + basesBeen.greenCount = plugin.getFactionManager().getColorFaction("Green").getMembers().size(); + basesBeen.blueCount = plugin.getFactionManager().getColorFaction("Blue").getMembers().size(); + basesBeen.yellowCount = plugin.getFactionManager().getColorFaction("Yellow").getMembers().size(); + basesBeen.redCount = plugin.getFactionManager().getColorFaction("Red").getMembers().size(); + jedis.setex("bases-data-" + serverName, 20, new Gson().toJson(basesBeen)); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + try + { + Thread.sleep(5000); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + } + }.runTaskAsynchronously(this); + } + + public void ensureLeaveFromOthers(UUID player, ColorFaction toJoin) + { + + ColorFaction green = plugin.getFactionManager().getColorFaction("Green"); + ColorFaction blue = plugin.getFactionManager().getColorFaction("Blue"); + ColorFaction yellow = plugin.getFactionManager().getColorFaction("Yellow"); + ColorFaction red = plugin.getFactionManager().getColorFaction("Red"); + if (green != toJoin && green.getMember(player) != null) + { + green.setMember(player, null, true); + } + if (blue != toJoin && blue.getMember(player) != null) + { + blue.setMember(player, null, true); + } + if (yellow != toJoin && yellow.getMember(player) != null) + { + yellow.setMember(player, null, true); + } + if (red != toJoin && red.getMember(player) != null) + { + red.setMember(player, null, true); + } + } +} diff --git a/main/java/me/prestige/bases/DateTimeFormats.java b/main/java/me/prestige/bases/DateTimeFormats.java new file mode 100644 index 0000000..50143bb --- /dev/null +++ b/main/java/me/prestige/bases/DateTimeFormats.java @@ -0,0 +1,40 @@ +package me.prestige.bases; + +import org.apache.commons.lang.time.FastDateFormat; + +import java.text.DecimalFormat; +import java.time.ZoneId; +import java.util.Locale; +import java.util.TimeZone; + +public final class DateTimeFormats { + public static final TimeZone SERVER_TIME_ZONE; + public static final ZoneId SERVER_ZONE_ID; + public static final FastDateFormat DAY_MTH_HR_MIN_SECS; + public static final FastDateFormat HR_MIN; + public static final FastDateFormat MIN_SECS; + public static final FastDateFormat KOTH_FORMAT; + public static final ThreadLocal REMAINING_SECONDS; + public static final ThreadLocal REMAINING_SECONDS_TRAILING; + + static { + SERVER_TIME_ZONE = TimeZone.getTimeZone("EST"); + SERVER_ZONE_ID = DateTimeFormats.SERVER_TIME_ZONE.toZoneId(); + DAY_MTH_HR_MIN_SECS = FastDateFormat.getInstance("MM/dd/yy HH:mm:ss", DateTimeFormats.SERVER_TIME_ZONE, Locale.ENGLISH); + HR_MIN = FastDateFormat.getInstance("hh:mm", DateTimeFormats.SERVER_TIME_ZONE, Locale.ENGLISH); + KOTH_FORMAT = FastDateFormat.getInstance("m:ss", DateTimeFormats.SERVER_TIME_ZONE, Locale.ENGLISH); + MIN_SECS = FastDateFormat.getInstance("mm:ss", DateTimeFormats.SERVER_TIME_ZONE, Locale.ENGLISH); + REMAINING_SECONDS = new ThreadLocal() { + @Override + protected DecimalFormat initialValue() { + return new DecimalFormat("0.#"); + } + }; + REMAINING_SECONDS_TRAILING = new ThreadLocal() { + @Override + protected DecimalFormat initialValue() { + return new DecimalFormat("0.0"); + } + }; + } +} diff --git a/main/java/me/prestige/bases/KothStartTimer.java b/main/java/me/prestige/bases/KothStartTimer.java new file mode 100644 index 0000000..ed8e555 --- /dev/null +++ b/main/java/me/prestige/bases/KothStartTimer.java @@ -0,0 +1,24 @@ +package me.prestige.bases; + +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.faction.EventFaction; +import me.prestige.bases.kothgame.faction.KothFaction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.logging.Level; + +public class KothStartTimer extends BukkitRunnable { + @Override + public void run() { + try { + Bases.getPlugin().getTimerManager().eventTimer.tryContesting(((EventFaction) Bases.getPlugin().getFactionManager().getFaction(Bases.getPlugin().getConfig().getString("koth_faction_name"))), null); + return; + }catch (NullPointerException e){ + Bases.getPlugin().getServer().getLogger().log(Level.WARNING, "The koth configured in the 'config.yml' in 'bases' folder is not found."); + Bases.getPlugin().getServer().getLogger().log(Level.WARNING, "No koth will start, you must stop the game and setup the koth!"); + Bases.getPlugin().getGameManager().end(null); + } + } +} diff --git a/main/java/me/prestige/bases/command/CreateArenaCommand.java b/main/java/me/prestige/bases/command/CreateArenaCommand.java new file mode 100644 index 0000000..1b00f8c --- /dev/null +++ b/main/java/me/prestige/bases/command/CreateArenaCommand.java @@ -0,0 +1,37 @@ +package me.prestige.bases.command; + +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldedit.bukkit.selections.Selection; +import me.prestige.bases.Bases; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * Created by TREHOME on 02/14/2017. + */ +public class CreateArenaCommand implements CommandExecutor { + @Override + public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "Only players can set event claim areas"); + return true; + } + final WorldEditPlugin worldEditPlugin = Bases.getPlugin().getWorldEditPlugin(); + if(worldEditPlugin == null) { + sender.sendMessage(ChatColor.RED + "WorldEdit must be installed to set event claim areas."); + return true; + } + final Player player = (Player) sender; + final Selection selection = worldEditPlugin.getSelection(player); + if(selection == null) { + sender.sendMessage(ChatColor.RED + "You must make a WorldEdit selection to do this."); + return true; + } + Bases.getPlugin().getGameManager().saveArena(selection.getMaximumPoint(), selection.getMinimumPoint()); + player.sendMessage(ChatColor.YELLOW + "You have " + ChatColor.GREEN + "successfully " + ChatColor.YELLOW + "created the arena. Every game from now on will load on this save." ); + return false; + } +} diff --git a/main/java/me/prestige/bases/command/ForceStartCommand.java b/main/java/me/prestige/bases/command/ForceStartCommand.java new file mode 100644 index 0000000..5196502 --- /dev/null +++ b/main/java/me/prestige/bases/command/ForceStartCommand.java @@ -0,0 +1,30 @@ +package me.prestige.bases.command; + +import com.customhcf.util.ItemBuilder; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import net.md_5.bungee.api.ChatColor; +import net.minecraft.server.v1_7_R4.WorldServer; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +public class ForceStartCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + Player player = (Player) commandSender; + player.sendMessage(ChatColor.YELLOW + "You have successfully forced the game to start"); + Bases.getPlugin().getGameManager().startGame(); + return false; + } + +} diff --git a/main/java/me/prestige/bases/economy/EconomyCommand.java b/main/java/me/prestige/bases/economy/EconomyCommand.java new file mode 100644 index 0000000..290710f --- /dev/null +++ b/main/java/me/prestige/bases/economy/EconomyCommand.java @@ -0,0 +1,122 @@ +package me.prestige.bases.economy; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; + +import com.customhcf.base.Constants; +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.JavaUtils; +import com.google.common.collect.ImmutableList; +import com.google.common.primitives.Ints; + +import me.prestige.bases.Bases; + +public class EconomyCommand implements CommandExecutor, TabCompleter { + private static final ImmutableList COMPLETIONS; + private static final ImmutableList GIVE; + private static final ImmutableList TAKE; + + + static { + TAKE = ImmutableList.of("take", "negate", "minus", "subtract"); + GIVE = ImmutableList.of("give", "add"); + COMPLETIONS = ImmutableList.of("add", "set", "take"); + } + + private final Bases plugin; + + public EconomyCommand(final Bases plugin) { + this.plugin = plugin; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + final boolean hasStaffPermission = sender.hasPermission(command.getPermission() + ".staff"); + OfflinePlayer target; + if(args.length > 0 && hasStaffPermission) { + if(args[0].equalsIgnoreCase("all") || args[0].equalsIgnoreCase("*") && hasStaffPermission){ + Integer amount = Ints.tryParse(args[1]); + for(UUID user : plugin.getUserManager().getUsers().keySet()){ + this.plugin.getEconomyManager().addBalance(user, amount); + } + Bukkit.broadcastMessage(ChatColor.YELLOW + sender.getName() + " gave all players " + amount + ""); + return true; + } + target = BukkitUtils.offlinePlayerWithNameOrUUID(args[0]); + } else { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "Usage: /" + label + " "); + return true; + } + target = (OfflinePlayer) sender; + } + if(!target.hasPlayedBefore() && !target.isOnline()) { + sender.sendMessage(String.format(Constants.PLAYER_WITH_NAME_OR_UUID_NOT_FOUND, args[0])); + return true; + } + final UUID uuid = target.getUniqueId(); + final int balance = this.plugin.getEconomyManager().getBalance(uuid); + if(args.length < 2 || !hasStaffPermission) { + sender.sendMessage(ChatColor.YELLOW + (sender.equals(target) ? "Your balance" : ("Balance of " + target.getName())) + " is " + ChatColor.GREEN + "$" + balance + ChatColor.YELLOW + '.'); + return true; + } + if(GIVE.contains(args[1].toLowerCase())) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: /" + label + ' ' + target.getName() + ' ' + args[1] + " "); + return true; + } + final Integer amount = Ints.tryParse(args[2]); + if(amount == null) { + sender.sendMessage(ChatColor.RED + "'" + args[2] + "' is not a valid number."); + return true; + } + final int newBalance = this.plugin.getEconomyManager().addBalance(uuid, amount); + sender.sendMessage(new String[]{ChatColor.YELLOW + "Added " + "$" + JavaUtils.format((Number) amount) + " to balance of " + target.getName() + '.', ChatColor.YELLOW + "Balance of " + target.getName() + " is now " +"$" + newBalance + '.'}); + return true; + } else if(TAKE.contains(args[1].toLowerCase())) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: /" + label + ' ' + target.getName() + ' ' + args[1] + " "); + return true; + } + final Integer amount = Ints.tryParse(args[2]); + if(amount == null) { + sender.sendMessage(ChatColor.RED + "'" + args[2] + "' is not a valid number."); + return true; + } + final int newBalance = this.plugin.getEconomyManager().subtractBalance(uuid, amount); + sender.sendMessage(new String[]{ChatColor.YELLOW + "Taken " + "$"+ JavaUtils.format((Number) amount) + " from balance of " + target.getName() + '.', ChatColor.YELLOW + "Balance of " + target.getName() + " is now " + "$" + newBalance + '.'}); + return true; + } else { + if(!args[1].equalsIgnoreCase("set")) { + sender.sendMessage(ChatColor.GOLD + (sender.equals(target) ? "Your balance" : ("Balance of " + target.getName())) + " is " + ChatColor.YELLOW + "$" + balance + ChatColor.GOLD + '.'); + return true; + } + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: /" + label + ' ' + target.getName() + ' ' + args[1] + " "); + return true; + } + final Integer amount = Ints.tryParse(args[2]); + if(amount == null) { + sender.sendMessage(ChatColor.RED + "'" + args[2] + "' is not a valid number."); + return true; + } + final int newBalance = this.plugin.getEconomyManager().setBalance(uuid, amount); + sender.sendMessage(ChatColor.YELLOW + "Set balance of " + target.getName() + " to " +"$"+ JavaUtils.format((Number) newBalance) + '.'); + return true; + } + } + + @Override + public List onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { + return (args.length == 2) ? BukkitUtils.getCompletions(args, COMPLETIONS) : (args.length == 1 ) ? null : Collections.emptyList(); + } +} diff --git a/main/java/me/prestige/bases/economy/EconomyItem.java b/main/java/me/prestige/bases/economy/EconomyItem.java new file mode 100644 index 0000000..b9b2634 --- /dev/null +++ b/main/java/me/prestige/bases/economy/EconomyItem.java @@ -0,0 +1,23 @@ +package me.prestige.bases.economy; + +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.ItemBuilder; +import me.prestige.bases.Bases; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class EconomyItem { + + private ItemStack stack; + + + public EconomyItem(Player player, Material material, String name, Integer price, Integer amount){ + stack = new ItemBuilder(material, amount).displayName((Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= price ? ChatColor.GREEN : ChatColor.RED) +name).lore(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 25), ChatColor.GRAY.toString() + amount + " x " + name, ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 25), ChatColor.GRAY + "Price" + ChatColor.GRAY +": " +(Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= price ? ChatColor.GREEN : ChatColor.RED) + "$" +price).build(); + } + + public ItemStack build(){ + return stack; + } +} diff --git a/main/java/me/prestige/bases/economy/EconomyListener.java b/main/java/me/prestige/bases/economy/EconomyListener.java new file mode 100644 index 0000000..5d39f9f --- /dev/null +++ b/main/java/me/prestige/bases/economy/EconomyListener.java @@ -0,0 +1,127 @@ +package me.prestige.bases.economy; + +import me.prestige.bases.Bases; +import me.prestige.bases.economy.gui.BlockShop; +import me.prestige.bases.economy.gui.CombatShop; +import me.prestige.bases.economy.gui.EnchantShop; +import me.prestige.bases.economy.gui.SellShop; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.nms.*; +import net.md_5.bungee.api.ChatColor; +import net.minecraft.server.v1_7_R4.WorldServer; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftVillager; +import org.bukkit.entity.*; +import org.bukkit.entity.Villager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.*; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +public class EconomyListener implements Listener { + + private Bases plugin; + public static Map respawners; + + public EconomyListener(Bases plugin){ + this.plugin = plugin; + respawners = new ConcurrentHashMap<>(); + } + + + @EventHandler + public void onDamageVillager(EntityDamageByEntityEvent e){ + if(e.getEntity() instanceof Villager){ + if(e.getDamager() instanceof Player){ + if(((Villager) e.getEntity()).getCustomName().contains("respawns")){ + e.setCancelled(true); + return; + } + Faction factionAt = plugin.getFactionManager().getFactionAt(e.getEntity().getLocation()); + ColorFaction colorFaction = plugin.getFactionManager().getColorFaction(e.getDamager().getUniqueId()); + if(factionAt.equals(colorFaction)){ + ((Player) e.getDamager()).sendMessage(ChatColor.WHITE + "You " + ChatColor.RED + "cannot" + ChatColor.WHITE + " damage your own teams villager!"); + e.setCancelled(true); + }else{ + e.setCancelled(true); + ((Villager) e.getEntity()).damage(e.getDamage()); + } + } + } + } + + + @EventHandler + public void onIneract(PlayerInteractEntityEvent e){ + if(e.getRightClicked() instanceof Villager){ + e.setCancelled(true); + Entity villager = e.getRightClicked(); + if(((CraftVillager)villager).getHandle().getName().contains("respawn")) { + e.setCancelled(true); + return; + } + Faction villagerFaction = plugin.getFactionManager().getFactionAt(villager.getLocation()); + ColorFaction colorFaction = plugin.getFactionManager().getColorFaction(e.getPlayer().getUniqueId()); + if(villagerFaction.equals(colorFaction)){ + if(((CraftVillager)villager).getHandle().getName().contains("Combat")) { + new CombatShop(e.getPlayer()).showMenu(e.getPlayer()); + return; + } + if(((CraftVillager)villager).getHandle().getName().contains("Build")) { + new BlockShop(e.getPlayer()).showMenu(e.getPlayer()); + return; + } + if(((CraftVillager)villager).getHandle().getName().toLowerCase().contains("enchant")) { + new EnchantShop(e.getPlayer()).showMenu(e.getPlayer()); + return; + } + if(((CraftVillager)villager).getHandle().getName().toLowerCase().contains("sell")) { + new SellShop(e.getPlayer()).showMenu(e.getPlayer()); + return; + } + }else if(villagerFaction instanceof ColorFaction && ((ColorFaction) villagerFaction).getDeathsUntilRaidable() <= 0){ + + }else{ + return; + } + return; + } + } + + + + + @EventHandler + public void onDeath(EntityDeathEvent e){ + if(e.getEntity() instanceof Villager){ + final WorldServer mcWorld = ((CraftWorld)e.getEntity().getLocation().getWorld()).getHandle(); + final me.prestige.bases.nms.Villager customEnt = new me.prestige.bases.nms.Villager(mcWorld); + customEnt.setCustomName(ChatColor.GRAY + ChatColor.stripColor(e.getEntity().getCustomName()) + " respawns in " + Bases.getRemaining(TimeUnit.MINUTES.toMillis(5) - (System.currentTimeMillis()), true)); + customEnt.setCustomNameVisible(true); + customEnt.setJob(e.getEntity().getCustomName()); + customEnt.setPosition(e.getEntity().getLocation().getX(), e.getEntity().getLocation().getY(), e.getEntity().getLocation().getZ()); + mcWorld.addEntity(customEnt, CreatureSpawnEvent.SpawnReason.CUSTOM); + respawners.put(customEnt, System.currentTimeMillis()); + } + } + + + @EventHandler + public void onPotion(PotionEffectAddEvent e){ + if(e.getEntity() instanceof Villager){ + e.setCancelled(true); + } + } + +} diff --git a/main/java/me/prestige/bases/economy/EconomyManager.java b/main/java/me/prestige/bases/economy/EconomyManager.java new file mode 100644 index 0000000..1265154 --- /dev/null +++ b/main/java/me/prestige/bases/economy/EconomyManager.java @@ -0,0 +1,20 @@ +package me.prestige.bases.economy; + +import net.minecraft.util.gnu.trove.map.TObjectIntMap; + +import java.util.UUID; + +public interface EconomyManager { + + TObjectIntMap getBalanceMap(); + + Integer getBalance(UUID p0); + + Integer setBalance(UUID p0, int p1); + + Integer addBalance(UUID p0, int p1); + + Integer subtractBalance(UUID p0, int p1); + + +} diff --git a/main/java/me/prestige/bases/economy/EconomyRunnable.java b/main/java/me/prestige/bases/economy/EconomyRunnable.java new file mode 100644 index 0000000..91a0db8 --- /dev/null +++ b/main/java/me/prestige/bases/economy/EconomyRunnable.java @@ -0,0 +1,58 @@ +package me.prestige.bases.economy; + +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.ItemBuilder; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.gui.BlockShop; +import me.prestige.bases.economy.gui.CombatShop; +import me.prestige.bases.economy.gui.EnchantShop; +import me.prestige.bases.economy.gui.SellShop; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Map; + +public class EconomyRunnable extends BukkitRunnable { + + private Bases plugin; + + public EconomyRunnable(Bases plugin){ + this.plugin = plugin; + } + + + @Override + public void run() { + for(Player on : Bukkit.getOnlinePlayers()){ + plugin.getEconomyManager().addBalance(on.getUniqueId(), 3); + if(on.getOpenInventory().getTitle().contains("Combat")){ + for(Map.Entry itemStack : CombatShop.createLoadMap().entrySet()){ + on.getOpenInventory().setItem(itemStack.getKey(), null); + on.getOpenInventory().setItem(itemStack.getKey(), itemStack.getValue()); + } + } + if(on.getOpenInventory().getTitle().contains("Blcok")){ + for(Map.Entry itemStack : BlockShop.createLoadMap().entrySet()){ + on.getOpenInventory().setItem(itemStack.getKey(), null); + on.getOpenInventory().setItem(itemStack.getKey(), itemStack.getValue()); + } + } + if(on.getOpenInventory().getTitle().contains("Sell")){ + for(Map.Entry itemStack : SellShop.createLoadMap().entrySet()){ + on.getOpenInventory().setItem(itemStack.getKey(), null); + on.getOpenInventory().setItem(itemStack.getKey(), itemStack.getValue()); + } + } + if(on.getOpenInventory().getTitle().contains("enchant")){ + for(Map.Entry itemStack : EnchantShop.createLoadMap().entrySet()){ + on.getOpenInventory().setItem(itemStack.getKey(), null); + on.getOpenInventory().setItem(itemStack.getKey(), itemStack.getValue()); + } + } + } + } +} diff --git a/main/java/me/prestige/bases/economy/FlatFileEconomyManager.java b/main/java/me/prestige/bases/economy/FlatFileEconomyManager.java new file mode 100644 index 0000000..24e29eb --- /dev/null +++ b/main/java/me/prestige/bases/economy/FlatFileEconomyManager.java @@ -0,0 +1,48 @@ +package me.prestige.bases.economy; + +import com.customhcf.util.Config; +import com.mongodb.DBCursor; +import com.mongodb.DBObject; +import me.prestige.bases.Bases; +import net.minecraft.util.gnu.trove.map.TObjectIntMap; +import net.minecraft.util.gnu.trove.map.hash.TObjectIntHashMap; + +import java.util.UUID; + +public class FlatFileEconomyManager implements EconomyManager { + private TObjectIntMap balanceMap; + + public FlatFileEconomyManager(final Bases plugin) { + this.balanceMap = new TObjectIntHashMap<>(); + } + + @Override + public TObjectIntMap getBalanceMap() { + return this.balanceMap; + } + + @Override + public Integer getBalance(final UUID uuid) { + balanceMap.putIfAbsent(uuid, 0); + return this.balanceMap.get(uuid); + } + + @Override + public Integer setBalance(final UUID uuid, final int amount) { + this.balanceMap.put(uuid, amount); + return amount; + } + + @Override + public Integer addBalance(final UUID uuid, final int amount) { + return this.setBalance(uuid, this.getBalance(uuid) + amount); + } + + @Override + public Integer subtractBalance(final UUID uuid, final int amount) { + return this.setBalance(uuid, this.getBalance(uuid) - amount); + } + + + +} diff --git a/main/java/me/prestige/bases/economy/PayCommand.java b/main/java/me/prestige/bases/economy/PayCommand.java new file mode 100644 index 0000000..86cf0ba --- /dev/null +++ b/main/java/me/prestige/bases/economy/PayCommand.java @@ -0,0 +1,72 @@ +package me.prestige.bases.economy; + +import java.util.Collections; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; + +import com.customhcf.base.Constants; +import com.google.common.primitives.Ints; + +import me.prestige.bases.Bases; + +public class PayCommand implements CommandExecutor, TabCompleter { + private final Bases plugin; + + public PayCommand(final Bases plugin) { + this.plugin = plugin; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: /" + label + " "); + return true; + } + final Integer amount = Ints.tryParse(args[1]); + if(amount == null) { + sender.sendMessage(ChatColor.RED + "'" + args[1] + "' is not a valid number."); + return true; + } + if(amount <= 0) { + sender.sendMessage(ChatColor.RED + "You must send money in positive quantities."); + return true; + } + final Player senderPlayer = (Player) sender; + final int senderBalance = (senderPlayer != null) ? this.plugin.getEconomyManager().getBalance(senderPlayer.getUniqueId()) : 1024; + if(senderBalance < amount) { + sender.sendMessage(ChatColor.RED + "You do not have that much money, you have: " + ChatColor.GREEN + senderBalance); + return true; + } + final OfflinePlayer target = Bukkit.getOfflinePlayer(args[0]); + if(sender.equals(target)) { + sender.sendMessage(ChatColor.RED + "You cannot send money to yourself."); + return true; + } + final Player targetPlayer = target.getPlayer(); + if(!target.hasPlayedBefore() && targetPlayer == null) { + sender.sendMessage(String.format(Constants.PLAYER_WITH_NAME_OR_UUID_NOT_FOUND, args[0])); + return true; + } + if(targetPlayer == null) { + return false; + } + if(senderPlayer != null) { + this.plugin.getEconomyManager().subtractBalance(senderPlayer.getUniqueId(), amount); + } + this.plugin.getEconomyManager().addBalance(targetPlayer.getUniqueId(), amount); + targetPlayer.sendMessage(ChatColor.GOLD + sender.getName() + " has sent you " + ChatColor.GOLD + " $ " + amount + ChatColor.YELLOW + '.'); + sender.sendMessage(ChatColor.YELLOW + "You have sent " + ChatColor.GOLD + " $ " + amount + ChatColor.YELLOW + " to " + target.getName() + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + return (args.length == 1) ? null : Collections.emptyList(); + } +} diff --git a/main/java/me/prestige/bases/economy/VillagerRunnable.java b/main/java/me/prestige/bases/economy/VillagerRunnable.java new file mode 100644 index 0000000..34298ed --- /dev/null +++ b/main/java/me/prestige/bases/economy/VillagerRunnable.java @@ -0,0 +1,39 @@ +package me.prestige.bases.economy; + +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.nms.Villager; +import net.md_5.bungee.api.ChatColor; +import net.minecraft.server.v1_7_R4.WorldServer; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class VillagerRunnable extends BukkitRunnable { + @Override + public void run() { + if(EconomyListener.respawners.isEmpty()) return; + for(Map.Entry entry : EconomyListener.respawners.entrySet()){ + if(System.currentTimeMillis() - entry.getValue() >= TimeUnit.MINUTES.toMillis(5)){ + Location loc = entry.getKey().getBukkitEntity().getLocation(); + final WorldServer mcWorld = ((CraftWorld)loc.getWorld()).getHandle(); + final Villager customEnt = new Villager(mcWorld); + customEnt.setCustomName(entry.getKey().getJob()); + customEnt.setJob(entry.getKey().getJob()); + customEnt.setCustomNameVisible(true); + customEnt.setPosition(loc.getX(), loc.getY(), loc.getZ()); + mcWorld.addEntity(customEnt, CreatureSpawnEvent.SpawnReason.CUSTOM); + ((ColorFaction) Bases.getPlugin().getFactionManager().getFactionAt(loc)).broadcast(ChatColor.WHITE + "Your " + entry.getKey().getJob() + ChatColor.WHITE + " villager respawned."); + mcWorld.removeEntity(entry.getKey()); + EconomyListener.respawners.remove(entry.getKey(), entry.getValue()); + continue; + }else{ + entry.getKey().setCustomName( ChatColor.GRAY + ChatColor.stripColor(entry.getKey().getJob()) + " respawns in " + Bases.getRemaining( TimeUnit.MINUTES.toMillis(5) - (System.currentTimeMillis() - entry.getValue()), true)); + } + } + } +} diff --git a/main/java/me/prestige/bases/economy/gui/BlockShop.java b/main/java/me/prestige/bases/economy/gui/BlockShop.java new file mode 100644 index 0000000..cbcbeeb --- /dev/null +++ b/main/java/me/prestige/bases/economy/gui/BlockShop.java @@ -0,0 +1,77 @@ +package me.prestige.bases.economy.gui; + +import com.customhcf.base.BasePlugin; +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.ItemBuilder; +import com.customhcf.util.Menu; +import com.google.common.primitives.Ints; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.EconomyItem; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Material; +import org.bukkit.enchantments.EnchantmentTarget; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class BlockShop extends Menu { + private static Player player; + + public BlockShop(Player player) { + super(ChatColor.RED + ChatColor.BOLD.toString() + "Build Shop", 6); + this.player = player; + this.fill(new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 15).displayName(" ").build()); + loadItems(); + } + + public static Map createLoadMap() { + Map itemStackMap = new HashMap<>(); + itemStackMap.put(0, new EconomyItem(player, Material.CHEST, "Chest", 250, 16).build()); + itemStackMap.put(1, new EconomyItem(player, Material.STONE, "Stone", 10, 16).build()); + itemStackMap.put(2, new EconomyItem(player, Material.COBBLESTONE, "Cobblestone", 10, 16).build()); + itemStackMap.put(3, new EconomyItem(player, Material.SMOOTH_BRICK, "Stone Bricks", 10, 16).build()); + itemStackMap.put(4, new EconomyItem(player, Material.STEP, "Stone Slab", 5, 16).build()); + itemStackMap.put(5, new EconomyItem(player, Material.FENCE_GATE, "Fence Gate", 30, 16).build()); + itemStackMap.put(6, new EconomyItem(player, Material.STONE_PLATE, "Pressure Plate", 30, 16).build()); + itemStackMap.put(7, new EconomyItem(player, Material.LADDER, "Ladder", 10, 16).build()); + itemStackMap.put(8, new EconomyItem(player, Material.STONE_BUTTON, "Button", 5, 16).build()); + + itemStackMap.put(48, new EconomyItem(player, Material.DIAMOND_PICKAXE, "Diamond Pickaxe", 50, 1).build()); + itemStackMap.put(49, new EconomyItem(player, Material.DIAMOND_AXE, "Diamond Axe", 25, 1).build()); + itemStackMap.put(50, new EconomyItem(player, Material.DIAMOND_SPADE, "Diamond Shovel", 25, 1).build()); + return itemStackMap; + } + + private void loadItems() { + for (Map.Entry items : createLoadMap().entrySet()) { + this.setItem(items.getKey(), items.getValue()); + } + loadClicks(); + } + + + + private Integer getPriceFromString(String string){ + return Ints.tryParse(string.replace(ChatColor.GRAY + "Price" + ChatColor.GRAY + ": ", "").replace(ChatColor.GREEN.toString(), "").replace("$", "").replace(ChatColor.RED.toString(), "")); + } + + private void loadClicks() { + this.setGlobalAction((player, inventory, itemStack, slot, action) -> { + Integer price = getPriceFromString(itemStack.getItemMeta().getLore().get(3)); + if (player.getInventory().firstEmpty() == -1) { + player.sendMessage(ChatColor.RED + "Your inventory is full."); + return; + } + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < price) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + player.getInventory().addItem(new ItemStack(itemStack.getType(), itemStack.getAmount())); + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), price); + return; + }); + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/economy/gui/CombatShop.java b/main/java/me/prestige/bases/economy/gui/CombatShop.java new file mode 100644 index 0000000..f12e6e2 --- /dev/null +++ b/main/java/me/prestige/bases/economy/gui/CombatShop.java @@ -0,0 +1,217 @@ +package me.prestige.bases.economy.gui; + +import com.customhcf.base.BasePlugin; +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.ItemBuilder; +import com.customhcf.util.Menu; +import com.google.common.primitives.Ints; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.EconomyItem; +import net.md_5.bungee.api.ChatColor; +import net.minecraft.server.v1_7_R4.ChatMessage; +import net.minecraft.server.v1_7_R4.EntityPlayer; +import net.minecraft.server.v1_7_R4.Item; +import net.minecraft.server.v1_7_R4.PacketPlayOutOpenWindow; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer; +import org.bukkit.enchantments.EnchantmentTarget; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class CombatShop extends Menu { + + private static Player player; + + public CombatShop(Player player) { + super(ChatColor.RED + ChatColor.BOLD.toString() + "Combat Shop", 6); + this.player = player; + this.fill(new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 15).displayName(" ").build()); + loadItems(); + loadClicks(); + } + + public static Map createLoadMap(){ + Map itemStackMap = new HashMap<>(); + itemStackMap.put(10, new EconomyItem(player, Material.DIAMOND_HELMET, "Diamond Helmet", 75, 1).build()); + itemStackMap.put(19, new EconomyItem(player, Material.DIAMOND_CHESTPLATE, "Diamond Chestplate", 200, 1).build()); + itemStackMap.put(28, new EconomyItem(player, Material.DIAMOND_LEGGINGS, "Diamond Leggings", 150, 1).build()); + itemStackMap.put(37, new EconomyItem(player, Material.DIAMOND_BOOTS, "Diamond Boots", 75, 1).build()); + itemStackMap.put(18, new EconomyItem(player, Material.DIAMOND_SWORD, "Diamond Sword", 100, 1).build()); + itemStackMap.put(20, new ItemBuilder(Material.DIAMOND).displayName(getName("Full Armor", 500)) + .lore(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 25), + ChatColor.GRAY + "1 x Diamond Helmet", + ChatColor.GRAY + "1 x Diamond Chestplate", + ChatColor.GRAY + "1 x Diamond Leggings", + ChatColor.GRAY + "1 x Diamond Boots", + ChatColor.GRAY + "1 x Diamond Sword", + ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 25), + ChatColor.WHITE + "Price" + ChatColor.GRAY + ": " + (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= 500 ? ChatColor.GREEN : ChatColor.RED) + "$500") + .build()); + itemStackMap.put(21, new ItemBuilder(Material.ENDER_PEARL, 16).displayName(getName("Ender Pearl", 25)) + .lore(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 31), + ChatColor.GRAY + "Buy 1 x Ender Pearl", ChatColor.GRAY + "Right click to buy 16 x Ender Pearl", + ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 31), + ChatColor.GRAY + "Price" + ChatColor.GRAY + ": " + (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= 25 ? ChatColor.GREEN : ChatColor.RED) + "$25" + ChatColor.GRAY + " or " + (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= 400 ? ChatColor.GREEN : ChatColor.RED) + "$400" + ChatColor.GRAY + " for 16.").build()); + itemStackMap.put(41, new EconomyItem(player, Material.COOKED_BEEF, "Steak", 75, 16).build()); + itemStackMap.put(14, new ItemBuilder(new EconomyItem(player, Material.POTION, "Speed II (1:30)", 10, 1).build()).data((short) 8226).build()); + itemStackMap.put(15, new ItemBuilder(new EconomyItem(player, Material.POTION, "Fire Resistance (8:00)", 0, 1).build()).data((short) 8259).build()); + itemStackMap.put(16, new ItemBuilder(new EconomyItem(player, Material.POTION, "Team Invis (6:00)", 1250, 1).build()).data((short) 16462).build()); + itemStackMap.put(23, new ItemBuilder(new EconomyItem(player, Material.POTION, "Lesser Invis (3:00)", 100, 1).build()).data((short) 8238).build()); + itemStackMap.put(24, new ItemBuilder(new EconomyItem(player, Material.POTION, "Health Potion II", 20, 1).build()).lore(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 30), ChatColor.GRAY + "1 x Health Potion II", ChatColor.GRAY + "Right click to fill your inventory", ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 30), ChatColor.GRAY + "Price" + ChatColor.GRAY + ": " + (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= 20 ? ChatColor.GREEN : ChatColor.RED) + "$20" + ChatColor.GRAY + " or " + (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= (getEmptySlots(player.getInventory()) * 20) ? ChatColor.GREEN : ChatColor.RED) + "$" + (getEmptySlots(player.getInventory()) * 20) + ChatColor.GRAY + " for " + getEmptySlots(player.getInventory()) + ".").data((short) 16421).build()); + itemStackMap.put(34, new ItemBuilder(new EconomyItem(player, Material.POTION, "Slowness Potion (1:07)", 50, 1).build()).data((short) 16426).build()); + itemStackMap.put(25, new ItemBuilder(new EconomyItem(player, Material.POTION, "Poison Potion (0:33)", 50, 1).build()).data((short) 16388).build()); + return itemStackMap; + } + + private static int getEmptySlots(Inventory inventory) { + int i = 0; + for (ItemStack is : inventory.getContents()) { + if (is == null || is.getType() == Material.AIR) { + i++; + } + } + return i; + } + + private void loadItems() { + for(Map.Entry items : createLoadMap().entrySet()){ + this.setItem(items.getKey(), items.getValue()); + } + } + + private static String getName(String name, Integer price){ + String newName; + if(Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) >= price){ + newName = ChatColor.GREEN + name; + }else{ + newName = ChatColor.RED + name; + } + return newName; + } + + + private Integer getPriceFromString(String string){ + return Ints.tryParse(string.replace(ChatColor.GRAY + "Price" + ChatColor.GRAY + ": ", "").replace(ChatColor.GREEN.toString(), "").replace("$", "").replace(ChatColor.RED.toString(), "")); + } + + + private void loadClicks() { + this.setGlobalAction((player, inventory, itemStack, slot, action) -> { + if(itemStack.getType() == Material.STAINED_GLASS_PANE){ + return; + } + Integer price = getPriceFromString(itemStack.getItemMeta().getLore().get(3)); + if (!itemStack.getType().equals(Material.ENDER_PEARL) &&player.getInventory().firstEmpty() == -1) { + player.sendMessage(ChatColor.RED + "Your inventory is full."); + return; + } + if (price == null) { + if (itemStack.getType().equals(Material.ENDER_PEARL)) { + price = 25; + if (action == InventoryAction.PICKUP_HALF) { + price = 400; + } + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < price) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + Map tooFull = player.getInventory().addItem(price == 25 ? new ItemStack(Material.ENDER_PEARL) : new ItemStack(Material.ENDER_PEARL, 16)); + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), price); + if(!tooFull.isEmpty()){ + player.closeInventory(); + Inventory takeIt = Bukkit.createInventory(null , 9 ); + takeIt.addItem(tooFull.values().toArray(new ItemStack[0])); + player.openInventory(takeIt); + } + return; + } + if (itemStack.getType().equals(Material.DIAMOND)) { + price = 500; + if (player.getInventory().getHelmet() != null || player.getInventory().getChestplate() != null || player.getInventory().getLeggings() != null || player.getInventory().getBoots() != null) { + player.sendMessage(ChatColor.RED + "You have armor on already!"); + return; + } + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < price) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + player.getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + player.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + player.getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + player.getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + player.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD)); + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), price); + return; + } + if(itemStack.getType().equals(Material.POTION) && itemStack.getDurability() == (short) 16421){ + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < 20) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + if (action == InventoryAction.PICKUP_HALF) { + int emptySlot = getEmptySlots(player.getInventory()); + for(int i = 0; i < emptySlot ; i++){ + player.getInventory().addItem(new ItemBuilder(Material.POTION).data((short)16421).build()); + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), 20); + } + return; + }else{ + player.getInventory().addItem(new ItemBuilder(Material.POTION).data((short) 16421).build()); + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), 20); + return; + } + } + return; + } + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < price) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + if(EnchantmentTarget.ARMOR.includes(itemStack)){ + if(EnchantmentTarget.ARMOR_HEAD.includes(itemStack)){ + if (player.getInventory().getHelmet() != null) { + player.sendMessage(ChatColor.RED + "You have a helmet on already!"); + return; + } + player.getInventory().setHelmet(new ItemStack(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability())); + } + if(EnchantmentTarget.ARMOR_TORSO.includes(itemStack)){ + if (player.getInventory().getChestplate() != null) { + player.sendMessage(ChatColor.RED + "You have chestplate on already!"); + return; + } + player.getInventory().setChestplate(new ItemStack(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability())); + } + if(EnchantmentTarget.ARMOR_LEGS.includes(itemStack)){ + if (player.getInventory().getLeggings() != null) { + player.sendMessage(ChatColor.RED + "You have leggings on already!"); + return; + } + player.getInventory().setLeggings(new ItemStack(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability())); + } + if(EnchantmentTarget.ARMOR_FEET.includes(itemStack)){ + if (player.getInventory().getBoots() != null) { + player.sendMessage(ChatColor.RED + "You have boots on already!"); + return; + } + player.getInventory().setBoots(new ItemStack(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability())); + } + }else{ + player.getInventory().addItem(new ItemStack(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability())); + } + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), price); + return; + }); + } + + + +} diff --git a/main/java/me/prestige/bases/economy/gui/EnchantShop.java b/main/java/me/prestige/bases/economy/gui/EnchantShop.java new file mode 100644 index 0000000..f7864c1 --- /dev/null +++ b/main/java/me/prestige/bases/economy/gui/EnchantShop.java @@ -0,0 +1,90 @@ +package me.prestige.bases.economy.gui; + +import com.customhcf.base.BasePlugin; +import com.customhcf.util.ItemBuilder; +import com.customhcf.util.Menu; +import com.google.common.primitives.Ints; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.EconomyItem; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.enchantments.EnchantmentTarget; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class EnchantShop extends Menu { + private static Player player; + + public EnchantShop(Player player) { + super(ChatColor.GREEN + ChatColor.BOLD.toString() + "Tim the enchanter", 1); + this.player = player; + this.fill(new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 15).displayName(" ").build()); + loadItems(); + } + + public static Map createLoadMap() { + Map itemStackMap = new HashMap<>(); + itemStackMap.put(0, new EconomyItem(player, Material.ENCHANTED_BOOK, "Protection I", 1200, 1).build()); + itemStackMap.put(1, new EconomyItem(player, Material.ENCHANTED_BOOK, "Sharpness I", 300, 1).build()); + itemStackMap.put(2, new EconomyItem(player, Material.ENCHANTED_BOOK, "Feather Falling IV", 200, 1).build()); + return itemStackMap; + } + + private void loadItems() { + for (Map.Entry items : createLoadMap().entrySet()) { + this.setItem(items.getKey(), items.getValue()); + } + loadClicks(); + } + + + + private Integer getPriceFromString(String string){ + return Ints.tryParse(string.replace(ChatColor.GRAY + "Price" + ChatColor.GRAY + ": ", "").replace(ChatColor.GREEN.toString(), "").replace("$", "").replace(ChatColor.RED.toString(), "")); + } + + + private void loadClicks() { + this.setGlobalAction((player, inventory, itemStack, slot, action) -> { + Integer price = getPriceFromString(itemStack.getItemMeta().getLore().get(3)); + if (Bases.getPlugin().getEconomyManager().getBalance(player.getUniqueId()) < price) { + player.sendMessage(ChatColor.RED + "You do not have enough money for this!"); + return; + } + Bases.getPlugin().getEconomyManager().subtractBalance(player.getUniqueId(), price); + if(price == 1200){ + int count = 0; + for(ItemStack armor : player.getInventory().getArmorContents()){ + if(armor == null) continue; + count++; + armor.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1); + } + if(count == 0){ + player.sendMessage(ChatColor.RED + "You do not have any armor on!"); + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), price); + return; + } + } + if(price == 300){ + for(ItemStack sword : player.getInventory().getContents()){ + if(sword == null || !sword.getType().equals(Material.DIAMOND_SWORD)) continue; + sword.addEnchantment(Enchantment.DAMAGE_ALL, 1); + return; + } + } + if(price == 200){ + if(player.getInventory().getBoots() == null){ + player.sendMessage(ChatColor.RED + "You do not have any boots on!"); + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), price); + return; + } + player.getInventory().getBoots().addEnchantment(Enchantment.PROTECTION_FALL, 4); + return; + } + }); + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/economy/gui/SellShop.java b/main/java/me/prestige/bases/economy/gui/SellShop.java new file mode 100644 index 0000000..b5c49a0 --- /dev/null +++ b/main/java/me/prestige/bases/economy/gui/SellShop.java @@ -0,0 +1,185 @@ +package me.prestige.bases.economy.gui; + +import com.customhcf.base.BasePlugin; +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.ItemBuilder; +import com.customhcf.util.Menu; +import com.google.common.primitives.Ints; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.EconomyItem; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class SellShop extends Menu { + private static Player player; + + public SellShop(Player player) { + super(ChatColor.RED + ChatColor.BOLD.toString() + "Sell Items", 1); + this.player = player; + this.fill(new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 15).displayName(" ").build()); + loadItems(); + } + + public static Map createLoadMap() { + Map itemStackMap = new HashMap<>(); + itemStackMap.put(1, new ItemBuilder(Material.DIAMOND).displayName((hasItem(Material.DIAMOND) ? ChatColor.AQUA : ChatColor.RED) + "Sell Diamond").lore((hasItem(Material.DIAMOND) ? getLore(Material.DIAMOND, "Diamond", 100) : new String[]{ChatColor.GRAY + "You can sell Diamond here.", ChatColor.GRAY + "They sell for $100 each."})).build()); + itemStackMap.put(3, new ItemBuilder(Material.IRON_INGOT).displayName((hasItem(Material.IRON_INGOT) ? ChatColor.AQUA : ChatColor.RED) + "Sell Iron").lore((hasItem(Material.IRON_INGOT) ? getLore(Material.IRON_INGOT, "Iron Ingot", 25) : new String[]{ChatColor.GRAY + "You can sell Iron Ingot here.", ChatColor.GRAY + "They sell for $25 each."})).build()); + itemStackMap.put(5, new ItemBuilder(Material.COAL).displayName((hasItem(Material.COAL) ? ChatColor.AQUA : ChatColor.RED) + "Sell Coal").lore((hasItem(Material.COAL) ? getLore(Material.COAL, "Coal", 15) : new String[]{ChatColor.GRAY + "You can sell Coal here.", ChatColor.GRAY + "They sell for $15 each"})).build()); + itemStackMap.put(7, new ItemBuilder(Material.GOLD_INGOT).displayName((hasItem(Material.GOLD_INGOT) ? ChatColor.AQUA : ChatColor.RED) + "Sell Gold").lore((hasItem(Material.GOLD_INGOT) ? getLore(Material.GOLD_INGOT, "Gold Ingot", 50) : new String[]{ChatColor.GRAY + "You can sell Gold here.", ChatColor.GRAY + "They sell for $50 each"})).build()); + return itemStackMap; + } + + private void loadItems() { + for (Map.Entry items : createLoadMap().entrySet()) { + this.setItem(items.getKey(), items.getValue()); + } + loadClicks(); + } + + private static String[] getLore(Material material, String name, Integer price){ + return new String[]{ + ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 38), + ChatColor.GRAY + "Left click to sell 1 x " + name + " for " + ChatColor.GREEN + '$' +price + ChatColor.GRAY + '.', + ChatColor.GRAY + "Right click to sell " + getAmount(player.getInventory(), material) + " x " + name +" for " + ChatColor.GREEN + '$' + (price * getAmount(player.getInventory(), material)) + ChatColor.GRAY + '.', + ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT.substring(0, 38) + }; + } + + private static int getAmount(Inventory inventory, Material material) { + int i = 0; + for (ItemStack is : inventory.getContents()) { + if (is == null || !is.getType().equals(material)) { + continue; + } + i += is.getAmount(); + } + return i; + } + + + private static boolean hasItem(Material material){ + for(ItemStack itemStack1 : player.getInventory().getContents()){ + if(itemStack1 == null) continue; + if(itemStack1.getType().equals(material)){ + return true; + } + } + return false; + } + + + + + private void loadClicks() { + this.setGlobalAction((player, inventory, itemStack, slot, action) -> { + if(action == InventoryAction.PICKUP_HALF){ + if(slot == 1){ + int amount = 0; + for(ItemStack stack : player.getInventory().getContents()){ + if(stack == null) continue; + if(stack.getType().equals(Material.DIAMOND)){ + amount += stack.getAmount(); + player.getInventory().remove(stack); + } + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), amount * 100); + }else if(slot == 3){ + int amount = 0; + for(ItemStack stack : player.getInventory().getContents()){ + if(stack == null) continue; + if(stack.getType().equals(Material.IRON_INGOT)){ + amount += stack.getAmount(); + player.getInventory().remove(stack); + } + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), amount * 25); + }else if (slot == 5){ + int amount = 0; + for(ItemStack stack : player.getInventory().getContents()){ + if(stack == null) continue; + if(stack.getType().equals(Material.COAL)){ + amount += stack.getAmount(); + player.getInventory().remove(stack); + } + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), amount * 15); + }else { + if(slot != 7){ + return; + } + int amount = 0; + for(ItemStack stack : player.getInventory().getContents()){ + if(stack == null) continue; + if(stack.getType().equals(Material.GOLD_INGOT)){ + amount += stack.getAmount(); + player.getInventory().remove(stack); + } + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), amount * 50); + + } + return; + }else { + if(slot == 1){ + for(ItemStack stack : player.getInventory().getContents()){ + if(stack != null && stack.getType().equals(Material.DIAMOND)) { + if(stack.getAmount() <= 1){ + player.getInventory().remove(stack); + }else { + stack.setAmount(stack.getAmount() - 1); + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), 100); + return; + } + } + }else if(slot == 3){ + for(ItemStack stack : player.getInventory().getContents()){ + if(stack != null && stack.getType().equals(Material.IRON_INGOT)){ + if(stack.getAmount() <= 1){ + player.getInventory().remove(stack); + }else { + stack.setAmount(stack.getAmount() - 1); + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), 25); + return; + } + } + }else if (slot == 5){ + for(ItemStack stack : player.getInventory().getContents()){ + if(stack != null && stack.getType().equals(Material.COAL)){ + if(stack.getAmount() <= 1){ + player.getInventory().remove(stack); + }else { + stack.setAmount(stack.getAmount() - 1); + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), 15); + return; + } + } + }else { + if(slot != 7){ + return; + } + for(ItemStack stack : player.getInventory().getContents()){ + if(stack != null && stack.getType().equals(Material.GOLD_INGOT)){ + if(stack.getAmount() <= 1){ + player.getInventory().remove(stack); + }else { + stack.setAmount(stack.getAmount() - 1); + } + Bases.getPlugin().getEconomyManager().addBalance(player.getUniqueId(), 50); + return; + } + } + } + } + }); + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/faction/FactionExecutor.java b/main/java/me/prestige/bases/faction/FactionExecutor.java new file mode 100644 index 0000000..dc5621d --- /dev/null +++ b/main/java/me/prestige/bases/faction/FactionExecutor.java @@ -0,0 +1,54 @@ +package me.prestige.bases.faction; + +import com.customhcf.util.command.ArgumentExecutor; +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.argument.*; +import me.prestige.bases.faction.argument.staff.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class FactionExecutor extends ArgumentExecutor { + private final CommandArgument helpArgument; + + public FactionExecutor(final Bases plugin) { + super("faction"); + addArgument(new FactionPunishArgument(plugin)); + addArgument(new FactionLockArgument(plugin)); + addArgument(new FactionChatArgument(plugin)); + addArgument(new FactionClearClaimsArgument(plugin)); + addArgument(new FactionForceJoinArgument(plugin)); + addArgument(this.helpArgument = new FactionHelpArgument(this)); + addArgument(new FactionHomeArgument(this, plugin)); + addArgument(new FactionSetHomeForArgument(plugin)); + addArgument(new FactionSetVillagerArgument(plugin)); + addArgument(new FactionSpawnVillagerArgument(plugin)); + addArgument(new FactionClaimForArgument(plugin)); + addArgument(new FactionMessageArgument(plugin)); + addArgument(new FactionVersionArgument()); + addArgument(new FactionRemoveArgument(plugin)); + addArgument(new FactionSetDtrArgument(plugin)); + addArgument(new FactionSetDeathbanMultiplierArgument(plugin)); + addArgument(new FactionShowArgument(plugin)); + addArgument(new FactionStuckArgument(plugin)); + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 1) { + this.helpArgument.onCommand(sender, command, label, args); + return true; + } + final CommandArgument argument = this.getArgument(args[0]); + if(argument != null) { + final String permission = argument.getPermission(); + if(permission == null || sender.hasPermission(permission)) { + argument.onCommand(sender, command, label, args); + return true; + } + } + this.helpArgument.onCommand(sender, command, label, args); + return true; + } + + +} diff --git a/main/java/me/prestige/bases/faction/FactionManager.java b/main/java/me/prestige/bases/faction/FactionManager.java new file mode 100644 index 0000000..967423e --- /dev/null +++ b/main/java/me/prestige/bases/faction/FactionManager.java @@ -0,0 +1,67 @@ +package me.prestige.bases.faction; + +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; + +import java.util.Collection; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public interface FactionManager { + long MAX_DTR_REGEN_MILLIS = TimeUnit.HOURS.toMillis(3L); + String MAX_DTR_REGEN_WORDS = DurationFormatUtils.formatDurationWords(FactionManager.MAX_DTR_REGEN_MILLIS, true, true); + Map getFactionNameMap(); + + + Collection getFactions(); + + Collection getClaimableFactions(); + + Collection getPlayerFactions(); + + + + Claim getClaimAt(Location p0); + + Claim getClaimAt(World p0, int p1, int p2); + + Faction getFactionAt(Location p0); + + Faction getFactionAt(Block p0); + + Faction getFactionAt(World p0, int p1, int p2); + + Faction getFaction(String p0); + + Faction getFaction(UUID p0); + + PlayerFaction getContainingPlayerFaction(String p0); + + PlayerFaction getPlayerFaction(UUID p0); + + ColorFaction getColorFaction(UUID p0); + + ColorFaction getColorFaction(String p0); + + + Faction getContainingFaction(String p0); + + + + boolean createFaction(Faction p0, CommandSender p1); + + boolean removeFaction(Faction p0, CommandSender p1); + + void reloadFactionData(); + + void saveFactionData(); +} diff --git a/main/java/me/prestige/bases/faction/FactionMember.java b/main/java/me/prestige/bases/faction/FactionMember.java new file mode 100644 index 0000000..58a32f0 --- /dev/null +++ b/main/java/me/prestige/bases/faction/FactionMember.java @@ -0,0 +1,75 @@ +package me.prestige.bases.faction; + +import com.google.common.base.Enums; +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.struct.Role; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.Player; + +import java.util.Map; +import java.util.UUID; + +public class FactionMember implements ConfigurationSerializable { + private final UUID uniqueID; + private ChatChannel chatChannel; + private Role role; + + public FactionMember(final Player player, final ChatChannel chatChannel, final Role role) { + this.uniqueID = player.getUniqueId(); + this.chatChannel = chatChannel; + this.role = role; + } + public FactionMember(final UUID uuid, final ChatChannel chatChannel, final Role role) { + this.uniqueID = uuid; + this.chatChannel = chatChannel; + this.role = role; + } + + public FactionMember(final Map map) { + this.uniqueID = UUID.fromString((String) map.get("uniqueID")); + this.chatChannel = (ChatChannel) Enums.getIfPresent((Class) ChatChannel.class, (String) map.get("chatChannel")).or((Object) ChatChannel.PUBLIC); + this.role = (Role) Enums.getIfPresent((Class) Role.class, (String) map.get("role")).or((Object) Role.MEMBER); + } + + public Map serialize() { + final Map map = Maps.newLinkedHashMap(); + map.put("uniqueID", this.uniqueID.toString()); + map.put("chatChannel", this.chatChannel.name()); + map.put("role", this.role.name()); + return map; + } + + public String getName() { + final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(this.uniqueID); + return (offlinePlayer.hasPlayedBefore() || offlinePlayer.isOnline()) ? offlinePlayer.getName() : null; + } + + public UUID getUniqueId() { + return this.uniqueID; + } + + public ChatChannel getChatChannel() { + return this.chatChannel; + } + + public void setChatChannel(final ChatChannel chatChannel) { + Preconditions.checkNotNull((Object) chatChannel, (Object) "ChatChannel cannot be null"); + this.chatChannel = chatChannel; + } + + public Role getRole() { + return this.role; + } + + public void setRole(final Role role) { + this.role = role; + } + + public Player toOnlinePlayer() { + return Bukkit.getPlayer(this.uniqueID); + } +} diff --git a/main/java/me/prestige/bases/faction/FlatFileFactionManager.java b/main/java/me/prestige/bases/faction/FlatFileFactionManager.java new file mode 100644 index 0000000..4942557 --- /dev/null +++ b/main/java/me/prestige/bases/faction/FlatFileFactionManager.java @@ -0,0 +1,304 @@ +package me.prestige.bases.faction; + + +import com.customhcf.util.Config; +import com.customhcf.util.JavaUtils; +import com.customhcf.util.cuboid.CoordinatePair; +import com.google.common.base.Preconditions; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.event.*; +import me.prestige.bases.faction.event.cause.ClaimChangeCause; +import me.prestige.bases.faction.type.*; +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.MemorySection; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class FlatFileFactionManager implements Listener, FactionManager { + private final WarzoneFaction warzone; + private final Map claimPositionMap = new HashMap<>(); + private final Map factionPlayerUuidMap = new ConcurrentHashMap<>(); + private final Map factionUUIDMap = new HashMap<>(); + private final Map factionNameMap = new CaseInsensitiveMap<>(); + private final Bases plugin; + private Config config; + + public FlatFileFactionManager(final Bases plugin) { + this.plugin = plugin; + plugin.getServer().getPluginManager().registerEvents( this, plugin); + this.warzone = new WarzoneFaction(); + this.reloadFactionData(); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerJoinedFaction(final PlayerJoinedFactionEvent event) { + this.factionPlayerUuidMap.put(event.getUniqueID(), event.getFaction().getUniqueID()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerLeftFaction(final PlayerLeftFactionEvent event) { + this.factionPlayerUuidMap.remove(event.getUniqueID()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onFactionRename(final FactionRenameEvent event) { + this.factionNameMap.remove(event.getOriginalName()); + this.factionNameMap.put(event.getNewName(), event.getFaction().getUniqueID()); + } + + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onFactionClaim(final FactionClaimChangedEvent event) { + for(final Claim claim : event.getAffectedClaims()) { + this.cacheClaim(claim, event.getCause()); + } + } + + @Deprecated + public Map getFactionNameMap() { + return this.factionNameMap; + } + + public List getFactions() { + List asd = new ArrayList<>(); + for(Faction fac : factionUUIDMap.values()){ + asd.add(fac); + } + return asd; + } + + @Override + public List getClaimableFactions(){ + List factions = new ArrayList<>(); + for(Faction faction : getFactions()){ + if(faction instanceof ClaimableFaction){ + factions.add((ClaimableFaction) faction); + } + } + return factions; + } + + + + @Override + public Collection getPlayerFactions() { + List factions = new ArrayList<>(); + for(Faction faction : getFactions()){ + if(faction instanceof PlayerFaction){ + factions.add((PlayerFaction) faction); + } + } + return factions; + } + + public Claim getClaimAt(final World world, final int x, final int z) { + return this.claimPositionMap.get(new CoordinatePair(world, x, z)); + } + + public Claim getClaimAt(final Location location) { + return this.getClaimAt(location.getWorld(), location.getBlockX(), location.getBlockZ()); + } + + public Faction getFactionAt(final World world, final int x, final int z) { + final World.Environment environment = world.getEnvironment(); + final Claim claim = this.getClaimAt(world, x, z); + if(claim != null) { + final Faction faction = claim.getFaction(); + if(faction != null) { + return faction; + } + } + return this.warzone; + } + + public Faction getFactionAt(final Location location) { + return this.getFactionAt(location.getWorld(), location.getBlockX(), location.getBlockZ()); + } + + public Faction getFactionAt(final Block block) { + return this.getFactionAt(block.getLocation()); + } + + public Faction getFaction(final String factionName) { + final UUID uuid = this.factionNameMap.get(factionName); + return (uuid == null) ? null : this.factionUUIDMap.get(uuid); + } + + public ColorFaction getColorFaction(final String factionName) { + final UUID uuid = this.factionNameMap.get(factionName); + return (uuid == null) ? null : (ColorFaction) this.factionUUIDMap.get(uuid); + } + + public Faction getFaction(final UUID factionUUID) { + return this.factionUUIDMap.get(factionUUID); + } + + public PlayerFaction getPlayerFaction(final UUID playerUUID) { + final UUID uuid = this.factionPlayerUuidMap.get(playerUUID); + final Faction faction = (uuid == null) ? null : this.factionUUIDMap.get(uuid); + return (faction instanceof PlayerFaction) ? ((PlayerFaction) faction) : null; + } + + public ColorFaction getColorFaction(final UUID playerUUID) { + final UUID uuid = this.factionPlayerUuidMap.get(playerUUID); + final Faction faction = (uuid == null) ? null : this.factionUUIDMap.get(uuid); + return (faction instanceof ColorFaction) ? (ColorFaction) faction : null; + } + + + + public PlayerFaction getPlayerFaction(final Player player) { + return this.getPlayerFaction(player.getUniqueId()); + } + + public PlayerFaction getContainingPlayerFaction(final String search) { + final OfflinePlayer target = JavaUtils.isUUID(search) ? Bukkit.getOfflinePlayer(UUID.fromString(search)) : Bukkit.getOfflinePlayer(search); + return (target.hasPlayedBefore() || target.isOnline()) ? this.getPlayerFaction(target.getUniqueId()) : null; + } + + public Faction getContainingFaction(final String search) { + final Faction faction = this.getFaction(search); + if(faction != null) { + return faction; + } + final UUID playerUUID = Bukkit.getOfflinePlayer(search).getUniqueId(); + if(playerUUID != null) { + return this.getPlayerFaction(playerUUID); + } + return null; + } + + + + public boolean containsFaction(final Faction faction) { + return this.factionNameMap.containsKey(faction.getName()); + } + + public boolean createFaction(final Faction faction) { + return this.createFaction(faction, Bukkit.getConsoleSender()); + } + + public boolean createFaction(final Faction faction, final CommandSender sender) { + if(this.factionUUIDMap.putIfAbsent(faction.getUniqueID(), faction) != null) { + return false; + } + this.factionNameMap.put(faction.getName(), faction.getUniqueID()); + final FactionCreateEvent createEvent = new FactionCreateEvent(faction, sender); + Bukkit.getPluginManager().callEvent( createEvent); + return !createEvent.isCancelled(); + } + + public boolean removeFaction(final Faction faction, final CommandSender sender) { + if(this.factionUUIDMap.remove(faction.getUniqueID()) == null) { + return false; + } + this.factionNameMap.remove(faction.getName()); + final FactionRemoveEvent removeEvent = new FactionRemoveEvent(faction, sender); + Bukkit.getPluginManager().callEvent( removeEvent); + if(removeEvent.isCancelled()) { + return false; + } + if(faction instanceof ClaimableFaction) { + Bukkit.getPluginManager().callEvent( new FactionClaimChangedEvent(sender, ClaimChangeCause.UNCLAIM, ((ClaimableFaction) faction).getClaims())); + } + if(faction instanceof PlayerFaction) { + final PlayerFaction playerFaction = (PlayerFaction) faction; + + for(final UUID uuid : playerFaction.getMembers().keySet()) { + playerFaction.setMember(uuid, null, true); + } + } + + return true; + } + + private void cacheClaim(final Claim claim, final ClaimChangeCause cause) { + Preconditions.checkNotNull((Object) claim, "Claim cannot be null"); + Preconditions.checkNotNull((Object) cause, "Cause cannot be null"); + Preconditions.checkArgument(cause != ClaimChangeCause.RESIZE, "Cannot cache claims of resize type"); + final World world = claim.getWorld(); + if(world == null) { + return; + } + final int minX = Math.min(claim.getX1(), claim.getX2()); + final int maxX = Math.max(claim.getX1(), claim.getX2()); + final int minZ = Math.min(claim.getZ1(), claim.getZ2()); + final int maxZ = Math.max(claim.getZ1(), claim.getZ2()); + for(int x = minX; x <= maxX; ++x) { + for(int z = minZ; z <= maxZ; ++z) { + final CoordinatePair coordinatePair = new CoordinatePair(world, x, z); + if(cause == ClaimChangeCause.CLAIM) { + this.claimPositionMap.put(coordinatePair, claim); + } else if(cause == ClaimChangeCause.UNCLAIM) { + this.claimPositionMap.remove(coordinatePair); + } + } + } + } + + private void cacheFaction(final Faction faction) { + this.factionNameMap.put(faction.getName(), faction.getUniqueID()); + this.factionUUIDMap.put(faction.getUniqueID(), faction); + if(faction instanceof ClaimableFaction) { + ClaimableFaction claimableFaction = (ClaimableFaction) faction; + for(final Claim claim : claimableFaction.getClaims()) { + this.cacheClaim(claim, ClaimChangeCause.CLAIM); + } + } + if(faction instanceof PlayerFaction) { + for(final FactionMember factionMember : ((PlayerFaction) faction).getMembers().values()) { + this.factionPlayerUuidMap.put(factionMember.getUniqueId(), faction.getUniqueID()); + } + } + } + + public void reloadFactionData() { + this.factionNameMap.clear(); + this.config = new Config( this.plugin, "factions"); + final Object object = this.config.get("factions"); + if(object instanceof MemorySection) { + final MemorySection section = (MemorySection) object; + for(final String factionName : section.getKeys(false)) { + final Object next = this.config.get(section.getCurrentPath() + '.' + factionName); + if(next instanceof Faction) { + this.cacheFaction((Faction) next); + } + } + } else if(object instanceof List) { + final List list = (List) object; + for(final Object next2 : list) { + if(next2 instanceof Faction) { + this.cacheFaction((Faction) next2); + } + } + } + final Set adding = new HashSet<>(); + if(!this.factionNameMap.containsKey("Green")){ + adding.add(new ColorFaction.GreenFaction()); + adding.add(new ColorFaction.BlueFaction()); + adding.add(new ColorFaction.YellowFaction()); + adding.add(new ColorFaction.RedFaction()); + } + if(!this.factionNameMap.containsKey("Warzone")){ + adding.add(new WarzoneFaction()); + } + for(final Faction added : adding) { + this.cacheFaction(added); + Bukkit.getConsoleSender().sendMessage(ChatColor.BLUE + "Faction " + added.getName() + " not found, created."); + } + } + + public void saveFactionData() { + this.config.set("factions", new ArrayList<>(factionUUIDMap.values())); + this.config.save(); + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/faction/argument/FactionChatArgument.java b/main/java/me/prestige/bases/faction/argument/FactionChatArgument.java new file mode 100644 index 0000000..a98abcd --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionChatArgument.java @@ -0,0 +1,70 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.type.PlayerFaction; +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class FactionChatArgument extends CommandArgument { + private final Bases plugin; + + public FactionChatArgument(final Bases plugin) { + super("chat", "Toggle faction chat only mode on or off.", new String[]{"c"}); + this.plugin = plugin; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " [fac|public|ally] [message]"; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "This command is only executable by players."); + return true; + } + final Player player = (Player) sender; + final PlayerFaction playerFaction = this.plugin.getFactionManager().getPlayerFaction(player.getUniqueId()); + if(playerFaction == null) { + sender.sendMessage(ChatColor.RED + "You are not in a faction."); + return true; + } + final FactionMember member = playerFaction.getMember(player.getUniqueId()); + final ChatChannel currentChannel = member.getChatChannel(); + final ChatChannel parsed = (args.length >= 2) ? ChatChannel.parse(args[1], null) : currentChannel.getRotation(); + if(parsed == null && currentChannel != ChatChannel.PUBLIC) { + final Collection recipients = playerFaction.getOnlinePlayers(); + final String format = String.format(currentChannel.getRawFormat(player), "", StringUtils.join((Object[]) args, ' ', 1, args.length)); + for(final Player recipient : recipients) { + recipient.sendMessage(format); + } + return true; + } + final ChatChannel newChannel = (parsed == null) ? currentChannel.getRotation() : parsed; + member.setChatChannel(newChannel); + sender.sendMessage(ChatColor.WHITE + "You are now in " + ChatColor.GREEN + newChannel.getDisplayName().toLowerCase() + ChatColor.WHITE + " chat mode."); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + final ChatChannel[] values = ChatChannel.values(); + final List results = new ArrayList(values.length); + for(final ChatChannel type : values) { + results.add(type.getName()); + } + return results; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionHelpArgument.java b/main/java/me/prestige/bases/faction/argument/FactionHelpArgument.java new file mode 100644 index 0000000..61081f7 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionHelpArgument.java @@ -0,0 +1,93 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.chat.ClickAction; +import com.customhcf.util.chat.Text; +import com.customhcf.util.command.CommandArgument; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.Multimap; +import com.google.common.primitives.Ints; +import me.prestige.bases.faction.FactionExecutor; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class FactionHelpArgument extends CommandArgument { + private static final int HELP_PER_PAGE = 10; + private final FactionExecutor executor; + private ImmutableMultimap pages; + + public FactionHelpArgument(final FactionExecutor executor) { + super("help", "View help on how to use factions."); + this.executor = executor; + this.isPlayerOnly = true; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName(); + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + this.showPage(sender, label, 1); + return true; + } + final Integer page = Ints.tryParse(args[1]); + if(page == null) { + sender.sendMessage(ChatColor.RED + "'" + args[1] + "' is not a valid number."); + return true; + } + this.showPage(sender, label, page); + return true; + } + + private void showPage(final CommandSender sender, final String label, final int pageNumber) { + if(this.pages == null) { + final boolean isPlayer = sender instanceof Player; + int val = 1; + int count = 0; + final Multimap pages = ArrayListMultimap.create(); + for(final CommandArgument argument : this.executor.getArguments()) { + if(argument.equals((Object) this)) { + continue; + } + final String permission = argument.getPermission(); + if(permission != null && !sender.hasPermission(permission)) { + continue; + } + if(argument.isPlayerOnly() && !isPlayer) { + continue; + } + ++count; + pages.get(val).add(new Text(ChatColor.GREEN + " /" + label + ' ' + argument.getName() + ChatColor.GRAY + " - " + ChatColor.GRAY + argument.getDescription()).setColor(ChatColor.GRAY).setClick(ClickAction.SUGGEST_COMMAND, "/"+label +" "+argument.getName())); + if(count % HELP_PER_PAGE != 0) { + continue; + } + ++val; + } + this.pages = ImmutableMultimap.copyOf(pages); + } + final int totalPageCount = this.pages.size() / HELP_PER_PAGE + 1; + if(pageNumber < 1) { + sender.sendMessage(ChatColor.RED + "You cannot view a page less than 1."); + return; + } + if(pageNumber > totalPageCount) { + sender.sendMessage(ChatColor.RED + "There are only " + totalPageCount + " pages."); + return; + } + sender.sendMessage(ChatColor.DARK_GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + sender.sendMessage(ChatColor.GOLD + ChatColor.BOLD.toString() + " Faction Help " + ChatColor.GREEN + "[" + pageNumber + '/' + totalPageCount + ']'); + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + for(final Text message : this.pages.get(pageNumber)) { + message.send(sender); + } + sender.sendMessage(ChatColor.GRAY + " Use " + ChatColor.GREEN + '/' + label + ' ' + this.getName() + " <#>" + ChatColor.GRAY + " to view other pages."); + if(pageNumber == 1){ + sender.sendMessage(ChatColor.GRAY + "Click a command to '"+ ChatColor.ITALIC + "instantly" + ChatColor.GRAY + "' preform it."); + } + sender.sendMessage(ChatColor.DARK_GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionHomeArgument.java b/main/java/me/prestige/bases/faction/argument/FactionHomeArgument.java new file mode 100644 index 0000000..e461fbc --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionHomeArgument.java @@ -0,0 +1,93 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.FactionExecutor; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import me.prestige.bases.kothgame.faction.EventFaction; +import me.prestige.bases.timer.PlayerTimer; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.UUID; + +public class FactionHomeArgument extends CommandArgument { + private final FactionExecutor factionExecutor; + private final Bases plugin; + + public FactionHomeArgument(final FactionExecutor factionExecutor, final Bases plugin) { + super("home", "Teleport to the faction home."); + this.factionExecutor = factionExecutor; + this.plugin = plugin; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName(); + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "This command is only executable by players."); + return true; + } + final Player player = (Player) sender; + final UUID uuid = player.getUniqueId(); + PlayerTimer timer = this.plugin.getTimerManager().enderPearlTimer; + long remaining = timer.getRemaining(player); + if(remaining > 0L) { + sender.sendMessage(ChatColor.RED + "You cannot warp whilst your " + timer.getDisplayName() + ChatColor.RED + " timer is active [" + ChatColor.BOLD + Bases.getRemaining(remaining, true, false) + ChatColor.RED + " remaining]"); + return true; + } + if((remaining = (timer = this.plugin.getTimerManager().spawnTagTimer).getRemaining(player)) > 0L) { + sender.sendMessage(ChatColor.RED + "You cannot warp whilst your " + timer.getDisplayName() + ChatColor.RED + " timer is active [" + ChatColor.BOLD + Bases.getRemaining(remaining, true, false) + ChatColor.RED + " remaining]"); + return true; + } + final PlayerFaction playerFaction = this.plugin.getFactionManager().getPlayerFaction(uuid); + if(playerFaction == null) { + sender.sendMessage(ChatColor.RED + "You are not in a faction."); + return true; + } + final Location home = playerFaction.getHome(); + if(home == null) { + sender.sendMessage(ChatColor.RED + "Your faction does not have a home set."); + return true; + } + final Faction factionAt = this.plugin.getFactionManager().getFactionAt(player.getLocation()); + if(factionAt instanceof EventFaction) { + sender.sendMessage(ChatColor.RED + "You cannot warp whilst in event zones."); + return true; + } + long millis; + + switch(player.getWorld().getEnvironment()) { + case THE_END: { + millis = 30000L; + break; + } + case NETHER: { + millis = 30000L; + break; + } + default: { + millis = 10000L; + break; + } + } + if(!factionAt.equals(playerFaction) && factionAt instanceof PlayerFaction) { + if(!((PlayerFaction) factionAt).isRaidable()) { + player.sendMessage(ChatColor.RED + "You are in a claim, if your stuck use /f stuck"); + return true; + } else { + millis *= 2l; + } + } + this.plugin.getTimerManager().teleportTimer.teleport(player, home, 1, ChatColor.WHITE + "Teleported to your faction home "+ChatColor.GOLD +"instantly "+ChatColor.WHITE +"since there is no enemies nearby.", PlayerTeleportEvent.TeleportCause.COMMAND); + return true; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionMessageArgument.java b/main/java/me/prestige/bases/faction/argument/FactionMessageArgument.java new file mode 100644 index 0000000..14e0eb0 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionMessageArgument.java @@ -0,0 +1,51 @@ +package me.prestige.bases.faction.argument; + + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Iterator; + +public class FactionMessageArgument extends CommandArgument { + private final Bases plugin; + + public FactionMessageArgument(final Bases plugin) { + super("message", "Sends a message to your faction."); + this.plugin = plugin; + this.aliases = new String[]{"msg"}; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "Only players can use faction chat."); + return true; + } + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + final Player player = (Player) sender; + final PlayerFaction playerFaction = this.plugin.getFactionManager().getPlayerFaction(player.getUniqueId()); + if(playerFaction == null) { + sender.sendMessage(ChatColor.RED + "You are not in a faction."); + return true; + } + String format = String.format(ChatChannel.FACTION.getRawFormat(player), "", org.apache.commons.lang.StringUtils.join((Object[]) args, (char) ' ', (int) 1, (int) args.length)); + Iterator iterator = playerFaction.getOnlinePlayers().iterator(); + while(iterator.hasNext()) { + Player target = iterator.next(); + target.sendMessage(format); + } + return true; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionShowArgument.java b/main/java/me/prestige/bases/faction/argument/FactionShowArgument.java new file mode 100644 index 0000000..fd8ec9b --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionShowArgument.java @@ -0,0 +1,83 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionShowArgument extends CommandArgument { + private final Bases plugin; + + public FactionShowArgument(final Bases plugin) { + super("show", "Get details about a faction.", new String[]{"i", "info", "who"}); + this.plugin = plugin; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " [playerName|factionName]"; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + Faction playerFaction = null; + Faction namedFaction; + if(args.length < 2) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + namedFaction = this.plugin.getFactionManager().getPlayerFaction(((Player) sender).getUniqueId()); + if(namedFaction == null) { + sender.sendMessage(ChatColor.RED + "You are not in a faction."); + return true; + } + } else { + + namedFaction = this.plugin.getFactionManager().getFaction(args[1]); + playerFaction = this.plugin.getFactionManager().getFaction(args[1]); + + if(Bukkit.getPlayer(args[1]) != null){ + playerFaction = this.plugin.getFactionManager().getPlayerFaction(Bukkit.getPlayer(args[1]).getUniqueId()); + }else{ + if(Bukkit.getOfflinePlayer(args[1]).hasPlayedBefore()){ + playerFaction = this.plugin.getFactionManager().getPlayerFaction(Bukkit.getOfflinePlayer(args[1]).getUniqueId()); + } + } + if(namedFaction == null && playerFaction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + } + if(namedFaction != null) { + namedFaction.printDetails(sender); + } + if(playerFaction != null && (namedFaction == null || !namedFaction.equals(playerFaction))) { + playerFaction.printDetails(sender); + } + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionStuckArgument.java b/main/java/me/prestige/bases/faction/argument/FactionStuckArgument.java new file mode 100644 index 0000000..b220601 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionStuckArgument.java @@ -0,0 +1,43 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.timer.type.StuckTimer; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class FactionStuckArgument extends CommandArgument { + private final Bases plugin; + + public FactionStuckArgument(final Bases plugin) { + super("stuck", "Teleport to a safe position.", new String[]{"trap", "trapped"}); + this.plugin = plugin; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName(); + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "This command is only executable by players."); + return true; + } + final Player player = (Player) sender; + if(player.getWorld().getEnvironment() != World.Environment.NORMAL) { + sender.sendMessage(ChatColor.RED + "You can only use this command from the overworld."); + return true; + } + final StuckTimer stuckTimer = this.plugin.getTimerManager().stuckTimer; + if(!stuckTimer.setCooldown(player, player.getUniqueId())) { + sender.sendMessage(ChatColor.WHITE + "Your " + stuckTimer.getDisplayName() + ChatColor.WHITE + " timer has a remaining " + ChatColor.LIGHT_PURPLE + DurationFormatUtils.formatDurationWords(stuckTimer.getRemaining(player), true, true)+ChatColor.WHITE + '.'); + return true; + } + sender.sendMessage(ChatColor.WHITE + stuckTimer.getDisplayName() + ChatColor.WHITE + " timer has started. " + "\nTeleportation will commence in " + ChatColor.LIGHT_PURPLE + Bases.getRemaining(stuckTimer.getRemaining(player), true, false) + ChatColor.WHITE + ". " + "\nThis will cancel if you move more than " + 5 + " blocks."); + return true; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/FactionVersionArgument.java b/main/java/me/prestige/bases/faction/argument/FactionVersionArgument.java new file mode 100644 index 0000000..b1c0f97 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/FactionVersionArgument.java @@ -0,0 +1,24 @@ +package me.prestige.bases.faction.argument; + +import com.customhcf.util.command.CommandArgument; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class FactionVersionArgument extends CommandArgument { + public FactionVersionArgument() { + super("version", "Gets the faction version information."); + } + + @Override + public String getUsage(final String label) { + return ""; + } + + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + commandSender.sendMessage(ChatColor.YELLOW + "This plugin was made by " + ChatColor.RED + "Addons & Squirted" + ChatColor.GOLD + "\nLicensed for Kirai.rip "); + return false; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionClaimForArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionClaimForArgument.java new file mode 100644 index 0000000..e3cb480 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionClaimForArgument.java @@ -0,0 +1,101 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import com.customhcf.util.cuboid.Cuboid; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldedit.bukkit.selections.Selection; +import me.prestige.bases.Bases; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by TREHOME on 01/20/2016. + */ +public class FactionClaimForArgument extends CommandArgument { + private static final int MIN_EVENT_CLAIM_AREA; + + + private final Bases plugin; + + public FactionClaimForArgument(final Bases plugin) { + super("claimfor", "Claims for a faction"); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " [shouldClearClaims]"; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Faction faction = plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof ClaimableFaction)){ + sender.sendMessage(ChatColor.RED + "This is not a claimable faction (cannot contain claims)"); + return true; + } + final WorldEditPlugin worldEditPlugin = this.plugin.getWorldEditPlugin(); + if(worldEditPlugin == null) { + sender.sendMessage(ChatColor.RED + "WorldEdit must be installed to set event claim areas."); + return true; + } + final Player player = (Player) sender; + final Selection selection = worldEditPlugin.getSelection(player); + if(selection == null) { + sender.sendMessage(ChatColor.RED + "You must make a WorldEdit selection to do this."); + return true; + } + if(selection.getWidth() < MIN_EVENT_CLAIM_AREA || selection.getLength() < MIN_EVENT_CLAIM_AREA) { + sender.sendMessage(ChatColor.RED + "Event claim areas must be at least " + MIN_EVENT_CLAIM_AREA + 'x' + MIN_EVENT_CLAIM_AREA + '.'); + return true; + } + ClaimableFaction claimableFaction = (ClaimableFaction) faction; + if(args.length == 3 && (args[2].toLowerCase().contains("true") || args[2].toLowerCase().contains("yes")) && ((ClaimableFaction) faction).getClaims().size() > 0){ + sender.sendMessage(ChatColor.WHITE + "Set claim for " + faction.getDisplayName(sender) + ChatColor.WHITE + '.'); + if(claimableFaction.getClaims().size() > 0) { + for (Claim claim : claimableFaction.getClaims()) { + claimableFaction.removeClaim(claim, sender); + } + claimableFaction.getClaims().clear(); + } + claimableFaction.setClaim(new Cuboid(selection.getMinimumPoint(), selection.getMaximumPoint()), player); + return true; + } + claimableFaction.addClaim(new Claim(claimableFaction, selection.getMinimumPoint(), selection.getMaximumPoint()), player); + sender.sendMessage(ChatColor.WHITE + "Added claim for " + faction.getDisplayName(sender) + ChatColor.WHITE + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + switch (args.length){ + case 2 :{ + final List results = new ArrayList<>(plugin.getFactionManager().getClaimableFactions().size()); + for(ClaimableFaction claimableFaction : plugin.getFactionManager().getClaimableFactions()){ + results.add(claimableFaction.getName()); + } + return results; + } + default: { + return Collections.emptyList(); + } + } + } + static { + MIN_EVENT_CLAIM_AREA = 2; + } + +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionClearClaimsArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionClearClaimsArgument.java new file mode 100644 index 0000000..a83b53d --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionClearClaimsArgument.java @@ -0,0 +1,121 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.conversations.*; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionClearClaimsArgument extends CommandArgument { + private final ConversationFactory factory; + private final Bases plugin; + + public FactionClearClaimsArgument(final Bases plugin) { + super("clearclaims", "Clears the claims of a faction."); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + this.factory = new ConversationFactory((Plugin) plugin).withFirstPrompt((Prompt) new ClaimClearAllPrompt(plugin)).withEscapeSequence("/no").withTimeout(10).withModality(false).withLocalEcho(true); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + if(args[1].equalsIgnoreCase("all")) { + + final Conversable conversable = (Conversable) sender; + conversable.beginConversation(this.factory.buildConversation(conversable)); + return true; + } else { + final Faction faction = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + if(faction instanceof ClaimableFaction) { + final ClaimableFaction claimableFaction = (ClaimableFaction) faction; + claimableFaction.removeClaims(claimableFaction.getClaims(), sender); + for(Claim claim : claimableFaction.getClaims()){ + claimableFaction.removeClaim(claim, sender); + } + claimableFaction.getClaims().clear(); + if(claimableFaction instanceof PlayerFaction) { + ((PlayerFaction) claimableFaction).broadcast(ChatColor.GOLD.toString() + ChatColor.BOLD + "Your claims have been forcefully wiped by " + sender.getName() + '.'); + } + } + sender.sendMessage(ChatColor.WHITE.toString() + "Claims belonging to " + ChatColor.GOLD + faction.getName() + ChatColor.WHITE + " have been forcefully wiped."); + return true; + } + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } + + private static class ClaimClearAllPrompt extends StringPrompt { + private final Bases plugin; + + public ClaimClearAllPrompt(final Bases plugin) { + this.plugin = plugin; + } + + public String getPromptText(final ConversationContext context) { + return ChatColor.WHITE + "Are you sure you want to do this? " + ChatColor.RED + ChatColor.BOLD + "All claims" + ChatColor.WHITE + " will be cleared. " + "Type " + ChatColor.GREEN + "yes" + ChatColor.WHITE + " to confirm or " + ChatColor.RED + "no" + ChatColor.WHITE + " to deny."; + } + + public Prompt acceptInput(final ConversationContext context, final String string) { + final String lowerCase = string.toLowerCase(); + switch(lowerCase) { + case "yes": { + for(final Faction faction : this.plugin.getFactionManager().getFactions()) { + if(faction instanceof ClaimableFaction) { + final ClaimableFaction claimableFaction = (ClaimableFaction) faction; + claimableFaction.removeClaims(claimableFaction.getClaims(), (CommandSender) Bukkit.getConsoleSender()); + } + } + final Conversable conversable = context.getForWhom(); + Bukkit.broadcastMessage(ChatColor.GOLD.toString() + ChatColor.BOLD + "All claims have been cleared" + ((conversable instanceof CommandSender) ? (" by " + ((CommandSender) conversable).getName()) : "") + '.'); + return Prompt.END_OF_CONVERSATION; + } + case "no": { + context.getForWhom().sendRawMessage(ChatColor.BLUE + "Cancelled the process of clearing all faction claims."); + return Prompt.END_OF_CONVERSATION; + } + default: { + context.getForWhom().sendRawMessage(ChatColor.RED + "Unrecognized response. Process of clearing all faction claims cancelled."); + return Prompt.END_OF_CONVERSATION; + } + } + } + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionForceJoinArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionForceJoinArgument.java new file mode 100644 index 0000000..f4ee655 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionForceJoinArgument.java @@ -0,0 +1,80 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.struct.Role; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionForceJoinArgument extends CommandArgument { + private final Bases plugin; + + public FactionForceJoinArgument(final Bases plugin) { + super("forcejoin", "Forcefully join a faction."); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(!(sender instanceof Player)) { + sender.sendMessage(ChatColor.RED + "Only players can join factions."); + return true; + } + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + final Player player = (Player) sender; + PlayerFaction playerFaction = this.plugin.getFactionManager().getPlayerFaction(player.getUniqueId()); + if(playerFaction != null) { + sender.sendMessage(ChatColor.RED + "You are already in a faction."); + return true; + } + final Faction faction = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + if(!(faction instanceof PlayerFaction)) { + sender.sendMessage(ChatColor.RED + "You can only join player factions."); + return true; + } + playerFaction = (PlayerFaction) faction; + if(playerFaction.setMember(player, new FactionMember(player, ChatChannel.PUBLIC, Role.MEMBER), true)) { + playerFaction.broadcast(ChatColor.WHITE.toString() + sender.getName() + " has joined your faction forcefully."); + } + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionLockArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionLockArgument.java new file mode 100644 index 0000000..03277fe --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionLockArgument.java @@ -0,0 +1,60 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; + +/** + * Created by TREHOME on 01/20/2016. + */ +public class FactionLockArgument extends CommandArgument { + private final Bases plugin; + + public FactionLockArgument(final Bases plugin) { + super("lock", "Lock all factions"); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " [on|off]"; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + if (args[1].equalsIgnoreCase("on")) { + Bukkit.broadcastMessage(ChatColor.RED + "All Factions are being locked!"); + for (Faction faction : plugin.getFactionManager().getFactions()) { + if (faction instanceof PlayerFaction) { + faction.setLocked(true); + } + } + } + if (args[1].equalsIgnoreCase("off")) { + Bukkit.broadcastMessage(ChatColor.GREEN + "All Factions are being un-locked!"); + for (Faction faction : plugin.getFactionManager().getFactions()) { + if (faction instanceof PlayerFaction) { + faction.setLocked(false); + } + } + } + + + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + return (args.length == 2) ? null : Collections.emptyList(); + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionPunishArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionPunishArgument.java new file mode 100644 index 0000000..ca31c58 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionPunishArgument.java @@ -0,0 +1,130 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.base.BasePlugin; +import com.customhcf.util.ItemBuilder; +import com.customhcf.util.Menu; +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionPunishArgument extends CommandArgument { + private final Bases plugin; + + public FactionPunishArgument(final Bases plugin) { + super("punish", ""); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " [reason]"; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + String message = StringUtils.join(args, ' ', 2, args.length); + final Player player = (Player) sender; + final Faction faction = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + if(!(faction instanceof PlayerFaction)) { + sender.sendMessage(ChatColor.RED + "You can only punish player factions."); + return true; + } + final PlayerFaction fac = (PlayerFaction) faction; + Menu menu = new Menu(faction.getName(), 3); + menu.fill(new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 15).displayName("").build()); + + menu.setItem(10, new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 0).displayName(ChatColor.WHITE + ChatColor.BOLD.toString() + "Freeze Faction").build()); + + if(player.hasPermission("command.faction.punish.ban")) { + menu.setItem(12, new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 14).displayName(ChatColor.RED + ChatColor.BOLD.toString() + "Ban Faction").build()); + }else{ + menu.setItem(12, new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 14).displayName(ChatColor.DARK_RED + ChatColor.BOLD.toString() + "No Permission").build()); + } + + menu.setItem(14, new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 11).displayName(ChatColor.AQUA + ChatColor.BOLD.toString() + "Mute Faction").build()); + + menu.setItem(16, new ItemBuilder(Material.STAINED_GLASS_PANE).data((short) 2).displayName(ChatColor.LIGHT_PURPLE + ChatColor.BOLD.toString() + "Kick Faction").build()); + + menu.runWhenEmpty(false); + + menu.setGlobalAction((player1, inventory, itemStack, slot, inventoryAction) -> { + switch (slot) { + case 10: { + for (FactionMember factionMember : fac.getMembers().values()) { + if (Bukkit.getPlayer(factionMember.getUniqueId()) != null) { + Bukkit.dispatchCommand(player1, "freeze " + factionMember.getName()); + } + } + Bukkit.broadcastMessage(ChatColor.GREEN + player1.getName() + " has frozen the faction " + fac.getName()); + break; + } + case 12: { + if(itemStack.getItemMeta().getDisplayName().contains(ChatColor.DARK_RED.toString())) return; + for (FactionMember factionMember : fac.getMembers().values()) { + Bukkit.dispatchCommand(player1, "ban -s " + factionMember.getName() + " " + message); + } + Bukkit.broadcastMessage(ChatColor.GREEN + player1.getName() + " has banned the faction " + fac.getName()); + break; + } + case 14: { + for (FactionMember factionMember : fac.getMembers().values()) { + Bukkit.dispatchCommand(player1, "mute -s " + factionMember.getName() + " " + message); + } + Bukkit.broadcastMessage(ChatColor.GREEN + player1.getName() + " has muted the faction " + fac.getName()); + break; + } + case 16: { + for (FactionMember factionMember : fac.getMembers().values()) { + Bukkit.dispatchCommand(player1, "kick -s " + factionMember.getName() + " " + message); + } + Bukkit.broadcastMessage(ChatColor.GREEN + player1.getName() + " has kicked the faction " + fac.getName()); + break; + } + default: { + return; + } + } + + }); + menu.showMenu(player); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } + +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionRemoveArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionRemoveArgument.java new file mode 100644 index 0000000..afdb173 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionRemoveArgument.java @@ -0,0 +1,111 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.conversations.*; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionRemoveArgument extends CommandArgument { + private final ConversationFactory factory; + private final Bases plugin; + + public FactionRemoveArgument(final Bases plugin) { + super("remove", "Remove a faction."); + this.plugin = plugin; + this.aliases = new String[]{"delete", "forcedisband", "forceremove"}; + this.permission = "command.faction." + this.getName(); + this.factory = new ConversationFactory((Plugin) plugin).withFirstPrompt((Prompt) new RemoveAllPrompt(plugin)).withEscapeSequence("/no").withTimeout(10).withModality(false).withLocalEcho(true); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + if(args[1].equalsIgnoreCase("all")) { + if(!(sender instanceof ConsoleCommandSender)) { + sender.sendMessage(ChatColor.RED + "This command can be only executed from console."); + return true; + } + final Conversable conversable = (Conversable) sender; + conversable.beginConversation(this.factory.buildConversation(conversable)); + return true; + } else { + final Faction faction = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + if(this.plugin.getFactionManager().removeFaction(faction, sender)) { + Command.broadcastCommandMessage(sender, ChatColor.WHITE + "Disbanded faction " + ChatColor.GOLD + faction.getName() + ChatColor.WHITE + '.'); + } + return true; + } + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } + + private static class RemoveAllPrompt extends StringPrompt { + private final Bases plugin; + + public RemoveAllPrompt(final Bases plugin) { + this.plugin = plugin; + } + + public String getPromptText(final ConversationContext context) { + return ChatColor.WHITE + "Are you sure you want to do this? " + ChatColor.RED + ChatColor.BOLD + "All factions" + ChatColor.WHITE + " will be cleared. " + "Type " + ChatColor.GREEN + "yes" + ChatColor.WHITE + " to confirm or " + ChatColor.RED + "no" + ChatColor.WHITE + " to deny."; + } + + public Prompt acceptInput(final ConversationContext context, final String string) { + final String lowerCase = string.toLowerCase(); + switch(lowerCase) { + case "yes": { + for(final Faction faction : this.plugin.getFactionManager().getPlayerFactions()) { + this.plugin.getFactionManager().removeFaction(faction, Bukkit.getConsoleSender()); + } + final Conversable conversable = context.getForWhom(); + Bukkit.broadcastMessage(ChatColor.GOLD.toString() + ChatColor.BOLD + "All factions have been disbanded" + ((conversable instanceof CommandSender) ? (" by " + ((CommandSender) conversable).getName()) : "") + '.'); + return Prompt.END_OF_CONVERSATION; + } + case "no": { + context.getForWhom().sendRawMessage(ChatColor.BLUE + "Cancelled the process of disbanding all factions."); + return Prompt.END_OF_CONVERSATION; + } + default: { + context.getForWhom().sendRawMessage(ChatColor.RED + "Unrecognized response. Process of disbanding all factions cancelled."); + return Prompt.END_OF_CONVERSATION; + } + } + } + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionSetDeathbanMultiplierArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionSetDeathbanMultiplierArgument.java new file mode 100644 index 0000000..4440678 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionSetDeathbanMultiplierArgument.java @@ -0,0 +1,55 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import com.google.common.primitives.Doubles; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class FactionSetDeathbanMultiplierArgument extends CommandArgument { + private static final double MIN_MULTIPLIER = 0.0; + private static final double MAX_MULTIPLIER = 5.0; + private final Bases plugin; + + public FactionSetDeathbanMultiplierArgument(final Bases plugin) { + super("setdeathbanmultiplier", "Sets the deathban multiplier of a faction."); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + final Faction faction = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + final Double multiplier = Doubles.tryParse(args[2]); + if(multiplier == null) { + sender.sendMessage(ChatColor.RED + "'" + args[2] + "' is not a valid number."); + return true; + } + if(multiplier < MIN_MULTIPLIER) { + sender.sendMessage(ChatColor.RED + "Deathban multipliers may not be less than " + MIN_MULTIPLIER + '.'); + return true; + } + if(multiplier > MAX_MULTIPLIER) { + sender.sendMessage(ChatColor.RED + "Deathban multipliers may not be more than " + MAX_MULTIPLIER + '.'); + return true; + } + final double previousMultiplier = faction.getDeathbanMultiplier(); + faction.setDeathbanMultiplier(multiplier); + Command.broadcastCommandMessage(sender, ChatColor.WHITE + "Set deathban multiplier of " + faction.getName() + " from " + previousMultiplier + " to " + multiplier + '.'); + return true; + } + +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionSetDtrArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionSetDtrArgument.java new file mode 100644 index 0000000..2570baa --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionSetDtrArgument.java @@ -0,0 +1,82 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import com.google.common.primitives.Doubles; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionSetDtrArgument extends CommandArgument { + private final Bases plugin; + + public FactionSetDtrArgument(final Bases plugin) { + super("setdtr", "Sets the DTR of a faction."); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Double newDTR = Doubles.tryParse(args[2]); + if(newDTR == null) { + sender.sendMessage(ChatColor.RED + "'" + args[2] + "' is not a valid number."); + return true; + } + if(args[1].equalsIgnoreCase("all")) { + for(final Faction faction : this.plugin.getFactionManager().getFactions()) { + if(faction instanceof PlayerFaction) { + ((PlayerFaction) faction).setDeathsUntilRaidable(newDTR); + } + } + Command.broadcastCommandMessage(sender, ChatColor.WHITE + "Set DTR of all factions to " + newDTR + '.'); + return true; + } + final Faction faction2 = this.plugin.getFactionManager().getContainingFaction(args[1]); + if(faction2 == null) { + sender.sendMessage(ChatColor.RED + "Faction named or containing member with IGN or UUID " + args[1] + " not found."); + return true; + } + if(!(faction2 instanceof PlayerFaction)) { + sender.sendMessage(ChatColor.RED + "You can only set DTR of player factions."); + return true; + } + final PlayerFaction playerFaction = (PlayerFaction) faction2; + final double previousDtr = playerFaction.getDeathsUntilRaidable(); + newDTR = playerFaction.setDeathsUntilRaidable(newDTR); + Command.broadcastCommandMessage(sender, ChatColor.WHITE + "Set DTR of " + faction2.getName() + " from " + previousDtr + " to " + newDTR + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2 || !(sender instanceof Player)) { + return Collections.emptyList(); + } + if(args[1].isEmpty()) { + return null; + } + final Player player = (Player) sender; + final List results = new ArrayList(this.plugin.getFactionManager().getFactionNameMap().keySet()); + for(final Player target : Bukkit.getOnlinePlayers()) { + if(player.canSee(target) && !results.contains(target.getName())) { + results.add(target.getName()); + } + } + return results; + } +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionSetHomeForArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionSetHomeForArgument.java new file mode 100644 index 0000000..6ea6edd --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionSetHomeForArgument.java @@ -0,0 +1,76 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.command.CommandArgument; +import com.customhcf.util.cuboid.Cuboid; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldedit.bukkit.selections.Selection; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionSetHomeForArgument extends CommandArgument { + private static final int MIN_EVENT_CLAIM_AREA; + + + private final Bases plugin; + + public FactionSetHomeForArgument(final Bases plugin) { + super("sethomefor", "Sethome for a faction"); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + @Override + public boolean isPlayerOnly() { + return true; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Player player = (Player) sender; + Faction faction = plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof PlayerFaction)){ + sender.sendMessage(ChatColor.RED + "This is not a claimable faction (cannot contain claims)"); + return true; + } + ((PlayerFaction) faction).setHome(player.getLocation()); + sender.sendMessage(ChatColor.WHITE + "Set home for " + ChatColor.GOLD + faction.getDisplayName(sender) + ChatColor.WHITE + " at your location"+ ChatColor.WHITE + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + switch (args.length){ + case 2 :{ + final List results = new ArrayList<>(plugin.getFactionManager().getClaimableFactions().size()); + for(ClaimableFaction claimableFaction : plugin.getFactionManager().getClaimableFactions()){ + results.add(claimableFaction.getName()); + } + return results; + } + default: { + return Collections.emptyList(); + } + } + } + static { + MIN_EVENT_CLAIM_AREA = 2; + } + +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionSetVillagerArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionSetVillagerArgument.java new file mode 100644 index 0000000..a0d6054 --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionSetVillagerArgument.java @@ -0,0 +1,102 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.PersistableLocation; +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class FactionSetVillagerArgument extends CommandArgument { + + + private final Bases plugin; + + public FactionSetVillagerArgument(final Bases plugin) { + super("setvillager", "Sets villager at a location"); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + @Override + public boolean isPlayerOnly() { + return true; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Player player = (Player) sender; + Faction faction = plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof ColorFaction)){ + sender.sendMessage(ChatColor.RED + "This is not a claimable faction (cannot contain claims)"); + return true; + } + final String upperCase = args[2].toUpperCase(); + switch(upperCase) { + case "BUY": { + ((ColorFaction) faction).setBuyVillager(new PersistableLocation(player.getLocation())); + break; + } + case "SELL": { + ((ColorFaction) faction).setSellVillager(new PersistableLocation(player.getLocation())); + break; + } + case "ENCHANT": { + ((ColorFaction) faction).setEnchantVillager(new PersistableLocation(player.getLocation())); + break; + } + case "BLOCK": { + ((ColorFaction) faction).setBlockVillager(new PersistableLocation(player.getLocation())); + break; + } + default: { + sender.sendMessage(this.getUsage(label)); + return true; + } + } + sender.sendMessage(ChatColor.WHITE + "Set villager location for " + ChatColor.GOLD + faction.getDisplayName(sender) + ChatColor.WHITE + " at your location"+ ChatColor.WHITE + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + switch (args.length){ + case 2 :{ + final List results = new ArrayList<>(plugin.getFactionManager().getClaimableFactions().size()); + for(ClaimableFaction claimableFaction : plugin.getFactionManager().getClaimableFactions()){ + results.add(claimableFaction.getName()); + } + return results; + } + case 3 :{ + List result = new ArrayList<>(); + result.add("BUY"); + result.add("SELL"); + result.add("BLOCK"); + result.add("ENCHANT"); + return result; + } + default: { + return Collections.emptyList(); + } + } + } + +} diff --git a/main/java/me/prestige/bases/faction/argument/staff/FactionSpawnVillagerArgument.java b/main/java/me/prestige/bases/faction/argument/staff/FactionSpawnVillagerArgument.java new file mode 100644 index 0000000..5d1657b --- /dev/null +++ b/main/java/me/prestige/bases/faction/argument/staff/FactionSpawnVillagerArgument.java @@ -0,0 +1,111 @@ +package me.prestige.bases.faction.argument.staff; + +import com.customhcf.util.PersistableLocation; +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.economy.EconomyListener; +import me.prestige.bases.economy.VillagerRunnable; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.nms.Villager; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import java.util.*; + +public class FactionSpawnVillagerArgument extends CommandArgument { + + + private final Bases plugin; + + public FactionSpawnVillagerArgument(final Bases plugin) { + super("spawnvillager", "Spawns a vilager for a faction at its location"); + this.plugin = plugin; + this.permission = "command.faction." + this.getName(); + } + + @Override + public boolean isPlayerOnly() { + return true; + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Player player = (Player) sender; + Faction faction = plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof ColorFaction)){ + sender.sendMessage(ChatColor.RED + "This is not a claimable faction (cannot contain claims)"); + return true; + } + final String upperCase = args[2].toUpperCase(); + switch(upperCase) { + case "BUY": { + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getBuyVillager(), ((ColorFaction) faction).getColor() + "Combat Shop"); + break; + } + case "SELL": { + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getSellVillager(), ((ColorFaction) faction).getColor() + "Sell Items"); + break; + } + case "ENCHANT": { + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getEnchantVillager(), ((ColorFaction) faction).getColor() + "Tim the Enchanter"); + break; + } + case "BLOCK": { + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getBlockVillager(), ((ColorFaction) faction).getColor() + "Build Shop"); + break; + } + case "ALL": { + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getBlockVillager(), ((ColorFaction) faction).getColor() + "Build Shop"); + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getBuyVillager(), ((ColorFaction) faction).getColor() + "Combat Shop"); + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getSellVillager(), ((ColorFaction) faction).getColor() + "Sell Items"); + plugin.getGameManager().spawnVillager(((ColorFaction) faction).getEnchantVillager(), ((ColorFaction) faction).getColor() + "Tim the Enchanter"); + break; + } + default: { + sender.sendMessage(this.getUsage(label)); + return true; + } + } + sender.sendMessage(ChatColor.WHITE + "You should have spawned a "+ args[2] + " for the faction " + faction.getDisplayName(sender) ); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + switch (args.length){ + case 2 :{ + final List results = new ArrayList<>(plugin.getFactionManager().getClaimableFactions().size()); + for(ClaimableFaction claimableFaction : plugin.getFactionManager().getClaimableFactions()){ + results.add(claimableFaction.getName()); + } + return results; + } + case 3 :{ + List result = new ArrayList<>(); + result.add("BUY"); + result.add("SELL"); + result.add("BLOCK"); + result.add("ENCHANT"); + result.add("ALL"); + return result; + } + default: { + return Collections.emptyList(); + } + } + } + + + +} diff --git a/main/java/me/prestige/bases/faction/claim/Claim.java b/main/java/me/prestige/bases/faction/claim/Claim.java new file mode 100644 index 0000000..a206d92 --- /dev/null +++ b/main/java/me/prestige/bases/faction/claim/Claim.java @@ -0,0 +1,145 @@ +package me.prestige.bases.faction.claim; + +import com.customhcf.util.GenericUtils; +import com.customhcf.util.cuboid.Cuboid; +import com.customhcf.util.cuboid.NamedCuboid; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.ClaimableFaction; +import me.prestige.bases.faction.type.Faction; +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.*; + +public class Claim extends NamedCuboid implements Cloneable, ConfigurationSerializable { + private static final Random RANDOM = new Random(); + private final UUID claimUniqueID; + private final UUID factionUUID; + private Faction faction; + private boolean loaded = false; + + public Claim(Map map) { + super(map); + this.name = (String) map.get("name"); + this.claimUniqueID = UUID.fromString((String) map.get("claimUUID")); + this.factionUUID = UUID.fromString((String) map.get("factionUUID")); + + } + + public Claim(Faction faction, Location location) { + super(location, location); + this.name = this.generateName(); + this.factionUUID = faction.getUniqueID(); + this.claimUniqueID = UUID.randomUUID(); + } + + public Claim(Faction faction, Location location1, Location location2) { + super(location1, location2); + this.name = this.generateName(); + this.factionUUID = faction.getUniqueID(); + this.claimUniqueID = UUID.randomUUID(); + } + + public Claim(Faction faction, World world, int x1, int y1, int z1, int x2, int y2, int z2) { + super(world, x1, y1, z1, x2, y2, z2); + this.name = this.generateName(); + this.factionUUID = faction.getUniqueID(); + this.claimUniqueID = UUID.randomUUID(); + } + + public Claim(Faction faction, Cuboid cuboid) { + super(cuboid); + this.name = this.generateName(); + this.factionUUID = faction.getUniqueID(); + this.claimUniqueID = UUID.randomUUID(); + } + + public Map serialize() { + final Map map = super.serialize(); + map.put("name", this.name); + map.put("claimUUID", this.claimUniqueID.toString()); + map.put("factionUUID", this.factionUUID.toString()); + return map; + } + + private String generateName() { + return String.valueOf(Claim.RANDOM.nextInt(899) + 100); + } + + public UUID getClaimUniqueID() { + return this.claimUniqueID; + } + + public ClaimableFaction getFaction() { + if(!this.loaded && this.faction == null) { + this.faction = Bases.getPlugin().getFactionManager().getFaction(this.factionUUID); + this.loaded = true; + } + return (this.faction instanceof ClaimableFaction) ? ((ClaimableFaction) this.faction) : null; + } + + + public String getFormattedName() { + return this.getName() + ": (" + this.worldName + ", " + this.x1 + ", " + this.y1 + ", " + this.z1 + ") - (" + this.worldName + ", " + this.x2 + ", " + this.y2 + ", " + this.z2 + ')'; + } + + public Claim clone() { + return (Claim) super.clone(); + } + + public boolean equals(final Object o) { + if(this == o) { + return true; + } + if(o == null || this.getClass() != o.getClass()) { + return false; + } + final Claim blocks = (Claim) o; + if(this.loaded != blocks.loaded) { + return false; + } + Label_0110: + { + if(this.claimUniqueID != null) { + if(this.claimUniqueID.equals(blocks.claimUniqueID)) { + break Label_0110; + } + } else if(blocks.claimUniqueID == null) { + break Label_0110; + } + return false; + } + Label_0143: + { + if(this.factionUUID != null) { + if(this.factionUUID.equals(blocks.factionUUID)) { + break Label_0143; + } + } else if(blocks.factionUUID == null) { + break Label_0143; + } + return false; + } + if(this.faction != null) { + if(!this.faction.equals(blocks.faction)) { + return false; + } + } else if(blocks.faction != null) { + return false; + } + return true; + } + + public int hashCode() { + int result = 0; + result = 31 * result + ((this.claimUniqueID != null) ? this.claimUniqueID.hashCode() : 0); + result = 31 * result + ((this.factionUUID != null) ? this.factionUUID.hashCode() : 0); + result = 31 * result + ((this.faction != null) ? this.faction.hashCode() : 0); + result = 31 * result + (this.loaded ? 1 : 0); + return result; + } + + +} diff --git a/main/java/me/prestige/bases/faction/event/CaptureZoneEnterEvent.java b/main/java/me/prestige/bases/faction/event/CaptureZoneEnterEvent.java new file mode 100644 index 0000000..64a4d09 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/CaptureZoneEnterEvent.java @@ -0,0 +1,57 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Preconditions; +import me.prestige.bases.kothgame.CaptureZone; +import me.prestige.bases.kothgame.faction.CapturableFaction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class CaptureZoneEnterEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CaptureZone captureZone; + private final Player player; + private boolean cancelled; + + public CaptureZoneEnterEvent(final Player player, final CapturableFaction capturableFaction, final CaptureZone captureZone) { + super(capturableFaction); + Preconditions.checkNotNull((Object) player, (Object) "Player cannot be null"); + Preconditions.checkNotNull((Object) captureZone, (Object) "Capture zone cannot be null"); + this.captureZone = captureZone; + this.player = player; + } + + public static HandlerList getHandlerList() { + return CaptureZoneEnterEvent.handlers; + } + + @Override + public CapturableFaction getFaction() { + return (CapturableFaction) super.getFaction(); + } + + public CaptureZone getCaptureZone() { + return this.captureZone; + } + + public Player getPlayer() { + return this.player; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return CaptureZoneEnterEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/CaptureZoneLeaveEvent.java b/main/java/me/prestige/bases/faction/event/CaptureZoneLeaveEvent.java new file mode 100644 index 0000000..9d21c74 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/CaptureZoneLeaveEvent.java @@ -0,0 +1,57 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Preconditions; +import me.prestige.bases.kothgame.CaptureZone; +import me.prestige.bases.kothgame.faction.CapturableFaction; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class CaptureZoneLeaveEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CaptureZone captureZone; + private final Player player; + private boolean cancelled; + + public CaptureZoneLeaveEvent(final Player player, final CapturableFaction capturableFaction, final CaptureZone captureZone) { + super(capturableFaction); + Preconditions.checkNotNull((Object) player, (Object) "Player cannot be null"); + Preconditions.checkNotNull((Object) captureZone, (Object) "Capture zone cannot be null"); + this.captureZone = captureZone; + this.player = player; + } + + public static HandlerList getHandlerList() { + return CaptureZoneLeaveEvent.handlers; + } + + @Override + public CapturableFaction getFaction() { + return (CapturableFaction) super.getFaction(); + } + + public CaptureZone getCaptureZone() { + return this.captureZone; + } + + public Player getPlayer() { + return this.player; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return CaptureZoneLeaveEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionChatEvent.java b/main/java/me/prestige/bases/faction/event/FactionChatEvent.java new file mode 100644 index 0000000..c997eec --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionChatEvent.java @@ -0,0 +1,77 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.struct.ChatChannel; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.Collection; + +public class FactionChatEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final Player player; + private final FactionMember factionMember; + private final ChatChannel chatChannel; + private final String message; + private final Collection recipients; + private final String fallbackFormat; + private boolean cancelled; + + public FactionChatEvent(final boolean async, final PlayerFaction faction, final Player player, final ChatChannel chatChannel, final Collection recipients, final String message) { + super(faction, async); + this.player = player; + this.factionMember = faction.getMember(player.getUniqueId()); + this.chatChannel = chatChannel; + this.recipients = recipients; + this.message = message; + this.fallbackFormat = chatChannel.getRawFormat(player); + } + + public static HandlerList getHandlerList() { + return FactionChatEvent.handlers; + } + + public Player getPlayer() { + return this.player; + } + + public FactionMember getFactionMember() { + return this.factionMember; + } + + public ChatChannel getChatChannel() { + return this.chatChannel; + } + + public Collection getRecipients() { + return this.recipients; + } + + public String getMessage() { + return this.message; + } + + public String getFallbackFormat() { + return this.fallbackFormat; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return FactionChatEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionClaimChangeEvent.java b/main/java/me/prestige/bases/faction/event/FactionClaimChangeEvent.java new file mode 100644 index 0000000..0887cfb --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionClaimChangeEvent.java @@ -0,0 +1,71 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.event.cause.ClaimChangeCause; +import me.prestige.bases.faction.type.ClaimableFaction; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.Collection; + +public class FactionClaimChangeEvent extends Event implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final ClaimChangeCause cause; + private final Collection affectedClaims; + private final ClaimableFaction claimableFaction; + private final CommandSender sender; + private boolean cancelled; + + public FactionClaimChangeEvent(final CommandSender sender, final ClaimChangeCause cause, final Collection affectedClaims, final ClaimableFaction claimableFaction) { + Preconditions.checkNotNull((Object) sender, (Object) "CommandSender cannot be null"); + Preconditions.checkNotNull((Object) cause, (Object) "Cause cannot be null"); + Preconditions.checkNotNull((Object) affectedClaims, (Object) "Affected claims cannot be null"); + Preconditions.checkNotNull((Object) affectedClaims.isEmpty(), (Object) "Affected claims cannot be empty"); + Preconditions.checkNotNull((Object) claimableFaction, (Object) "ClaimableFaction cannot be null"); + this.sender = sender; + this.cause = cause; + this.affectedClaims = (Collection) ImmutableList.copyOf((Collection) affectedClaims); + this.claimableFaction = claimableFaction; + } + + public static HandlerList getHandlerList() { + return FactionClaimChangeEvent.handlers; + } + + public CommandSender getSender() { + return this.sender; + } + + public ClaimChangeCause getCause() { + return this.cause; + } + + public Collection getAffectedClaims() { + return this.affectedClaims; + } + + public ClaimableFaction getClaimableFaction() { + return this.claimableFaction; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return FactionClaimChangeEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionClaimChangedEvent.java b/main/java/me/prestige/bases/faction/event/FactionClaimChangedEvent.java new file mode 100644 index 0000000..eaa5228 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionClaimChangedEvent.java @@ -0,0 +1,47 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.event.cause.ClaimChangeCause; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.Collection; + +public class FactionClaimChangedEvent extends Event { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CommandSender sender; + private final ClaimChangeCause cause; + private final Collection affectedClaims; + + public FactionClaimChangedEvent(final CommandSender sender, final ClaimChangeCause cause, final Collection affectedClaims) { + this.sender = sender; + this.cause = cause; + this.affectedClaims = affectedClaims; + } + + public static HandlerList getHandlerList() { + return FactionClaimChangedEvent.handlers; + } + + public CommandSender getSender() { + return this.sender; + } + + public ClaimChangeCause getCause() { + return this.cause; + } + + public Collection getAffectedClaims() { + return this.affectedClaims; + } + + public HandlerList getHandlers() { + return FactionClaimChangedEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionCreateEvent.java b/main/java/me/prestige/bases/faction/event/FactionCreateEvent.java new file mode 100644 index 0000000..7e43268 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionCreateEvent.java @@ -0,0 +1,42 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.type.Faction; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class FactionCreateEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CommandSender sender; + private boolean cancelled; + + public FactionCreateEvent(final Faction faction, final CommandSender sender) { + super(faction); + this.sender = sender; + } + + public static HandlerList getHandlerList() { + return FactionCreateEvent.handlers; + } + + public CommandSender getSender() { + return this.sender; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return FactionCreateEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionDtrChangeEvent.java b/main/java/me/prestige/bases/faction/event/FactionDtrChangeEvent.java new file mode 100644 index 0000000..73d2ed1 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionDtrChangeEvent.java @@ -0,0 +1,69 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.struct.Raidable; +import me.prestige.bases.faction.type.ColorFaction; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class FactionDtrChangeEvent extends Event implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final DtrUpdateCause cause; + private final ColorFaction raidable; + private final double originalDtr; + private boolean cancelled; + private double newDtr; + + public FactionDtrChangeEvent(final DtrUpdateCause cause, final ColorFaction raidable, final double originalDtr, final double newDtr) { + this.cause = cause; + this.raidable = raidable; + this.originalDtr = originalDtr; + this.newDtr = newDtr; + } + + public static HandlerList getHandlerList() { + return FactionDtrChangeEvent.handlers; + } + + public DtrUpdateCause getCause() { + return this.cause; + } + + public ColorFaction getRaidable() { + return this.raidable; + } + + public double getOriginalDtr() { + return this.originalDtr; + } + + public double getNewDtr() { + return this.newDtr; + } + + public void setNewDtr(final double newDtr) { + this.newDtr = newDtr; + } + + public boolean isCancelled() { + return this.cancelled || Math.abs(this.newDtr - this.originalDtr) == 0.0; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return FactionDtrChangeEvent.handlers; + } + + public enum DtrUpdateCause { + REGENERATION, + MEMBER_DEATH; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionEvent.java b/main/java/me/prestige/bases/faction/event/FactionEvent.java new file mode 100644 index 0000000..161fca3 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionEvent.java @@ -0,0 +1,22 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Preconditions; +import me.prestige.bases.faction.type.Faction; +import org.bukkit.event.Event; + +public abstract class FactionEvent extends Event { + protected final Faction faction; + + public FactionEvent(final Faction faction) { + this.faction = (Faction) Preconditions.checkNotNull((Object) faction, (Object) "Faction cannot be null"); + } + + FactionEvent(final Faction faction, final boolean async) { + super(async); + this.faction = (Faction) Preconditions.checkNotNull((Object) faction, (Object) "Faction cannot be null"); + } + + public Faction getFaction() { + return this.faction; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionFocusChangeEvent.java b/main/java/me/prestige/bases/faction/event/FactionFocusChangeEvent.java new file mode 100644 index 0000000..7770078 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionFocusChangeEvent.java @@ -0,0 +1,49 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class FactionFocusChangeEvent extends Event { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final PlayerFaction senderFaction; + private final Player player; + private final UUID oldFocus; + + + public FactionFocusChangeEvent(final PlayerFaction senderFaction, Player player, UUID oldFocus) { + this.senderFaction = senderFaction; + this.player = player; + this.oldFocus = oldFocus; + } + + public UUID getOldFocus() { + return oldFocus; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public PlayerFaction getSenderFaction() { + return this.senderFaction; + } + + + public Player getPlayer() { + return this.player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionRelationCreateEvent.java b/main/java/me/prestige/bases/faction/event/FactionRelationCreateEvent.java new file mode 100644 index 0000000..7307a70 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionRelationCreateEvent.java @@ -0,0 +1,54 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.struct.Relation; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class FactionRelationCreateEvent extends Event implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final PlayerFaction senderFaction; + private final PlayerFaction targetFaction; + private final Relation relation; + private boolean cancelled; + + public FactionRelationCreateEvent(final PlayerFaction senderFaction, final PlayerFaction targetFaction, final Relation relation) { + this.senderFaction = senderFaction; + this.targetFaction = targetFaction; + this.relation = relation; + } + + public static HandlerList getHandlerList() { + return FactionRelationCreateEvent.handlers; + } + + public PlayerFaction getSenderFaction() { + return this.senderFaction; + } + + public PlayerFaction getTargetFaction() { + return this.targetFaction; + } + + public Relation getRelation() { + return this.relation; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return FactionRelationCreateEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionRelationRemoveEvent.java b/main/java/me/prestige/bases/faction/event/FactionRelationRemoveEvent.java new file mode 100644 index 0000000..71bf809 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionRelationRemoveEvent.java @@ -0,0 +1,54 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.struct.Relation; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class FactionRelationRemoveEvent extends Event implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final PlayerFaction senderFaction; + private final PlayerFaction targetFaction; + private final Relation relation; + private boolean cancelled; + + public FactionRelationRemoveEvent(final PlayerFaction senderFaction, final PlayerFaction targetFaction, final Relation relation) { + this.senderFaction = senderFaction; + this.targetFaction = targetFaction; + this.relation = relation; + } + + public static HandlerList getHandlerList() { + return FactionRelationRemoveEvent.handlers; + } + + public PlayerFaction getSenderFaction() { + return this.senderFaction; + } + + public PlayerFaction getTargetFaction() { + return this.targetFaction; + } + + public Relation getRelation() { + return this.relation; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return FactionRelationRemoveEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionRemoveEvent.java b/main/java/me/prestige/bases/faction/event/FactionRemoveEvent.java new file mode 100644 index 0000000..d6c6eb4 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionRemoveEvent.java @@ -0,0 +1,42 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.type.Faction; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class FactionRemoveEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CommandSender sender; + private boolean cancelled; + + public FactionRemoveEvent(final Faction faction, final CommandSender sender) { + super(faction); + this.sender = sender; + } + + public static HandlerList getHandlerList() { + return FactionRemoveEvent.handlers; + } + + public CommandSender getSender() { + return this.sender; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return FactionRemoveEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/FactionRenameEvent.java b/main/java/me/prestige/bases/faction/event/FactionRenameEvent.java new file mode 100644 index 0000000..7905202 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/FactionRenameEvent.java @@ -0,0 +1,60 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.type.Faction; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class FactionRenameEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final CommandSender sender; + private final String originalName; + private boolean cancelled; + private String newName; + + public FactionRenameEvent(final Faction faction, final CommandSender sender, final String originalName, final String newName) { + super(faction); + this.sender = sender; + this.originalName = originalName; + this.newName = newName; + } + + public static HandlerList getHandlerList() { + return FactionRenameEvent.handlers; + } + + public CommandSender getSender() { + return this.sender; + } + + public String getOriginalName() { + return this.originalName; + } + + public String getNewName() { + return this.newName; + } + + public void setNewName(final String newName) { + if(!newName.equals(this.newName)) { + this.newName = newName; + } + } + + public boolean isCancelled() { + return this.cancelled || this.originalName.equals(this.newName); + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return FactionRenameEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/PlayerClaimEnterEvent.java b/main/java/me/prestige/bases/faction/event/PlayerClaimEnterEvent.java new file mode 100644 index 0000000..95dbec5 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/PlayerClaimEnterEvent.java @@ -0,0 +1,78 @@ +package me.prestige.bases.faction.event; + +import me.prestige.bases.faction.type.Faction; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class PlayerClaimEnterEvent extends Event implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final Player player; + private final Faction fromFaction; + private final Faction toFaction; + private final Location from; + private final Location to; + private final EnterCause enterCause; + private boolean cancelled; + + public PlayerClaimEnterEvent(final Player player, final Location from, final Location to, final Faction fromFaction, final Faction toFaction, final EnterCause enterCause) { + this.player = player; + this.from = from; + this.to = to; + this.fromFaction = fromFaction; + this.toFaction = toFaction; + this.enterCause = enterCause; + } + + public static HandlerList getHandlerList() { + return PlayerClaimEnterEvent.handlers; + } + + public Faction getFromFaction() { + return this.fromFaction; + } + + public Faction getToFaction() { + return this.toFaction; + } + + public Player getPlayer() { + return this.player; + } + + public Location getFrom() { + return this.from; + } + + public Location getTo() { + return this.to; + } + + public EnterCause getEnterCause() { + return this.enterCause; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return PlayerClaimEnterEvent.handlers; + } + + public enum EnterCause { + TELEPORT, + MOVEMENT; + } +} diff --git a/main/java/me/prestige/bases/faction/event/PlayerJoinFactionEvent.java b/main/java/me/prestige/bases/faction/event/PlayerJoinFactionEvent.java new file mode 100644 index 0000000..d3efb03 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/PlayerJoinFactionEvent.java @@ -0,0 +1,83 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class PlayerJoinFactionEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final UUID uniqueID; + private boolean cancelled; + private Optional player; + private Optional from; + + + public PlayerJoinFactionEvent(final Player player, final PlayerFaction playerFaction, PlayerFaction faction) { + super(playerFaction); + Preconditions.checkNotNull((Object) player, (Object) "Player cannot be null"); + this.player = Optional.of(player); + this.uniqueID = player.getUniqueId(); + if(faction == null){ + Optional.absent(); + }else { + this.from = Optional.of(faction); + } + } + + public PlayerJoinFactionEvent(final UUID playerUUID, final PlayerFaction playerFaction, PlayerFaction faction) { + super(playerFaction); + Preconditions.checkNotNull((Object) playerUUID, (Object) "Player UUID cannot be null"); + this.uniqueID = playerUUID; + if(faction == null){ + Optional.absent(); + }else { + this.from = Optional.of(faction); + } + } + + public static HandlerList getHandlerList() { + return PlayerJoinFactionEvent.handlers; + } + + public Optional getPlayer() { + if(this.player == null) { + this.player = Optional.fromNullable(Bukkit.getPlayer(this.uniqueID)); + } + return this.player; + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return PlayerJoinFactionEvent.handlers; + } + + public Optional getFrom() { + return from; + } + + public void setFrom(Optional from) { + this.from = from; + } +} diff --git a/main/java/me/prestige/bases/faction/event/PlayerJoinedFactionEvent.java b/main/java/me/prestige/bases/faction/event/PlayerJoinedFactionEvent.java new file mode 100644 index 0000000..3baf138 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/PlayerJoinedFactionEvent.java @@ -0,0 +1,72 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Optional; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class PlayerJoinedFactionEvent extends FactionEvent { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final UUID uniqueID; + private Optional player; + private Optional from; + + public PlayerJoinedFactionEvent(final Player player, final PlayerFaction playerFaction) { + super(playerFaction); + this.player = Optional.of(player); + this.uniqueID = player.getUniqueId(); + } + + public PlayerJoinedFactionEvent(final Player player, final PlayerFaction playerFaction, final PlayerFaction from) { + super(playerFaction); + this.player = Optional.of(player); + this.uniqueID = player.getUniqueId(); + this.from = Optional.of(from); + } + + public PlayerJoinedFactionEvent(final UUID playerUUID, final PlayerFaction playerFaction) { + super(playerFaction); + this.uniqueID = playerUUID; + } + + public static HandlerList getHandlerList() { + return PlayerJoinedFactionEvent.handlers; + } + + @Override + public PlayerFaction getFaction() { + return (PlayerFaction)this.faction; + } + + public Optional getPlayer() { + if (this.player == null) { + this.player = Optional.fromNullable(Bukkit.getPlayer(this.uniqueID)); + } + return this.player; + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public HandlerList getHandlers() { + return PlayerJoinedFactionEvent.handlers; + } + + public Optional getFrom() { + return from; + } + + public void setFrom(PlayerFaction from) { + this.from = Optional.of(from); + } +} diff --git a/main/java/me/prestige/bases/faction/event/PlayerLeaveFactionEvent.java b/main/java/me/prestige/bases/faction/event/PlayerLeaveFactionEvent.java new file mode 100644 index 0000000..6596c2a --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/PlayerLeaveFactionEvent.java @@ -0,0 +1,75 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import me.prestige.bases.faction.event.cause.FactionLeaveCause; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class PlayerLeaveFactionEvent extends FactionEvent implements Cancellable { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final UUID uniqueID; + private final FactionLeaveCause cause; + private boolean cancelled; + private Optional player; + + public PlayerLeaveFactionEvent(final Player player, final PlayerFaction playerFaction, final FactionLeaveCause cause) { + super(playerFaction); + Preconditions.checkNotNull((Object) player, (Object) "Player cannot be null"); + Preconditions.checkNotNull((Object) playerFaction, (Object) "Player faction cannot be null"); + Preconditions.checkNotNull((Object) "Leave cause cannot be null"); + this.player = Optional.of(player); + this.uniqueID = player.getUniqueId(); + this.cause = cause; + } + + public PlayerLeaveFactionEvent(final UUID playerUUID, final PlayerFaction playerFaction, final FactionLeaveCause cause) { + super(playerFaction); + Preconditions.checkNotNull((Object) playerUUID, (Object) "Player UUID cannot be null"); + Preconditions.checkNotNull((Object) playerFaction, (Object) "Player faction cannot be null"); + Preconditions.checkNotNull((Object) "Leave cause cannot be null"); + this.uniqueID = playerUUID; + this.cause = cause; + } + + public static HandlerList getHandlerList() { + return PlayerLeaveFactionEvent.handlers; + } + + public Optional getPlayer() { + if(this.player == null) { + this.player = Optional.fromNullable(Bukkit.getPlayer(this.uniqueID)); + } + return this.player; + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public FactionLeaveCause getLeaveCause() { + return this.cause; + } + + public HandlerList getHandlers() { + return PlayerLeaveFactionEvent.handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(final boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/main/java/me/prestige/bases/faction/event/PlayerLeftFactionEvent.java b/main/java/me/prestige/bases/faction/event/PlayerLeftFactionEvent.java new file mode 100644 index 0000000..b9baa4d --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/PlayerLeftFactionEvent.java @@ -0,0 +1,63 @@ +package me.prestige.bases.faction.event; + +import com.google.common.base.Optional; +import me.prestige.bases.faction.event.cause.FactionLeaveCause; +import me.prestige.bases.faction.type.PlayerFaction; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class PlayerLeftFactionEvent extends FactionEvent { + private static final HandlerList handlers; + + static { + handlers = new HandlerList(); + } + + private final UUID uniqueID; + private final FactionLeaveCause cause; + private Optional player; + + public PlayerLeftFactionEvent(final Player player, final PlayerFaction playerFaction, final FactionLeaveCause cause) { + super(playerFaction); + this.player = Optional.of(player); + this.uniqueID = player.getUniqueId(); + this.cause = cause; + } + + public PlayerLeftFactionEvent(final UUID playerUUID, final PlayerFaction playerFaction, final FactionLeaveCause cause) { + super(playerFaction); + this.uniqueID = playerUUID; + this.cause = cause; + } + + public static HandlerList getHandlerList() { + return PlayerLeftFactionEvent.handlers; + } + + @Override + public PlayerFaction getFaction() { + return (PlayerFaction) super.getFaction(); + } + + public Optional getPlayer() { + if(this.player == null) { + this.player = Optional.fromNullable(Bukkit.getPlayer(this.uniqueID)); + } + return this.player; + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public FactionLeaveCause getCause() { + return this.cause; + } + + public HandlerList getHandlers() { + return PlayerLeftFactionEvent.handlers; + } +} diff --git a/main/java/me/prestige/bases/faction/event/cause/ClaimChangeCause.java b/main/java/me/prestige/bases/faction/event/cause/ClaimChangeCause.java new file mode 100644 index 0000000..62d048a --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/cause/ClaimChangeCause.java @@ -0,0 +1,7 @@ +package me.prestige.bases.faction.event.cause; + +public enum ClaimChangeCause { + UNCLAIM, + CLAIM, + RESIZE; +} diff --git a/main/java/me/prestige/bases/faction/event/cause/FactionLeaveCause.java b/main/java/me/prestige/bases/faction/event/cause/FactionLeaveCause.java new file mode 100644 index 0000000..8877d58 --- /dev/null +++ b/main/java/me/prestige/bases/faction/event/cause/FactionLeaveCause.java @@ -0,0 +1,7 @@ +package me.prestige.bases.faction.event.cause; + +public enum FactionLeaveCause { + KICK, + LEAVE, + DISBAND; +} diff --git a/main/java/me/prestige/bases/faction/struct/ChatChannel.java b/main/java/me/prestige/bases/faction/struct/ChatChannel.java new file mode 100644 index 0000000..d555d05 --- /dev/null +++ b/main/java/me/prestige/bases/faction/struct/ChatChannel.java @@ -0,0 +1,103 @@ +package me.prestige.bases.faction.struct; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.Locale; + +public enum ChatChannel { + FACTION("Faction"), + PUBLIC("Public"); + + private final String name; + + private ChatChannel(final String name) { + this.name = name; + } + + public static ChatChannel parse(final String id) { + return parse(id, ChatChannel.PUBLIC); + } + + public static ChatChannel parse(String id, final ChatChannel def) { + final String lowerCase; + id = (lowerCase = id.toLowerCase(Locale.ENGLISH)); + switch(lowerCase) { + case "f": + case "faction": + case "fc": + case "fac": + case "fact": { + return ChatChannel.FACTION; + } + case "p": + case "pc": + case "g": + case "gc": + case "global": + case "pub": + case "publi": + case "public": { + return ChatChannel.PUBLIC; + } + default: { + return (def == null) ? null : def.getRotation(); + } + } + } + + public String getName() { + return this.name; + } + + public String getDisplayName() { + String prefix = null; + switch(this) { + case FACTION: { + prefix = ChatColor.GREEN.toString(); + break; + } + default: { + prefix = ChatColor.RED.toString(); + break; + } + } + return prefix + this.name; + } + + public String getShortName() { + switch(this) { + case FACTION: { + return "FC"; + } + default: { + return "PC"; + } + } + } + + public ChatChannel getRotation() { + switch(this) { + case FACTION: { + return ChatChannel.PUBLIC; + } + case PUBLIC: { + return ChatChannel.FACTION; + } + default: { + return ChatChannel.PUBLIC; + } + } + } + + public String getRawFormat(final Player player) { + switch(this) { + case FACTION: { + return ChatColor.GRAY + "[" + ChatColor.LIGHT_PURPLE + "Team" + ChatColor.GRAY +"] " + ChatColor.LIGHT_PURPLE+ player.getName() + ChatColor.WHITE + " %2$s"; + } + default: { + throw new IllegalArgumentException("Cannot get the raw format for public chat channel"); + } + } + } +} diff --git a/main/java/me/prestige/bases/faction/struct/Raidable.java b/main/java/me/prestige/bases/faction/struct/Raidable.java new file mode 100644 index 0000000..78d4aec --- /dev/null +++ b/main/java/me/prestige/bases/faction/struct/Raidable.java @@ -0,0 +1,14 @@ +package me.prestige.bases.faction.struct; + +public interface Raidable { + boolean isRaidable(); + + double getDeathsUntilRaidable(); + + double getMaximumDeathsUntilRaidable(); + + double setDeathsUntilRaidable(double p0); + + + RegenStatus getRegenStatus(); +} diff --git a/main/java/me/prestige/bases/faction/struct/RegenStatus.java b/main/java/me/prestige/bases/faction/struct/RegenStatus.java new file mode 100644 index 0000000..330a6fc --- /dev/null +++ b/main/java/me/prestige/bases/faction/struct/RegenStatus.java @@ -0,0 +1,18 @@ +package me.prestige.bases.faction.struct; + +import org.bukkit.ChatColor; + +public enum RegenStatus { + FULL(ChatColor.GREEN.toString() + '\u25b6'), + REGENERATING(ChatColor.GOLD.toString() + '\u25B2'), + PAUSED(ChatColor.RED.toString() + '\u25a0'); + private final String symbol; + + private RegenStatus(final String symbol) { + this.symbol = symbol; + } + + public String getSymbol() { + return this.symbol; + } +} diff --git a/main/java/me/prestige/bases/faction/struct/Relation.java b/main/java/me/prestige/bases/faction/struct/Relation.java new file mode 100644 index 0000000..85ae860 --- /dev/null +++ b/main/java/me/prestige/bases/faction/struct/Relation.java @@ -0,0 +1,60 @@ +package me.prestige.bases.faction.struct; + +import com.customhcf.util.BukkitUtils; +import org.bukkit.ChatColor; +import org.bukkit.DyeColor; + +public enum Relation { + MEMBER(3), + ENEMY(1); + + private final int value; + + private Relation(final int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public boolean isAtLeast(final Relation relation) { + return this.value >= relation.value; + } + + public boolean isAtMost(final Relation relation) { + return this.value <= relation.value; + } + + public boolean isMember() { + return this == Relation.MEMBER; + } + + + public boolean isEnemy() { + return this == Relation.ENEMY; + } + + public String getDisplayName() { + switch(this) { + default: { + return this.toChatColour() + this.name().toLowerCase(); + } + } + } + + public ChatColor toChatColour() { + switch(this) { + case MEMBER: { + return ChatColor.GREEN; + } + default: { + return ChatColor.DARK_AQUA; + } + } + } + + public DyeColor toDyeColour() { + return BukkitUtils.toDyeColor(this.toChatColour()); + } +} diff --git a/main/java/me/prestige/bases/faction/struct/Role.java b/main/java/me/prestige/bases/faction/struct/Role.java new file mode 100644 index 0000000..50d08ff --- /dev/null +++ b/main/java/me/prestige/bases/faction/struct/Role.java @@ -0,0 +1,21 @@ +package me.prestige.bases.faction.struct; + +public enum Role { + MEMBER("Member", ""); + + private final String name; + private final String astrix; + + Role(final String name, final String astrix) { + this.name = name; + this.astrix = astrix; + } + + public String getName() { + return this.name; + } + + public String getAstrix() { + return this.astrix; + } +} diff --git a/main/java/me/prestige/bases/faction/type/ClaimableFaction.java b/main/java/me/prestige/bases/faction/type/ClaimableFaction.java new file mode 100644 index 0000000..80153e2 --- /dev/null +++ b/main/java/me/prestige/bases/faction/type/ClaimableFaction.java @@ -0,0 +1,93 @@ +package me.prestige.bases.faction.type; + +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.GenericUtils; +import com.customhcf.util.cuboid.Cuboid; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.claim.Claim; +import me.prestige.bases.faction.event.FactionClaimChangeEvent; +import me.prestige.bases.faction.event.FactionClaimChangedEvent; +import me.prestige.bases.faction.event.cause.ClaimChangeCause; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; + +import java.util.*; + +public class ClaimableFaction extends Faction { + protected static final ImmutableMap ENVIRONMENT_MAPPINGS = Maps.immutableEnumMap(ImmutableMap.of(World.Environment.NETHER, "Nether", World.Environment.NORMAL, "Overworld", World.Environment.THE_END, "The End")); + + + protected final Set claims; + + public ClaimableFaction(final String name) { + super(name); + this.claims = new HashSet<>(); + } + + public ClaimableFaction(final Map map) { + super(map); + (this.claims = new HashSet<>()).addAll(GenericUtils.createList(map.get("claims"), Claim.class)); + } + + @Override + public Map serialize() { + final Map map = super.serialize(); + map.put("claims", new ArrayList(claims)); + return map; + } + + @Override + public void printDetails(final CommandSender sender) { + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + sender.sendMessage(this.getDisplayName(sender)); + for(final Claim claim : this.claims) { + final Location location = claim.getCenter(); + sender.sendMessage(ChatColor.YELLOW + " Location: " + ChatColor.WHITE.toString() + ClaimableFaction.ENVIRONMENT_MAPPINGS.get( location.getWorld().getEnvironment()) + ", " + location.getBlockX() + " | " + location.getBlockZ()); + } + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + } + + public Set getClaims() { + return this.claims; + } + + public boolean addClaim(final Claim claim, final CommandSender sender) { + return this.addClaims(Collections.singleton(claim), sender); + } + + public void setClaim(final Cuboid cuboid, final CommandSender sender) { + this.removeClaims(this.getClaims(), sender); + final Location min = cuboid.getMinimumPoint(); + min.setY(0); + final Location max = cuboid.getMaximumPoint(); + max.setY(256); + addClaim(new Claim(this, min, max), sender); + } + + public boolean addClaims(final Collection adding, CommandSender sender) { + if(sender == null) { + sender = Bukkit.getConsoleSender(); + } + final FactionClaimChangeEvent event = new FactionClaimChangeEvent(sender, ClaimChangeCause.CLAIM, adding, this); + Bukkit.getPluginManager().callEvent(event); + if(event.isCancelled() || !this.claims.addAll(adding)) { + return false; + } + Bukkit.getPluginManager().callEvent( new FactionClaimChangedEvent(sender, ClaimChangeCause.CLAIM, adding)); + return true; + } + + public boolean removeClaim(final Claim claim, final CommandSender sender) { + return this.removeClaims(Collections.singleton(claim), sender); + } + + public boolean removeClaims(final Collection removing, CommandSender sender) { + Bukkit.getPluginManager().callEvent( new FactionClaimChangedEvent(sender, ClaimChangeCause.UNCLAIM, removing)); + return true; + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/faction/type/ColorFaction.java b/main/java/me/prestige/bases/faction/type/ColorFaction.java new file mode 100644 index 0000000..0c30862 --- /dev/null +++ b/main/java/me/prestige/bases/faction/type/ColorFaction.java @@ -0,0 +1,439 @@ +package me.prestige.bases.faction.type; + +import com.customhcf.util.PersistableLocation; +import jdk.nashorn.internal.objects.annotations.Getter; +import jdk.nashorn.internal.objects.annotations.Setter; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class ColorFaction extends PlayerFaction implements ConfigurationSerializable { + + + public ColorFaction(String name) { + super(name); + } + + public ColorFaction(final Map map) { + super(map); + } + + + + + public static class GreenFaction extends ColorFaction implements ConfigurationSerializable{ + + private boolean hasVillager; + + public GreenFaction() { + super("Green"); + members.clear(); + deathsUntilRaidable = 5; + hasVillager = false; + } + + + private PersistableLocation buyVillager; + private PersistableLocation sellVillager; + private PersistableLocation enchantVillager; + private PersistableLocation blockVillager; + + public GreenFaction(final Map map) { + super(map); + buyVillager = (PersistableLocation) map.get("buyVillager"); + sellVillager = (PersistableLocation) map.get("sellVillager"); + enchantVillager = (PersistableLocation) map.get("enchantVillager"); + blockVillager = (PersistableLocation) map.get("blockVillager"); + + } + + public Map serialize() { + Map map = super.serialize(); + map.put("buyVillager", buyVillager); + map.put("sellVillager", sellVillager); + map.put("enchantVillager", enchantVillager); + map.put("blockVillager", blockVillager); + return map; + } + + public void setBuyVillager(PersistableLocation buyVillager) { + this.buyVillager = buyVillager; + } + + public void setSellVillager(PersistableLocation sellVillager) { + this.sellVillager = sellVillager; + } + + public void setEnchantVillager(PersistableLocation enchantVillager) { + this.enchantVillager = enchantVillager; + } + + public void setBlockVillager(PersistableLocation blockVillager) { + this.blockVillager = blockVillager; + } + + public Location getBuyVillager() { + return buyVillager.getLocation(); + } + + public Location getSellVillager() { + return sellVillager.getLocation(); + } + + public Location getEnchantVillager() { + return enchantVillager.getLocation(); + } + + public Location getBlockVillager() { + return blockVillager.getLocation(); + } + + + @Override + public String getDisplayName(CommandSender sender) { + return ChatColor.GREEN + "Green"; + } + + @Override + public String getDisplayName(Faction other) { + return ChatColor.GREEN + "Green"; + } + + @Override + public ChatColor getColor() { + return ChatColor.GREEN; + } + + @Getter + public boolean isHasVillager() { + return hasVillager; + } + @Setter + public void setHasVillager(boolean hasVillager) { + this.hasVillager = hasVillager; + } + } + + + public static class YellowFaction extends ColorFaction implements ConfigurationSerializable { + + private boolean hasVillager; + + + public YellowFaction() { + super("Yellow"); + members.clear(); + deathsUntilRaidable = 5; + } + + private PersistableLocation buyVillager; + private PersistableLocation sellVillager; + private PersistableLocation enchantVillager; + private PersistableLocation blockVillager; + + public YellowFaction(final Map map) { + super(map); + buyVillager = (PersistableLocation) map.get("buyVillager"); + sellVillager = (PersistableLocation) map.get("sellVillager"); + enchantVillager = (PersistableLocation) map.get("enchantVillager"); + blockVillager = (PersistableLocation) map.get("blockVillager"); + + } + + public Map serialize() { + Map map = super.serialize(); + map.put("buyVillager", buyVillager); + map.put("sellVillager", sellVillager); + map.put("enchantVillager", enchantVillager); + map.put("blockVillager", blockVillager); + return map; + } + + public void setBuyVillager(PersistableLocation buyVillager) { + this.buyVillager = buyVillager; + } + + public void setSellVillager(PersistableLocation sellVillager) { + this.sellVillager = sellVillager; + } + + public void setEnchantVillager(PersistableLocation enchantVillager) { + this.enchantVillager = enchantVillager; + } + + public void setBlockVillager(PersistableLocation blockVillager) { + this.blockVillager = blockVillager; + } + + public Location getBuyVillager() { + return buyVillager.getLocation(); + } + + public Location getSellVillager() { + return sellVillager.getLocation(); + } + + public Location getEnchantVillager() { + return enchantVillager.getLocation(); + } + + public Location getBlockVillager() { + return blockVillager.getLocation(); + } + @Override + public String getDisplayName(CommandSender sender) { + return ChatColor.YELLOW + "Yellow"; + } + + @Override + public ChatColor getColor() { + return ChatColor.YELLOW; + } + + @Override + public String getDisplayName(Faction other) { + return ChatColor.YELLOW + "Yellow"; + } + + @Getter + public boolean isHasVillager() { + return hasVillager; + } + @Setter + public void setHasVillager(boolean hasVillager) { + this.hasVillager = hasVillager; + } + + } + public static class BlueFaction extends ColorFaction implements ConfigurationSerializable{ + + private boolean hasVillager; + + + public BlueFaction() { + super("Blue"); + members.clear(); + deathsUntilRaidable = 5; + } + + private PersistableLocation buyVillager; + private PersistableLocation sellVillager; + private PersistableLocation enchantVillager; + private PersistableLocation blockVillager; + + public BlueFaction(final Map map) { + super(map); + buyVillager = (PersistableLocation) map.get("buyVillager"); + sellVillager = (PersistableLocation) map.get("sellVillager"); + enchantVillager = (PersistableLocation) map.get("enchantVillager"); + blockVillager = (PersistableLocation) map.get("blockVillager"); + + } + + public Map serialize() { + Map map = super.serialize(); + map.put("buyVillager", buyVillager); + map.put("sellVillager", sellVillager); + map.put("enchantVillager", enchantVillager); + map.put("blockVillager", blockVillager); + return map; + } + + @Override + public ChatColor getColor() { + return ChatColor.BLUE; + } + + public void setBuyVillager(PersistableLocation buyVillager) { + this.buyVillager = buyVillager; + } + + public void setSellVillager(PersistableLocation sellVillager) { + this.sellVillager = sellVillager; + } + + public void setEnchantVillager(PersistableLocation enchantVillager) { + this.enchantVillager = enchantVillager; + } + + public void setBlockVillager(PersistableLocation blockVillager) { + this.blockVillager = blockVillager; + } + + public Location getBuyVillager() { + return buyVillager.getLocation(); + } + + public Location getSellVillager() { + return sellVillager.getLocation(); + } + + public Location getEnchantVillager() { + return enchantVillager.getLocation(); + } + + public Location getBlockVillager() { + return blockVillager.getLocation(); + } + + @Override + public String getDisplayName(CommandSender sender) { + return ChatColor.BLUE + "Blue"; + } + + @Override + public String getDisplayName(Faction other) { + return ChatColor.BLUE + "Blue"; + } + + @Getter + public boolean isHasVillager() { + return hasVillager; + } + @Setter + public void setHasVillager(boolean hasVillager) { + this.hasVillager = hasVillager; + } + } + public static class RedFaction extends ColorFaction implements ConfigurationSerializable{ + + private boolean hasVillager; + + + public RedFaction() { + super("Red"); + members.clear(); + deathsUntilRaidable = 5; + } + + private PersistableLocation buyVillager; + private PersistableLocation sellVillager; + private PersistableLocation enchantVillager; + private PersistableLocation blockVillager; + + public RedFaction(final Map map) { + super(map); + buyVillager = (PersistableLocation) map.get("buyVillager"); + sellVillager = (PersistableLocation) map.get("sellVillager"); + enchantVillager = (PersistableLocation) map.get("enchantVillager"); + blockVillager = (PersistableLocation) map.get("blockVillager"); + + } + + public Map serialize() { + Map map = super.serialize(); + map.put("buyVillager", buyVillager); + map.put("sellVillager", sellVillager); + map.put("enchantVillager", enchantVillager); + map.put("blockVillager", blockVillager); + return map; + } + + @Override + public ChatColor getColor() { + return ChatColor.RED; + } + + public void setBuyVillager(PersistableLocation buyVillager) { + this.buyVillager = buyVillager; + } + + public void setSellVillager(PersistableLocation sellVillager) { + this.sellVillager = sellVillager; + } + + public void setEnchantVillager(PersistableLocation enchantVillager) { + this.enchantVillager = enchantVillager; + } + + public void setBlockVillager(PersistableLocation blockVillager) { + this.blockVillager = blockVillager; + } + + public Location getBuyVillager() { + return buyVillager.getLocation(); + } + + public Location getSellVillager() { + return sellVillager.getLocation(); + } + + public Location getEnchantVillager() { + return enchantVillager.getLocation(); + } + + public Location getBlockVillager() { + return blockVillager.getLocation(); + } + + @Override + public String getDisplayName(CommandSender sender) { + return ChatColor.RED + "Red"; + } + + @Override + public String getDisplayName(Faction other) { + return ChatColor.RED + "Red"; + } + + @Getter + public boolean isHasVillager() { + return hasVillager; + } + @Setter + public void setHasVillager(boolean hasVillager) { + this.hasVillager = hasVillager; + } + } + + public ChatColor getColor(){ + return null; + } + + public void setBuyVillager(PersistableLocation buyVillager) { + } + + public void setSellVillager(PersistableLocation sellVillager) { + } + + public void setEnchantVillager(PersistableLocation enchantVillager) { + } + + public void setBlockVillager(PersistableLocation blockVillager) { + } + + public Location getBuyVillager() { + return null; + } + + public Location getSellVillager() { + return null; + } + + public Location getEnchantVillager() { + return null; + } + + public Location getBlockVillager() { + return null; + } + + public boolean isHasVillager() { + return true; + } + public void setHasVillager(boolean hasVillager) { + + } + + + + + + + +} diff --git a/main/java/me/prestige/bases/faction/type/Faction.java b/main/java/me/prestige/bases/faction/type/Faction.java new file mode 100644 index 0000000..64ba917 --- /dev/null +++ b/main/java/me/prestige/bases/faction/type/Faction.java @@ -0,0 +1,217 @@ +package me.prestige.bases.faction.type; + +import com.customhcf.util.BukkitUtils; +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.event.FactionRenameEvent; +import me.prestige.bases.faction.struct.Relation; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.Listener; + +import java.util.Map; +import java.util.UUID; + +public abstract class Faction implements ConfigurationSerializable, Listener { + protected final UUID uniqueID; + public long lastRenameMillis; + protected String name; + protected boolean needSave; + protected long creationMillis; + protected double dtrLossMultiplier = 1; + protected double deathbanMultiplier = 1; + protected boolean safezone; + protected boolean loading; + protected boolean locked; + + + public Faction(String name) { + this.uniqueID = UUID.randomUUID(); + this.name = name; + this.needSave = false; + loading = false; + } + + public Faction(Map map) { + this.uniqueID = UUID.fromString((String) map.get("uniqueID")); + this.name = (String) map.get("name"); + this.creationMillis = Long.parseLong((String) map.get("creationMillis")); + this.lastRenameMillis = Long.parseLong((String) map.get("lastRenameMillis")); + this.deathbanMultiplier = ((Double) map.get("deathbanMultiplier")).doubleValue(); + this.safezone = ((Boolean) map.get("safezone")).booleanValue(); + } + + public Map serialize() { + final Map map = Maps.newLinkedHashMap(); + map.put("uniqueID", this.uniqueID.toString()); + map.put("name", this.name); + map.put("creationMillis", Long.toString(this.creationMillis)); + map.put("lastRenameMillis", Long.toString(this.lastRenameMillis)); + map.put("deathbanMultiplier", this.deathbanMultiplier); + map.put("safezone", this.safezone); + return map; + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public String getName() { + return this.name; + } + + public boolean setName(final String name) { + return this.setName(name, (CommandSender) Bukkit.getConsoleSender()); + } + + public boolean setName(final String name, final CommandSender sender) { + if(this.name.equals(name)) { + return false; + } + final FactionRenameEvent event = new FactionRenameEvent(this, sender, this.name, name); + Bukkit.getPluginManager().callEvent((Event) event); + if(event.isCancelled()) { + return false; + } + this.lastRenameMillis = System.currentTimeMillis(); + this.name = name; + return true; + } + + public Relation getFactionRelation(final Faction faction) { + if(faction == null) { + return Relation.ENEMY; + } + if(faction instanceof PlayerFaction) { + final PlayerFaction playerFaction = (PlayerFaction) faction; + if(playerFaction.equals(this)) { + return Relation.MEMBER; + } + } + return Relation.ENEMY; + } + + public Relation getRelation(final CommandSender sender) { + if(!(sender instanceof Player)) { + return Relation.ENEMY; + } + final Player player = (Player) sender; + return this.getFactionRelation(Bases.getPlugin().getFactionManager().getPlayerFaction(player.getUniqueId())); + } + + public String getDisplayName(final CommandSender sender) { + return (ChatColor.DARK_PURPLE) + this.name; + } + + public String getDisplayName(final Faction other) { + return this.getFactionRelation(other).toChatColour() + this.name; + } + + public void printDetails(final CommandSender sender) { + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + sender.sendMessage(' ' + this.getDisplayName(sender)); + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + } + + public boolean isDeathban() { + return !this.safezone && this.deathbanMultiplier > 0.0; + } + + public void setDeathban(final boolean deathban) { + if(deathban != this.isDeathban()) { + this.deathbanMultiplier = (deathban ? 1.0 : 0.0); + } + } + + public double getDeathbanMultiplier() { + return this.deathbanMultiplier; + } + + public void setDeathbanMultiplier(final double deathbanMultiplier) { + Preconditions.checkArgument(deathbanMultiplier >= 0.0, (Object) "Deathban multiplier may not be negative"); + this.deathbanMultiplier = deathbanMultiplier; + } + + public double getDtrLossMultiplier() { + return this.dtrLossMultiplier; + } + + public void setDtrLossMultiplier(final double dtrLossMultiplier) { + this.dtrLossMultiplier = dtrLossMultiplier; + } + + public void setLocked(boolean locked) {this.locked = locked; } + + public boolean isLocked(){ return this.locked; } + + public boolean isSafezone() { + return this.safezone; + } + + @Override + public boolean equals(final Object o) { + if(this == o) { + return true; + } + if(!(o instanceof Faction)) { + return false; + } + final Faction faction = (Faction) o; + if(this.creationMillis != faction.creationMillis) { + return false; + } + if(this.lastRenameMillis != faction.lastRenameMillis) { + return false; + } + if(Double.compare(faction.dtrLossMultiplier, this.dtrLossMultiplier) != 0) { + return false; + } + if(Double.compare(faction.deathbanMultiplier, this.deathbanMultiplier) != 0) { + return false; + } + if(this.safezone != faction.safezone) { + return false; + } + Label_0127: + { + if(this.uniqueID != null) { + if(this.uniqueID.equals(faction.uniqueID)) { + break Label_0127; + } + } else if(faction.uniqueID == null) { + break Label_0127; + } + return false; + } + if(this.name != null) { + if(!this.name.equals(faction.name)) { + return false; + } + } else if(faction.name != null) { + return false; + } + return true; + + } + + @Override + public int hashCode() { + int result = (this.uniqueID != null) ? this.uniqueID.hashCode() : 0; + result = 31 * result + ((this.name != null) ? this.name.hashCode() : 0); + result = 31 * result + (int) (this.creationMillis ^ this.creationMillis >>> 32); + result = 31 * result + (int) (this.lastRenameMillis ^ this.lastRenameMillis >>> 32); + long temp = Double.doubleToLongBits(this.dtrLossMultiplier); + result = 31 * result + (int) (temp ^ temp >>> 32); + temp = Double.doubleToLongBits(this.deathbanMultiplier); + result = 31 * result + (int) (temp ^ temp >>> 32); + result = 31 * result + (this.safezone ? 1 : 0); + return result; + } + + +} diff --git a/main/java/me/prestige/bases/faction/type/PlayerFaction.java b/main/java/me/prestige/bases/faction/type/PlayerFaction.java new file mode 100644 index 0000000..abfdf38 --- /dev/null +++ b/main/java/me/prestige/bases/faction/type/PlayerFaction.java @@ -0,0 +1,332 @@ +package me.prestige.bases.faction.type; + +import com.customhcf.util.BukkitUtils; +import com.customhcf.util.GenericUtils; +import com.customhcf.util.JavaUtils; +import com.customhcf.util.PersistableLocation; +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.google.common.primitives.Doubles; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.event.FactionDtrChangeEvent; +import me.prestige.bases.faction.event.PlayerJoinedFactionEvent; +import me.prestige.bases.faction.event.PlayerLeaveFactionEvent; +import me.prestige.bases.faction.event.PlayerLeftFactionEvent; +import me.prestige.bases.faction.event.cause.FactionLeaveCause; +import me.prestige.bases.faction.struct.Raidable; +import me.prestige.bases.faction.struct.RegenStatus; +import me.prestige.bases.faction.struct.Relation; +import me.prestige.bases.faction.struct.Role; +import me.prestige.bases.listener.DeathListener; +import me.prestige.bases.timer.type.TeleportTimer; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import javax.annotation.Nullable; +import java.util.*; + +public class PlayerFaction extends ClaimableFaction implements Raidable { + private static final UUID[] EMPTY_UUID_ARRAY; + + static { + EMPTY_UUID_ARRAY = new UUID[0]; + } + + protected final Map members = new HashMap(); + protected UUID focus; + protected PersistableLocation home; + protected double deathsUntilRaidable; + + public PlayerFaction(final String name) { + super(name); + this.deathsUntilRaidable = 5.0D; + } + + public PlayerFaction(Map map) { + super(map); + this.deathsUntilRaidable = 5.0D; + Object object1 = map.get("home"); + if(object1 != null) { + this.home = (PersistableLocation) object1; + } + } + + public Map serialize() { + Map map = super.serialize(); + if(this.home != null) { + map.put("home", this.home); + } + return map; + } + + + public boolean setMember(final UUID playerUUID, final FactionMember factionMember) { + return this.setMember(null, playerUUID, factionMember, false); + } + + public boolean setMember(final UUID playerUUID, final FactionMember factionMember, final boolean force) { + return this.setMember(null, playerUUID, factionMember, force); + } + + public boolean setMember(final Player player, final FactionMember factionMember) { + return this.setMember(player, player.getUniqueId(), factionMember, false); + } + + public boolean setMember(final Player player, final FactionMember factionMember, final boolean force) { + return this.setMember(player, player.getUniqueId(), factionMember, force); + } + + private boolean setMember( final Player player, final UUID playerUUID, final FactionMember factionMember, final boolean force) { + + if(factionMember == null) { + if(!force) { + final PlayerLeaveFactionEvent event = (player == null) ? new PlayerLeaveFactionEvent(playerUUID, this, FactionLeaveCause.LEAVE) : new PlayerLeaveFactionEvent(player, this, FactionLeaveCause.LEAVE); + Bukkit.getPluginManager().callEvent( event); + if(event.isCancelled()) { + return false; + } + } + this.members.remove(playerUUID); + final PlayerLeftFactionEvent event2 = (player == null) ? new PlayerLeftFactionEvent(playerUUID, this, FactionLeaveCause.LEAVE) : new PlayerLeftFactionEvent(player, this, FactionLeaveCause.LEAVE); + Bukkit.getPluginManager().callEvent(event2); + return true; + } + if(members.size() >= 5){ + player.sendMessage(ChatColor.RED + "Team Full!"); + return false; + } + this.members.put(playerUUID, factionMember); + final PlayerJoinedFactionEvent eventPre = (player == null) ? new PlayerJoinedFactionEvent(playerUUID, this) : new PlayerJoinedFactionEvent(player, this); + Bukkit.getPluginManager().callEvent(eventPre); + return true; + } + + + + + + + + public Map getMembers() { + return ImmutableMap.copyOf(members); + } + + public Set getOnlinePlayers() { + return getOnlinePlayers(null); + } + + public Set getOnlinePlayers(CommandSender sender) { + Set entrySet = this.getOnlineMembers(sender).entrySet(); + HashSet results = new HashSet(entrySet.size()); + Iterator var4 = entrySet.iterator(); + + while(var4.hasNext()) { + Map.Entry entry = (Map.Entry) var4.next(); + results.add(Bukkit.getPlayer((UUID) entry.getKey())); + } + + return results; + } + + public Map getOnlineMembers() { + return this.getOnlineMembers(null); + } + + public Map getOnlineMembers(CommandSender sender) { + Player senderPlayer = sender instanceof Player ? (Player)sender : null; + HashMap results = new HashMap(); + Iterator> iterator = this.members.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + Player target = Bukkit.getPlayer((UUID)entry.getKey()); + if (target == null) continue; + if (senderPlayer != null && !senderPlayer.canSee(target)) continue; + results.put(entry.getKey(), entry.getValue()); + } + return results; + } + + + @Deprecated + public FactionMember getMember(String memberName) { + UUID uuid = Bukkit.getOfflinePlayer(memberName).getUniqueId(); + if (uuid == null) { + return null; + } + FactionMember factionMember = (FactionMember) this.members.get(uuid); + return factionMember; + } + + public FactionMember getMember(Player player) { + return this.getMember(player.getUniqueId()); + } + + public FactionMember getMember(UUID memberUUID) { + return (FactionMember) this.members.get(memberUUID); + } + + + public Location getHome() { + return (this.home == null) ? null : this.home.getLocation(); + } + + public void setHome( Location home) { + if(home == null && this.home != null) { + TeleportTimer timer = Bases.getPlugin().getTimerManager().teleportTimer; + Iterator var3 = this.getOnlinePlayers().iterator(); + + while(var3.hasNext()) { + Player player = (Player) var3.next(); + Location destination = (Location) timer.getDestination(player); + if(Objects.equal(destination, this.home.getLocation())) { + timer.clearCooldown(player); + player.sendMessage(ChatColor.RED + "Your home was unset, so your " + timer.getDisplayName() + ChatColor.RED + " timer has been cancelled"); + } + } + } + + this.home = home == null ? null : new PersistableLocation(home); + } + + + @Override + public boolean isRaidable() { + return this.deathsUntilRaidable <= 0.0; + } + + @Override + public double getDeathsUntilRaidable() { + return deathsUntilRaidable; + } + + @Override + public double getMaximumDeathsUntilRaidable() { + return 5; + } + + + + public ChatColor getDtrColour() { + if(this.deathsUntilRaidable < 0.0) { + return ChatColor.RED; + } + if(this.deathsUntilRaidable < 3.0) { + return ChatColor.YELLOW; + } + return ChatColor.GREEN; + } + + + @Override + public double setDeathsUntilRaidable(final double deathsUntilRaidable) { + return this.setDeathsUntilRaidable(deathsUntilRaidable, true); + } + + private double setDeathsUntilRaidable(double deathsUntilRaidable, final boolean limit) { + deathsUntilRaidable = deathsUntilRaidable * 100.0 / 100.0; + if(limit) { + deathsUntilRaidable = Math.min(deathsUntilRaidable, this.getMaximumDeathsUntilRaidable()); + } + if(deathsUntilRaidable - this.deathsUntilRaidable != 0.0) { + final FactionDtrChangeEvent event = new FactionDtrChangeEvent(FactionDtrChangeEvent.DtrUpdateCause.REGENERATION, Bases.getPlugin().getFactionManager().getColorFaction(this.getName()), this.deathsUntilRaidable, deathsUntilRaidable); + Bukkit.getPluginManager().callEvent(event); + if(!event.isCancelled()) { + deathsUntilRaidable = event.getNewDtr(); + if(deathsUntilRaidable > 0.0 && deathsUntilRaidable <= 0.0) { + Bases.getPlugin().getLogger().info("Faction " + this.getName() + " is now raidable."); + } + return this.deathsUntilRaidable = deathsUntilRaidable; + } + } + return this.deathsUntilRaidable; + } + + @Override + public RegenStatus getRegenStatus() { + return RegenStatus.FULL; + } + + + public void printDetails(CommandSender sender) { + PlayerFaction playerFaction; + HashSet memberNames = new HashSet(); + Iterator playerFaction1 = this.members.entrySet().iterator(); + while(playerFaction1.hasNext()) { + final Map.Entry entry = (Map.Entry) playerFaction1.next(); + final FactionMember factionMember = (FactionMember) entry.getValue(); + final Player target = factionMember.toOnlinePlayer(); + ChatColor colour; + if (DeathListener.spectators.containsKey(factionMember.getUniqueId())) { + colour = ChatColor.RED; + }else + if (target == null || (sender instanceof Player && !((Player)sender).canSee(target))) { + colour = ChatColor.GRAY; + } + else { + colour = ChatColor.GREEN; + } + final String memberName = colour + factionMember.getName() + ChatColor.GRAY + '[' + ChatColor.GREEN + Bases.getPlugin().getUserManager().getUser(factionMember.getUniqueId()).getKills() +ChatColor.GRAY + ']'; + switch (factionMember.getRole()) { + case MEMBER: { + memberNames.add(memberName); + } + } + } + + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + sender.sendMessage(ChatColor.GOLD + this.getDisplayName(sender)+ ChatColor.GRAY+" ["+this.getOnlineMembers().size()+"/"+this.getMembers().size()+"] "+ ChatColor.GREEN + " - " + ChatColor.YELLOW + "Home: " + ChatColor.WHITE + (this.home == null ? "None" : ChatColor.WHITE.toString() + this.home.getLocation().getBlockX() + " | " + this.home.getLocation().getBlockZ())); + + if(!memberNames.isEmpty()) { + sender.sendMessage(ChatColor.YELLOW + "Members: " + ChatColor.RED + StringUtils.join(memberNames, ChatColor.GRAY + ", ")); + } + + + + sender.sendMessage(ChatColor.YELLOW + "Deaths until Raidable: "+ this.getRegenStatus().getSymbol() + this.getDtrColour() + JavaUtils.format(getDeathsUntilRaidable())); + sender.sendMessage(ChatColor.GRAY + BukkitUtils.STRAIGHT_LINE_DEFAULT); + } + + public UUID getFocus() { + return focus; + } + + public void setFocus(UUID uuid){ + this.focus = uuid; + } + + public void broadcast(final String message) { + this.broadcast(message, PlayerFaction.EMPTY_UUID_ARRAY); + } + + public void broadcast(final String[] messages) { + this.broadcast(messages, PlayerFaction.EMPTY_UUID_ARRAY); + } + + public void broadcast(final String message, @Nullable final UUID... ignore) { + this.broadcast(new String[]{message}, ignore); + } + + public void broadcast(final String[] messages, final UUID... ignore) { + Preconditions.checkNotNull((Object) messages, "Messages cannot be null"); + Preconditions.checkArgument(messages.length > 0, "Message array cannot be empty"); + final Collection players = this.getOnlinePlayers(); + final Collection ignores = ((ignore.length == 0) ? Collections.emptySet() : Sets.newHashSet(ignore)); + for(final Player player : players) { + if(!ignores.contains(player.getUniqueId())) { + player.sendMessage(messages); + } + } + } + + + +} diff --git a/main/java/me/prestige/bases/faction/type/WarzoneFaction.java b/main/java/me/prestige/bases/faction/type/WarzoneFaction.java new file mode 100644 index 0000000..809f042 --- /dev/null +++ b/main/java/me/prestige/bases/faction/type/WarzoneFaction.java @@ -0,0 +1,21 @@ +package me.prestige.bases.faction.type; + +import net.md_5.bungee.api.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Map; + +public class WarzoneFaction extends Faction { + public WarzoneFaction() { + super("Warzone"); + } + + public WarzoneFaction(final Map map) { + super(map); + } + + @Override + public String getDisplayName(final CommandSender sender) { + return ChatColor.GRAY + this.getName(); + } +} diff --git a/main/java/me/prestige/bases/game/GameManager.java b/main/java/me/prestige/bases/game/GameManager.java new file mode 100644 index 0000000..cc99d17 --- /dev/null +++ b/main/java/me/prestige/bases/game/GameManager.java @@ -0,0 +1,278 @@ +package me.prestige.bases.game; + +import com.customhcf.util.ItemBuilder; +import com.google.common.base.Preconditions; +import com.sk89q.worldedit.EmptyClipboardException; +import com.sk89q.worldedit.FilenameException; +import com.sk89q.worldedit.MaxChangedBlocksException; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldedit.data.DataException; +import me.prestige.bases.Bases; +import me.prestige.bases.KothStartTimer; +import me.prestige.bases.economy.EconomyListener; +import me.prestige.bases.faction.FactionMember; +import me.prestige.bases.faction.type.ColorFaction; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.listener.WorldListener; +import me.prestige.bases.nms.Villager; +import me.prestige.bases.user.FactionUser; +import net.md_5.bungee.api.ChatColor; +import net.minecraft.server.v1_7_R4.Village; +import net.minecraft.server.v1_7_R4.WorldServer; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.v1_7_R4.CraftWorld; +import org.bukkit.craftbukkit.v1_7_R4.entity.CraftLivingEntity; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import javax.persistence.EntityManager; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.TimeUnit; + +public class GameManager { + + private Bases plugin; + private GameState gameState; + private long gameStartTimeStamp; + private Set deadFactions = new HashSet<>(); + + public GameManager(Bases plugin) { + this.plugin = plugin; + gameState = GameState.WAITING; + if (!Bases.getPlugin().getConfig().getBoolean("setup")) { + loadArena(); + } + } + + public void end(ColorFaction colorFaction) { + if (!gameState.equals(GameState.STARTING)) { + return; + } + + gameStartTimeStamp = 0; + gameState = GameState.ENDING; + String winner; + if (colorFaction == null) { + winner = "nobody " + ChatColor.RED + "[Forced End]"; + } else { + winner = colorFaction.getDisplayName(Bukkit.getConsoleSender()); + } + for (Player on : Bukkit.getOnlinePlayers()) { + on.kickPlayer(ChatColor.YELLOW + "The winner is " + winner); + } + for (World world : Bukkit.getWorlds()) { + for (Entity entity : world.getEntities()) { + if (entity.getType() == EntityType.PLAYER) continue; + entity.remove(); + } + } + + } + + + public void startGame() { + this.gameStartTimeStamp = System.currentTimeMillis(); + gameState = GameState.STARTING; + plugin.deleteRedis(); + new KothStartTimer().runTaskLater(plugin, 3 * 60 * 20); + for(FactionUser user : plugin.getUserManager().getUsers().values()){ + user.setKills(0); + user.setDeaths(0); + } + for (Faction colorFaction : plugin.getFactionManager().getFactions()) { + if (colorFaction instanceof ColorFaction) { + for (Player on : ((ColorFaction) colorFaction).getOnlinePlayers()) { + plugin.getEconomyManager().setBalance(on.getUniqueId(), 500); + on.getInventory().clear(); + on.getInventory().setArmorContents(null); + on.setHealth(20); + on.setFoodLevel(20); + on.setGameMode(GameMode.SURVIVAL); + on.getInventory().addItem(new ItemBuilder(Material.STONE_PICKAXE).lore(ChatColor.GOLD + "Soul Bound").build()); + on.getInventory().addItem(new ItemBuilder(Material.COOKED_BEEF, 16).build()); + on.getInventory().addItem(new ItemBuilder(Material.STONE_AXE).lore(ChatColor.GOLD + "Soul Bound").build()); + on.teleport(((ColorFaction) colorFaction).getHome().clone().add(0 , 0.5 ,0), PlayerTeleportEvent.TeleportCause.PLUGIN); + } + switch (((ColorFaction) colorFaction).getColor()) { + case GREEN: { + new BukkitRunnable() { + @Override + public void run() { + if (spawnVillager(((ColorFaction) colorFaction).getBlockVillager(), ((ColorFaction) colorFaction).getColor() + "Build Shop") && spawnVillager(((ColorFaction) colorFaction).getBuyVillager(), ((ColorFaction) colorFaction).getColor() + "Combat Shop") && + spawnVillager(((ColorFaction) colorFaction).getSellVillager(), ((ColorFaction) colorFaction).getColor() + "Sell Items") && spawnVillager(((ColorFaction) colorFaction).getEnchantVillager(), ((ColorFaction) colorFaction).getColor() + "Tim the Enchanter")) { + ((ColorFaction) colorFaction).setHasVillager(true); + } else { + System.out.println("Failed to spawn " + ((ColorFaction) colorFaction).getDisplayName(Bukkit.getConsoleSender())); + ((ColorFaction) colorFaction).setHasVillager(false); + } + } + }.runTaskLater(plugin, 20); + break; + } + case RED: { + new BukkitRunnable() { + @Override + public void run() { + if (spawnVillager(((ColorFaction) colorFaction).getBlockVillager(), ((ColorFaction) colorFaction).getColor() + "Build Shop") && spawnVillager(((ColorFaction) colorFaction).getBuyVillager(), ((ColorFaction) colorFaction).getColor() + "Combat Shop") && + spawnVillager(((ColorFaction) colorFaction).getSellVillager(), ((ColorFaction) colorFaction).getColor() + "Sell Items") && spawnVillager(((ColorFaction) colorFaction).getEnchantVillager(), ((ColorFaction) colorFaction).getColor() + "Tim the Enchanter")) { + ((ColorFaction) colorFaction).setHasVillager(true); + } else { + System.out.println("Failed to spawn " + ((ColorFaction) colorFaction).getDisplayName(Bukkit.getConsoleSender())); + ((ColorFaction) colorFaction).setHasVillager(false); + } + } + }.runTaskLater(plugin, 40); + break; + } + case BLUE: { + new BukkitRunnable() { + @Override + public void run() { + if (spawnVillager(((ColorFaction) colorFaction).getBlockVillager(), ((ColorFaction) colorFaction).getColor() + "Build Shop") && spawnVillager(((ColorFaction) colorFaction).getBuyVillager(), ((ColorFaction) colorFaction).getColor() + "Combat Shop") && + spawnVillager(((ColorFaction) colorFaction).getSellVillager(), ((ColorFaction) colorFaction).getColor() + "Sell Items") && spawnVillager(((ColorFaction) colorFaction).getEnchantVillager(), ((ColorFaction) colorFaction).getColor() + "Tim the Enchanter")) { + ((ColorFaction) colorFaction).setHasVillager(true); + } else { + System.out.println("Failed to spawn " + ((ColorFaction) colorFaction).getDisplayName(Bukkit.getConsoleSender())); + ((ColorFaction) colorFaction).setHasVillager(false); + } + } + }.runTaskLater(plugin, 60); + break; + } + case YELLOW: { + new BukkitRunnable() { + @Override + public void run() { + if (spawnVillager(((ColorFaction) colorFaction).getBlockVillager(), ((ColorFaction) colorFaction).getColor() + "Build Shop") && spawnVillager(((ColorFaction) colorFaction).getBuyVillager(), ((ColorFaction) colorFaction).getColor() + "Combat Shop") && + spawnVillager(((ColorFaction) colorFaction).getSellVillager(), ((ColorFaction) colorFaction).getColor() + "Sell Items") && spawnVillager(((ColorFaction) colorFaction).getEnchantVillager(), ((ColorFaction) colorFaction).getColor() + "Tim the Enchanter")) { + ((ColorFaction) colorFaction).setHasVillager(true); + } else { + System.out.println("Failed to spawn " + ((ColorFaction) colorFaction).getDisplayName(Bukkit.getConsoleSender())); + ((ColorFaction) colorFaction).setHasVillager(false); + } + } + }.runTaskLater(plugin, 0); + break; + } + + default: { + break; + } + } + } + } + } + + + public void saveArena(Location l1, Location l2) { + // Location l1 = new Location(Bukkit.getWorld("world"), 127.476, 69.00, -12.508);// Location representing one corner of the region + // Location l2 = new Location(Bukkit.getWorld("world"), 156.554, 69.00, -32.518); // Location representing the corner opposite to + if (plugin.getWorldEditPlugin() == null) + return; + +// OR - without needing an associated Player + TerrainManager tm = new TerrainManager(plugin.getWorldEditPlugin(), Bukkit.getWorld("world")); + +// don't include an extension - TerrainManager will auto-add ".schematic" + File saveFile = new File(plugin.getDataFolder(), "testWorld"); + +// save the terrain to a schematic file + try { + tm.saveTerrain(saveFile, l1, l2); + } catch (FilenameException e) { + // thrown by WorldEdit - it doesn't like the file name/location etc. + } catch (DataException e) { + // thrown by WorldEdit - problem with the data + } catch (IOException e) { + // problem with creating/writing to the file + } + } + + public void loadArena() { + Preconditions.checkNotNull(plugin.getWorldEditPlugin()); + TerrainManager tm = new TerrainManager(plugin.getWorldEditPlugin(), Bukkit.getWorld("world")); + Preconditions.checkNotNull(tm); +// don't include an extension - TerrainManager will auto-add ".schematic" + File saveFile = new File(plugin.getDataFolder(), "testWorld"); + Preconditions.checkNotNull(saveFile); + +// reload a schematic + try { + tm.loadSchematic(saveFile); + } catch (FilenameException e) { + // thrown by WorldEdit - it doesn't like the file name/location etc. + } catch (DataException e) { + // thrown by WorldEdit - problem with the data + } catch (IOException e) { + // problem with opening/reading the file + } catch (MaxChangedBlocksException e) { + // thrown by WorldEdit - the schematic is larger than the configured block limit for the player + } catch (EmptyClipboardException e) { +// thrown by WorldEdit - should be self-explanatory + } + } + + public boolean spawnVillager(Location loc, String name) { + loc.getChunk().load(); + + final WorldServer mcWorld = ((CraftWorld) loc.getWorld()).getHandle(); + final Villager customEnt = new Villager(mcWorld); + customEnt.setCustomName(name); + customEnt.setCustomNameVisible(true); + customEnt.setJob(name); + customEnt.setLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); + customEnt.setPosition(loc.getX(), loc.getY(), loc.getZ()); + + boolean result = mcWorld.addEntity(customEnt, CreatureSpawnEvent.SpawnReason.CUSTOM); + if(result){ + Iterator> iterator = EconomyListener.respawners.entrySet().iterator(); + while(iterator.hasNext()){ + Map.Entry entry = iterator.next(); + if(entry.getKey().getBukkitEntity().getLocation().distanceSquared(loc) <= 4){ + if(ChatColor.stripColor(entry.getKey().getCustomName()).contains(ChatColor.stripColor(name))){ + iterator.remove(); + System.out.println("Removing from respawnee: " + name); + } + } + } + for(Entity entity : customEnt.getBukkitEntity().getNearbyEntities(4 , 4, 4)){ + if(entity instanceof LivingEntity && !(entity instanceof Player) && entity != customEnt.getBukkitEntity()){ + LivingEntity livingEntity = (LivingEntity) entity; + if(livingEntity.getCustomName() != null && ChatColor.stripColor(livingEntity.getCustomName()).contains(ChatColor.stripColor(name))){ + livingEntity.remove(); + System.out.println("Removing from already spawned: " + name); + } + } + } + } + return result; + } + + + public GameState getGameState() { + return gameState; + } + + public void setGameState(GameState gameState) { + this.gameState = gameState; + } + + public long getGameTimer() { + return gameStartTimeStamp; + } + + public Set getDeadFactions() { + return deadFactions; + } +} diff --git a/main/java/me/prestige/bases/game/GameState.java b/main/java/me/prestige/bases/game/GameState.java new file mode 100644 index 0000000..e1e0327 --- /dev/null +++ b/main/java/me/prestige/bases/game/GameState.java @@ -0,0 +1,7 @@ +package me.prestige.bases.game; + +public enum GameState { + WAITING, + STARTING, + ENDING +} diff --git a/main/java/me/prestige/bases/game/TerrainManager.java b/main/java/me/prestige/bases/game/TerrainManager.java new file mode 100644 index 0000000..4b00574 --- /dev/null +++ b/main/java/me/prestige/bases/game/TerrainManager.java @@ -0,0 +1,150 @@ +package me.prestige.bases.game; + + +import java.io.File; +import java.io.IOException; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import com.sk89q.worldedit.CuboidClipboard; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.EmptyClipboardException; +import com.sk89q.worldedit.FilenameException; +import com.sk89q.worldedit.LocalPlayer; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.MaxChangedBlocksException; +import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.bukkit.BukkitWorld; +import com.sk89q.worldedit.bukkit.WorldEditPlugin; +import com.sk89q.worldedit.data.DataException; +import com.sk89q.worldedit.schematic.SchematicFormat; + +/** + * @author desht + * + * A wrapper class for the WorldEdit terrain loading & saving API to make things a little + * simple for other plugins to use. + */ +public class TerrainManager { + private static final String EXTENSION = "schematic"; + + private final WorldEdit we; + private final LocalSession localSession; + private final EditSession editSession; + private final LocalPlayer localPlayer; + + /** + * Constructor + * + * @param wep the WorldEdit plugin instance + * @param player the player to work with + */ + public TerrainManager(WorldEditPlugin wep, Player player) { + we = wep.getWorldEdit(); + localPlayer = wep.wrapPlayer(player); + localSession = we.getSession(localPlayer); + editSession = localSession.createEditSession(localPlayer); + } + + /** + * Constructor + * + * @param wep the WorldEdit plugin instance + * @param world the world to work in + */ + public TerrainManager(WorldEditPlugin wep, World world) { + we = wep.getWorldEdit(); + localPlayer = null; + localSession = new LocalSession(we.getConfiguration()); + editSession = new EditSession(new BukkitWorld(world), we.getConfiguration().maxChangeLimit); + } + + /** + * Write the terrain bounded by the given locations to the given file as a MCedit format + * schematic. + * + * @param saveFile a File representing the schematic file to create + * @param l1 one corner of the region to save + * @param l2 the corner of the region to save, opposite to l1 + * @throws DataException + * @throws IOException + */ + public void saveTerrain(File saveFile, Location l1, Location l2) throws FilenameException, DataException, IOException { + Vector min = getMin(l1, l2); + Vector max = getMax(l1, l2); + + saveFile = we.getSafeSaveFile(localPlayer, + saveFile.getParentFile(), saveFile.getName(), + EXTENSION, new String[] { EXTENSION }); + + editSession.enableQueue(); + CuboidClipboard clipboard = new CuboidClipboard(max.subtract(min).add(new Vector(1, 1, 1)), min); + clipboard.copy(editSession); + SchematicFormat.MCEDIT.save(clipboard, saveFile); + editSession.flushQueue(); + } + + /** + * Load the data from the given schematic file and paste it at the given location. If the location is null, then + * paste it at the saved data's origin. + * + * @param saveFile a File representing the schematic file to load + * @param loc the location to paste the clipboard at (may be null) + * @throws FilenameException + * @throws DataException + * @throws IOException + * @throws MaxChangedBlocksException + * @throws EmptyClipboardException + */ + public void loadSchematic(File saveFile, Location loc) throws FilenameException, DataException, IOException, MaxChangedBlocksException, EmptyClipboardException { + saveFile = we.getSafeSaveFile(localPlayer, + saveFile.getParentFile(), saveFile.getName(), + EXTENSION, new String[] { EXTENSION }); + + editSession.enableQueue(); + localSession.setClipboard(SchematicFormat.MCEDIT.load(saveFile)); + localSession.getClipboard().place(editSession, getPastePosition(loc), false); + editSession.flushQueue(); + we.flushBlockBag(localPlayer, editSession); + } + + /** + * Load the data from the given schematic file and paste it at the saved clipboard's origin. + * + * @param saveFile + * @throws FilenameException + * @throws DataException + * @throws IOException + * @throws MaxChangedBlocksException + * @throws EmptyClipboardException + */ + public void loadSchematic(File saveFile) throws FilenameException, DataException, IOException, MaxChangedBlocksException, EmptyClipboardException { + loadSchematic(saveFile, null); + } + + private Vector getPastePosition(Location loc) throws EmptyClipboardException { + if (loc == null) + return localSession.getClipboard().getOrigin(); + else + return new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + + private Vector getMin(Location l1, Location l2) { + return new Vector( + Math.min(l1.getBlockX(), l2.getBlockX()), + Math.min(l1.getBlockY(), l2.getBlockY()), + Math.min(l1.getBlockZ(), l2.getBlockZ()) + ); + } + + private Vector getMax(Location l1, Location l2) { + return new Vector( + Math.max(l1.getBlockX(), l2.getBlockX()), + Math.max(l1.getBlockY(), l2.getBlockY()), + Math.max(l1.getBlockZ(), l2.getBlockZ()) + ); + } +} diff --git a/main/java/me/prestige/bases/inventory/InventoryHandler.java b/main/java/me/prestige/bases/inventory/InventoryHandler.java new file mode 100644 index 0000000..ad09584 --- /dev/null +++ b/main/java/me/prestige/bases/inventory/InventoryHandler.java @@ -0,0 +1,21 @@ +package me.prestige.bases.inventory; + +import me.prestige.bases.Bases; +import me.prestige.bases.inventory.inventorys.WaitingInventory; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.potion.PotionEffect; + +public class InventoryHandler { + + public WaitingInventory waitingInventory; + + public InventoryHandler(Bases plugin){ + waitingInventory = new WaitingInventory(plugin); + + } + +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/inventory/InventorySnapshot.java b/main/java/me/prestige/bases/inventory/InventorySnapshot.java new file mode 100644 index 0000000..5560010 --- /dev/null +++ b/main/java/me/prestige/bases/inventory/InventorySnapshot.java @@ -0,0 +1,46 @@ +package me.prestige.bases.inventory; + +import me.prestige.bases.Bases; +import me.prestige.bases.scoreboard.PlayerBoard; +import me.prestige.bases.scoreboard.SidebarProvider; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.potion.PotionEffect; + +public abstract class InventorySnapshot { + public final SidebarProvider sidebarProvider; + private final Bases plugin; + private final Location location; + + + public InventorySnapshot(final Bases plugin, final SidebarProvider sidebarProvider, final Location location) { + this.plugin = plugin; + this.sidebarProvider = sidebarProvider; + this.location = location; + } + + public void applyTo(final Player player, final boolean teleport, final boolean setItems) { + if (this.sidebarProvider != null) { + /* + final PlayerBoard playerBoard = this.plugin.getScoreboardHandler().getPlayerBoard(player.getUniqueId()); + if (playerBoard != null) { + playerBoard.setDefaultSidebar(this.sidebarProvider, 2L); + } + */ + } + for (final PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + if (setItems) { + final PlayerInventory inventory = player.getInventory(); + inventory.clear(); + inventory.setArmorContents(new ItemStack[inventory.getArmorContents().length]); + } + if (teleport && this.location != null && !player.isDead()) { + player.teleport(this.location, PlayerTeleportEvent.TeleportCause.PLUGIN); + } + } +} \ No newline at end of file diff --git a/main/java/me/prestige/bases/inventory/inventorys/WaitingInventory.java b/main/java/me/prestige/bases/inventory/inventorys/WaitingInventory.java new file mode 100644 index 0000000..b69df70 --- /dev/null +++ b/main/java/me/prestige/bases/inventory/inventorys/WaitingInventory.java @@ -0,0 +1,54 @@ +package me.prestige.bases.inventory.inventorys; + +import com.customhcf.util.ItemBuilder; +import me.prestige.bases.Bases; +import me.prestige.bases.inventory.InventorySnapshot; +import me.prestige.bases.scoreboard.provider.GameProvider; +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Bukkit; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class WaitingInventory extends InventorySnapshot { + + public static ItemStack blue; + public static ItemStack red; + public static ItemStack random; + public static ItemStack yellow; + public static ItemStack green; + + static { + blue = new ItemBuilder(Material.INK_SACK).data(DyeColor.BLUE.getDyeData()).displayName(ChatColor.AQUA + "Join Blue " + ChatColor.GRAY + "(Right Click)").build(); + red = new ItemBuilder(Material.INK_SACK).data(DyeColor.RED.getDyeData()).displayName(ChatColor.RED + "Join Red " + ChatColor.GRAY + "(Right Click)").build(); + random = new ItemBuilder(Material.NETHER_STAR).displayName(ChatColor.LIGHT_PURPLE + "Random Team " + ChatColor.GRAY + "(Right Click)").build(); + yellow = new ItemBuilder(Material.INK_SACK).data(DyeColor.YELLOW.getDyeData()).displayName(ChatColor.YELLOW + "Join Yellow " + ChatColor.GRAY + "(Right Click)").build(); + green = new ItemBuilder(Material.INK_SACK).data(DyeColor.GREEN.getDyeData()).displayName(ChatColor.GREEN + "Join Green " + ChatColor.GRAY + "(Right Click)").build(); + } + + + Bases plugin; + public WaitingInventory(Bases plugin) { + super(plugin, null, Bukkit.getWorld("world").getSpawnLocation()); + this.plugin = plugin; + } + + @Override + public void applyTo(Player player, boolean teleport, boolean setItems) { + super.applyTo(player, teleport, setItems); + if(setItems){ + Inventory inventory = player.getInventory(); + inventory.setItem(2, blue); + inventory.setItem(3, red); + + inventory.setItem(4, random); + + inventory.setItem(5, yellow); + inventory.setItem(6, green); + + } + } +} diff --git a/main/java/me/prestige/bases/kothgame/CaptureZone.java b/main/java/me/prestige/bases/kothgame/CaptureZone.java new file mode 100644 index 0000000..8c4ea83 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/CaptureZone.java @@ -0,0 +1,128 @@ +package me.prestige.bases.kothgame; + +import com.customhcf.util.cuboid.Cuboid; +import com.google.common.collect.Maps; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.Player; + +import javax.annotation.Nullable; +import java.util.Map; + +public class CaptureZone implements ConfigurationSerializable { + private String name; + private String prefix; + private Cuboid cuboid; + private Player cappingPlayer; + private long defaultCaptureMillis; + private String defaultCaptureWords; + + private long endMillis; + + public CaptureZone(final String name, final Cuboid cuboid, final long defaultCaptureMillis) { + this(name, "", cuboid, defaultCaptureMillis); + } + + public CaptureZone(final String name, final String prefix, final Cuboid cuboid, final long defaultCaptureMillis) { + this.name = name; + this.prefix = prefix; + this.cuboid = cuboid; + this.setDefaultCaptureMillis(defaultCaptureMillis); + } + + public CaptureZone(final Map map) { + this.name = (String) map.get("name"); + Object obj = map.get("prefix"); + if(obj instanceof String) { + this.prefix = (String) obj; + } + obj = map.get("cuboid"); + if(obj instanceof Cuboid) { + this.cuboid = (Cuboid) obj; + } + this.setDefaultCaptureMillis(Long.parseLong((String) map.get("captureMillis"))); + } + + public Map serialize() { + final Map map = Maps.newLinkedHashMap(); + map.put("name", this.name); + if(this.prefix != null) { + map.put("prefix", this.prefix); + } + if(this.cuboid != null) { + map.put("cuboid", this.cuboid); + } + map.put("captureMillis", Long.toString(this.defaultCaptureMillis)); + return map; + } + + public boolean isActive() { + return this.getRemainingCaptureMillis() > 0L; + } + + public String getName() { + return this.name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getPrefix() { + if(this.prefix == null) { + this.prefix = ""; + } + return this.prefix; + } + + public String getDisplayName() { + return getPrefix() + this.name; + } + + public Cuboid getCuboid() { + return this.cuboid; + } + + public long getRemainingCaptureMillis() { + if(this.endMillis == Long.MIN_VALUE) { + return -1L; + } + if(this.cappingPlayer == null) { + return this.defaultCaptureMillis; + } + return this.endMillis - System.currentTimeMillis(); + } + + public void setRemainingCaptureMillis(final long millis) { + this.endMillis = System.currentTimeMillis() + millis; + } + + public long getDefaultCaptureMillis() { + return this.defaultCaptureMillis; + } + + + public void setDefaultCaptureMillis(final long millis) { + if(this.defaultCaptureMillis != millis) { + this.defaultCaptureMillis = millis; + this.defaultCaptureWords = DurationFormatUtils.formatDurationWords(millis, true, true); + } + } + + public String getDefaultCaptureWords() { + return this.defaultCaptureWords; + } + + public Player getCappingPlayer() { + return this.cappingPlayer; + } + + public void setCappingPlayer(@Nullable final Player player) { + this.cappingPlayer = player; + if(player == null) { + this.endMillis = this.defaultCaptureMillis; + } else { + this.endMillis = System.currentTimeMillis() + this.defaultCaptureMillis; + } + } +} diff --git a/main/java/me/prestige/bases/kothgame/EventExecutor.java b/main/java/me/prestige/bases/kothgame/EventExecutor.java new file mode 100644 index 0000000..4f0b0ab --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/EventExecutor.java @@ -0,0 +1,20 @@ +package me.prestige.bases.kothgame; + +import com.customhcf.util.command.ArgumentExecutor; +import me.prestige.bases.Bases; +import me.prestige.bases.kothgame.argument.*; + +public class EventExecutor extends ArgumentExecutor { + public EventExecutor(final Bases plugin) { + super("game"); + addArgument(new GameCancelArgument(plugin)); + addArgument(new GameCreateArgument(plugin)); + addArgument(new GameDeleteArgument(plugin)); + addArgument(new GameRenameArgument(plugin)); + addArgument(new GameSetAreaArgument(plugin)); + addArgument(new GameSetCapzoneArgument(plugin)); + addArgument(new GameStartArgument(plugin)); + addArgument(new GameScheduleArgument(plugin)); + addArgument(new GameUptimeArgument(plugin)); + } +} diff --git a/main/java/me/prestige/bases/kothgame/EventTimer.java b/main/java/me/prestige/bases/kothgame/EventTimer.java new file mode 100644 index 0000000..7de0a38 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/EventTimer.java @@ -0,0 +1,226 @@ +package me.prestige.bases.kothgame; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import me.prestige.bases.DateTimeFormats; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.event.CaptureZoneEnterEvent; +import me.prestige.bases.faction.event.CaptureZoneLeaveEvent; +import me.prestige.bases.kothgame.faction.EventFaction; +import me.prestige.bases.kothgame.faction.KothFaction; +import me.prestige.bases.timer.GlobalTimer; +import org.apache.commons.lang.time.DurationFormatUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.LeavesDecayEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +public class EventTimer extends GlobalTimer implements Listener { + private static final long RESCHEDULE_FREEZE_MILLIS; + private static final String RESCHEDULE_FREEZE_WORDS; + + static { + RESCHEDULE_FREEZE_MILLIS = TimeUnit.SECONDS.toMillis(15L); + RESCHEDULE_FREEZE_WORDS = DurationFormatUtils.formatDurationWords(EventTimer.RESCHEDULE_FREEZE_MILLIS, true, true); + } + + private final Bases plugin; + private long startStamp; + private long lastContestedEventMillis; + private EventFaction eventFaction; + + public EventTimer(final Bases plugin) { + super("Event", 0L); + this.plugin = plugin; + new BukkitRunnable() { + public void run() { + if(EventTimer.this.eventFaction != null) { + EventTimer.this.eventFaction.getEventType().getEventTracker().tick(EventTimer.this, EventTimer.this.eventFaction); + return; + } + final LocalDateTime now = LocalDateTime.now(DateTimeFormats.SERVER_ZONE_ID); + final int day = now.getDayOfYear(); + final int hour = now.getHour(); + final int minute = now.getMinute(); + + + } + }.runTaskTimer((Plugin) plugin, 20L, 20L); + } + + public EventFaction getEventFaction() { + return this.eventFaction; + } + + public String getScoreboardPrefix() { + return ChatColor.GOLD.toString() + ChatColor.BOLD.toString(); + } + + public String getName() { + return (this.eventFaction == null) ? "Event" : this.eventFaction.getName(); + } + + @Override + public boolean clearCooldown() { + boolean result = super.clearCooldown(); + if(this.eventFaction != null) { + for(final CaptureZone captureZone : this.eventFaction.getCaptureZones()) { + captureZone.setCappingPlayer(null); + } + this.eventFaction.setDeathban(true); + this.eventFaction = null; + this.startStamp = -1L; + result = true; + } + return result; + } + + @EventHandler + public void onDecay(LeavesDecayEvent e){ + if(plugin.getFactionManager().getFactionAt(e.getBlock()) != null){ + e.setCancelled(true); + } + } + + @Override + public long getRemaining() { + if(this.eventFaction == null) { + return 0L; + } + if(this.eventFaction instanceof KothFaction) { + return ((KothFaction) this.eventFaction).getCaptureZone().getRemainingCaptureMillis(); + } + return super.getRemaining(); + } + + public void handleWinner(final Player winner) { + if(this.eventFaction == null) { + return; + } + plugin.getGameManager().end(plugin.getFactionManager().getColorFaction(winner.getUniqueId())); + //TODO add/loss win to player + + this.clearCooldown(); + } + + public boolean tryContesting(final EventFaction eventFaction, CommandSender sender) { + if(sender == null){ + sender = Bukkit.getConsoleSender(); + } + if(this.eventFaction != null) { + sender.sendMessage(ChatColor.RED + "There is already an active event, use /game cancel to end it."); + return false; + } + if(eventFaction instanceof KothFaction) { + final KothFaction kothFaction = (KothFaction) eventFaction; + if(kothFaction.getCaptureZone() == null) { + sender.sendMessage(ChatColor.RED + "Cannot schedule " + eventFaction.getName() + " as its' capture zone is not set."); + return false; + } + } + final long millis = System.currentTimeMillis(); + if(this.lastContestedEventMillis + EventTimer.RESCHEDULE_FREEZE_MILLIS - millis > 0L) { + sender.sendMessage(ChatColor.RED + "Cannot reschedule events within " + EventTimer.RESCHEDULE_FREEZE_WORDS + '.'); + return false; + } + this.lastContestedEventMillis = millis; + this.startStamp = millis; + this.eventFaction = eventFaction; + final Collection captureZones = eventFaction.getCaptureZones(); + for(final CaptureZone captureZone : captureZones) { + if(captureZone.isActive()) { + final Player player = (Player) Iterables.getFirst((Iterable) captureZone.getCuboid().getPlayers(), (Object) null); + if(player == null || !eventFaction.getEventType().getEventTracker().onControlTake(player, captureZone)) { + continue; + } + captureZone.setCappingPlayer(player); + } + } + eventFaction.setDeathban(true); + return true; + } + + public long getUptime() { + return System.currentTimeMillis() - this.startStamp; + } + + public long getStartStamp() { + return this.startStamp; + } + + private void handleDisconnect(final Player player) { + Preconditions.checkNotNull((Object) player); + if(this.eventFaction == null) { + return; + } + final Collection captureZones = this.eventFaction.getCaptureZones(); + for(final CaptureZone captureZone : captureZones) { + if(player.getUniqueId().equals(captureZone.getCappingPlayer().getUniqueId())) { + this.eventFaction.getEventType().getEventTracker().onControlLoss(player, captureZone, this.eventFaction); + captureZone.setCappingPlayer(null); + break; + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerDeath(final PlayerDeathEvent event) { + this.handleDisconnect(event.getEntity()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerLogout(final PlayerQuitEvent event) { + this.handleDisconnect(event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerKick(final PlayerKickEvent event) { + this.handleDisconnect(event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onCaptureZoneEnter(final CaptureZoneEnterEvent event) { + if(this.eventFaction == null) { + return; + } + final CaptureZone captureZone = event.getCaptureZone(); + if(!this.eventFaction.getCaptureZones().contains(captureZone)) { + return; + } + final Player player = event.getPlayer(); + if(captureZone.getCappingPlayer() == null && this.eventFaction.getEventType().getEventTracker().onControlTake(player, captureZone)) { + captureZone.setCappingPlayer(player); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onCaptureZoneLeave(final CaptureZoneLeaveEvent event) { + if(Objects.equal(event.getFaction(), this.eventFaction)) { + final Player player = event.getPlayer(); + final CaptureZone captureZone = event.getCaptureZone(); + if(Objects.equal((Object) player, (Object) captureZone.getCappingPlayer()) && this.eventFaction.getEventType().getEventTracker().onControlLoss(player, captureZone, this.eventFaction)) { + captureZone.setCappingPlayer(null); + for(final Player target : captureZone.getCuboid().getPlayers()) { + if(target != null && !target.equals(player) && this.eventFaction.getEventType().getEventTracker().onControlTake(target, captureZone)) { + captureZone.setCappingPlayer(target); + break; + } + } + } + } + } +} diff --git a/main/java/me/prestige/bases/kothgame/EventType.java b/main/java/me/prestige/bases/kothgame/EventType.java new file mode 100644 index 0000000..9ef5390 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/EventType.java @@ -0,0 +1,43 @@ +package me.prestige.bases.kothgame; + +import com.google.common.collect.ImmutableBiMap; +import com.google.common.collect.ImmutableMap; +import me.prestige.bases.Bases; +import me.prestige.bases.kothgame.tracker.EventTracker; +import me.prestige.bases.kothgame.tracker.KothTracker; + +public enum EventType { + KOTH("KOTH", new KothTracker(Bases.getPlugin())), ; + + + private static final ImmutableMap byDisplayName; + + static { + final ImmutableMap.Builder builder = (ImmutableMap.Builder) new ImmutableBiMap.Builder(); + for(final EventType eventType : values()) { + builder.put(eventType.displayName.toLowerCase(), eventType); + } + byDisplayName = builder.build(); + } + + private final EventTracker eventTracker; + private final String displayName; + + EventType(final String displayName, final EventTracker eventTracker) { + this.displayName = displayName; + this.eventTracker = eventTracker; + } + + @Deprecated + public static EventType getByDisplayName(final String name) { + return (EventType) EventType.byDisplayName.get((Object) name.toLowerCase()); + } + + public EventTracker getEventTracker() { + return this.eventTracker; + } + + public String getDisplayName() { + return this.displayName; + } +} diff --git a/main/java/me/prestige/bases/kothgame/argument/GameCancelArgument.java b/main/java/me/prestige/bases/kothgame/argument/GameCancelArgument.java new file mode 100644 index 0000000..ba2b197 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/argument/GameCancelArgument.java @@ -0,0 +1,35 @@ +package me.prestige.bases.kothgame.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.EventTimer; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class GameCancelArgument extends CommandArgument { + private final Bases plugin; + + public GameCancelArgument(final Bases plugin) { + super("cancel", "Cancels a running event", new String[]{"stop", "end"}); + this.plugin = plugin; + this.permission = "command.game." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName(); + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + final EventTimer eventTimer = this.plugin.getTimerManager().eventTimer; + final Faction eventFaction = eventTimer.getEventFaction(); + if(!eventTimer.clearCooldown()) { + sender.sendMessage(ChatColor.RED + "There is not a running event."); + return true; + } + Bukkit.broadcastMessage(ChatColor.BLUE + sender.getName() + ChatColor.WHITE + " has cancelled " + ((eventFaction == null) ? "the active event" : ChatColor.GOLD +(eventFaction.getName() + ChatColor.WHITE)) + "."); + return true; + } +} diff --git a/main/java/me/prestige/bases/kothgame/argument/GameCreateArgument.java b/main/java/me/prestige/bases/kothgame/argument/GameCreateArgument.java new file mode 100644 index 0000000..3bd24c0 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/argument/GameCreateArgument.java @@ -0,0 +1,67 @@ +package me.prestige.bases.kothgame.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.EventType; +import me.prestige.bases.kothgame.faction.KothFaction; +import org.apache.commons.lang.WordUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class GameCreateArgument extends CommandArgument { + private final Bases plugin; + + public GameCreateArgument(final Bases plugin) { + super("create", "Defines a new event", new String[]{"make", "define"}); + this.plugin = plugin; + this.permission = "command.game." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Faction faction = this.plugin.getFactionManager().getFaction(args[1]); + if(faction != null) { + sender.sendMessage(ChatColor.RED + "There is already a faction named " + args[1] + '.'); + return true; + } + final String upperCase = args[2].toUpperCase(); + switch(upperCase) { + case "KOTH": { + faction = new KothFaction(args[1]); + break; + } + default: { + sender.sendMessage(this.getUsage(label)); + return true; + } + } + this.plugin.getFactionManager().createFaction(faction, sender); + sender.sendMessage(ChatColor.WHITE + "Created event faction " + ChatColor.GOLD + faction.getDisplayName(sender) + ChatColor.WHITE + " with type " + ChatColor.GOLD + WordUtils.capitalizeFully(args[2]) + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 3) { + return Collections.emptyList(); + } + final EventType[] eventTypes = EventType.values(); + final List results = new ArrayList(eventTypes.length); + for(final EventType eventType : eventTypes) { + results.add(eventType.name()); + } + return results; + } +} diff --git a/main/java/me/prestige/bases/kothgame/argument/GameDeleteArgument.java b/main/java/me/prestige/bases/kothgame/argument/GameDeleteArgument.java new file mode 100644 index 0000000..8aa8eba --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/argument/GameDeleteArgument.java @@ -0,0 +1,52 @@ +package me.prestige.bases.kothgame.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.faction.EventFaction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class GameDeleteArgument extends CommandArgument { + private final Bases plugin; + + public GameDeleteArgument(final Bases plugin) { + super("delete", "Deletes an event"); + this.plugin = plugin; + this.aliases = new String[]{"remove", "del"}; + this.permission = "command.game." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + final Faction faction = this.plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof EventFaction)) { + sender.sendMessage(ChatColor.RED + "There is not an event faction named '" + args[1] + "'."); + return true; + } + + if(this.plugin.getFactionManager().removeFaction(faction, sender)) { + sender.sendMessage(ChatColor.WHITE + "Deleted event faction " + ChatColor.GOLD + faction.getDisplayName(sender) + ChatColor.WHITE + '.'); + } + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2) { + return Collections.emptyList(); + } + return this.plugin.getFactionManager().getFactions().stream().filter(faction -> faction instanceof EventFaction).map(Faction::getName).collect(Collectors.toList()); + } +} diff --git a/main/java/me/prestige/bases/kothgame/argument/GameRenameArgument.java b/main/java/me/prestige/bases/kothgame/argument/GameRenameArgument.java new file mode 100644 index 0000000..e731530 --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/argument/GameRenameArgument.java @@ -0,0 +1,55 @@ +package me.prestige.bases.kothgame.argument; + +import com.customhcf.util.command.CommandArgument; +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.faction.EventFaction; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class GameRenameArgument extends CommandArgument { + private final Bases plugin; + + public GameRenameArgument(final Bases plugin) { + super("rename", "Renames an event"); + this.plugin = plugin; + this.permission = "command.game." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + " "; + } + + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length < 3) { + sender.sendMessage(ChatColor.RED + "Usage: " + this.getUsage(label)); + return true; + } + Faction faction = this.plugin.getFactionManager().getFaction(args[2]); + if(faction != null) { + sender.sendMessage(ChatColor.RED + "There is already a faction named " + args[2] + '.'); + return true; + } + faction = this.plugin.getFactionManager().getFaction(args[1]); + if(!(faction instanceof EventFaction)) { + sender.sendMessage(ChatColor.RED + "There is not an event faction named '" + args[1] + "'."); + return true; + } + final String oldName = faction.getName(); + faction.setName(args[2], sender); + sender.sendMessage(ChatColor.WHITE + "Renamed event " + ChatColor.GOLD + oldName + ChatColor.WHITE + " to " + ChatColor.GOLD + faction.getName() + ChatColor.WHITE + '.'); + return true; + } + + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + if(args.length != 2) { + return Collections.emptyList(); + } + return this.plugin.getFactionManager().getFactions().stream().filter(faction -> faction instanceof EventFaction).map(Faction::getName).collect(Collectors.toList()); + } +} diff --git a/main/java/me/prestige/bases/kothgame/argument/GameScheduleArgument.java b/main/java/me/prestige/bases/kothgame/argument/GameScheduleArgument.java new file mode 100644 index 0000000..2622f1c --- /dev/null +++ b/main/java/me/prestige/bases/kothgame/argument/GameScheduleArgument.java @@ -0,0 +1,58 @@ +package me.prestige.bases.kothgame.argument; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import com.customhcf.base.DateTimeFormats; +import com.customhcf.util.JavaUtils; +import com.customhcf.util.command.CommandArgument; + +import me.prestige.bases.Bases; +import me.prestige.bases.faction.type.Faction; +import me.prestige.bases.kothgame.faction.EventFaction; + +public class GameScheduleArgument extends CommandArgument { + private final Bases plugin; + + public GameScheduleArgument(final Bases plugin) { + super("schedule", "Schedules a game"); + this.plugin = plugin; + this.permission = "command.game." + this.getName(); + } + + public String getUsage(final String label) { + return '/' + label + ' ' + this.getName() + "