Search in sources :

Example 6 with Game

use of com.ebicep.warlords.game.Game in project Warlords by ebicep.

the class ImposterModeOption method sendPoll.

public void sendPoll(Team team) {
    poll = new GamePoll.Builder(game).setQuestion("Who is the most SUS on your team?").setTimeLeft(60).setOptions(game.offlinePlayersWithoutSpectators().filter(uuidTeamEntry -> uuidTeamEntry.getValue() == team).map(offlinePlayerTeamEntry -> offlinePlayerTeamEntry.getKey().getName()).collect(Collectors.toList())).setExcludedPlayers(game.offlinePlayersWithoutSpectators().filter(uuidTeamEntry -> uuidTeamEntry.getValue() != team).map(offlinePlayerTeamEntry -> offlinePlayerTeamEntry.getKey().getUniqueId()).collect(Collectors.toList())).setRunnableAfterPollEnded(p -> {
        int mostVotes = Collections.max(p.getOptionsWithVotes().entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getValue();
        List<WarlordsPlayer> votedOut = p.getOptionsWithVotes().entrySet().stream().filter(stringIntegerEntry -> stringIntegerEntry.getValue() == mostVotes).map(Map.Entry::getKey).map(s -> game.warlordsPlayers().filter(warlordsPlayer -> warlordsPlayer.getName().equals(s)).findFirst().get()).collect(Collectors.toList());
        // If multiple top votes and one is imposter then voted wrong
        boolean votedCorrectly = votedOut.size() == 1 && imposters.get(team).stream().anyMatch(warlordsPlayer -> warlordsPlayer == votedOut.get(0));
        new GameRunnable(game, true) {

            int counter = 0;

            @Override
            public void run() {
                String title = "";
                String subtitle = "";
                switch(counter) {
                    case 0:
                    case 1:
                        title = team.teamColor + team.name + " voted...";
                        break;
                    case 2:
                    case 3:
                        if (votedCorrectly) {
                            title = ChatColor.GREEN + "Correctly!";
                        } else {
                            title = ChatColor.RED + "Incorrectly!";
                        }
                        subtitle = team.teamColor + imposters.get(team).get(0).getName() + ChatColor.YELLOW + " was the imposter";
                        break;
                }
                counter++;
                if (counter < 6) {
                    sendTitle(title, subtitle);
                } else if (counter == 6) {
                    game.onlinePlayersWithoutSpectators().forEach(playerTeamEntry -> {
                        Player player = playerTeamEntry.getKey();
                        player.removePotionEffect(PotionEffectType.BLINDNESS);
                        showWinLossMessage(team, player, votedCorrectly, playerTeamEntry.getValue() == team);
                    });
                } else if (counter == 9) {
                    game.removeFrozenCause(team.teamColor + team.name + ChatColor.GREEN + " is voting!");
                    int scoreNeededToEndGame = game.getOptions().stream().filter(e -> e instanceof WinByPointsOption).mapToInt(e -> ((WinByPointsOption) e).getPointLimit()).sorted().findFirst().orElse(Integer.MAX_VALUE);
                    if (votedCorrectly) {
                        game.setPoints(team, scoreNeededToEndGame);
                    } else {
                        // team with most points win, excluding voting team
                        game.setPoints(TeamMarker.getTeams(game).stream().filter(t -> t != team).min(Comparator.comparingInt(o -> game.getPoints(o))).get(), scoreNeededToEndGame);
                    }
                    ((PlayingState) game.getState()).skipTimer();
                    game.onlinePlayers().forEach(playerTeamEntry -> {
                        Player player = playerTeamEntry.getKey();
                        sendImpostorResult(player);
                    });
                    this.cancel();
                }
            }
        }.runTaskTimer(10, 20);
    }).get();
}
Also used : java.util(java.util) GameRunnable(com.ebicep.warlords.util.warlords.GameRunnable) PacketUtils(com.ebicep.warlords.util.bukkit.PacketUtils) Team(com.ebicep.warlords.game.Team) PlayingState(com.ebicep.warlords.game.state.PlayingState) GamePoll(com.ebicep.warlords.poll.polls.GamePoll) Warlords(com.ebicep.warlords.Warlords) Player(org.bukkit.entity.Player) ChatUtils(com.ebicep.warlords.util.chat.ChatUtils) Collectors(java.util.stream.Collectors) SimpleScoreboardHandler(com.ebicep.warlords.game.option.marker.scoreboard.SimpleScoreboardHandler) Game(com.ebicep.warlords.game.Game) ScoreboardHandler(com.ebicep.warlords.game.option.marker.scoreboard.ScoreboardHandler) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) ChatColor(org.bukkit.ChatColor) TeamMarker(com.ebicep.warlords.game.option.marker.TeamMarker) Nonnull(javax.annotation.Nonnull) PotionEffectType(org.bukkit.potion.PotionEffectType) Nullable(javax.annotation.Nullable) Player(org.bukkit.entity.Player) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) GamePoll(com.ebicep.warlords.poll.polls.GamePoll) GameRunnable(com.ebicep.warlords.util.warlords.GameRunnable)

Example 7 with Game

use of com.ebicep.warlords.game.Game in project Warlords by ebicep.

the class WinAfterTimeoutOption method register.

