aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/cowtipper/cowlection/handler/DungeonCache.java
blob: e06ba7d5ab09d02882407974d38a158089456f55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package de.cowtipper.cowlection.handler;

import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import de.cowtipper.cowlection.Cowlection;
import de.cowtipper.cowlection.util.TickDelay;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiPlayerTabOverlay;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.WorldSettings;

import java.util.*;
import java.util.stream.Collectors;

public class DungeonCache {
    private static final Ordering<NetworkPlayerInfo> playerOrderer = Ordering.from(new PlayerComparator());

    private final Cowlection main;
    private final Map<String, Integer> deathCounter;
    private final Set<String> deadPlayers;
    private final Set<String> failedPuzzles;
    private final Set<UUID> destroyedCrypts;
    private int cryptsOffset;

    private boolean isInDungeon;
    private int elapsedMinutes;
    private int classMilestone;
    private long lastScoreboardCheck;
    private long nextPerformanceSend;
    private String queuedFloor;

    public DungeonCache(Cowlection main) {
        this.main = main;
        deathCounter = new HashMap<>();
        deadPlayers = new HashSet<>();
        failedPuzzles = new HashSet<>();
        destroyedCrypts = new HashSet<>();
        cryptsOffset = 0;
    }

    public boolean isInDungeon() {
        return isInDungeon;
    }

    public void onDungeonEnterOrLeave(boolean isInDungeonNow) {
        boolean wasInDungeon = isInDungeon;

        if (!wasInDungeon && isInDungeonNow) {
            onDungeonEntered();
        } else if (wasInDungeon && !isInDungeonNow) {
            onDungeonLeft();
        }
    }

    public void onDungeonEntered() {
        main.getLogger().info("Entered SkyBlock Dungeon!");
        isInDungeon = true;
        resetCounters();
    }

    public void onDungeonLeft() {
        main.getLogger().info("Leaving SkyBlock Dungeon!");
        isInDungeon = false;
        resetCounters();
    }

    public void sendDungeonPerformance() {
        if (System.currentTimeMillis() < nextPerformanceSend) {
            // already sent dungeon performance less than 260ms ago
            return;
        }
        String dungeonPerformance;
        boolean hasPointPenalty = false;
        if (deathCounter.isEmpty()) {
            dungeonPerformance = EnumChatFormatting.GOLD + "☠ Deaths: " + EnumChatFormatting.WHITE + "none \\o/";
        } else {
            hasPointPenalty = true;
            String deaths = deathCounter.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).map(deathEntry -> "  " + EnumChatFormatting.WHITE + deathEntry.getKey() + ": " + EnumChatFormatting.LIGHT_PURPLE + deathEntry.getValue())
                    .collect(Collectors.joining("\n"));
            dungeonPerformance = EnumChatFormatting.RED + "☠ " + EnumChatFormatting.BOLD + "Deaths: " + EnumChatFormatting.DARK_RED + "-" + (getTotalDeaths() * 2) + " Skill points\n" + deaths;
        }
        if (failedPuzzles.size() > 0) {
            hasPointPenalty = true;
            dungeonPerformance += "\n" + EnumChatFormatting.RED + "Failed puzzles: " + EnumChatFormatting.LIGHT_PURPLE + failedPuzzles.size() + EnumChatFormatting.RED + " (" + EnumChatFormatting.DARK_RED + "-" + failedPuzzles.size() * 14 + " Skill points" + EnumChatFormatting.RED + ")";
        }