@Override
public void register(Game game) {
    new TimerSkipAbleMarker() {

        @Override
        public int getDelay() {
            return timeRemaining * 20;
        }

        @Override
        public void skipTimer(int delay) {
            timeRemaining -= delay / 20;
        }
    }.register(game);
    game.registerGameMarker(ScoreboardHandler.class, scoreboard = new SimpleScoreboardHandler(SCOREBOARD_PRIORITY, "timeout") {

        @Override
        public List<String> computeLines(@Nullable WarlordsPlayer player) {
            final EnumSet<Team> teams = TeamMarker.getTeams(game);
            Team winner = null;
            if (teams.size() > 1) {
                List<PointPredicterMarker> predictionMarkers = game.getMarkers(PointPredicterMarker.class);
                int scoreNeededToEndGame = game.getOptions().stream().filter(e -> e instanceof WinByPointsOption).mapToInt(e -> ((WinByPointsOption) e).getPointLimit()).sorted().findFirst().orElse(Integer.MAX_VALUE);
                int highestScore = Integer.MIN_VALUE;
                int highestWinInSeconds = Integer.MAX_VALUE;
                for (Team team : teams) {
                    int points = game.getPoints(team);
                    int winInSeconds;
                    if (predictionMarkers.isEmpty()) {
                        winInSeconds = Integer.MAX_VALUE;
                    } else {
                        double pointsPerMinute = predictionMarkers.stream().mapToDouble(e -> e.predictPointsNextMinute(team)).sum();
                        int pointsRemaining = scoreNeededToEndGame - points;
                        int winInSecondsCalculated = pointsPerMinute <= 0 ? Integer.MAX_VALUE : (int) (pointsRemaining / pointsPerMinute * 60);
                        int pointsAfterTimeIsOver = (int) (points + timeRemaining * pointsPerMinute / 60);
                        if (winInSecondsCalculated >= 0 && winInSecondsCalculated < timeRemaining) {
                            // This teamis going to win before the timer is over
                            winInSeconds = winInSecondsCalculated;
                            points = scoreNeededToEndGame;
                        } else {
                            winInSeconds = timeRemaining;
                            points = pointsAfterTimeIsOver;
                        }
                    }
                    if (points > highestScore) {
                        highestScore = points;
                        highestWinInSeconds = winInSeconds;
                        winner = team;
                    } else if (points == highestScore) {
                        if (winInSeconds < highestWinInSeconds) {
                            highestWinInSeconds = winInSeconds;
                            winner = team;
                        } else if (winInSeconds == highestWinInSeconds) {
                            winner = null;
                        }
                    }
                }
            }
            StringBuilder message = new StringBuilder(64);
            if (winner != null) {
                message.append(winner.coloredPrefix()).append(ChatColor.GOLD).append(" Wins in: ");
            } else {
                message.append(ChatColor.WHITE).append("Time Left: ");
            }
            message.append(ChatColor.GREEN);
            Utils.formatTimeLeft(message, timeRemaining);
            return Collections.singletonList(message.toString());
        }
    });
}
Also used : Utils(com.ebicep.warlords.util.warlords.Utils) GameRunnable(com.ebicep.warlords.util.warlords.GameRunnable) Team(com.ebicep.warlords.game.Team) PointPredicterMarker(com.ebicep.warlords.game.option.marker.PointPredicterMarker) OptionalInt(java.util.OptionalInt) SimpleScoreboardHandler(com.ebicep.warlords.game.option.marker.scoreboard.SimpleScoreboardHandler) WarlordsGameTriggerWinEvent(com.ebicep.warlords.events.WarlordsGameTriggerWinEvent) SECOND(com.ebicep.warlords.util.warlords.GameRunnable.SECOND) List(java.util.List) Game(com.ebicep.warlords.game.Game) ScoreboardHandler(com.ebicep.warlords.game.option.marker.scoreboard.ScoreboardHandler) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) BukkitTask(org.bukkit.scheduler.BukkitTask) ChatColor(org.bukkit.ChatColor) TeamMarker(com.ebicep.warlords.game.option.marker.TeamMarker) TimerSkipAbleMarker(com.ebicep.warlords.game.option.marker.TimerSkipAbleMarker) Nonnull(javax.annotation.Nonnull) Collections(java.util.Collections) Nullable(javax.annotation.Nullable) EnumSet(java.util.EnumSet) Bukkit(org.bukkit.Bukkit) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) TimerSkipAbleMarker(com.ebicep.warlords.game.option.marker.TimerSkipAbleMarker) SimpleScoreboardHandler(com.ebicep.warlords.game.option.marker.scoreboard.SimpleScoreboardHandler) Team(com.ebicep.warlords.game.Team) Nullable(javax.annotation.Nullable) PointPredicterMarker(com.ebicep.warlords.game.option.marker.PointPredicterMarker)

Example 8 with Game

use of com.ebicep.warlords.game.Game in project Warlords by ebicep.

the class EndState method begin.

@Override
public void begin() {
    for (Option option : game.getOptions()) {
        option.onGameEnding(game);
    }
    this.resetTimer();
    boolean teamBlueWins = winEvent != null && winEvent.getDeclaredWinner() == Team.BLUE;
    boolean teamRedWins = winEvent != null && winEvent.getDeclaredWinner() == Team.RED;
    List<WarlordsPlayer> players = game.warlordsPlayers().collect(Collectors.toList());
    if (players.isEmpty())
        return;
    sendMessageToAllGamePlayer(game, "" + ChatColor.GREEN + ChatColor.BOLD + "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬", false);
    sendMessageToAllGamePlayer(game, "" + ChatColor.WHITE + ChatColor.BOLD + "  Warlords", true);
    sendMessageToAllGamePlayer(game, "", false);
    if (teamBlueWins) {
        sendMessageToAllGamePlayer(game, ChatColor.YELLOW + "Winner" + ChatColor.GRAY + " - " + ChatColor.BLUE + "BLU", true);
    } else if (teamRedWins) {
        sendMessageToAllGamePlayer(game, ChatColor.YELLOW + "Winner" + ChatColor.GRAY + " - " + ChatColor.RED + "RED", true);
    } else {
        if (game.getAddons().contains(GameAddon.IMPOSTER_MODE)) {
            sendMessageToAllGamePlayer(game, ChatColor.YELLOW + "Winner" + ChatColor.GRAY + " - " + ChatColor.LIGHT_PURPLE + "GAME END", true);
        } else {
            sendMessageToAllGamePlayer(game, ChatColor.YELLOW + "Winner" + ChatColor.GRAY + " - " + ChatColor.LIGHT_PURPLE + "DRAW", true);
        }
    }
    sendMessageToAllGamePlayer(game, "", false);
    TextComponent mvp = new TextComponent("" + ChatColor.LIGHT_PURPLE + ChatColor.BOLD + "✚ MVP ✚");
    mvp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.LIGHT_PURPLE + "Total Flag Captures (everyone): " + ChatColor.GOLD + NumberFormat.addCommaAndRound(players.stream().mapToInt(WarlordsPlayer::getFlagsCaptured).sum()) + "\n" + ChatColor.LIGHT_PURPLE + "Total Flag Returns (everyone): " + ChatColor.GOLD + NumberFormat.addCommaAndRound(players.stream().mapToInt(WarlordsPlayer::getFlagsCaptured).sum())).create()));
    sendCenteredHoverableMessageToAllGamePlayer(game, Collections.singletonList(mvp));
    players = players.stream().sorted(Comparator.comparing(WarlordsPlayer::getTotalCapsAndReturnsWeighted).reversed()).collect(Collectors.toList());
    TextComponent playerMvp = new TextComponent(ChatColor.AQUA + players.get(0).getName());
    playerMvp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.LIGHT_PURPLE + "Flag Captures: " + ChatColor.GOLD + players.get(0).getFlagsCaptured() + "\n" + ChatColor.LIGHT_PURPLE + "Flag Returns: " + ChatColor.GOLD + players.get(0).getFlagsReturned()).create()));
    sendCenteredHoverableMessageToAllGamePlayer(game, Collections.singletonList(playerMvp));
    sendMessageToAllGamePlayer(game, "", false);
    TextComponent totalDamage = new TextComponent("" + ChatColor.RED + ChatColor.BOLD + "✚ TOP DAMAGE ✚");
    totalDamage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.RED + "Total Damage (everyone)" + ChatColor.GRAY + ": " + ChatColor.GOLD + NumberFormat.addCommaAndRound(players.stream().mapToLong(wp -> wp.getMinuteStats().total().getDamage()).sum())).create()));
    sendCenteredHoverableMessageToAllGamePlayer(game, Collections.singletonList(totalDamage));
    players = players.stream().sorted(Comparator.comparing((WarlordsPlayer wp) -> wp.getMinuteStats().total().getDamage()).reversed()).collect(Collectors.toList());
    List<TextComponent> leaderboardPlayersDamage = new ArrayList<>();
    for (int i = 0; i < players.size() && i < 3; i++) {
        WarlordsPlayer warlordsPlayer = players.get(i);
        TextComponent player = new TextComponent(ChatColor.AQUA + warlordsPlayer.getName() + ChatColor.GRAY + ": " + ChatColor.GOLD + NumberFormat.getSimplifiedNumber(warlordsPlayer.getMinuteStats().total().getDamage()));
        player.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.DARK_GRAY + "Lv" + ChatColor.GRAY + ExperienceManager.getLevelForSpec(warlordsPlayer.getUuid(), warlordsPlayer.getSpecClass()) + " " + ChatColor.GOLD + warlordsPlayer.getSpec().getClassName() + ChatColor.GREEN + " (" + warlordsPlayer.getSpec().getClass().getSimpleName() + ")").create()));
        leaderboardPlayersDamage.add(player);
        if (i != players.size() - 1 && i != 2) {
            leaderboardPlayersDamage.add(ChatUtils.SPACER);
        }
    }
    sendCenteredHoverableMessageToAllGamePlayer(game, leaderboardPlayersDamage);
    sendMessageToAllGamePlayer(game, "", false);
    TextComponent totalHealing = new TextComponent("" + ChatColor.GREEN + ChatColor.BOLD + "✚ TOP HEALING ✚");
    totalHealing.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.GREEN + "Total Healing (everyone)" + ChatColor.GRAY + ": " + ChatColor.GOLD + NumberFormat.addCommaAndRound(players.stream().mapToLong(wp -> wp.getMinuteStats().total().getHealing()).sum())).create()));
    sendCenteredHoverableMessageToAllGamePlayer(game, Collections.singletonList(totalHealing));
    players = players.stream().sorted(Comparator.comparing((WarlordsPlayer wp) -> wp.getMinuteStats().total().getHealing()).reversed()).collect(Collectors.toList());
    List<TextComponent> leaderboardPlayersHealing = new ArrayList<>();
    for (int i = 0; i < players.size() && i < 3; i++) {
        WarlordsPlayer warlordsPlayer = players.get(i);
        TextComponent player = new TextComponent(ChatColor.AQUA + warlordsPlayer.getName() + ChatColor.GRAY + ": " + ChatColor.GOLD + NumberFormat.getSimplifiedNumber(warlordsPlayer.getMinuteStats().total().getHealing()));
        player.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.DARK_GRAY + "Lv" + ChatColor.GRAY + ExperienceManager.getLevelForSpec(warlordsPlayer.getUuid(), warlordsPlayer.getSpecClass()) + " " + ChatColor.GOLD + warlordsPlayer.getSpec().getClassName() + ChatColor.GREEN + " (" + warlordsPlayer.getSpec().getClass().getSimpleName() + ")").create()));
        leaderboardPlayersHealing.add(player);
        if (i != players.size() - 1 && i != 2) {
            leaderboardPlayersHealing.add(ChatUtils.SPACER);
        }
    }
    sendCenteredHoverableMessageToAllGamePlayer(game, leaderboardPlayersHealing);
    sendMessageToAllGamePlayer(game, "", false);
    TextComponent yourStatistics = new TextComponent("" + ChatColor.GOLD + ChatColor.BOLD + "✚ YOUR STATISTICS ✚");
    yourStatistics.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.WHITE + "Total Kills (everyone): " + ChatColor.GREEN + NumberFormat.addCommaAndRound(players.stream().mapToInt(wp -> wp.getMinuteStats().total().getKills()).sum()) + "\n" + ChatColor.WHITE + "Total Assists (everyone): " + ChatColor.GREEN + NumberFormat.addCommaAndRound(players.stream().mapToInt(wp -> wp.getMinuteStats().total().getAssists()).sum()) + "\n" + ChatColor.WHITE + "Total Deaths (everyone): " + ChatColor.GREEN + NumberFormat.addCommaAndRound(players.stream().mapToInt(wp -> wp.getMinuteStats().total().getDeaths()).sum())).create()));
    sendCenteredHoverableMessageToAllGamePlayer(game, Collections.singletonList(yourStatistics));
    for (WarlordsPlayer wp : PlayerFilter.playingGame(game)) {
        Player player = Bukkit.getPlayer(wp.getUuid());
        if (player == null)
            continue;
        TextComponent kills = new TextComponent(ChatColor.WHITE + "Kills: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getKills()));
        TextComponent assists = new TextComponent(ChatColor.WHITE + "Assists: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getAssists()));
        TextComponent deaths = new TextComponent(ChatColor.WHITE + "Deaths: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getDeaths()));
        kills.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Kills")).create()));
        assists.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Assists")).create()));
        deaths.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Deaths")).create()));
        ChatUtils.sendCenteredMessageWithEvents(player, Arrays.asList(kills, ChatUtils.SPACER, assists, ChatUtils.SPACER, deaths));
        TextComponent damage = new TextComponent(ChatColor.WHITE + "Damage: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getDamage()));
        TextComponent heal = new TextComponent(ChatColor.WHITE + "Healing: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getHealing()));
        TextComponent absorb = new TextComponent(ChatColor.WHITE + "Absorbed: " + ChatColor.GOLD + NumberFormat.addCommaAndRound(wp.getMinuteStats().total().getAbsorbed()));
        damage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Damage")).create()));
        heal.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Healing")).create()));
        absorb.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(wp.getStatString("Absorbed")).create()));
        ChatUtils.sendCenteredMessageWithEvents(player, Arrays.asList(damage, ChatUtils.SPACER, heal, ChatUtils.SPACER, absorb));
        player.setGameMode(GameMode.ADVENTURE);
        player.setAllowFlight(true);
        if (!game.getAddons().contains(GameAddon.IMPOSTER_MODE)) {
            if (winEvent == null || winEvent.getDeclaredWinner() == null) {
                player.playSound(player.getLocation(), "defeat", 500, 1);
                PacketUtils.sendTitle(player, "§d§lDRAW", "", 0, 100, 0);
            } else if (wp.getTeam() == winEvent.getDeclaredWinner()) {
                player.playSound(player.getLocation(), "victory", 500, 1);
                PacketUtils.sendTitle(player, "§6§lVICTORY!", "", 0, 100, 0);
            } else {
                player.playSound(player.getLocation(), "defeat", 500, 1);
                PacketUtils.sendTitle(player, "§c§lDEFEAT", "", 0, 100, 0);
            }
        }
    }
    if (game.playersCount() >= 12 && previousGames.get(previousGames.size() - 1).isCounted()) {
        sendMessageToAllGamePlayer(game, "", false);
        sendMessageToAllGamePlayer(game, ChatColor.YELLOW.toString() + ChatColor.BOLD + "✚ EXPERIENCE SUMMARY ✚", true);
        for (WarlordsPlayer wp : PlayerFilter.playingGame(game)) {
            Player player = Bukkit.getPlayer(wp.getUuid());
            if (player == null)
                continue;
            LinkedHashMap<String, Long> expSummary = ExperienceManager.getExpFromGameStats(wp, false);
            long experienceEarnedUniversal = expSummary.values().stream().mapToLong(Long::longValue).sum();
            long experienceEarnedSpec = ExperienceManager.getSpecExpFromSummary(expSummary);
            long experienceOnSpec = ExperienceManager.getExperienceForSpec(wp.getUuid(), wp.getSpecClass());
            long experienceUniversal = ExperienceManager.getUniversalLevel(wp.getUuid());
            StringBuilder specExpSummary = new StringBuilder();
            StringBuilder universalExpSummary = new StringBuilder();
            expSummary.forEach((s, aLong) -> {
                if (!s.equals("First Game of the Day") && !s.equals("Second Game of the Day") && !s.equals("Third Game of the Day")) {
                    specExpSummary.append(ChatColor.AQUA).append(s).append(ChatColor.WHITE).append(": ").append(ChatColor.DARK_GRAY).append("+").append(ChatColor.DARK_GREEN).append(aLong).append("\n");
                }
                universalExpSummary.append(ChatColor.AQUA).append(s).append(ChatColor.WHITE).append(": ").append(ChatColor.DARK_GRAY).append("+").append(ChatColor.DARK_GREEN).append(aLong).append("\n");
            });
            specExpSummary.setLength(specExpSummary.length() - 1);
            universalExpSummary.setLength(universalExpSummary.length() - 1);
            TextComponent classSpecExp = new TextComponent(ChatColor.GRAY + "+" + ChatColor.DARK_GREEN + NumberFormat.addCommaAndRound(experienceEarnedSpec) + " " + ChatColor.GOLD + wp.getSpec().getClassName() + " Experience " + ChatColor.GRAY + "(" + wp.getSpecClass().specType.chatColor + wp.getSpecClass().name + ChatColor.GRAY + ")");
            classSpecExp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(specExpSummary.toString()).create()));
            ChatUtils.sendCenteredMessageWithEvents(player, Collections.singletonList(classSpecExp));
            ExperienceManager.giveLevelUpMessage(player, experienceOnSpec, experienceOnSpec + experienceEarnedSpec);
            TextComponent universalExp = new TextComponent(ChatColor.GRAY + "+" + ChatColor.DARK_AQUA + NumberFormat.addCommaAndRound(experienceEarnedUniversal) + " " + ChatColor.GOLD + "Universal Experience ");
            universalExp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(universalExpSummary.toString()).create()));
            ChatUtils.sendCenteredMessageWithEvents(player, Collections.singletonList(universalExp));
            ExperienceManager.giveLevelUpMessage(player, experienceUniversal, experienceUniversal + experienceEarnedUniversal);
        }
    }
    sendMessageToAllGamePlayer(game, "" + ChatColor.GREEN + ChatColor.BOLD + "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬", false);
}
Also used : TextComponent(net.md_5.bungee.api.chat.TextComponent) HoverEvent(net.md_5.bungee.api.chat.HoverEvent) GameAddon(com.ebicep.warlords.game.GameAddon) java.util(java.util) PacketUtils(com.ebicep.warlords.util.bukkit.PacketUtils) Team(com.ebicep.warlords.game.Team) DatabaseGameBase.previousGames(com.ebicep.warlords.database.repositories.games.pojos.DatabaseGameBase.previousGames) Player(org.bukkit.entity.Player) ChatUtils(com.ebicep.warlords.util.chat.ChatUtils) NumberFormat(com.ebicep.warlords.util.java.NumberFormat) Collectors(java.util.stream.Collectors) PlayerFilter(com.ebicep.warlords.util.warlords.PlayerFilter) WarlordsGameTriggerWinEvent(com.ebicep.warlords.events.WarlordsGameTriggerWinEvent) TextComponent(net.md_5.bungee.api.chat.TextComponent) ComponentBuilder(net.md_5.bungee.api.chat.ComponentBuilder) GameMode(org.bukkit.GameMode) Game(com.ebicep.warlords.game.Game) ExperienceManager(com.ebicep.warlords.player.ExperienceManager) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) ChatColor(org.bukkit.ChatColor) Option(com.ebicep.warlords.game.option.Option) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Bukkit(org.bukkit.Bukkit) HoverEvent(net.md_5.bungee.api.chat.HoverEvent) Player(org.bukkit.entity.Player) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) WarlordsPlayer(com.ebicep.warlords.player.WarlordsPlayer) Option(com.ebicep.warlords.game.option.Option) ComponentBuilder(net.md_5.bungee.api.chat.ComponentBuilder)