        if (hasPointPenalty) {
            dungeonPerformance += "\n" + EnumChatFormatting.LIGHT_PURPLE + "➜ " + EnumChatFormatting.RED + EnumChatFormatting.BOLD + "Skill " + EnumChatFormatting.RED + "score penalty: " + EnumChatFormatting.DARK_RED + getSkillScorePenalty() + " points";
        }
        main.getChatHelper().sendMessage(EnumChatFormatting.WHITE, dungeonPerformance);
        nextPerformanceSend = System.currentTimeMillis() + 260;
    }

    /**
     * Fetch info from scoreboard (right) and tab list
     */
    public void fetchScoreboardData() {
        long now = System.currentTimeMillis();
        if (now - lastScoreboardCheck > 10000) { // run every 10 seconds
            lastScoreboardCheck = now;
            Minecraft mc = Minecraft.getMinecraft();
            if (mc.theWorld != null) {
                Scoreboard scoreboard = mc.theWorld.getScoreboard();

                // check scoreboard (right)
                ScoreObjective scoreboardSidebar = scoreboard.getObjectiveInDisplaySlot(1);
                if (scoreboardSidebar != null) {
                    Collection<Score> scoreboardLines = scoreboard.getSortedScores(scoreboardSidebar);
                    for (Score line : scoreboardLines) {
                        ScorePlayerTeam scorePlayerTeam = scoreboard.getPlayersTeam(line.getPlayerName());
                        if (scorePlayerTeam != null) {
                            String lineWithoutFormatting = EnumChatFormatting.getTextWithoutFormattingCodes(scorePlayerTeam.getColorPrefix() + scorePlayerTeam.getColorSuffix());

                            String timeElapsed = "Time Elapsed: ";
                            if (lineWithoutFormatting.startsWith(timeElapsed)) {
                                // dungeon timer: 05m 22s
                                String timeString = lineWithoutFormatting.substring(timeElapsed.length());
                                try {
                                    int indexOfMinute = timeString.indexOf('m');
                                    if (indexOfMinute > -1) {
                                        elapsedMinutes = (Integer.parseInt(timeString.substring(0, indexOfMinute)));
                                    }
                                } catch (NumberFormatException ex) {
                                    // couldn't parse dungeon time from scoreboard
                                    ex.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }

            // check tab list
            Collection<NetworkPlayerInfo> playerInfoMap = mc.thePlayer.sendQueue.getPlayerInfoMap();
            List<NetworkPlayerInfo> networkPlayerInfos = playerOrderer.sortedCopy(playerInfoMap);
            GuiPlayerTabOverlay tabList = mc.ingameGUI.getTabList();
            for (NetworkPlayerInfo playerInfo : networkPlayerInfos) {
                if (playerInfo.getGameProfile().getName().startsWith("!")) {
                    String tabListEntry = EnumChatFormatting.getTextWithoutFormattingCodes(tabList.getPlayerName(playerInfo));
                    if (tabListEntry != null && tabListEntry.startsWith(" Crypts: ")) {
                        try {
                            int cryptsFromTabList = Integer.parseInt(tabListEntry.substring(" Crypts: ".length()).trim());
                            cryptsOffset = cryptsFromTabList - destroyedCrypts.size();
                        } catch (NumberFormatException | IndexOutOfBoundsException ex) {
                            // couldn't parse crypts count from tab list
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    // setter/adder
    public void setQueuedFloor(String floorNr) {
        this.queuedFloor = floorNr;
    }

    public void addDeath(String playerName) {
        boolean playerWasDeadAlready = !deadPlayers.add(playerName);
        if (playerWasDeadAlready) {
            // dead player "died" again (e.g. caused by disconnecting while being dead); don't count again!
            return;
        }
        int previousPlayerDeaths = deathCounter.getOrDefault(playerName, 0);
        deathCounter.put(playerName, previousPlayerDeaths + 1);

        new TickDelay(this::sendDungeonPerformance, 1);
    }

    public void revivedPlayer(String playerName) {
        deadPlayers.remove(playerName);
    }

    public void addFailedPuzzle(String text) {
        failedPuzzles.add(text);
    }

    public void setClassMilestone(int classMilestone) {
        this.classMilestone = classMilestone;
    }

    public void addDestroyedCrypt(UUID uuid) {
        destroyedCrypts.add(uuid);
    }

    // getter
    public String getQueuedFloor() {
        return queuedFloor;
    }

    public int getMaxSkillScore() {
        return 100 - getSkillScorePenalty();
    }

    private int getSkillScorePenalty() {
        return getTotalDeaths() * 2 + failedPuzzles.size() * 14;
    }

    public int getTotalDeaths() {
        int totalDeaths = 0;
        for (int deathCount : deathCounter.values()) {
            totalDeaths += deathCount;
        }
        return totalDeaths;
    }

    public int getFailedPuzzles() {
        return failedPuzzles.size();
    }

    public int getClassMilestone() {
        return classMilestone;
    }

    public int getDestroyedCrypts() {
        return destroyedCrypts.size() + cryptsOffset;
    }

    public int getElapsedMinutes() {
        return elapsedMinutes;
    }

    // resetter
    private void resetCounters() {
        deathCounter.clear();
        deadPlayers.clear();
        failedPuzzles.clear();
        destroyedCrypts.clear();
        cryptsOffset = 0;
        elapsedMinutes = 0;
        classMilestone = 0;
        nextPerformanceSend = 0;
        queuedFloor = null;
    }

    /**
     * see: GuiPlayerTabOverlay.PlayerComparator
     */
    static class PlayerComparator implements Comparator<NetworkPlayerInfo> {
        private PlayerComparator() {
        }

        public int compare(NetworkPlayerInfo playerInfo1, NetworkPlayerInfo playerInfo2) {
            ScorePlayerTeam scorePlayerTeam1 = playerInfo1.getPlayerTeam();
            ScorePlayerTeam scorePlayerTeam2 = playerInfo2.getPlayerTeam();
            return ComparisonChain.start().compareTrueFirst(playerInfo1.getGameType() != WorldSettings.GameType.SPECTATOR, playerInfo2.getGameType() != WorldSettings.GameType.SPECTATOR).compare(scorePlayerTeam1 != null ? scorePlayerTeam1.getRegisteredName() : "", scorePlayerTeam2 != null ? scorePlayerTeam2.getRegisteredName() : "").compare(playerInfo1.getGameProfile().getName(), playerInfo2.getGameProfile().getName()).result();
        }
    }
}