Example 9 with Game

use of com.ebicep.warlords.game.Game in project Warlords by ebicep.

the class PreLobbyState method run.

@Override
public State run() {
    if (hasEnoughPlayers() || timerHasBeenSkipped) {
        timerHasBeenSkipped = false;
        if (timer % 20 == 0) {
            int time = timer / 20;
            game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                giveLobbyScoreboard(false, player);
                player.setAllowFlight(false);
            });
            if (time == 30) {
                game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                    sendMessage(player, false, ChatColor.YELLOW + "The game starts in " + ChatColor.GREEN + "30 " + ChatColor.YELLOW + "seconds!");
                    player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1, 1);
                });
            } else if (time == 20) {
                game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                    sendMessage(player, false, ChatColor.YELLOW + "The game starts in 20 seconds!");
                    player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1, 1);
                });
            } else if (time == 10) {
                game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                    sendMessage(player, false, ChatColor.YELLOW + "The game starts in " + ChatColor.GOLD + "10 " + ChatColor.YELLOW + "seconds!");
                    player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1, 1);
                });
            } else if (time <= 5 && time != 0) {
                game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                    String s = time == 1 ? "!" : "s!";
                    sendMessage(player, false, ChatColor.YELLOW + "The game starts in " + ChatColor.RED + time + ChatColor.YELLOW + " second" + s);
                    player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1, 1);
                });
            } else if (time == 0) {
                game.forEachOnlinePlayerWithoutSpectators((player, team) -> {
                    player.playSound(player.getLocation(), "gamestart", 1, 1);
                    player.setAllowFlight(false);
                });
            }
        }
        if (timer <= 0) {
            // this is needed for when we support more teams in the future
            if (!game.getAddons().contains(GameAddon.PRIVATE_GAME)) {
                // separating internalPlayers into even teams because it might be uneven bc internalPlayers couldve left
                // balancing based on specs
                // parties first
                int sameTeamPartyLimit = 2;
                HashMap<Team, List<Player>> partyMembers = new HashMap<Team, List<Player>>() {

                    {
                        put(Team.BLUE, new ArrayList<>());
                        put(Team.RED, new ArrayList<>());
                    }
                };
                game.onlinePlayersWithoutSpectators().filter(e -> e.getValue() != null).forEach(e -> {
                    Player player = e.getKey();
                    Team team = e.getValue();
                    // TODO Test this logic if player are not online if this happens (we do not have player objects in this case)
                    if (partyMembers.values().stream().anyMatch(list -> list.contains(player))) {
                        return;
                    }
                    Warlords.partyManager.getPartyFromAny(player.getUniqueId()).ifPresent(party -> {
                        List<Player> partyPlayersInGame = party.getAllPartyPeoplePlayerOnline().stream().filter(p -> game.getPlayers().containsKey(p.getUniqueId())).collect(Collectors.toList());
                        // check if party has more than limit to get on one team, if so then skip party, they get normally balanced
                        if (partyPlayersInGame.size() > sameTeamPartyLimit) {
                            return;
                        }
                        List<Player> bluePlayers = partyMembers.get(Team.BLUE);
                        List<Player> redPlayers = partyMembers.get(Team.RED);
                        List<Player> partyPlayers = new ArrayList<>(partyPlayersInGame);
                        Collections.shuffle(partyPlayers);
                        int teamSizeDiff = Math.abs(bluePlayers.size() - redPlayers.size());
                        // check if whole party can go on the same team to get an even amount of internalPlayers on each team
                        if (teamSizeDiff > partyPlayers.size()) {
                            if (bluePlayers.size() > redPlayers.size())
                                bluePlayers.addAll(partyPlayers);
                            else
                                redPlayers.addAll(partyPlayers);
                        } else {
                            bluePlayers.addAll(partyPlayers);
                        }
                    });
                });
                HashMap<String, Integer> playersSR = new HashMap<>();
                SRCalculator.playersSR.forEach((key, value1) -> playersSR.put(key.getUuid(), value1 == null ? 500 : value1));
                HashMap<Player, Team> bestTeam = new HashMap<>();
                int bestBlueSR = 0;
                int bestRedSR = 0;
                int bestTeamSRDifference = Integer.MAX_VALUE;
                int maxSRDiff = 200;
                for (int i = 0; i < 5000; i++) {
                    HashMap<Player, Team> teams = new HashMap<>();
                    HashMap<Classes, List<Player>> playerSpecs = new HashMap<>();
                    game.onlinePlayersWithoutSpectators().filter(e -> e.getValue() != null).forEach(e -> {
                        Player player = e.getKey();
                        Team team = e.getValue();
                        PlayerSettings playerSettings = Warlords.getPlayerSettings(player.getUniqueId());
                        playerSpecs.computeIfAbsent(playerSettings.getSelectedClass(), v -> new ArrayList<>()).add(player);
                    });
                    // specs that dont have an even amount of players to redistribute later
                    List<Player> playersLeft = new ArrayList<>();
                    // distributing specs evenly
                    playerSpecs.forEach((classes, playerList) -> {
                        int amountOfTargetSpecsOnBlue = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE && Warlords.getPlayerSettings(playerTeamEntry.getKey().getUniqueId()).getSelectedClass() == classes).count();
                        int amountOfTargetSpecsOnRed = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED && Warlords.getPlayerSettings(playerTeamEntry.getKey().getUniqueId()).getSelectedClass() == classes).count();
                        for (Player player : playerList) {
                            // add to red team
                            if (amountOfTargetSpecsOnBlue > amountOfTargetSpecsOnRed) {
                                teams.put(player, Team.RED);
                                amountOfTargetSpecsOnRed++;
                            } else // add to blue team
                            if (amountOfTargetSpecsOnRed > amountOfTargetSpecsOnBlue) {
                                teams.put(player, Team.BLUE);
                                amountOfTargetSpecsOnBlue++;
                            } else // same amount on each team - add to playersleft to redistribute
                            {
                                playersLeft.add(player);
                            }
                        }
                    });
                    // start on team with least amount of players
                    int blueSR = teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE).mapToInt(value -> playersSR.getOrDefault(value.getKey().getUniqueId().toString(), 500)).sum();
                    int redSR = teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED).mapToInt(value -> playersSR.getOrDefault(value.getKey().getUniqueId().toString(), 500)).sum();
                    // .collect(Collectors.toList());
                    for (Player player : playersLeft) {
                        if (redSR > blueSR) {
                            teams.put(player, Team.BLUE);
                            blueSR += playersSR.getOrDefault(player.getUniqueId().toString(), 500);
                        } else {
                            teams.put(player, Team.RED);
                            redSR += playersSR.getOrDefault(player.getUniqueId().toString(), 500);
                        }
                    }
                    int bluePlayers = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE).count();
                    int redPlayers = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED).count();
                    // uneven teams
                    if ((bluePlayers + redPlayers) % 2 != 0) {
                        int srDiffRed = Math.abs(redSR - 3500 - blueSR);
                        int srDiffBlue = Math.abs(blueSR - 3500 - redSR);
                        if ((bluePlayers > redPlayers && srDiffRed > maxSRDiff && srDiffRed > 0) || (redPlayers > bluePlayers && srDiffBlue > maxSRDiff && srDiffBlue > 0)) {
                            maxSRDiff++;
                            continue;
                        }
                    } else {
                        if (Math.abs(redSR - blueSR) > maxSRDiff) {
                            maxSRDiff++;
                            continue;
                        }
                    }
                    if (Math.abs(bluePlayers - redPlayers) > 1) {
                        maxSRDiff++;
                        continue;
                    }
                    if (Math.abs(redSR - blueSR) < bestTeamSRDifference) {
                        bestTeam = teams;
                        bestBlueSR = blueSR;
                        bestRedSR = redSR;
                        bestTeamSRDifference = Math.abs(redSR - blueSR);
                    }
                }
                boolean failSafeActive = false;
                boolean secondFailSafeActive = false;
                // INCASE COULDNT BALANCE
                if (bestTeam.isEmpty()) {
                    failSafeActive = true;
                    HashMap<Player, Team> teams = new HashMap<>();
                    HashMap<Classes, List<Player>> playerSpecs = new HashMap<>();
                    // all players are online or else they wouldve been removed from queue
                    game.onlinePlayersWithoutSpectators().filter(e -> e.getValue() != null).forEach(e -> {
                        Player player = e.getKey();
                        Team team = e.getValue();
                        PlayerSettings playerSettings = Warlords.getPlayerSettings(player.getUniqueId());
                        playerSpecs.computeIfAbsent(playerSettings.getSelectedClass(), v -> new ArrayList<>()).add(player);
                    });
                    List<Player> playersLeft = new ArrayList<>();
                    // distributing specs evenly
                    playerSpecs.forEach((classes, playerList) -> {
                        int amountOfTargetSpecsOnBlue = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE && Warlords.getPlayerSettings(playerTeamEntry.getKey().getUniqueId()).getSelectedClass() == classes).count();
                        int amountOfTargetSpecsOnRed = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED && Warlords.getPlayerSettings(playerTeamEntry.getKey().getUniqueId()).getSelectedClass() == classes).count();
                        for (Player player : playerList) {
                            // add to red team
                            if (amountOfTargetSpecsOnBlue > amountOfTargetSpecsOnRed) {
                                teams.put(player, Team.RED);
                                amountOfTargetSpecsOnRed++;
                            } else // add to blue team
                            if (amountOfTargetSpecsOnRed > amountOfTargetSpecsOnBlue) {
                                teams.put(player, Team.BLUE);
                                amountOfTargetSpecsOnBlue++;
                            } else // same amount on each team - add to playersleft to redistribute
                            {
                                playersLeft.add(player);
                            }
                        }
                    });
                    // start on team with least amount of players
                    int amountOnBlue = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE).count();
                    int amountOnRed = (int) teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED).count();
                    final boolean[] toBlueTeam = { amountOnBlue <= amountOnRed };
                    playersLeft.stream().sorted(Comparator.comparing(o -> Warlords.getPlayerSettings(o.getUniqueId()).getSelectedClass().specType)).forEachOrdered(player -> {
                        if (toBlueTeam[0]) {
                            teams.put(player, Team.BLUE);
                        } else {
                            teams.put(player, Team.RED);
                        }
                        toBlueTeam[0] = !toBlueTeam[0];
                    });
                    bestTeam = teams;
                    bestBlueSR = teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE).mapToInt(value -> playersSR.getOrDefault(value.getKey().getUniqueId().toString(), 500)).sum();
                    bestRedSR = teams.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED).mapToInt(value -> playersSR.getOrDefault(value.getKey().getUniqueId().toString(), 500)).sum();
                    bestTeamSRDifference = Math.abs(bestBlueSR - bestRedSR);
                }
                if (bestTeamSRDifference > 5000) {
                    secondFailSafeActive = true;
                    HashMap<Player, Team> teams = new HashMap<>();
                    HashMap<Classes, List<Player>> playerSpecs = new HashMap<>();
                    game.onlinePlayersWithoutSpectators().filter(e -> e.getValue() != null).forEach(e -> {
                        Player player = e.getKey();
                        Team team = e.getValue();
                        PlayerSettings playerSettings = Warlords.getPlayerSettings(player.getUniqueId());
                        playerSpecs.computeIfAbsent(playerSettings.getSelectedClass(), v -> new ArrayList<>()).add(player);
                    });
                    int blueSR = 0;
                    int redSR = 0;
                    for (List<Player> value : playerSpecs.values()) {
                        for (Player player : value) {
                            if (blueSR > redSR) {
                                teams.put(player, Team.RED);
                                redSR += playersSR.getOrDefault(player.getUniqueId().toString(), 500);
                            } else {
                                teams.put(player, Team.BLUE);
                                blueSR += playersSR.getOrDefault(player.getUniqueId().toString(), 500);
                            }
                        }
                    }
                    bestTeam = teams;
                    bestBlueSR = blueSR;
                    bestRedSR = redSR;
                    bestTeamSRDifference = Math.abs(bestBlueSR - bestRedSR);
                }
                bestTeam.forEach((player, team) -> {
                    game.setPlayerTeam(player, team);
                    ArmorManager.resetArmor(player, Warlords.getPlayerSettings(player.getUniqueId()).getSelectedClass(), team);
                    LobbyLocationMarker location = LobbyLocationMarker.getFirstLobbyLocation(game, team);
                    if (location != null) {
                        player.teleport(location.getLocation());
                    }
                });
                int bluePlayers = (int) bestTeam.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.BLUE).count();
                int redPlayers = (int) bestTeam.entrySet().stream().filter(playerTeamEntry -> playerTeamEntry.getValue() == Team.RED).count();
                for (Map.Entry<UUID, Team> uuidTeamEntry : game.getPlayers().entrySet()) {
                    Player value = Bukkit.getPlayer(uuidTeamEntry.getKey());
                    if (value == null)
                        continue;
                    if (value.hasPermission(WARLORDS_DATABASE_MESSAGEFEED)) {
                        value.sendMessage(ChatColor.DARK_AQUA + "----- BALANCE INFORMATION -----");
                        value.sendMessage(ChatColor.GREEN + "Max SR Diff: " + maxSRDiff);
                        value.sendMessage(ChatColor.GREEN + "SR Diff: " + bestTeamSRDifference);
                        value.sendMessage(ChatColor.BLUE + "Blue Players: " + ChatColor.GOLD + bluePlayers + ChatColor.GRAY + " - " + ChatColor.BLUE + "SR: " + ChatColor.GOLD + bestBlueSR);
                        value.sendMessage(ChatColor.RED + "Red Players: " + ChatColor.GOLD + redPlayers + ChatColor.GRAY + " - " + ChatColor.RED + "SR: " + ChatColor.GOLD + bestRedSR);
                        value.sendMessage(ChatColor.GREEN + "Fail Safe: " + ChatColor.GOLD + failSafeActive);
                        value.sendMessage(ChatColor.GREEN + "Second Fail Safe: " + ChatColor.GOLD + secondFailSafeActive);
                        value.sendMessage(ChatColor.DARK_AQUA + "-------------------------------");
                        bestTeam.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(playerTeamEntry -> {
                            Classes classes = Warlords.getPlayerSettings(playerTeamEntry.getKey().getUniqueId()).getSelectedClass();
                            value.sendMessage(playerTeamEntry.getValue().teamColor() + playerTeamEntry.getKey().getName() + ChatColor.GRAY + " - " + classes.specType.chatColor + classes.name + ChatColor.GRAY + " - " + ChatColor.GOLD + playersSR.get(playerTeamEntry.getKey().getUniqueId().toString()));
                        });
                        value.sendMessage(ChatColor.DARK_AQUA + "-------------------------------");
                    }
                }
            }
            if (game.getPlayers().size() >= 14) {
                boolean isPrivate = game.getAddons().contains(GameAddon.PRIVATE_GAME);
                BotManager.sendMessageToNotificationChannel("[GAME] A " + (isPrivate ? "" : "Public ") + "**" + game.getMap().getMapName() + "** started with **" + game.getPlayers().size() + (game.getPlayers().size() == 1 ? "** player!" : "** players!"), isPrivate, !isPrivate);
            }
            return new PlayingState(game);
        }
        timer--;
    } else {
        resetTimer();
        game.forEachOnlinePlayerWithoutSpectators((player, team) -> giveLobbyScoreboard(false, player));
    }
    return null;
}
Also used : BotManager(com.ebicep.jda.BotManager) PreGameItemOption(com.ebicep.warlords.game.option.PreGameItemOption) Utils(com.ebicep.warlords.util.warlords.Utils) GameAddon(com.ebicep.warlords.game.GameAddon) java.util(java.util) Team(com.ebicep.warlords.game.Team) SimpleDateFormat(java.text.SimpleDateFormat) Warlords(com.ebicep.warlords.Warlords) SRCalculator(com.ebicep.warlords.sr.SRCalculator) Player(org.bukkit.entity.Player) Collectors(java.util.stream.Collectors) org.bukkit(org.bukkit) com.ebicep.warlords.player(com.ebicep.warlords.player) Game(com.ebicep.warlords.game.Game) LobbyLocationMarker(com.ebicep.warlords.game.option.marker.LobbyLocationMarker) ChatUtils.sendMessage(com.ebicep.warlords.util.chat.ChatUtils.sendMessage) Option(com.ebicep.warlords.game.option.Option) LobbyLocationMarker(com.ebicep.warlords.game.option.marker.LobbyLocationMarker) Player(org.bukkit.entity.Player) Team(com.ebicep.warlords.game.Team)

Example 10 with Game

use of com.ebicep.warlords.game.Game in project Warlords by ebicep.

the class DebugMenuPlayerOptions method openTeleportLocations.

public static void openTeleportLocations(Player player, WarlordsPlayer target) {
    Menu menu = new Menu("Teleport To: " + target.getName(), 9 * 5);
    Game game = target.getGame();
    int x = 0;
    int y = 0;
    for (DebugLocationMarker marker : game.getMarkers(DebugLocationMarker.class)) {
        menu.setItem(x, y, marker.getAsItem(), (m, e) -> {
            target.teleport(marker.getLocation());
            player.sendMessage(ChatColor.RED + "DEV: " + target.getColoredName() + "§a was teleported to " + marker.getName());
        });
        x++;
        if (x > 8) {
            x = 0;
            y++;
        }
    }
    menu.setItem(3, 4, MENU_BACK, (m, e) -> openPlayerMenu(player, target));
    menu.setItem(4, 4, MENU_CLOSE, ACTION_CLOSE_MENU);
    menu.openForPlayer(player);
}
Also used : Game(com.ebicep.warlords.game.Game) DebugLocationMarker(com.ebicep.warlords.game.option.marker.DebugLocationMarker) Menu(com.ebicep.warlords.menu.Menu)

Aggregations

Game (com.ebicep.warlords.game.Game)25 Team (com.ebicep.warlords.game.Team)15 ChatColor (org.bukkit.ChatColor)13 Warlords (com.ebicep.warlords.Warlords)12 WarlordsPlayer (com.ebicep.warlords.player.WarlordsPlayer)12 Nonnull (javax.annotation.Nonnull)12 Nullable (javax.annotation.Nullable)12 Player (org.bukkit.entity.Player)11 GameRunnable (com.ebicep.warlords.util.warlords.GameRunnable)9 java.util (java.util)8 GameAddon (com.ebicep.warlords.game.GameAddon)7 Utils (com.ebicep.warlords.util.warlords.Utils)7 ScoreboardHandler (com.ebicep.warlords.game.option.marker.scoreboard.ScoreboardHandler)6 PacketUtils (com.ebicep.warlords.util.bukkit.PacketUtils)6 PlayerFilter (com.ebicep.warlords.util.warlords.PlayerFilter)6 Location (org.bukkit.Location)6 WarlordsGameTriggerWinEvent (com.ebicep.warlords.events.WarlordsGameTriggerWinEvent)5 GameHolder (com.ebicep.warlords.game.GameManager.GameHolder)5 SimpleScoreboardHandler (com.ebicep.warlords.game.option.marker.scoreboard.SimpleScoreboardHandler)5 PlayingState (com.ebicep.warlords.game.state.PlayingState)5