diff --git a/.github/workflows/code_quality.yml b/.github/workflows/code_quality.yml new file mode 100644 index 000000000..b3e26625a --- /dev/null +++ b/.github/workflows/code_quality.yml @@ -0,0 +1,29 @@ +name: Qodana +on: + workflow_dispatch: + pull_request: + push: + +permissions: + contents: write + pull-requests: write + checks: write + +jobs: + qodana: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + checks: write + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} # to check out the actual pull request commit, not the merge commit + fetch-depth: 0 # a full history is required for pull request analysis + - name: 'Qodana Scan' + uses: JetBrains/qodana-action@v2024.3 + env: + QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }} + with: + push-fixes: pull-request diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index adbec510a..27375443d 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -12,17 +12,18 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up JDK 17 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: java-version: 17 + distribution: corretto - name: Build with Maven env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: mvn -B package --file pom.xml - name: Capture build artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: Artifacts path: | diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml deleted file mode 100644 index fe725d137..000000000 --- a/.github/workflows/qodana.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Qodana - Code Inspection -on: - push: - -jobs: - qodana: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Qodana Scan - uses: JetBrains/qodana-action@v4.2.2 \ No newline at end of file diff --git a/language/files/de.json b/language/files/de.json index d92a6884a..db6acbadb 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1,1846 +1,1866 @@ { - "syntax": "Bitte nutze §e/{0}", - "reload": "Challenges Plugin wird neu geladen...", - "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", - "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", - "player-command": "Dazu musst du ein Spieler sein!", - "no-permission": "Dazu hast du §ckeine §7Rechte", - "enabled": "§aAktiviert", - "disabled": "§cDeaktiviert", - "customize": "§6Anpassen", - "navigate-back": "§8« §7Zurück", - "navigate-next": "§8» §7Weiter", - "seconds": "Sekunden", - "second": "Sekunde", - "minutes": "Minuten", - "minute": "Minute", - "hours": "Stunden", - "hour": "Stunde", - "amplifier": "Stärke", - "open": "Öffnen", - "everyone": "§5Alle", - "player": "§6Aktiver Spieler", - "none": "Nichts", - "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer zählt §ahoch", - "timer-counting-down": "§8» §7Timer zählt §crunter", - "timer-is-paused": "§8» §7Timer ist §cpausiert", - "timer-is-running": "§8» §7Timer ist §agestartet", - "confirm-reset": "Bestätige den Reset mit §e/{0}", - "no-fresh-reset": [ - "Der Server kann §cnicht resettet §7werden", - "Die Challenge wurde §cnoch nicht §7gestartet" - ], - "new-challenge": "§a§lNeu!", - "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", - "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", - "timer-not-started": "Der Timer wurde noch §cnicht gestartet", - "timer-was-started": "Der Timer wurde §agestartet", - "timer-was-paused": "Der Timer wurde §cpausiert", - "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", - "timer-already-started": "Der Timer §cläuft bereits", - "timer-already-paused": "Der Timer ist §cbereits pausiert", - "timer-mode-set-down": "Der Timer zählt nun §crunter", - "timer-mode-set-up": "Der Timer zählt nun §ahoch", - "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", - "fetching-data": "Daten werden abgerufen..", - "undefined": "undefiniert", - "no-such-material": "Dieses Material gibt es nicht", - "not-an-item": "§e{0} §7ist kein Item", - "no-such-entity": "Dieses Entity existiert nicht", - "not-alive": "§e{0} §7ist kein lebendes Entity", - "no-loot": "§e{0} §7hat keine Drops", - "deprecated-plugin-version": [ - " ", - "§7Ein neues Update ist verfügbar!", - "§7Download: §e§l{0}", - " " - ], - "deprecated-config-version": [ - "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", - "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" - ], - "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cEs fehlen keine Einstellungen in der Config.", - "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." - ], - "join-message": "§e{0} §7hat den Server §abetreten", - "quit-message": "§e{0} §7hat den Server §cverlassen", - "timer-paused-message": [ - "Der Timer ist noch §cpausiert", - "Nutze §e/timer resume §7um ihn zu starten" - ], - "cheats-detected": [ - "§e{0} §7hat §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "cheats-already-detected": [ - "Auf diesem Server wurde §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", - "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", - "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", - "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", - "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", - "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Drachen getötet", - "stat-deaths": "Tode", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Schaden ausgeteilt", - "stat-damage-taken": "Schaden genommen", - "stat-blocks-mined": "Blöcke abgebaut", - "stat-blocks-placed": "Blöcke platziert", - "stat-blocks-traveled": "Blöcke gereist", - "stat-challenges-played": "Challenges gespielt", - "stat-jumps": "Sprünge", - "stats-of": "§8» §7Stats von §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Platz" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positionen sind §cdeaktiviert", - "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", - "position-not-exists": "Die Position §e{0} §7existiert §cnicht", - "position-already-exists": "Die Position §e{0} §7existiert §cbereits", - "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", - "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", - "no-positions": [ - "Es sind keine §ePositionen §7in dieser Welt gesetzt", - "Erstelle eine mit §e/{0}" - ], - "no-positions-global": [ - "Es sind keine §ePositionen §7gesetzt", - "Erstelle eine mit §e/{0}" - ], - "command-no-target": "Es wurde §ckein §7Spieler gefunden", - "command-heal-healed": "Du wurdest §ageheilt", - "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", - "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", - "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", - "command-village-search": "Es wird nach einem Dorf gesucht..", - "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", - "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", - "command-weather-set-clear": "Wetter zu §eklar §7geändert", - "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", - "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", - "command-invsee-open": "Inventar von §e{0} §7geöffnet", - "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", - "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", - "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", - "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", - "command-search-result": "§e{0} §7droppt aus §e{1}", - "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", - "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", - "command-searchloot-result": [ - "§e{0} §7droppt den Loot von §e{1}", - "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" - ], - "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", - "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", - "command-time-query": [ - "§8» §7Derzeitige Ingamezeiten", - "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Mittag", - "command-time-night": "Nacht", - "command-time-midnight": "Mitternacht", - "command-time-day": "Tag", - "command-fly-enabled": "Du kannst §anun fliegen", - "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", - "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", - "command-feed-fed": "Dein Hunger wurde §agestillt", - "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", - "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", - "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", - "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", - "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", - "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", - "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", - "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", - "command-god-mode-enabled": "Du bist nun im §aGod-Mode", - "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", - "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", - "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", - "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", - "death-message": "§e{0} §7ist gestorben", - "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", - "health-inverted": "Deine Herzen wurden §cinvertiert", - "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", - "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", - "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", - "death-collected": "Todesgrund §e{0} §7wurde registriert", - "item-collected": "Item §e{0} §7wurde registriert", - "items-to-collect": "§7Items zu sammeln §8» §e{0}", - "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", - "backpack-opened": "Du hast den {0} §7geöffnet", - "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", - "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", - "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", - "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", - "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", - "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", - "only-dirt-failed": "§e{0} §7stand nicht auf Erde", - "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", - "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", - "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", - "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", - "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", - "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", - "sneak-damage-failed": "§e{0} §7ist geschlichen", - "jump-damage-failed": "§e{0} §7ist gesprungen", - "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", - "all-items-skipped": "Item §e{0} §7geskippt", - "all-items-already-finished": "Es wurden bereits alle Items gefunden", - "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", - "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", - "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", - "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", - "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", - "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", - "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", - "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", - "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", - "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", - "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", - "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", - "new-effect": "Effekt §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Welches Item fehlt?", - "missing-items-inventory-open": "§8[§aGUI öffnen§8]", - "loops-cleared": "§e{0} §7Loops abgebrochen", - "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", - "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", - "points-change": "§e{0} §7Punkte", - "force-item-battle-found": "Du hast §e{0} §7gefunden!", - "force-item-battle-new-item": "Item zu suchen: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", - "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "Du hast §e{0} §7gefunden!", - "force-block-battle-new-block": "Block zu suchen: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display":"§eItem: {0}", - "force-battle-height-target-display": "§eHöhe: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiom: {0}", - "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", - "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", - "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", - "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", - "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", - "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", - "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Bist du es?", - "Woahh! Das ist aber schnell" - ], - "random-event-entities": [ - "Ist das hier ein Zoo?", - "Wo kommt ihr denn her?", - "Was macht ihr denn hier?" - ], - "random-event-hole": [ - "Du bist aber ganz schön tief gefallen", - "Von ganz oben nach ganz unten..", - "Wo kommt denn das Loch her?" - ], - "random-event-fly": [ - "Guten Flug :)", - "I believe I can fly..", - "So fühlt sich also fliegen an" - ], - "random-event-webs": [ - "Liegen die schon lange hier?" - ], - "random-event-ores": [ - "Wo sind denn die ganzen Erze hin?", - "Gibt es hier keine Erze?", - "Gab es hier mal Erze?" - ], - "random-event-sickness": [ - "Bist du etwa krank?", - "Was geht denn jetzt ab" - ], - "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", - "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7Alle Items gefunden", - "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", - "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", - "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", - "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", - "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7Sekunden", - "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", - "subtitle-time-minutes": "§e{0} §7Minuten", - "subtitle-launcher-description": "§7Stärke §e{0}", - "subtitle-blocks": "§e{0} §7Blöcke", - "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Dein Platz §8» §e{0}", - "server-reset": [ - "§8————————————————————", - " ", - "§8» §cServerreset", - " ", - "§7Reset durch §4§l{0}", - "§7Der Server startet nun §cneu", - " ", - "§8————————————————————" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Gewinner: §e§l{1}", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", - "§7Zeit verschwendet: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §afortgesetzt" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpausiert" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aAktiviert" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeaktiviert" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Der Timer ist gestoppt.." - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", - "menu-title": "Menu", - "menu-timer": "§6Timer", - "menu-goal": "§5Ziel", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blöcke & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eEinstellungen", - "menu-custom": "§aIndividuelle Challenges", - "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Aktiviert §8» §aJa", - "lore-category-deactivated": "§7Aktiviert §8» §cNein", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-randomizer": [ - "§6Randomizer", - "Erlebe ein komplett", - "*durcheinandergebrachtes* Spiel" - ], - "category-limited_time": [ - "§aLimitierte Zeit", - "Du wirst bei verschiedenen", - "Faktoren *zeitlich eingeschränkt*" - ], - "category-force": [ - "§3Zwischenziele (Force)", - "Du musst *bestimmte Zwischenziele*", - "erfüllen, sonst stirbst du" - ], - "category-world": [ - "§4Weltveränderung", - "Die Welt wird nicht mehr", - "*wiedererkennbar* sein" - ], - "category-damage": [ - "§cSchaden", - "Neue *Schadens Regeln*" - ], - "category-effect": [ - "§5Effekte", - "Erlebe verrückte *Effekte*" - ], - "category-inventory": [ - "§6Inventory", - "Dein Inventar wird *verdreht*" - ], - "category-movement": [ - "§aBewegung", - "Du wirst in deinen Bewegungen *eingeschränkt*" - ], - "category-entities": [ - "§bEntities", - "Entities werden *verändert*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges, die in einer", - "*anderen Welt* spielen" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Ziele, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-kill_entity": [ - "§cEntity töten", - "Töte *bestimmte Entities*,", - "um zu gewinnen" - ], - "category-score_points": [ - "§eMeiste Punkte", - "Erziele die *meisten Punkte* in", - "einem *bestimmten Bereich*." - ], - "category-fastest_time": [ - "§6Schnellste Zeit", - "Sei der *schnellste Spieler*, der", - "das Ziel erfüllt" - ], - "category-force_battle": [ - "§bForce Battles", - "Erfülle die *vorgegebenen Zwischenziele*,", - "um Punkte zu erhalten.", - " ", - "Der Spieler mit den *meisten Punkten* gewinnt." - ], - "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", - "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", - "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Stärke: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", - "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", - "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", - "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", - "item-force-battle-goal-jokers": [ - "§6Anzahl der Joker", - "Die *Anzahl* der *Joker*,", - "die jeder Spieler hat" - ], - "item-force-battle-show-scoreboard": [ - "§bScoreboard anzeigen" - ], - "item-force-battle-duped-targets": [ - "§cDoppelte Ziele", - "Ziele können *mehrfach* vorkommen" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "Der *maximale Radius*, in dem sich die", - "Positionen befinden können" - ], - "item-difficulty-setting": [ - "§aSchwierigkeit", - "Stellt die *Schwierigkeitsstufe* ein" - ], - "item-one-life-setting": [ - "§cEin Teamleben", - "*Jeder* stirbt, wenn *einer stirbt*" - ], - "item-respawn-setting": [ - "§4Respawn", - "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" - ], - "item-death-message-setting": [ - "§6Todesnachrichten", - "Schaltet *Todesnachrichten* ein/aus" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMaximale Herzen", - "Stellt ein, wie viele", - "Herzen man hat" - ], - "item-soup-setting": [ - "§cSuppen Heilung", - "Wenn du eine *Pilzsuppe* benutzt,", - "wirst du um *4 Herzen* geheilt" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Schaden, den du nimmst, wird *multipliziert*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "Es wird im Chat angezeigt,", - "wenn jemand *Schaden* bekommt" - ], - "item-health-display-setting": [ - "§cHealth Display", - "Die *Herzen* aller Spieler", - "werden in der *Tablist* angezeigt" - ], - "item-position-setting": [ - "§9Positions", - "Erlaubt es dir *Positionen*", - "mit */pos* zu *markieren*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Erlaubt es dir, *deinen Backpack* oder den", - "*Team Backpack* mit */backpack* zu öffnen" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Verschiedene *Einstellungen*, die", - "das *Farmen* von Items *einfacher* machen" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Golderz* wird direkt zu *Goldbarren*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Eisenerz* wird direkt zu *Eisenbarren*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Kohleerz* wird direkt zu *Fackeln*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* droppt immer *Flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Erz Venen* werden direkt abgebaut" - ], - "item-cut-clean-inventory-setting": [ - "§6Direkt ins Inventar", - "*Items* werden, *anstatt gedroppt* zu werden,", - "*direkt* ins *Inventar* hinzugefügt" - ], - "item-cut-clean-food-setting": [ - "§cGebratenes Essen", - "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" - ], - "item-glow-setting": [ - "§fPlayerglow", - "*Spieler* sind durch die *Wand* sichtbar" - ], - "no-hunger-setting": [ - "§cKein Hunger", - "Du bekommst keinen *Hunger*" - ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "Du kannst dich *bewegen*, bevor", - "das Spiel *gestartet* hat" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "Nachdem du *Schaden* genommen hast,", - "kannst du *sofort* wieder Schaden *bekommen*" - ], - "item-timber-setting": [ - "§bTimber", - "Du kannst einen *Baum* zerstören,", - "indem du *einen Block* des Baumes abbaust" - ], - "item-timber-setting-logs": "§6Baumstämme", - "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "Du verlierst keine *Items*,", - "wenn du *stirbst*" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monster können *nichts zerstören*" - ], - "item-no-item-damage-setting": [ - "§5Kein Itemschaden", - "*Items* sind *unzerstörbar*" - ], - "top-command-setting": [ - "§dTop Command", - "Mit */top* kannst du dich", - "zur *Oberfläche* oder in", - "die *Overworld* teleportieren" - ], - "item-fortress-spawn-setting": [ - "§cFestungs Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Festung*" - ], - "item-bastion-spawn-setting": [ - "§cBastions Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Bastion*" - ], - "item-no-offhand-setting": [ - "§6Keine Offhand", - "Die *zweite Hand* wird geblockt" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Stellt ein, *ob* und", - "*wie* man *regeneriert*" - ], - "item-regeneration-setting-not_natural": "§6Nicht natürlich", - "item-immediate-respawn-setting": [ - "§6Direkter Respawn", - "Wenn du stirbst, *respawnst* du *automatisch,*", - "ohne den *Death Screen* zu sehen" - ], - "item-slot-limit-setting": [ - "§4Inventar Slots", - "Stellt ein, wie viele *Inventar*", - "*Slots* nutzbar sind" - ], - "item-death-position-setting": [ - "§cDeath Position", - "Wenn du stirbst, wird mit */pos* ", - "eine *Position an deinem Todespunkt* erstellt" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "Wenn du */ec* ausführst, öffnet", - "sich deine *Enderchest*" - ], - "item-split-health-setting": [ - "§cGeteilte Herzen", - "Stellt ein, ob sich *alle*", - "*Spieler* eine *Gesundheit teilen*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "Das *alte 1.8 PvP System* wird genutzt", - "Es gibt keinen *Attack Cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Tod Rettung", - "Wenn du durch eine Challenge *instant*", - "*stirbst*, können *Totems* dich retten" - ], - "item-traffic-light-challenge": [ - "§cAmpelchallenge", - "Die *Ampel* schaltet alle paar Minuten um", - "Wenn du bei *rot* gehst, stirbst du" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Jeder *Block* droppt ein *zufälliges Item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "Wenn ein *Entity* spawnt, spawnt ein *anderes*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" - ], - "item-damage-block-challenge": [ - "§4Schaden pro Block", - "Du bekommst *Schaden* durch", - "jeden *Block*, den du gehst" - ], - "item-hunger-block-challenge": [ - "§6Hunger pro Block", - "Du bekommst *Hunger* durch", - "jeden *Block*, den du gehst" - ], - "item-stone-sight-challenge": [ - "§fStein Blick", - "*Mobs*, denen du in die *Augen*", - "*schaust*, werden zu *Stein*" - ], - "item-no-mob-sight-challenge": [ - "§cMob Blick Schaden", - "Wenn du einen *Mob* in die *Augen*", - "*schaust*, erleidest du *Schaden*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Unter dir* entsteht die", - "ganze Zeit *Bedrock*" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Hinter dir *spawnen* riesige", - "*Wände* aus *Bedrock*" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "§7Hinter dir *verschwindet* der", - "*Boden* bis ins *Void*" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Die *Inventare* aller Spieler werden *geleert*,", - "wenn ein *Spieler* Schaden erleidet" - ], - "item-no-trading-challenge": [ - "§2Kein Handeln", - "Du kannst *nicht* mit", - "Villager *handeln*" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "Wenn du einen *Block abbaust*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "Wenn du einen *Block plazierst*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-no-exp-challenge": [ - "§aKeine XP", - "Wenn du *XP* aufsammelst, stirbst du" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Alle paar Minuten werden deine *Herzen invertiert*.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", - "welches jedes Mal *schwieriger* wird" - ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "Die *Leben* aller *Mobs*", - "sind *random*" - ], - "item-snake-challenge": [ - "§9Snake", - "*Jeder Spieler* zieht eine", - "tödliche Linie hinter sich her" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "Wenn du Entities *schlägst* oder *abschießt*,", - "bekommst du den *gleichen Schaden*" - ], - "item-duped-spawning-challenge": [ - "§cDoppeltes Spawning", - "Wenn ein Monster *spawnt*,", - "spawnt es *zweimal*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "Wenn du einen *Mob* tötest,", - "spawnen *zwei* neue" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "Wenn du einen *Mob* tötest,", - "spawnen *doppelt* so viele", - "wie beim *vorherigen* mal", - " ", - "Maximum beträgt *512* Mobs gleichzeitig" - ], - "item-floor-lava-challenge": [ - "§6Der Boden ist Lava", - "Alle *Blöcke* unter dir verwandeln sich", - "erst zu *Magma* und dann zu *Lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "Wenn du nicht auf *Erde*", - "stehst, *stirbst* du" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Du kannst jedes *Essen*", - "nur einmal *essen*" - ], - "item-food-once-challenge-player": "§6Spieler", - "item-food-once-challenge-everyone": "§5Jeder", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks*, in denen sich Spieler befinden,", - "*bauen* sich von *oben* aus ab" - ], - "item-one-durability-challenge": [ - "§4Eine Haltbarkeit", - "*Items* gehen nach *einer* Benutzung *kaputt*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "Die *Dropchance* jedes *Blockes* wird auf die", - "angegebene *Prozentzahl* gesetzt" - ], - "item-invisible-mobs-challenge": [ - "§fUnsichtbare Mobs", - "Alle *Mobs* haben einen", - "*Unsichtbarkeits* Effekt" - ], - "item-mob-transformation-challenge": [ - "§cMob Verwandlung", - "Wenn du einen Mob schlägst, *verwandelt* sich", - "dieser in den *letzen Mob*, den du *geschlagen* hast" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "Wenn du *springst*, *spawnt* ein", - "zufälliges *Entity*" - ], - "item-no-mouse-move-challenge": [ - "§cMausbewegung Schaden", - "Wenn du deinen *Blick bewegst*,", - "erleidest du den *gesetzen Schaden*" - ], - "item-no-duped-items-challenge": [ - "§6Keine Doppelten Items", - "Wenn *2 Spieler* das gleiche *Item* im", - "Inventar haben, *sterben* beide" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "Du musst *2 Blöcke* Abstand von allen ", - "*Mobs* halten oder du wirst *krank*" - ], - "item-only-down-challenge": [ - "§cNur nach unten", - "Wenn du *einen Block* nach", - "*oben* gehst, *stirbst* du" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Schaden", - "Du bekommst für jedes neue *Advancement*", - "die gesetze Anzahl *Schaden*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAlle Blöcke verschwinden", - "Bei verschiedenen *Interaktionen*", - "verschwinden alle *Blöcke* im *Chunk*", - "eines *bestimmten Types*" - ], - "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", - "item-all-blocks-disappear-break-challenge": [ - "§bBeim Abbauen", - "Wenn du einen Block *abbaust*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBeim Platzieren", - "Wenn du einen Block *platzierst*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-water-allergy-challenge": [ - "§9Wasserallergie", - "Wenn du in *Wasser* bist,", - "*erleidest* du den gesetzen Schaden" - ], - "item-max-biome-time-challenge": [ - "§2Maximale Biom Zeit", - "Die *Zeit*, die du in jedem *Biom*", - "sein darfst, ist *begrenzt*" - ], - "item-max-height-time-challenge": [ - "§9Maximale Höhen Zeit", - "Die *Zeit*, die du auf jeder *Höhe*", - "sein darfst, ist *begrenzt*" - ], - "item-permanent-item-challenge": [ - "§cPermanente Items", - "*Items* können nicht gedroppt", - "oder *weggelegt* werden" - ], - "item-sneak-damage-challenge": [ - "§6Schaden pro Schleichen", - "Du *erleidest* den gesetzten", - "*Schaden*, wenn du *schleichst*" - ], - "item-jump-damage-challenge": [ - "§6Schaden pro Sprung", - "Du *erleidest* den gesetzen", - "*Schaden*, wenn du *springst*" - ], - "item-random-dropping-challenge": [ - "§cZufälliges Item Droppen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gedroppt*" - ], - "item-random-swapping-challenge": [ - "§cZufälliges Item Mischen", - "Alle paar Sekunden wird ein", - "*zufälliges Item* aus deinem Inventar", - "mit einem anderem *getauscht*" - ], - "item-random-removing-challenge": [ - "§cZufälliges Item Löschen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gelöscht*" - ], - "item-death-on-fall-challenge": [ - "§fTod bei Fallschaden", - "Wenn du *Fallschaden* erleidest,", - "*stirbst* du sofort" - ], - "item-zero-hearts-challenge": [ - "§6Null Herzen", - "Nach einer *Schutzzeit* musst du", - "dauerhaft Absorption bekommen" - ], - "item-random-effect-challenge": [ - "§6Random Effekte", - "Du bekommst in einem gesetzen *Intervall*", - "einen *zufälligen Trank Effekt*" - ], - "menu-random-effect-challenge-settings": "Random Effekte", - "item-random-effect-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in dem man", - "einen *Effekt* erhält" - ], - "item-random-effect-length-challenge": [ - "§6Länge", - "Die *Länge*, die der", - "*Effekt* anhält" - ], - "item-random-effect-amplifier-challenge": [ - "§6Stärke", - "Die *Stärke*, die der", - "*Effekt* hat" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanente Effekte", - "Du bekommst immer, wenn du *Schaden*", - "erleidest, einen *zufälligen Effekt*" - ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In einem *gesetzten Intervall*", - "wird eine *Random Challenge* aktiviert" - ], - "item-anvil-rain-challenge": [ - "§cAmboss Regen", - "Vom *Himmel* fallen *Ambosse*" - ], - "menu-anvil-rain-challenge-settings": "Amboss Regen", - "item-anvil-rain-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in", - "dem *Ambosse* spawnen" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "Die *Reichweite*, in", - "der *Ambosse* spawnen" - ], - "item-anvil-rain-count-challenge": [ - "§6Anzahl", - "Die *Anzahl*, an *Ambossen*,", - "die in einem *Chunk* spawnen" - ], - "item-anvil-rain-damage-challenge": [ - "§6Schaden", - "Der *Schaden*, die", - "die *Ambosse* machen" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "Du musst *immer wieder*", - "einen *Water MLG* absolvieren" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Alle *paar Minuten* wirst du", - "mit einem *zufälligem Entity* aus", - "einem *200 Block* Radius *getauscht*" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Alle *paar Minuten* wird eines von", - "*{0} random Events* aktiviert" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "Es wird für jeden *Block* / *Chunk*,", - "den du dich *fortbewegst*, ein Item", - "aus deinem Inventar *gelöscht*" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "*Umso öfter* du springst,", - "*desto höher* springst du" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Alle *paar Minuten* musst du auf", - "eine *bestimmte Höhe* oder du stirbst" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Alle *paar Minuten* musst du auf", - "einen *bestimmten Block* oder du stirbst" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Alle *paar Minuten* musst du in", - "ein *bestimmtes Biom* oder du stirbst", - "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Entity* killen oder du stirbst" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Item* finden oder du stirbst" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "Ein *zufälliger Spieler* erhält alle paar", - "*Sekunden* ein *zufälliges Item*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "Du kannst *nicht aufhören*, vorwärts zu laufen" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "Wenn du ein *Item aufhebst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In einem *gesetztem Intervall*", - "*steigt* das *Wasser* in der *Overworld*", - "und die *Lava* in im *Nether*", - " ", - "Sollte mit wenigen Personen gespielt werden!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAlle Monster zum Todespunkt", - "Wenn ein *Mob* von einem Spieler", - "*getötet* wird, werden *alle* anderen", - "Monster vom *selben Typen* zum", - "*Todespunkt* teleportiert" - ], - "item-ice-floor-challenge": [ - "§bEisboden", - "Unter dir wird *Luft* zu einem", - "*3x3* Boden aus *Eis*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlöcke verschwinden nach Zeit", - "Blöcke, die du *platzierst*, *verschwinden*", - "nach ein *paar Sekunden* wieder" - ], - "item-missing-items-challenge": [ - "§9Items Fehlen", - "Alle paar Minuten *verschwindet* ein *Item* aus", - "deinem *Inventar* und du musst *erraten*, welches" - ], - "item-damage-item-challenge": [ - "§cSchaden pro Item", - "Wenn du ein *Item aufhebst* oder es", - "in deinem Inventar *anklickst* erleidest", - "du *0,5 ❤* multipliziert mit der Anzahl der Items" - ], - "item-damage-teleport-challenge": [ - "§cSchaden Random Teleport", - "Du wirst *zufällig teleportiert*,", - "wenn du *Schaden* erleidest" - ], - "item-loop-challenge": [ - "§6Wiederholungs Challenge", - "Verschiedene Aktionen *wiederholen* sich", - "unendlich oft, bis ein Spieler *schleicht*" - ], - "item-uncraft-challenge": [ - "§6Items craften sich zurück", - "Alle *Items* in deinem Inventar *craften*", - "sich alle paar Sekunden *zurück*" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "Für *jedes Herz*, das du *Schaden* erleidest, kannst", - "du dich für eine bestimmte Zeit *nicht bewegen*" - ], - "item-dont-stop-running-challenge": [ - "§9Nicht stehen bleiben", - "Du darfst nur eine bestimmte Zeit", - "*stehen bleiben* bevor du *stirbst*" - ], - "item-consume-launch-challenge": [ - "§cEssens Boost", - "Wenn du ein *Item isst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blöcke", - "*Alle* 500 Blöcke, die du *läufst*,", - "bekommst du *64* eines *zufälliges Items*.", - "Es droppen *keine Items* von", - "*Blöcken* und *Entities* mehr." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "Die *Border-Größe* passt sich dem *Spieler*", - "mit den *meisten Leveln* an." - ], - "item-chunk-effect-challenge": [ - "§3Zufällige Chunk Effekte", - "In *jedem Chunk* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-repeat-chunk-challenge": [ - "§2Wiederholende Chunks", - "Blöcke die *platziert oder zerstört* werden,", - "werden in *jedem Chunk* platziert / zerstört" - ], - "item-blocks-fly-challenge": [ - "§fBlöcke fliegen in die Luft", - "*Blöcke*, auf denen du *gelaufen* bist,", - "fliegen nach *einer Sekunde* in die *Luft*" - ], - "item-respawn-end-challenge": [ - "§5Mobs respawnen im End", - "Mobs, die *getötet werden*,", - "respawnen im *End*" - ], - "item-block-effect-challenge": [ - "§3Zufällige Block Effekte", - "Auf *jedem Block* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Haben Random Effekte", - "*Jedes Mob* hat einen zufälligen", - "Effekt auf *höchster Stufe*" - ], - "item-mob-damage-teleport-challenge": [ - "§5Mob Tausch Beim Schlagen", - "Jedes mal, wenn du einen *Mob schlägst*,", - "tauschst du mit einem *zufälligem Mob* die Position" - ], - "item-block-mob-challenge": [ - "§cMob Blöcke", - "Aus jedem abgebautem Block, *spawnt ein Mob*,", - "dass *getötet* werden muss, um den Block *zu erhalten*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "Alle Mob Drops sind *zufällig vertauscht*." - ], - "item-no-shared-advancements-challenge": [ - "§2Keine Gleichen Advancements", - "Spieler dürfen *nicht* die *gleichen Advancements*", - "abschließen, sonst *stirbt* der *Spieler*" - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Löschung", - "*Chunks*, in denen sich *Spieler* befinden,", - "werden nach gegebener *Zeit* komplett *gelöscht*" - ], - "item-dragon-goal": [ - "§5Enderdrache", - "Töte den *Enderdrachen* um zu gewinnen" - ], - "item-wither-goal": [ - "§dWither", - "Töte einen *Wither* um zu gewinnen" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Töte einen *Elder Guardian* um zu gewinnen" - ], - "item-warden-goal": [ - "§5Warden", - "Töte einen *Warden* um zu gewinnen" - ], - "item-iron-golem-goal": [ - "§bEisengolem", - "Töte einen *Eisengolem* um zu gewinnen" - ], - "item-snow-golem-goal": [ - "§bSchneemann", - "Töte einen *Schneemann* um zu gewinnen" - ], - "item-most-deaths-goal": [ - "§6Meiste Tode", - "Wer die meisten *verschiedenen Tode*", - "sammelt, *gewinnt*" - ], - "item-most-items-goal": [ - "§cMeisten Items", - "Wer die meisten *verschiedenen Items*", - "findet, *gewinnt*" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Wer *am Ende* noch *lebt*, gewinnt" - ], - "item-mine-most-blocks-goal": [ - "§eMeisten Blöcke", - "Wer die *meisten Blöcke* abbaut, gewinnt" - ], - "item-most-xp-goal": [ - "§aMeiste XP", - "Wer die meiste *XP sammelt*, gewinnt" - ], - "item-first-one-to-die-goal": [ - "§cErster Tod", - "Wer als *erstes stirbt*, gewinnt" - ], - "item-collect-wood-goal": [ - "§6Holzarten Sammeln", - "Wer als *erstes* alle *Holzarten*, die", - "*eingestellt* sind, gesammelt hat, gewinnt" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Beide", - "item-all-bosses-goal": [ - "§bAlle Bosse", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-bosses-new-goal": [ - "§5Alle Bosse (+ Warden)", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-mobs-goal": [ - "§bAlle Mobs", - "Es müssen *alle Mobs* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-monster-goal": [ - "§bAlle Monster", - "Es müssen *alle Monster* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-items-goal": [ - "§2Alle Items", - "Finde *alle Items*, die es *in Minecraft gibt*" - ], - "item-finish-raid-goal": [ - "§6Raid Gewinnen", - "Der erste Spieler, der einen *Raid*", - "*abschließt*, gewinnt" - ], - "item-most-emeralds-goal": [ - "§2Meisten Emeralds", - "Der Spieler mit den *meisten*", - "*Emeralds* gewinnt" - ], - "item-all-advancements-goal": [ - "§6Alle Advancements", - "Der Spieler, der als erstes *alle*", - "Errungenschaften *erhalten hat*, gewinnt" - ], - "item-max-height-goal": [ - "§fMaximale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-min-height-goal": [ - "§fMinimale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-race-goal": [ - "§5Wettrennen", - "Der Spieler, der als *erstes* an", - "einer *zufälligen* Position ist, gewinnt" - ], - "item-most-ores-goal": [ - "§9Meiste Erze", - "Der Spieler, der am *meisten Erze*", - "*abgebaut* hat, gewinnt" - ], - "item-find-elytra-goal": [ - "§fElytra Finden", - "Der Spieler, der als *erstes*", - "eine *Elytra findet*, gewinnt" - ], - "item-eat-cake-goal": [ - "§fKuchen Essen", - "Der Spieler, der als *erstes*", - "einen *Kuchen isst*, gewinnt" - ], - "item-collect-horse-armor-goal": [ - "§bSammle Pferderüstungen", - "Der Spieler, der als *erstes*", - "*alle Pferderüstungen* hat, gewinnt" - ], - "item-collect-ice-goal": [ - "§bSammle Eisblöcke", - "Der Spieler, der als *erstes*", - "*alle Eisblöcke* und Schnee hat, gewinnt" - ], - "item-collect-swords-goal": [ - "§9Sammle Schwerter", - "Der Spieler, der als *erstes*", - "*alle Schwerter* hat, gewinnt" - ], - "item-collect-workstations-item": [ - "§6Sammle Arbeitsblöcke", - "Der Spieler, der als *erstes*", - "*alle Villager Arbeitsblöcke* hat, gewinnt" - ], - "item-eat-most-goal": [ - "§6Am Meisten Essen", - "Der Spieler, der am *meisten isst*, gewinnt" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Jeder Spieler bekommt ein *zufälliges Item*,", - "das er finden muss.", - "Wer am Ende die *meisten Items* hat, gewinnt" - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bItem bei Skippen geben", - "Wenn ein Spieler ein Item *skippt*,", - "wird dieses in sein *Inventar hinzugefügt*" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Jeder Spieler bekommt ein *zufälliges Mob*,", - "das er töten muss." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Jeder Spieler bekommt ein *zufälliges*", - "*Advancement*, welches er erreichen muss." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Jeder Spieler bekommt einen *zufälligen*", - "*Block*, auf welchem er stehen muss" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bBlock bei Skippen geben", - "Wenn ein Spieler einen Block *skippt*,", - "wird dieser in sein *Inventar hinzugefügt*" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Jeder Spieler bekommt ein *zufälliges Biom*,", - "das er betreten muss" - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", - "die er *erhalten* muss" - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Jeder Spieler bekommt eine *zufällige Höhe*,", - "auf der er sich befinden muss." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Jeder Spieler bekommt eine *zufällige Position*,", - "die er erreichen muss." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Jeder Spieler bekommt ein *zufälliges Ziel*,", - "welches er erreichen muss" - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-get-full-health-goal": [ - "§aRegeneriere Volle Leben", - "The first player to gain full health wins." - ], - "item-damage-rule-none": [ - "§6Genereller Schaden", - "Stellt ein, ob du Schaden bekommen kannst" - ], - "item-damage-rule-fire": [ - "§6Feuer Schaden", - "Stellt ein, ob du Schaden durch", - "*Lava* und *Feuer* bekommen kannst" - ], - "item-damage-rule-attack": [ - "§3Angriff Schaden", - "Stellt ein, ob du Schaden durch", - "*Nahkampfangriffe von Entities* bekommen kannst" - ], - "item-damage-rule-projectile": [ - "§6Projektil Schaden", - "Stellt ein, ob du Schaden durch", - "*Projektile* bekommen kannst" - ], - "item-damage-rule-fall": [ - "§fFallschaden", - "Stellt ein, ob du *Fallschaden* bekommen kannst" - ], - "item-damage-rule-explosion": [ - "§cExplosions Schaden", - "Stellt ein, ob du *Explosions Schaden* bekommen kannst" - ], - "item-damage-rule-drowning": [ - "§9Ertrink Schaden", - "Stellt ein, ob du Schaden durch", - "*Ertrinken* bekommen kannst" - ], - "item-damage-rule-block": [ - "§eBlock Schaden", - "Stellt ein, ob du Schaden durch", - "*Fallende Blöcke* bekommen kannst" - ], - "item-damage-rule-magic": [ - "§5Magie Schaden", - "Stellt ein, ob du Schaden durch", - "*Gift*, *Wither* und andere *Tränke* bekommen kannst" - ], - "item-damage-rule-freeze": [ - "§fFrost Schaden", - "Stellt ein, ob du Schaden durch", - "*Frost* bekommen kannst" - ], - "item-block-material": [ - "{0}", - "Stellt ein, ob *{1}*", - "genutzt werden *kann*" - ], - "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", - "custom-not-deleted": "Diese Challenge existiert noch nicht!", - "custom-saved": "§7Challenge wurde lokal §agespeichert", - "custom-saved-db": [ - "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", - "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" - ], - "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", - "custom-name-info": "Schreibe den Namen der Challenge in den Chat", - "custom-command-info": [ - "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", - "Erlaubte Commands: §e{0}", - "§cWeitere Commands können in der Config erlaubt werden" - ], - "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", - "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", - "custom-not-loaded": [ - " ", - "Es sind derzeit keine Custom Challenges geladen.", - "Du vermisst deine Challenges? §e/db load customs", - "Du hast Probleme beim Speichern?", - "Speichere vorm verlassen manuell §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6Challenges Ansehen", - "custom-main-create-challenge": "§aChallenge Erstellen", - "custom-title-trigger": "Auslöser", - "custom-title-action": "Aktion", - "custom-title-view": "Gespeichert", - "custom-sub-finish": "§aFertig", - "item-custom-info-delete": [ - "§cLöschen", - "*Achtung* diese Aktion kann *nicht*", - "rückgängig gemacht werden" - ], - "item-custom-info-save": "§aSpeichern", - "item-custom-info-trigger": [ - "§cAuslöser", - "*Klicke* um einzustellen, was passieren", - "muss, damit die *Aktion* ausgeführt wird" - ], - "item-custom-info-action": [ - "§bAktion", - "*Klicke* um einzustellen, was passieren", - "soll, wenn der *Auslöser* erfüllt ist" - ], - "item-custom-info-material": [ - "§6Anzeige Item", - "*Klicke* um das Anzeigeitem zu ändern" - ], - "item-custom-info-name": [ - "§6Name", - "*Klicke* um den Namen über den Chat zu ändern", - "Maximale Zeichenanzahl: 50" - ], - "custom-info-currently": "§7Eingestellt §8» §e", - "custom-info-trigger": "§7Auslöser", - "custom-info-action": "§7Aktion", - "item-custom-trigger-jump": [ - "§aSpieler Springt" - ], - "item-custom-trigger-sneak": [ - "§aSpieler Schleicht" - ], - "item-custom-trigger-move_block": [ - "§6Spieler Läuft Einen Block" - ], - "item-custom-trigger-death": [ - "§cEntity Stirbt" - ], - "item-custom-trigger-damage": [ - "§cEntity Erleidet Schaden" - ], - "item-custom-trigger-damage-any": [ - "§aJeglicher Grund" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Bekommt Schaden Von Spieler" - ], - "item-custom-trigger-intervall": [ - "§6Intervall" - ], - "item-custom-trigger-intervall-second": [ - "§6Jede Sekunde" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Alle {0} Sekunden" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Alle {0} Minuten" - ], - "item-custom-trigger-block_place": [ - "§aBlock Platziert" - ], - "item-custom-trigger-block_break": [ - "§cBlock Zerstört" - ], - "item-custom-trigger-consume_item": [ - "§2Item Konsumieren" - ], - "item-custom-trigger-pickup_item": [ - "§bItem Aufheben" - ], - "item-custom-trigger-drop_item": [ - "§9Spieler Droppt Item" - ], - "item-custom-trigger-advancement": [ - "§cSpieler Erhält Errungenschaft" - ], - "item-custom-trigger-hunger": [ - "§2Spieler Verliert Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Block Nach Unten Bewegen" - ], - "item-custom-trigger-move_up": [ - "§6Block Nach Oben Bewegen" - ], - "item-custom-trigger-move_camera": [ - "§6Kamera Bewegen" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Spieler Ist Auf Bestimmten Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Spieler Ist Nicht Auf Bestimmten Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Spieler Bekommt XP" - ], - "item-custom-trigger-level_up": [ - "§5Spieler Levelt Auf" - ], - "item-custom-trigger-item_craft": [ - "§6Spieler Craftet Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Spieler In Flüssigkeit" - ], - "item-custom-trigger-get_item": [ - "§aItem bekommen", - "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" - ], - "item-custom-action-cancel": [ - "§4Auslöser Abbrechen", - "Verhindert, dass der Auslöser ausgeführt wird.", - "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", - "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" - ], - "item-custom-action-command": [ - "§4Command Ausführen", - "Lasse Spieler einen Command ausführen lassen", - "Die Commands werden für Spieler mit */execute as* von", - "der Konsole ausgeführt.", - "Erlaubte Commands werden in der Config eingestellt.", - "Der Spieler braucht *keine Rechte* auf den Command haben.", - "Spieler können *keine Plugin Commands* ausführen." - ], - "item-custom-action-kill": [ - "§4Töten", - "Töte Entities" - ], - "item-custom-action-damage": [ - "§cSchaden", - "Füge Entities Schaden zu" - ], - "item-custom-action-heal": [ - "§aHeilen", - "Heile Entities" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Füge Spielern Hunger hinzu" - ], - "item-custom-action-max_health": [ - "§cMaximale Leben Verändern", - "Verändere die Maximalen Leben von Spielern", - "Wird mit einem */gamestate reset* zurückgesetzt" - ], - "item-custom-action-max_health-offset": [ - "§cVeränderung", - "Wähle aus wie viele Leben verändert werden sollen" - ], - "item-custom-action-spawn_entity": [ - "§3Entity Spawnen", - "Spawne ein Entity bestimmten Types" - ], - "item-custom-action-random_mob": [ - "§6Zufälliges Entity", - "Spawne ein zufälliges Entity" - ], - "item-custom-action-random_item": [ - "§bZufälliges Item", - "Gebe Spielern zufällige Items" - ], - "item-custom-action-uncraft_inventory": [ - "§eInventar Zurück-Craften", - "Lasse das Inventar von Spielern Zurück-Craften" - ], - "item-custom-action-boost_in_air": [ - "§fIn Luft Schleudern", - "Schleudere Entities in die Luft" - ], - "item-custom-action-boost_in_air-strength": [ - "§fStärke" - ], - "item-custom-action-potion_effect": [ - "§dTrank Effekt", - "Gebe Entities einen bestimmten Trank Effekt" - ], - "item-custom-action-permanent_effect": [ - "§6Permanenten Trank Effekt", - "Füge Spieler einen Permanenten Effekt hinzu.", - "Die Aktion nutzt die Einstellungen", - "von der Permanenten Effekt Challenge." - ], - "item-custom-action-random_effect": [ - "§dZufälliger Trank Effekt", - "Gebe Entities einen zufälligen Trank Effekt" - ], - "item-custom-action-clear_inventory": [ - "§cInventar Leeren", - "Leere das Inventar von Spielern komplett" - ], - "item-custom-action-drop_random_item": [ - "§aItem Aus Inventar Droppen", - "Droppe ein Item aus dem Inventar auf den Boden" - ], - "item-custom-action-remove_random_item": [ - "§cItem Aus Inventar Entfernen", - "Entferne ein Item aus dem Inventar" - ], - "item-custom-action-swap_random_item": [ - "§6Items Im Inventar Tauschen", - "Tausche zwei Item im Inventar" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Friere Mobs Zeitweise ein.", - "Die Aktion nutzt die Einstellungen", - "von der Freeze On Damage Challenge." - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invertiere die Herzen eines Spielers.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "Alle Spieler müssen einen Water MLG machen" - ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "Ein zufälliger Spieler muss ein Jump And Run machen" - ], - "item-custom-action-win": [ - "§6Gewinnen", - "Die Challenge wird von *bestimmten Spielern* gewonnen" - ], - "item-custom-action-random_hotbar": [ - "§eZufällige Hotbar", - "Das Inventar wird geleert und der Spieler", - "bekommt zufällige Items in die HotBar" - ], - "item-custom-action-modify_border": [ - "§bWorld Border Verändern", - "Mache die Worldborder *größer* §7oder *kleiner*" - ], - "item-custom-action-modify_border-change": [ - "§dVeränderung" - ], - "item-custom-action-swap_mobs": [ - "§5Mobs tauschen", - "Tausche ein Mob mit einem zufälligen", - "anderem Mob aus der gleichen Welt" - ], - "item-custom-action-place_structure": [ - "§aStruktur Platzieren", - "Platziert eine Struktur" - ], - "item-custom-action-place_structure-random": "§bZufällige Struktur", - "item-custom-setting-target-current": [ - "§6Aktives Entity", - "Die Aktion wird für das *aktive Entity* ausgeführt" - ], - "item-custom-setting-target-every_mob": [ - "§4Alle Mobs", - "Die Aktion wird für *alle Mobs* ausgeführt" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Alle Mobs Außer Aktives", - "Die Aktion wird für *alle Mobs*", - "*außer* das Aktive ausgeführt ausgeführt" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Alle Mobs Außer Spieler", - "Die Aktion wird für *alle Mobs*", - "*außer* Spieler ausgeführt" - ], - "item-custom-setting-target-random_player": [ - "§5Zufälliger Spieler", - "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" - ], - "item-custom-setting-target-every_player": [ - "§cAlle Spieler", - "Die Aktion wird für *jeden Spieler* ausgeführt" - ], - "item-custom-setting-target-current_player": [ - "§aAktiver Spieler", - "Die Aktion wird für den *aktiven Spieler* ausgeführt", - "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" - ], - "item-custom-setting-target-console": [ - "§4Konsole", - "Die Aktion wird für die *Konsole* ausgeführt" - ], - "item-custom-setting-entity_type-any": "§cJegliches Entity", - "item-custom-setting-entity_type-player": "§aSpieler", - "item-custom-setting-block-any": "§2Jeglicher Block", - "item-custom-setting-item-any": "§2Jegliches Item", - "custom-subsetting-target_entity": "Ziel Entity", - "custom-subsetting-entity_type": "Entity Typ", - "custom-subsetting-liquid": "Flüssigkeit", - "custom-subsetting-time": "Zeit", - "custom-subsetting-damage_cause": "Schadens Art", - "custom-subsetting-amount": "Anzahl", - "custom-subsetting-value": "Werte Editor", - "custom-subsetting-health_offset": "Veränderung", - "custom-subsetting-length": "Länge", - "custom-subsetting-amplifier": "Stärke", - "custom-subsetting-change": "Veränderung", - "custom-subsetting-swap_targets": "Tausch Ziele" + "syntax": "Bitte nutze §e/{0}", + "reload": "Challenges Plugin wird neu geladen...", + "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", + "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", + "player-command": "Dazu musst du ein Spieler sein!", + "no-permission": "Dazu hast du §ckeine §7Rechte", + "enabled": "§aAktiviert", + "disabled": "§cDeaktiviert", + "customize": "§6Anpassen", + "navigate-back": "§8« §7Zurück", + "navigate-next": "§8» §7Weiter", + "seconds": "Sekunden", + "second": "Sekunde", + "minutes": "Minuten", + "minute": "Minute", + "hours": "Stunden", + "hour": "Stunde", + "amplifier": "Stärke", + "open": "Öffnen", + "everyone": "§5Alle", + "player": "§6Aktiver Spieler", + "none": "Nichts", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer zählt §ahoch", + "timer-counting-down": "§8» §7Timer zählt §crunter", + "timer-is-paused": "§8» §7Timer ist §cpausiert", + "timer-is-running": "§8» §7Timer ist §agestartet", + "confirm-reset": "Bestätige den Reset mit §e/{0}", + "no-fresh-reset": [ + "Der Server kann §cnicht resettet §7werden", + "Die Challenge wurde §cnoch nicht §7gestartet" + ], + "new-challenge": "§a§lNeu!", + "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", + "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", + "timer-not-started": "Der Timer wurde noch §cnicht gestartet", + "timer-was-started": "Der Timer wurde §agestartet", + "timer-was-paused": "Der Timer wurde §cpausiert", + "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", + "timer-already-started": "Der Timer §cläuft bereits", + "timer-already-paused": "Der Timer ist §cbereits pausiert", + "timer-mode-set-down": "Der Timer zählt nun §crunter", + "timer-mode-set-up": "Der Timer zählt nun §ahoch", + "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", + "fetching-data": "Daten werden abgerufen..", + "undefined": "undefiniert", + "no-such-material": "Dieses Material gibt es nicht", + "not-an-item": "§e{0} §7ist kein Item", + "no-such-entity": "Dieses Entity existiert nicht", + "not-alive": "§e{0} §7ist kein lebendes Entity", + "no-loot": "§e{0} §7hat keine Drops", + "deprecated-plugin-version": [ + " ", + "§7Ein neues Update ist verfügbar!", + "§7Download: §e§l{0}", + " " + ], + "deprecated-config-version": [ + "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", + "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" + ], + "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cEs fehlen keine Einstellungen in der Config.", + "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." + ], + "unsuported-language": [ + "§cDiese Sprache §7(§e{0}§7) wird nicht unterstützt" + ], + "not-op": [ + "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" + ], + "join-message": "§e{0} §7hat den Server §abetreten", + "quit-message": "§e{0} §7hat den Server §cverlassen", + "timer-paused-message": [ + "Der Timer ist noch §cpausiert", + "Nutze §e/timer resume §7um ihn zu starten" + ], + "cheats-detected": [ + "§e{0} §7hat §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "cheats-already-detected": [ + "Auf diesem Server wurde §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", + "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", + "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", + "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", + "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", + "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Drachen getötet", + "stat-deaths": "Tode", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Schaden ausgeteilt", + "stat-damage-taken": "Schaden genommen", + "stat-blocks-mined": "Blöcke abgebaut", + "stat-blocks-placed": "Blöcke platziert", + "stat-blocks-traveled": "Blöcke gereist", + "stat-challenges-played": "Challenges gespielt", + "stat-jumps": "Sprünge", + "stats-of": "§8» §7Stats von §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Platz" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positionen sind §cdeaktiviert", + "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", + "position-not-exists": "Die Position §e{0} §7existiert §cnicht", + "position-already-exists": "Die Position §e{0} §7existiert §cbereits", + "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", + "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", + "no-positions": [ + "Es sind keine §ePositionen §7in dieser Welt gesetzt", + "Erstelle eine mit §e/{0}" + ], + "no-positions-global": [ + "Es sind keine §ePositionen §7gesetzt", + "Erstelle eine mit §e/{0}" + ], + "command-no-target": "Es wurde §ckein §7Spieler gefunden", + "command-heal-healed": "Du wurdest §ageheilt", + "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", + "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", + "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", + "command-village-search": "Es wird nach einem Dorf gesucht..", + "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", + "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", + "command-weather-set-clear": "Wetter zu §eklar §7geändert", + "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", + "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", + "command-invsee-open": "Inventar von §e{0} §7geöffnet", + "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", + "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", + "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", + "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", + "command-search-result": "§e{0} §7droppt aus §e{1}", + "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", + "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", + "command-searchloot-result": [ + "§e{0} §7droppt den Loot von §e{1}", + "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" + ], + "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", + "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", + "command-time-query": [ + "§8» §7Derzeitige Ingamezeiten", + "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Mittag", + "command-time-night": "Nacht", + "command-time-midnight": "Mitternacht", + "command-time-day": "Tag", + "command-fly-enabled": "Du kannst §anun fliegen", + "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", + "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", + "command-feed-fed": "Dein Hunger wurde §agestillt", + "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", + "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", + "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", + "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", + "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", + "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", + "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", + "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", + "command-god-mode-enabled": "Du bist nun im §aGod-Mode", + "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", + "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", + "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", + "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", + "death-message": "§e{0} §7ist gestorben", + "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", + "health-inverted": "Deine Herzen wurden §cinvertiert", + "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", + "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", + "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", + "death-collected": "Todesgrund §e{0} §7wurde registriert", + "item-collected": "Item §e{0} §7wurde registriert", + "items-to-collect": "§7Items zu sammeln §8» §e{0}", + "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", + "backpack-opened": "Du hast den {0} §7geöffnet", + "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", + "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", + "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", + "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", + "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", + "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", + "only-dirt-failed": "§e{0} §7stand nicht auf Erde", + "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", + "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", + "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", + "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", + "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", + "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", + "sneak-damage-failed": "§e{0} §7ist geschlichen", + "jump-damage-failed": "§e{0} §7ist gesprungen", + "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", + "all-items-skipped": "Item §e{0} §7geskippt", + "all-items-already-finished": "Es wurden bereits alle Items gefunden", + "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", + "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", + "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", + "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", + "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", + "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", + "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", + "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", + "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", + "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", + "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", + "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", + "new-effect": "Effekt §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Welches Item fehlt?", + "missing-items-inventory-open": "§8[§aGUI öffnen§8]", + "loops-cleared": "§e{0} §7Loops abgebrochen", + "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", + "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", + "points-change": "§e{0} §7Punkte", + "force-item-battle-found": "Du hast §e{0} §7gefunden!", + "force-item-battle-new-item": "Item zu suchen: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", + "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "Du hast §e{0} §7gefunden!", + "force-block-battle-new-block": "Block zu suchen: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display": "§eItem: {0}", + "force-battle-height-target-display": "§eHöhe: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiom: {0}", + "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", + "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", + "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", + "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", + "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", + "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", + "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Bist du es?", + "Woahh! Das ist aber schnell" + ], + "random-event-entities": [ + "Ist das hier ein Zoo?", + "Wo kommt ihr denn her?", + "Was macht ihr denn hier?" + ], + "random-event-hole": [ + "Du bist aber ganz schön tief gefallen", + "Von ganz oben nach ganz unten..", + "Wo kommt denn das Loch her?" + ], + "random-event-fly": [ + "Guten Flug :)", + "I believe I can fly..", + "So fühlt sich also fliegen an" + ], + "random-event-webs": [ + "Liegen die schon lange hier?" + ], + "random-event-ores": [ + "Wo sind denn die ganzen Erze hin?", + "Gibt es hier keine Erze?", + "Gab es hier mal Erze?" + ], + "random-event-sickness": [ + "Bist du etwa krank?", + "Was geht denn jetzt ab" + ], + "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", + "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7Alle Items gefunden", + "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", + "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", + "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", + "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", + "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7Sekunden", + "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", + "subtitle-time-minutes": "§e{0} §7Minuten", + "subtitle-launcher-description": "§7Stärke §e{0}", + "subtitle-blocks": "§e{0} §7Blöcke", + "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Dein Platz §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServerreset", + " ", + "§7Reset durch §4§l{0}", + "§7Der Server startet nun §cneu", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Gewinner: §e§l{1}", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", + "§7Zeit verschwendet: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §afortgesetzt" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpausiert" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aAktiviert" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeaktiviert" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Der Timer ist gestoppt.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Ziel", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blöcke & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eEinstellungen", + "menu-custom": "§aIndividuelle Challenges", + "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Aktiviert §8» §aJa", + "lore-category-deactivated": "§7Aktiviert §8» §cNein", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-randomizer": [ + "§6Randomizer", + "Erlebe ein komplett", + "*durcheinandergebrachtes* Spiel" + ], + "category-limited_time": [ + "§aLimitierte Zeit", + "Du wirst bei verschiedenen", + "Faktoren *zeitlich eingeschränkt*" + ], + "category-force": [ + "§3Zwischenziele (Force)", + "Du musst *bestimmte Zwischenziele*", + "erfüllen, sonst stirbst du" + ], + "category-world": [ + "§4Weltveränderung", + "Die Welt wird nicht mehr", + "*wiedererkennbar* sein" + ], + "category-damage": [ + "§cSchaden", + "Neue *Schadens Regeln*" + ], + "category-effect": [ + "§5Effekte", + "Erlebe verrückte *Effekte*" + ], + "category-inventory": [ + "§6Inventory", + "Dein Inventar wird *verdreht*" + ], + "category-movement": [ + "§aBewegung", + "Du wirst in deinen Bewegungen *eingeschränkt*" + ], + "category-entities": [ + "§bEntities", + "Entities werden *verändert*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges, die in einer", + "*anderen Welt* spielen" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Ziele, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-kill_entity": [ + "§cEntity töten", + "Töte *bestimmte Entities*,", + "um zu gewinnen" + ], + "category-score_points": [ + "§eMeiste Punkte", + "Erziele die *meisten Punkte* in", + "einem *bestimmten Bereich*." + ], + "category-fastest_time": [ + "§6Schnellste Zeit", + "Sei der *schnellste Spieler*, der", + "das Ziel erfüllt" + ], + "category-force_battle": [ + "§bForce Battles", + "Erfülle die *vorgegebenen Zwischenziele*,", + "um Punkte zu erhalten.", + " ", + "Der Spieler mit den *meisten Punkten* gewinnt." + ], + "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", + "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", + "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Stärke: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", + "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", + "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", + "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", + "item-force-battle-goal-jokers": [ + "§6Anzahl der Joker", + "Die *Anzahl* der *Joker*,", + "die jeder Spieler hat" + ], + "item-force-battle-show-scoreboard": [ + "§bScoreboard anzeigen" + ], + "item-force-battle-duped-targets": [ + "§cDoppelte Ziele", + "Ziele können *mehrfach* vorkommen" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "Der *maximale Radius*, in dem sich die", + "Positionen befinden können" + ], + "item-language-setting": [ + "§bSprache", + "Setze die *Sprache*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", + "item-difficulty-setting": [ + "§aSchwierigkeit", + "Stellt die *Schwierigkeitsstufe* ein" + ], + "item-one-life-setting": [ + "§cEin Teamleben", + "*Jeder* stirbt, wenn *einer stirbt*" + ], + "item-respawn-setting": [ + "§4Respawn", + "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" + ], + "item-death-message-setting": [ + "§6Todesnachrichten", + "Schaltet *Todesnachrichten* ein/aus" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMaximale Herzen", + "Stellt ein, wie viele", + "Herzen man hat" + ], + "item-soup-setting": [ + "§cSuppen Heilung", + "Wenn du eine *Pilzsuppe* benutzt,", + "wirst du um *4 Herzen* geheilt" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Schaden, den du nimmst, wird *multipliziert*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "Es wird im Chat angezeigt,", + "wenn jemand *Schaden* bekommt" + ], + "item-health-display-setting": [ + "§cHealth Display", + "Die *Herzen* aller Spieler", + "werden in der *Tablist* angezeigt" + ], + "item-position-setting": [ + "§9Positions", + "Erlaubt es dir *Positionen*", + "mit */pos* zu *markieren*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Erlaubt es dir, *deinen Backpack* oder den", + "*Team Backpack* mit */backpack* zu öffnen" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Verschiedene *Einstellungen*, die", + "das *Farmen* von Items *einfacher* machen" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Golderz* wird direkt zu *Goldbarren*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Eisenerz* wird direkt zu *Eisenbarren*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Kohleerz* wird direkt zu *Fackeln*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* droppt immer *Flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Erz Venen* werden direkt abgebaut" + ], + "item-cut-clean-inventory-setting": [ + "§6Direkt ins Inventar", + "*Items* werden, *anstatt gedroppt* zu werden,", + "*direkt* ins *Inventar* hinzugefügt" + ], + "item-cut-clean-food-setting": [ + "§cGebratenes Essen", + "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" + ], + "item-glow-setting": [ + "§fPlayerglow", + "*Spieler* sind durch die *Wand* sichtbar" + ], + "no-hunger-setting": [ + "§cKein Hunger", + "Du bekommst keinen *Hunger*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "Du kannst dich *bewegen*, bevor", + "das Spiel *gestartet* hat" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "Nachdem du *Schaden* genommen hast,", + "kannst du *sofort* wieder Schaden *bekommen*" + ], + "item-timber-setting": [ + "§bTimber", + "Du kannst einen *Baum* zerstören,", + "indem du *einen Block* des Baumes abbaust" + ], + "item-timber-setting-logs": "§6Baumstämme", + "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "Du verlierst keine *Items*,", + "wenn du *stirbst*" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monster können *nichts zerstören*" + ], + "item-no-item-damage-setting": [ + "§5Kein Itemschaden", + "*Items* sind *unzerstörbar*" + ], + "top-command-setting": [ + "§dTop Command", + "Mit */top* kannst du dich", + "zur *Oberfläche* oder in", + "die *Overworld* teleportieren" + ], + "item-fortress-spawn-setting": [ + "§cFestungs Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Festung*" + ], + "item-bastion-spawn-setting": [ + "§cBastions Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Bastion*" + ], + "item-no-offhand-setting": [ + "§6Keine Offhand", + "Die *zweite Hand* wird geblockt" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Stellt ein, *ob* und", + "*wie* man *regeneriert*" + ], + "item-regeneration-setting-not_natural": "§6Nicht natürlich", + "item-immediate-respawn-setting": [ + "§6Direkter Respawn", + "Wenn du stirbst, *respawnst* du *automatisch,*", + "ohne den *Death Screen* zu sehen" + ], + "item-slot-limit-setting": [ + "§4Inventar Slots", + "Stellt ein, wie viele *Inventar*", + "*Slots* nutzbar sind" + ], + "item-death-position-setting": [ + "§cDeath Position", + "Wenn du stirbst, wird mit */pos* ", + "eine *Position an deinem Todespunkt* erstellt" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "Wenn du */ec* ausführst, öffnet", + "sich deine *Enderchest*" + ], + "item-split-health-setting": [ + "§cGeteilte Herzen", + "Stellt ein, ob sich *alle*", + "*Spieler* eine *Gesundheit teilen*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "Das *alte 1.8 PvP System* wird genutzt", + "Es gibt keinen *Attack Cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Tod Rettung", + "Wenn du durch eine Challenge *instant*", + "*stirbst*, können *Totems* dich retten" + ], + "item-traffic-light-challenge": [ + "§cAmpelchallenge", + "Die *Ampel* schaltet alle paar Minuten um", + "Wenn du bei *rot* gehst, stirbst du" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Jeder *Block* droppt ein *zufälliges Item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "Wenn ein *Entity* spawnt, spawnt ein *anderes*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" + ], + "item-damage-block-challenge": [ + "§4Schaden pro Block", + "Du bekommst *Schaden* durch", + "jeden *Block*, den du gehst" + ], + "item-hunger-block-challenge": [ + "§6Hunger pro Block", + "Du bekommst *Hunger* durch", + "jeden *Block*, den du gehst" + ], + "item-stone-sight-challenge": [ + "§fStein Blick", + "*Mobs*, denen du in die *Augen*", + "*schaust*, werden zu *Stein*" + ], + "item-no-mob-sight-challenge": [ + "§cMob Blick Schaden", + "Wenn du einen *Mob* in die *Augen*", + "*schaust*, erleidest du *Schaden*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Unter dir* entsteht die", + "ganze Zeit *Bedrock*" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Hinter dir *spawnen* riesige", + "*Wände* aus *Bedrock*" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "§7Hinter dir *verschwindet* der", + "*Boden* bis ins *Void*" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Die *Inventare* aller Spieler werden *geleert*,", + "wenn ein *Spieler* Schaden erleidet" + ], + "item-no-trading-challenge": [ + "§2Kein Handeln", + "Du kannst *nicht* mit", + "Villager *handeln*" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "Wenn du einen *Block abbaust*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "Wenn du einen *Block plazierst*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-no-exp-challenge": [ + "§aKeine XP", + "Wenn du *XP* aufsammelst, stirbst du" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Alle paar Minuten werden deine *Herzen invertiert*.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", + "welches jedes Mal *schwieriger* wird" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "Die *Leben* aller *Mobs*", + "sind *random*" + ], + "item-snake-challenge": [ + "§9Snake", + "*Jeder Spieler* zieht eine", + "tödliche Linie hinter sich her" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "Wenn du Entities *schlägst* oder *abschießt*,", + "bekommst du den *gleichen Schaden*" + ], + "item-duped-spawning-challenge": [ + "§cDoppeltes Spawning", + "Wenn ein Monster *spawnt*,", + "spawnt es *zweimal*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "Wenn du einen *Mob* tötest,", + "spawnen *zwei* neue" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "Wenn du einen *Mob* tötest,", + "spawnen *doppelt* so viele", + "wie beim *vorherigen* mal", + " ", + "Maximum beträgt *512* Mobs gleichzeitig" + ], + "item-floor-lava-challenge": [ + "§6Der Boden ist Lava", + "Alle *Blöcke* unter dir verwandeln sich", + "erst zu *Magma* und dann zu *Lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "Wenn du nicht auf *Erde*", + "stehst, *stirbst* du" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Du kannst jedes *Essen*", + "nur einmal *essen*" + ], + "item-food-once-challenge-player": "§6Spieler", + "item-food-once-challenge-everyone": "§5Jeder", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks*, in denen sich Spieler befinden,", + "*bauen* sich von *oben* aus ab" + ], + "item-one-durability-challenge": [ + "§4Eine Haltbarkeit", + "*Items* gehen nach *einer* Benutzung *kaputt*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "Die *Dropchance* jedes *Blockes* wird auf die", + "angegebene *Prozentzahl* gesetzt" + ], + "item-invisible-mobs-challenge": [ + "§fUnsichtbare Mobs", + "Alle *Mobs* haben einen", + "*Unsichtbarkeits* Effekt" + ], + "item-mob-transformation-challenge": [ + "§cMob Verwandlung", + "Wenn du einen Mob schlägst, *verwandelt* sich", + "dieser in den *letzen Mob*, den du *geschlagen* hast" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "Wenn du *springst*, *spawnt* ein", + "zufälliges *Entity*" + ], + "item-no-mouse-move-challenge": [ + "§cMausbewegung Schaden", + "Wenn du deinen *Blick bewegst*,", + "erleidest du den *gesetzen Schaden*" + ], + "item-no-duped-items-challenge": [ + "§6Keine Doppelten Items", + "Wenn *2 Spieler* das gleiche *Item* im", + "Inventar haben, *sterben* beide" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "Du musst *2 Blöcke* Abstand von allen ", + "*Mobs* halten oder du wirst *krank*" + ], + "item-only-down-challenge": [ + "§cNur nach unten", + "Wenn du *einen Block* nach", + "*oben* gehst, *stirbst* du" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Schaden", + "Du bekommst für jedes neue *Advancement*", + "die gesetze Anzahl *Schaden*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAlle Blöcke verschwinden", + "Bei verschiedenen *Interaktionen*", + "verschwinden alle *Blöcke* im *Chunk*", + "eines *bestimmten Types*" + ], + "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", + "item-all-blocks-disappear-break-challenge": [ + "§bBeim Abbauen", + "Wenn du einen Block *abbaust*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBeim Platzieren", + "Wenn du einen Block *platzierst*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-water-allergy-challenge": [ + "§9Wasserallergie", + "Wenn du in *Wasser* bist,", + "*erleidest* du den gesetzen Schaden" + ], + "item-max-biome-time-challenge": [ + "§2Maximale Biom Zeit", + "Die *Zeit*, die du in jedem *Biom*", + "sein darfst, ist *begrenzt*" + ], + "item-max-height-time-challenge": [ + "§9Maximale Höhen Zeit", + "Die *Zeit*, die du auf jeder *Höhe*", + "sein darfst, ist *begrenzt*" + ], + "item-permanent-item-challenge": [ + "§cPermanente Items", + "*Items* können nicht gedroppt", + "oder *weggelegt* werden" + ], + "item-sneak-damage-challenge": [ + "§6Schaden pro Schleichen", + "Du *erleidest* den gesetzten", + "*Schaden*, wenn du *schleichst*" + ], + "item-jump-damage-challenge": [ + "§6Schaden pro Sprung", + "Du *erleidest* den gesetzen", + "*Schaden*, wenn du *springst*" + ], + "item-random-dropping-challenge": [ + "§cZufälliges Item Droppen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gedroppt*" + ], + "item-random-swapping-challenge": [ + "§cZufälliges Item Mischen", + "Alle paar Sekunden wird ein", + "*zufälliges Item* aus deinem Inventar", + "mit einem anderem *getauscht*" + ], + "item-random-removing-challenge": [ + "§cZufälliges Item Löschen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gelöscht*" + ], + "item-death-on-fall-challenge": [ + "§fTod bei Fallschaden", + "Wenn du *Fallschaden* erleidest,", + "*stirbst* du sofort" + ], + "item-zero-hearts-challenge": [ + "§6Null Herzen", + "Nach einer *Schutzzeit* musst du", + "dauerhaft Absorption bekommen" + ], + "item-random-effect-challenge": [ + "§6Random Effekte", + "Du bekommst in einem gesetzen *Intervall*", + "einen *zufälligen Trank Effekt*" + ], + "menu-random-effect-challenge-settings": "Random Effekte", + "item-random-effect-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in dem man", + "einen *Effekt* erhält" + ], + "item-random-effect-length-challenge": [ + "§6Länge", + "Die *Länge*, die der", + "*Effekt* anhält" + ], + "item-random-effect-amplifier-challenge": [ + "§6Stärke", + "Die *Stärke*, die der", + "*Effekt* hat" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanente Effekte", + "Du bekommst immer, wenn du *Schaden*", + "erleidest, einen *zufälligen Effekt*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In einem *gesetzten Intervall*", + "wird eine *Random Challenge* aktiviert" + ], + "item-anvil-rain-challenge": [ + "§cAmboss Regen", + "Vom *Himmel* fallen *Ambosse*" + ], + "menu-anvil-rain-challenge-settings": "Amboss Regen", + "item-anvil-rain-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in", + "dem *Ambosse* spawnen" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "Die *Reichweite*, in", + "der *Ambosse* spawnen" + ], + "item-anvil-rain-count-challenge": [ + "§6Anzahl", + "Die *Anzahl*, an *Ambossen*,", + "die in einem *Chunk* spawnen" + ], + "item-anvil-rain-damage-challenge": [ + "§6Schaden", + "Der *Schaden*, die", + "die *Ambosse* machen" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "Du musst *immer wieder*", + "einen *Water MLG* absolvieren" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Alle *paar Minuten* wirst du", + "mit einem *zufälligem Entity* aus", + "einem *200 Block* Radius *getauscht*" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Alle *paar Minuten* wird eines von", + "*{0} random Events* aktiviert" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "Es wird für jeden *Block* / *Chunk*,", + "den du dich *fortbewegst*, ein Item", + "aus deinem Inventar *gelöscht*" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "*Umso öfter* du springst,", + "*desto höher* springst du" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Alle *paar Minuten* musst du auf", + "eine *bestimmte Höhe* oder du stirbst" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Alle *paar Minuten* musst du auf", + "einen *bestimmten Block* oder du stirbst" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Alle *paar Minuten* musst du in", + "ein *bestimmtes Biom* oder du stirbst", + "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Entity* killen oder du stirbst" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Item* finden oder du stirbst" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "Ein *zufälliger Spieler* erhält alle paar", + "*Sekunden* ein *zufälliges Item*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "Du kannst *nicht aufhören*, vorwärts zu laufen" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "Wenn du ein *Item aufhebst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In einem *gesetztem Intervall*", + "*steigt* das *Wasser* in der *Overworld*", + "und die *Lava* in im *Nether*", + " ", + "Sollte mit wenigen Personen gespielt werden!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAlle Monster zum Todespunkt", + "Wenn ein *Mob* von einem Spieler", + "*getötet* wird, werden *alle* anderen", + "Monster vom *selben Typen* zum", + "*Todespunkt* teleportiert" + ], + "item-ice-floor-challenge": [ + "§bEisboden", + "Unter dir wird *Luft* zu einem", + "*3x3* Boden aus *Eis*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlöcke verschwinden nach Zeit", + "Blöcke, die du *platzierst*, *verschwinden*", + "nach ein *paar Sekunden* wieder" + ], + "item-missing-items-challenge": [ + "§9Items Fehlen", + "Alle paar Minuten *verschwindet* ein *Item* aus", + "deinem *Inventar* und du musst *erraten*, welches" + ], + "item-damage-item-challenge": [ + "§cSchaden pro Item", + "Wenn du ein *Item aufhebst* oder es", + "in deinem Inventar *anklickst* erleidest", + "du *0,5 ❤* multipliziert mit der Anzahl der Items" + ], + "item-damage-teleport-challenge": [ + "§cSchaden Random Teleport", + "Du wirst *zufällig teleportiert*,", + "wenn du *Schaden* erleidest" + ], + "item-loop-challenge": [ + "§6Wiederholungs Challenge", + "Verschiedene Aktionen *wiederholen* sich", + "unendlich oft, bis ein Spieler *schleicht*" + ], + "item-uncraft-challenge": [ + "§6Items craften sich zurück", + "Alle *Items* in deinem Inventar *craften*", + "sich alle paar Sekunden *zurück*" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "Für *jedes Herz*, das du *Schaden* erleidest, kannst", + "du dich für eine bestimmte Zeit *nicht bewegen*" + ], + "item-dont-stop-running-challenge": [ + "§9Nicht stehen bleiben", + "Du darfst nur eine bestimmte Zeit", + "*stehen bleiben* bevor du *stirbst*" + ], + "item-consume-launch-challenge": [ + "§cEssens Boost", + "Wenn du ein *Item isst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blöcke", + "*Alle* 500 Blöcke, die du *läufst*,", + "bekommst du *64* eines *zufälliges Items*.", + "Es droppen *keine Items* von", + "*Blöcken* und *Entities* mehr." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "Die *Border-Größe* passt sich dem *Spieler*", + "mit den *meisten Leveln* an." + ], + "item-chunk-effect-challenge": [ + "§3Zufällige Chunk Effekte", + "In *jedem Chunk* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-repeat-chunk-challenge": [ + "§2Wiederholende Chunks", + "Blöcke die *platziert oder zerstört* werden,", + "werden in *jedem Chunk* platziert / zerstört" + ], + "item-blocks-fly-challenge": [ + "§fBlöcke fliegen in die Luft", + "*Blöcke*, auf denen du *gelaufen* bist,", + "fliegen nach *einer Sekunde* in die *Luft*" + ], + "item-respawn-end-challenge": [ + "§5Mobs respawnen im End", + "Mobs, die *getötet werden*,", + "respawnen im *End*" + ], + "item-block-effect-challenge": [ + "§3Zufällige Block Effekte", + "Auf *jedem Block* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Haben Random Effekte", + "*Jedes Mob* hat einen zufälligen", + "Effekt auf *höchster Stufe*" + ], + "item-mob-damage-teleport-challenge": [ + "§5Mob Tausch Beim Schlagen", + "Jedes mal, wenn du einen *Mob schlägst*,", + "tauschst du mit einem *zufälligem Mob* die Position" + ], + "item-block-mob-challenge": [ + "§cMob Blöcke", + "Aus jedem abgebautem Block, *spawnt ein Mob*,", + "dass *getötet* werden muss, um den Block *zu erhalten*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "Alle Mob Drops sind *zufällig vertauscht*." + ], + "item-no-shared-advancements-challenge": [ + "§2Keine Gleichen Advancements", + "Spieler dürfen *nicht* die *gleichen Advancements*", + "abschließen, sonst *stirbt* der *Spieler*" + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Löschung", + "*Chunks*, in denen sich *Spieler* befinden,", + "werden nach gegebener *Zeit* komplett *gelöscht*" + ], + "item-delay-damage-description": [ + "§4Verzögerter Schaden", + "Der *schaden* von allen *Spielern* ist", + "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." + ], + "item-dragon-goal": [ + "§5Enderdrache", + "Töte den *Enderdrachen* um zu gewinnen" + ], + "item-wither-goal": [ + "§dWither", + "Töte einen *Wither* um zu gewinnen" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Töte einen *Elder Guardian* um zu gewinnen" + ], + "item-warden-goal": [ + "§5Warden", + "Töte einen *Warden* um zu gewinnen" + ], + "item-iron-golem-goal": [ + "§bEisengolem", + "Töte einen *Eisengolem* um zu gewinnen" + ], + "item-snow-golem-goal": [ + "§bSchneemann", + "Töte einen *Schneemann* um zu gewinnen" + ], + "item-most-deaths-goal": [ + "§6Meiste Tode", + "Wer die meisten *verschiedenen Tode*", + "sammelt, *gewinnt*" + ], + "item-most-items-goal": [ + "§cMeisten Items", + "Wer die meisten *verschiedenen Items*", + "findet, *gewinnt*" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Wer *am Ende* noch *lebt*, gewinnt" + ], + "item-mine-most-blocks-goal": [ + "§eMeisten Blöcke", + "Wer die *meisten Blöcke* abbaut, gewinnt" + ], + "item-most-xp-goal": [ + "§aMeiste XP", + "Wer die meiste *XP sammelt*, gewinnt" + ], + "item-first-one-to-die-goal": [ + "§cErster Tod", + "Wer als *erstes stirbt*, gewinnt" + ], + "item-collect-wood-goal": [ + "§6Holzarten Sammeln", + "Wer als *erstes* alle *Holzarten*, die", + "*eingestellt* sind, gesammelt hat, gewinnt" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Beide", + "item-all-bosses-goal": [ + "§bAlle Bosse", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-bosses-new-goal": [ + "§5Alle Bosse (+ Warden)", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-mobs-goal": [ + "§bAlle Mobs", + "Es müssen *alle Mobs* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-monster-goal": [ + "§bAlle Monster", + "Es müssen *alle Monster* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-items-goal": [ + "§2Alle Items", + "Finde *alle Items*, die es *in Minecraft gibt*" + ], + "item-finish-raid-goal": [ + "§6Raid Gewinnen", + "Der erste Spieler, der einen *Raid*", + "*abschließt*, gewinnt" + ], + "item-most-emeralds-goal": [ + "§2Meisten Emeralds", + "Der Spieler mit den *meisten*", + "*Emeralds* gewinnt" + ], + "item-all-advancements-goal": [ + "§6Alle Advancements", + "Der Spieler, der als erstes *alle*", + "Errungenschaften *erhalten hat*, gewinnt" + ], + "item-max-height-goal": [ + "§fMaximale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-min-height-goal": [ + "§fMinimale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-race-goal": [ + "§5Wettrennen", + "Der Spieler, der als *erstes* an", + "einer *zufälligen* Position ist, gewinnt" + ], + "item-most-ores-goal": [ + "§9Meiste Erze", + "Der Spieler, der am *meisten Erze*", + "*abgebaut* hat, gewinnt" + ], + "item-find-elytra-goal": [ + "§fElytra Finden", + "Der Spieler, der als *erstes*", + "eine *Elytra findet*, gewinnt" + ], + "item-eat-cake-goal": [ + "§fKuchen Essen", + "Der Spieler, der als *erstes*", + "einen *Kuchen isst*, gewinnt" + ], + "item-collect-horse-armor-goal": [ + "§bSammle Pferderüstungen", + "Der Spieler, der als *erstes*", + "*alle Pferderüstungen* hat, gewinnt" + ], + "item-collect-ice-goal": [ + "§bSammle Eisblöcke", + "Der Spieler, der als *erstes*", + "*alle Eisblöcke* und Schnee hat, gewinnt" + ], + "item-collect-swords-goal": [ + "§9Sammle Schwerter", + "Der Spieler, der als *erstes*", + "*alle Schwerter* hat, gewinnt" + ], + "item-collect-workstations-item": [ + "§6Sammle Arbeitsblöcke", + "Der Spieler, der als *erstes*", + "*alle Villager Arbeitsblöcke* hat, gewinnt" + ], + "item-eat-most-goal": [ + "§6Am Meisten Essen", + "Der Spieler, der am *meisten isst*, gewinnt" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Jeder Spieler bekommt ein *zufälliges Item*,", + "das er finden muss.", + "Wer am Ende die *meisten Items* hat, gewinnt" + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bItem bei Skippen geben", + "Wenn ein Spieler ein Item *skippt*,", + "wird dieses in sein *Inventar hinzugefügt*" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Jeder Spieler bekommt ein *zufälliges Mob*,", + "das er töten muss." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Jeder Spieler bekommt ein *zufälliges*", + "*Advancement*, welches er erreichen muss." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Jeder Spieler bekommt einen *zufälligen*", + "*Block*, auf welchem er stehen muss" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bBlock bei Skippen geben", + "Wenn ein Spieler einen Block *skippt*,", + "wird dieser in sein *Inventar hinzugefügt*" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Jeder Spieler bekommt ein *zufälliges Biom*,", + "das er betreten muss" + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", + "die er *erhalten* muss" + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Jeder Spieler bekommt eine *zufällige Höhe*,", + "auf der er sich befinden muss." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Jeder Spieler bekommt eine *zufällige Position*,", + "die er erreichen muss." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Jeder Spieler bekommt ein *zufälliges Ziel*,", + "welches er erreichen muss" + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-get-full-health-goal": [ + "§aRegeneriere Volle Leben", + "The first player to gain full health wins." + ], + "item-damage-rule-none": [ + "§6Genereller Schaden", + "Stellt ein, ob du Schaden bekommen kannst" + ], + "item-damage-rule-fire": [ + "§6Feuer Schaden", + "Stellt ein, ob du Schaden durch", + "*Lava* und *Feuer* bekommen kannst" + ], + "item-damage-rule-attack": [ + "§3Angriff Schaden", + "Stellt ein, ob du Schaden durch", + "*Nahkampfangriffe von Entities* bekommen kannst" + ], + "item-damage-rule-projectile": [ + "§6Projektil Schaden", + "Stellt ein, ob du Schaden durch", + "*Projektile* bekommen kannst" + ], + "item-damage-rule-fall": [ + "§fFallschaden", + "Stellt ein, ob du *Fallschaden* bekommen kannst" + ], + "item-damage-rule-explosion": [ + "§cExplosions Schaden", + "Stellt ein, ob du *Explosions Schaden* bekommen kannst" + ], + "item-damage-rule-drowning": [ + "§9Ertrink Schaden", + "Stellt ein, ob du Schaden durch", + "*Ertrinken* bekommen kannst" + ], + "item-damage-rule-block": [ + "§eBlock Schaden", + "Stellt ein, ob du Schaden durch", + "*Fallende Blöcke* bekommen kannst" + ], + "item-damage-rule-magic": [ + "§5Magie Schaden", + "Stellt ein, ob du Schaden durch", + "*Gift*, *Wither* und andere *Tränke* bekommen kannst" + ], + "item-damage-rule-freeze": [ + "§fFrost Schaden", + "Stellt ein, ob du Schaden durch", + "*Frost* bekommen kannst" + ], + "item-block-material": [ + "{0}", + "Stellt ein, ob *{1}*", + "genutzt werden *kann*" + ], + "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", + "custom-not-deleted": "Diese Challenge existiert noch nicht!", + "custom-saved": "§7Challenge wurde lokal §agespeichert", + "custom-saved-db": [ + "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", + "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" + ], + "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", + "custom-name-info": "Schreibe den Namen der Challenge in den Chat", + "custom-command-info": [ + "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", + "Erlaubte Commands: §e{0}", + "§cWeitere Commands können in der Config erlaubt werden" + ], + "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", + "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", + "custom-not-loaded": [ + " ", + "Es sind derzeit keine Custom Challenges geladen.", + "Du vermisst deine Challenges? §e/db load customs", + "Du hast Probleme beim Speichern?", + "Speichere vorm verlassen manuell §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6Challenges Ansehen", + "custom-main-create-challenge": "§aChallenge Erstellen", + "custom-title-trigger": "Auslöser", + "custom-title-action": "Aktion", + "custom-title-view": "Gespeichert", + "custom-sub-finish": "§aFertig", + "item-custom-info-delete": [ + "§cLöschen", + "*Achtung* diese Aktion kann *nicht*", + "rückgängig gemacht werden" + ], + "item-custom-info-save": "§aSpeichern", + "item-custom-info-trigger": [ + "§cAuslöser", + "*Klicke* um einzustellen, was passieren", + "muss, damit die *Aktion* ausgeführt wird" + ], + "item-custom-info-action": [ + "§bAktion", + "*Klicke* um einzustellen, was passieren", + "soll, wenn der *Auslöser* erfüllt ist" + ], + "item-custom-info-material": [ + "§6Anzeige Item", + "*Klicke* um das Anzeigeitem zu ändern" + ], + "item-custom-info-name": [ + "§6Name", + "*Klicke* um den Namen über den Chat zu ändern", + "Maximale Zeichenanzahl: 50" + ], + "custom-info-currently": "§7Eingestellt §8» §e", + "custom-info-trigger": "§7Auslöser", + "custom-info-action": "§7Aktion", + "item-custom-trigger-jump": [ + "§aSpieler Springt" + ], + "item-custom-trigger-sneak": [ + "§aSpieler Schleicht" + ], + "item-custom-trigger-move_block": [ + "§6Spieler Läuft Einen Block" + ], + "item-custom-trigger-death": [ + "§cEntity Stirbt" + ], + "item-custom-trigger-damage": [ + "§cEntity Erleidet Schaden" + ], + "item-custom-trigger-damage-any": [ + "§aJeglicher Grund" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Bekommt Schaden Von Spieler" + ], + "item-custom-trigger-intervall": [ + "§6Intervall" + ], + "item-custom-trigger-intervall-second": [ + "§6Jede Sekunde" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Alle {0} Sekunden" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Alle {0} Minuten" + ], + "item-custom-trigger-block_place": [ + "§aBlock Platziert" + ], + "item-custom-trigger-block_break": [ + "§cBlock Zerstört" + ], + "item-custom-trigger-consume_item": [ + "§2Item Konsumieren" + ], + "item-custom-trigger-pickup_item": [ + "§bItem Aufheben" + ], + "item-custom-trigger-drop_item": [ + "§9Spieler Droppt Item" + ], + "item-custom-trigger-advancement": [ + "§cSpieler Erhält Errungenschaft" + ], + "item-custom-trigger-hunger": [ + "§2Spieler Verliert Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Block Nach Unten Bewegen" + ], + "item-custom-trigger-move_up": [ + "§6Block Nach Oben Bewegen" + ], + "item-custom-trigger-move_camera": [ + "§6Kamera Bewegen" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Spieler Ist Auf Bestimmten Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Spieler Ist Nicht Auf Bestimmten Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Spieler Bekommt XP" + ], + "item-custom-trigger-level_up": [ + "§5Spieler Levelt Auf" + ], + "item-custom-trigger-item_craft": [ + "§6Spieler Craftet Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Spieler In Flüssigkeit" + ], + "item-custom-trigger-get_item": [ + "§aItem bekommen", + "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ], + "item-custom-action-cancel": [ + "§4Auslöser Abbrechen", + "Verhindert, dass der Auslöser ausgeführt wird.", + "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", + "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" + ], + "item-custom-action-command": [ + "§4Command Ausführen", + "Lasse Spieler einen Command ausführen lassen", + "Die Commands werden für Spieler mit */execute as* von", + "der Konsole ausgeführt.", + "Erlaubte Commands werden in der Config eingestellt.", + "Der Spieler braucht *keine Rechte* auf den Command haben.", + "Spieler können *keine Plugin Commands* ausführen." + ], + "item-custom-action-kill": [ + "§4Töten", + "Töte Entities" + ], + "item-custom-action-damage": [ + "§cSchaden", + "Füge Entities Schaden zu" + ], + "item-custom-action-heal": [ + "§aHeilen", + "Heile Entities" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Füge Spielern Hunger hinzu" + ], + "item-custom-action-max_health": [ + "§cMaximale Leben Verändern", + "Verändere die Maximalen Leben von Spielern", + "Wird mit einem */gamestate reset* zurückgesetzt" + ], + "item-custom-action-max_health-offset": [ + "§cVeränderung", + "Wähle aus wie viele Leben verändert werden sollen" + ], + "item-custom-action-spawn_entity": [ + "§3Entity Spawnen", + "Spawne ein Entity bestimmten Types" + ], + "item-custom-action-random_mob": [ + "§6Zufälliges Entity", + "Spawne ein zufälliges Entity" + ], + "item-custom-action-random_item": [ + "§bZufälliges Item", + "Gebe Spielern zufällige Items" + ], + "item-custom-action-uncraft_inventory": [ + "§eInventar Zurück-Craften", + "Lasse das Inventar von Spielern Zurück-Craften" + ], + "item-custom-action-boost_in_air": [ + "§fIn Luft Schleudern", + "Schleudere Entities in die Luft" + ], + "item-custom-action-boost_in_air-strength": [ + "§fStärke" + ], + "item-custom-action-potion_effect": [ + "§dTrank Effekt", + "Gebe Entities einen bestimmten Trank Effekt" + ], + "item-custom-action-permanent_effect": [ + "§6Permanenten Trank Effekt", + "Füge Spieler einen Permanenten Effekt hinzu.", + "Die Aktion nutzt die Einstellungen", + "von der Permanenten Effekt Challenge." + ], + "item-custom-action-random_effect": [ + "§dZufälliger Trank Effekt", + "Gebe Entities einen zufälligen Trank Effekt" + ], + "item-custom-action-clear_inventory": [ + "§cInventar Leeren", + "Leere das Inventar von Spielern komplett" + ], + "item-custom-action-drop_random_item": [ + "§aItem Aus Inventar Droppen", + "Droppe ein Item aus dem Inventar auf den Boden" + ], + "item-custom-action-remove_random_item": [ + "§cItem Aus Inventar Entfernen", + "Entferne ein Item aus dem Inventar" + ], + "item-custom-action-swap_random_item": [ + "§6Items Im Inventar Tauschen", + "Tausche zwei Item im Inventar" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Friere Mobs Zeitweise ein.", + "Die Aktion nutzt die Einstellungen", + "von der Freeze On Damage Challenge." + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invertiere die Herzen eines Spielers.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "Alle Spieler müssen einen Water MLG machen" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "Ein zufälliger Spieler muss ein Jump And Run machen" + ], + "item-custom-action-win": [ + "§6Gewinnen", + "Die Challenge wird von *bestimmten Spielern* gewonnen" + ], + "item-custom-action-random_hotbar": [ + "§eZufällige Hotbar", + "Das Inventar wird geleert und der Spieler", + "bekommt zufällige Items in die HotBar" + ], + "item-custom-action-modify_border": [ + "§bWorld Border Verändern", + "Mache die Worldborder *größer* §7oder *kleiner*" + ], + "item-custom-action-modify_border-change": [ + "§dVeränderung" + ], + "item-custom-action-swap_mobs": [ + "§5Mobs tauschen", + "Tausche ein Mob mit einem zufälligen", + "anderem Mob aus der gleichen Welt" + ], + "item-custom-action-place_structure": [ + "§aStruktur Platzieren", + "Platziert eine Struktur" + ], + "item-custom-action-place_structure-random": "§bZufällige Struktur", + "item-custom-setting-target-current": [ + "§6Aktives Entity", + "Die Aktion wird für das *aktive Entity* ausgeführt" + ], + "item-custom-setting-target-every_mob": [ + "§4Alle Mobs", + "Die Aktion wird für *alle Mobs* ausgeführt" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Alle Mobs Außer Aktives", + "Die Aktion wird für *alle Mobs*", + "*außer* das Aktive ausgeführt ausgeführt" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Alle Mobs Außer Spieler", + "Die Aktion wird für *alle Mobs*", + "*außer* Spieler ausgeführt" + ], + "item-custom-setting-target-random_player": [ + "§5Zufälliger Spieler", + "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" + ], + "item-custom-setting-target-every_player": [ + "§cAlle Spieler", + "Die Aktion wird für *jeden Spieler* ausgeführt" + ], + "item-custom-setting-target-current_player": [ + "§aAktiver Spieler", + "Die Aktion wird für den *aktiven Spieler* ausgeführt", + "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" + ], + "item-custom-setting-target-console": [ + "§4Konsole", + "Die Aktion wird für die *Konsole* ausgeführt" + ], + "item-custom-setting-entity_type-any": "§cJegliches Entity", + "item-custom-setting-entity_type-player": "§aSpieler", + "item-custom-setting-block-any": "§2Jeglicher Block", + "item-custom-setting-item-any": "§2Jegliches Item", + "custom-subsetting-target_entity": "Ziel Entity", + "custom-subsetting-entity_type": "Entity Typ", + "custom-subsetting-liquid": "Flüssigkeit", + "custom-subsetting-time": "Zeit", + "custom-subsetting-damage_cause": "Schadens Art", + "custom-subsetting-amount": "Anzahl", + "custom-subsetting-value": "Werte Editor", + "custom-subsetting-health_offset": "Veränderung", + "custom-subsetting-length": "Länge", + "custom-subsetting-amplifier": "Stärke", + "custom-subsetting-change": "Veränderung", + "custom-subsetting-swap_targets": "Tausch Ziele" } diff --git a/language/files/en.json b/language/files/en.json index 351203878..57e13303d 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -1,1802 +1,1821 @@ { - "syntax": "Please use §e/{0}", - "reload": "Challenges Plugin is reloading...", - "reload-failed": "An §cerror &7occurred while reloading the plugin", - "reload-success": "Challenges Plugin §asuccessfully §7reloaded", - "player-command": "You must be a player!", - "no-permission": "You §cdon't §7have permissions to do this", - "enabled": "§aActivated", - "disabled": "§cDeactivated", - "customize": "§6Customize", - "navigate-back": "§8« §7Back", - "navigate-next": "§8» §7Next", - "seconds": "seconds", - "second": "second", - "minutes": "minutes", - "minute": "minute", - "hours": "hours", - "hour": "hour", - "amplifier": "amplifier", - "open": "Open", - "everyone": "§5Everyone", - "player": "§6Active player", - "none": "None", - "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer counting §aup", - "timer-counting-down": "§8» §7Timer counting §cdown", - "timer-is-paused": "§8» §7Timer §cpaused", - "timer-is-running": "§8» §7Timer §astarted", - "confirm-reset": "Confirm reset with §e/{0}", - "no-fresh-reset": [ - "The Server §ccan't §7be reset yet", - "The Challenge §chasn't been §7started" - ], - "new-challenge": "§a§lNew!", - "feature-disabled": "This function is currently §cdeactivated", - "challenge-disabled": "This challenge is currently §cdeactivated", - "timer-not-started": "The timer §chasn't been started", - "timer-was-started": "The timer has been §astarted", - "timer-was-paused": "The timer has been §cpaused", - "timer-was-set": "The timer has ben set on §e§l{0}", - "timer-already-started": "The timer is §calready running", - "timer-already-paused": "The timer is §calready paused", - "timer-mode-set-down": "The timer is counting §cdown", - "timer-mode-set-up": "The timer is counting §aup", - "no-database-connection": "There is §cno §7database connection", - "fetching-data": "Data is being retrieved..", - "undefined": "undefined", - "no-such-material": "This material doesn't exist", - "not-an-item": "§e{0} §7is not an item", - "no-such-entity": "This entity doesn't exist", - "not-alive": "§e{0} §7is not a living entity", - "no-loot": "§e{0} §7doesn't have any drops", - "deprecated-plugin-version": [ - " ", - "An update for the plugin is available", - "Download: §e{0}", - " " - ], - "deprecated-config-version": [ - "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", - "You can either manually add all missing settings or delete the old one" - ], - "missing-config-settings": "There are missing config settings: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cThere are no missing config settings.", - "§cYou can manually update it to §c§l{0}" - ], - "join-message": "§e{0} §7has §ajoined §7the server", - "quit-message": "§e{0} §7has §cleft §7the server", - "timer-paused-message": [ - "The timer is §cpaused", - "Use §e/timer resume §7to start it" - ], - "cheats-detected": [ - "§e{0} §7has §ccheated", - "§cNo §7further statistics can be collected" - ], - "cheats-already-detected": [ - "On this server has been §ccheated", - "§cNo §7further statistics can be collected" - ], - "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", - "config-reset": "The §elocal §7settings were reset §asuccessfully", - "player-config-loaded": "Your settings have been loaded §asuccessfully", - "player-config-saved": "Your settings have been saved §asuccessfully", - "player-config-reset": "Your settings were reset §asuccessfully", - "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", - "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", - "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Dragons killed", - "stat-deaths": "Deaths", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Damage dealt", - "stat-damage-taken": "Damage taken", - "stat-blocks-mined": "Blocks destroyed", - "stat-blocks-placed": "Blocks placed", - "stat-blocks-traveled": "Blocks travelled", - "stat-challenges-played": "Challenges played", - "stat-jumps": "Jumps", - "stats-of": "§8» §7Stats of §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Place" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positions are §cdeactivated", - "position-other-world": "This position is in another world §8(§e{0}§8)", - "position-not-exists": "The position §e{0} §cdoesn't §7exist", - "position-already-exists": "The position {0} §calready §7exist", - "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "no-positions": [ - "There are no §epositions §7set in this world", - "Create on with §e/{0}" - ], - "no-positions-global": [ - "There are no §epositions §7set", - "Create on with §e/{0}" - ], - "command-no-target": "§cNo §7players has been found", - "command-heal-healed": "You have been §ahealed", - "command-heal-healed-others": "You healed §e{0} player/s", - "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", - "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", - "command-village-search": "A village is being searched..", - "command-village-teleport": "You have been §ateleported to a village", - "command-village-not-found": "§cNo §7new village was found", - "command-weather-set-clear": "Weather was changed to §eclear", - "command-weather-set-rain": "Weather was changed to §erainy", - "command-weather-set-thunder": "Weather was changed to §ethundery", - "command-invsee-open": "Inventory of §e{0} §7opened", - "command-enderchest-open": "You opened your §5Enderchest", - "command-difficulty-change": "Difficulty changed to {0}", - "command-difficulty-current": "Current difficulty is {0}", - "command-search-nothing": "§e{0} §7is not dropped by any special block", - "command-search-result": "§e{0} §7drops from §e{1}", - "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", - "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", - "command-searchloot-result": [ - "§e{0} §7drops the loot of §e{1}", - "The loot of §e{0} §7is dropped by §e{2}" - ], - "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", - "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", - "command-time-query": [ - "§8» §7Current ingame times", - "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Noon", - "command-time-night": "Night", - "command-time-midnight": "Midnight", - "command-time-day": "Day", - "command-fly-enabled": "You can fly §anow", - "command-fly-disabled": "You can §cno longer §7fly", - "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", - "command-feed-fed": "Your appetite was §esated", - "command-feed-others": "You satiated the appetite of §e{0} §7player/s", - "command-gamestate-reload": "The gamestate was §areloaded", - "command-gamestate-reset": "The gamestate was §areset", - "command-world-teleport": "You'll be teleported into the §e{0}", - "command-back-no-locations": "You §cweren't §7teleported yet", - "command-back-teleported": "You were teleported §e{0} §7location back", - "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", - "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", - "command-god-mode-enabled": "You are now in §aGod mode", - "command-god-mode-disabled": "You are §cno longer in God mode", - "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", - "traffic-light-challenge-fail": "§e{0} §7went over §cred", - "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", - "death-message": "§e{0} §7died", - "death-message-cause": "§e{0} §7died by §e{1}", - "health-inverted": "Your hearts have been §cinverted", - "exp-picked-up": "§e{0} §7collected §cEXP", - "unable-to-find-fortress": "§cNo fortress §7could be found", - "unable-to-find-bastion": "§cNo bastion §7could be found", - "death-collected": "Death reason §e{0} §7registered", - "item-collected": "Item §e{0} §7registered", - "items-to-collect": "§7Items to collect §8» §e{0}", - "backpacks-disabled": "Backpacks are currently §cdeactivated", - "backpack-opened": "You opened the {0}", - "top-to-overworld": "You have been teleported to the §eoverworld", - "top-to-surface": "You have been teleported to the §etop", - "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", - "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", - "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", - "snake-failed": "§e{0} §7stepped over the §9line", - "only-dirt-failed": "§e{0} §7did not stand on dirt", - "no-mouse-move-failed": "§e{0} §7moved his mouse", - "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", - "only-down-failed": "§e{0} §7went up one block", - "food-once-failed": "§e{0} §7suffocated by §e{1}", - "food-once-new-food-team": "§e{0} §7ate §e{1}", - "food-once-new-food": "§eYou §7ate §e{1}", - "sneak-damage-failed": "§e{0} §7sneaked", - "jump-damage-failed": "§e{0} §7jumped", - "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", - "all-items-skipped": "Item §e{0} §7skipped", - "all-items-already-finished": "All items has been already found", - "all-items-found": "Item §e{0} §7registered by §e{1}", - "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Swapped with §e{0}", - "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", - "force-height-success": "All players were on the §aright §7height", - "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", - "force-block-success": "All players were on the §aright §7block", - "force-biome-fail": "The biome §e{0} §chasn't been found", - "force-biome-success": "§e{0} §7found the biome §e{1}", - "force-mob-fail": "The mob §e{0} §chasn't been killed", - "force-mob-success": "§e{0} §7killed the mob §e{1}", - "force-item-fail": "Item §e{0} §chasn't been found", - "force-item-success": "§e{0} §afound §7the item §e{1}", - "new-effect": "Effect §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Which item is missing?", - "missing-items-inventory-open": "§8[§aOpen GUI§8]", - "loops-cleared": "§e{0} §7Loops cancelled", - "stopped-moving": "§e{0} §7hasn't moved for too long", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "height-reached": "§e{0} §7reached §eY = {1} §7first!", - "race-goal-reached": "§e{0} §7reached the goal!", - "points-change": "§e{0} §7Points", - "force-item-battle-found": "You've found §e{0}!", - "force-item-battle-new-item": "Item to find: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "You've killed §e{0}!", - "force-mob-battle-new-mob": "Mob to kill: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "You've completed §e{0}!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "You've found §e{0}!", - "force-block-battle-new-block": "Block to find: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display":"§eItem: {0}", - "force-battle-height-target-display": "§eHeight: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiome: {0}", - "force-battle-damage-target-display": "§eDamage: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Height to reach: §e{0}", - "extreme-force-battle-reached-height": "You've reached height §e{0}!", - "extreme-force-battle-new-biome": "Biome to find: §e{0}", - "extreme-force-battle-found-biome": "You've found the biome §e{0}!", - "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", - "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position to reach: §e{0}", - "extreme-force-battle-reached-position": "You've reached the position §e{0}!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Is it you?", - "Woahh! That's fast" - ], - "random-event-entities": [ - "Is this a zoo?", - "Where did this come from?", - "What are you doing here?" - ], - "random-event-hole": [ - "But you fell pretty deep", - "From the very top to the very bottom..", - "Where did this hole come from?" - ], - "random-event-fly": [ - "Good flight :)", - "I believe I can fly..", - "So this is what flying feels like" - ], - "random-event-webs": [ - "Have they been here for a long time?" - ], - "random-event-ores": [ - "Where did all the ores go?", - "Aren't there any ores here?", - "Was there any ore here??" - ], - "random-event-sickness": [ - "Are you sick??", - "What's going on now?!" - ], - "bossbar-timer-paused": "§8» §7The timer is §cpaused", - "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7All items found", - "bossbar-force-height-waiting": "§8» §7Waiting for next height..", - "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Waiting for next block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", - "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Waiting for next item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", - "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", - "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", - "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7seconds", - "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", - "subtitle-time-minutes": "§e{0} §7minutes", - "subtitle-launcher-description": "§7Power §e{0}", - "subtitle-blocks": "§e{0} §7Blocks", - "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Your place §8» §e{0}", - "server-reset": [ - "§8————————————————————", - " ", - "§8» §cServer reset", - " ", - "§7Reset by §4§l{0}", - "§7The server is §crestarting", - " ", - "§8————————————————————" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cThe challenge is over!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cThe challenge is over!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7The challenge was ended!", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7The challenge was ended!", - "§7Winner: §e§l{1}", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cThe challenge is over! §6#FeelsBadMan ✞", - "§7Time wasted: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §acontinued" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpaused" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aActivated" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeactivated" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Timer is stopped.." - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", - "menu-title": "Menu", - "menu-timer": "§6Timer", - "menu-goal": "§5Goal", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blocks & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eSettings", - "menu-custom": "§aCustom Challenges", - "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Activated §8» §aYes", - "lore-category-deactivated": "§7Activated §8» §cNo", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges that *couldn't be*", - "*assigned* with a category" - ], - "category-randomizer": [ - "§6Randomizer", - "Experience a *randomized gameplay*" - ], - "category-limited_time": [ - "§aLimited Time", - "Some things are timely restricted" - ], - "category-force": [ - "§3Force", - "You have to fulfill specific", - "*intermediate goals* to survive" - ], - "category-world": [ - "§4World Change", - "The world will be *modified* significant" - ], - "category-damage": [ - "§cSchaden", - "New *damage rules*" - ], - "category-effect": [ - "§5Effekte", - "Have fun with *lots of effects*" - ], - "category-inventory": [ - "§6Inventory", - "You'll have problems managing *your inventory*" - ], - "category-movement": [ - "§aBewegung", - "You're *restricted in your movements*" - ], - "category-entities": [ - "§bEntities", - "Entities will be *modified*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges that will *send*", - "you to *another world*" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Goals that *couldn't be*", - "*assigned* with a category" - ], - "category-kill_entity": [ - "§cEntities töten", - "Kill *specific entities* to win" - ], - "category-score_points": [ - "§eBest Score", - "Get the best score *to win*" - ], - "category-fastest_time": [ - "§6Fastest Time", - "Be the fastest *to win*" - ], - "category-force_battle": [ - "§bForce Battles", - "Fulfill the given *intermediate goals*", - "to earn points.", - " ", - "The player with the *most points* wins." - ], - "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", - "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", - "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Max health: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Strength: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", - "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", - "item-blocks-description": "§8» Blocks to walk: §e{0}", - "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", - "item-force-battle-goal-jokers": [ - "§6Number of jokers", - "The *amount* of *jokers*", - "hat every player has" - ], - "item-force-battle-show-scoreboard": [ - "§bShow Scoreboard" - ], - "item-force-battle-duped-targets": [ - "§cDuped Targets", - "Targets can occur *multiple times*" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "The *maximum radius*, in which the", - "positions will be located" - ], - "item-difficulty-setting": [ - "§aDifficulty", - "Sets the *Difficulty*" - ], - "item-one-life-setting": [ - "§cOne Teamlife", - "*Everyone* dies when *one player dies*" - ], - "item-respawn-setting": [ - "§4Respawn", - "When you *die*, you won't be a *spectator*" - ], - "item-death-message-setting": [ - "§6Death messages", - "Toggles *death messages*" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMax health", - "Sets the *max health*", - "for *all players*" - ], - "item-soup-setting": [ - "§cSoup healing", - "When you use a *mushroom soup*", - "you will be healed for *4 hearts*" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Damage you take will be *multiplied*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "It will be displayed in the *chat*", - "when anybody takes *damage*" - ], - "item-health-display-setting": [ - "§cHealth Display", - "The *hearts* of all players", - "will be showed in the *tablist*" - ], - "item-position-setting": [ - "§9Positions", - "Allows you to mark *positions*", - "with */pos*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Allows you to open *your backpack* or", - "the *team backpack* with */backpack*" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Different *settings* to simplify", - "the *farming* of items" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Gold ore* will be directly dropped as *Gold ingot*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Iron ore* will be directly dropped as *Iron ingot*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Coal* will be directly dropped as *torches*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* will always drop *flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Ore veins* will be directly destroyed" - ], - "item-cut-clean-inventory-setting": [ - "§6Direct Into Inventory", - "*Items* will be put *directly* into your", - "*inventory* instead of dropping" - ], - "item-cut-clean-food-setting": [ - "§cCooked Food", - "*Raw meat* will be directly dropped as *cooked meat*" - ], - "item-glow-setting": [ - "§fPlayer Glow", - "*Players* are visible through *walls*" - ], - "no-hunger-setting": [ - "§cNo Hunger", - "You don't get *hungry*" - ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "You can *move* before", - "the game has been *started*" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "After you've *taken* damage", - "you can *get* damage *immediately* again" - ], - "item-timber-setting": [ - "§bTimber", - "You can destroy a *tree*", - "by breaking down *a single block* of the tree" - ], - "item-timber-setting-logs": "§6Logs", - "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "You don't lose any *items*", - "when you die" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monsters *can't destroy* anything" - ], - "item-no-item-damage-setting": [ - "§5No Item Damage", - "*Items* are *unbreakable*" - ], - "top-command-setting": [ - "§dTop Command", - "You can *teleport* to the *top*", - "of the world or to the *overworld*", - "with /top" - ], - "item-fortress-spawn-setting": [ - "§cFortress Spawn", - "When you go into the *nether*", - "you will always spawn in a *fortress*" - ], - "item-bastion-spawn-setting": [ - "§cBastion Spawn", - "When you go into the *nether*", - "you will always spawn in a *bastion*" - ], - "item-no-offhand-setting": [ - "§6No Offhand", - "The *second hand* will be blocked" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Sets *whether* and", - "*how* to *regenerate*" - ], - "item-regeneration-setting-not_natural": "§6Not Natural", - "item-immediate-respawn-setting": [ - "§6Direct Respawn", - "When you *die* you *respawn* automatically", - "*without* seeing the *death screen*" - ], - "item-slot-limit-setting": [ - "§4Inventory Slots", - "Sets how many *inventory*", - "*slots* are useable" - ], - "item-death-position-setting": [ - "§cDeath Position", - "When you die, */pos* creates", - "a position at your death point" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "When you execute */ec*,", - "your *Enderchest* opens" - ], - "item-split-health-setting": [ - "§cSplit Health", - "Sets whether *all players*", - "share the same *health*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "The *old 1.8 PvP System* will be used", - "There will be no *attack damage cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Death Rescue", - "If you *instant die* from a *challenge*", - "*totems* can *rescue* you" - ], - "item-traffic-light-challenge": [ - "§cTraffic Light Challenge", - "The *traffic light* switches every few minutes.", - "If you go on *red*, you die" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Each *block* drops a *random item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "If you *craft* something you will get another *random item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "When an *Entity* spawns, it spawns *twice*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Every *few minutes* every player gets *random items*" - ], - "item-damage-block-challenge": [ - "§4Damage per Block", - "You take *damage* for", - "every *block* you walk" - ], - "item-hunger-block-challenge": [ - "§6Hunger per Block", - "You lose *food* for", - "every *block* you walk" - ], - "item-stone-sight-challenge": [ - "§fStone Sight", - "*Mobs* that you look in the", - "*eyes* turn to stone" - ], - "item-no-mob-sight-challenge": [ - "§cMob Sight Damage", - "When you look into the *eyes* of an", - "*entity*, you get *damage*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Bedrock *generates* under you*", - "the whole time" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Huge *walls of bedrock*", - "are *generating* behind you" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "The *floor* is disappearing", - "to *void* behind you" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Player *inventories* are *cleared*", - "when a *player* takes damage" - ], - "item-no-trading-challenge": [ - "§2No Trading", - "You *cannot* trade", - "with villagers" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "If you *break* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "If you *place* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-no-exp-challenge": [ - "§aNo EXP", - "If you pickup *EXP* you die" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Every few minutes the *hearts are inverted*.", - "If you have *8 hearts*, you will have *2 hearts*", - "and the other way around" - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Every *few minutes* you have to do a random", - "*jump and run* which gets *harder* every time" - ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "The *health* of all mobs", - "is randomized" - ], - "item-snake-challenge": [ - "§9Snake", - "Each player draws a *deadly line*", - "behind them" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "If you deal damage to entites", - "you take the same damage" - ], - "item-duped-spawning-challenge": [ - "§cDuped Spawning", - "If a mob *spawns*", - "it spawns *two times*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "If you *kill* a mob", - "*two new* are spawning" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "If you kill a *mob* it", - "spawns *twice* as many", - "times as the *previous* time", - " ", - "Maximum are *512* Mobs each time" - ], - "item-floor-lava-challenge": [ - "§6The Floor Is Lava", - "*Blocks* below you transform first", - "to *magma* and then to *lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "You must stay on *dirt*", - "otherwise you will *die*" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Each *food* can be*", - "*eaten* only once" - ], - "item-food-once-challenge-player": "§6Player", - "item-food-once-challenge-everyone": "§5Everyone", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks* that players are in", - "*break* down from *above*" - ], - "item-one-durability-challenge": [ - "§4One Durability", - "Items are *destroyed* after one *use*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "The *drop chance* of each *block*", - "will be set to the defined *percentage*" - ], - "item-invisible-mobs-challenge": [ - "§fInvisible Mobs", - "All *Mobs* have an", - "*invisibility* effect" - ], - "item-mob-transformation-challenge": [ - "§cMob Transformation", - "When you hit a mob, it *turns*", - "into the last mob *you* hit" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "A *random entity* spawns", - "everytime you *jump*" - ], - "item-no-mouse-move-challenge": [ - "§cMouse Movement Damage", - "You take *damage* everytime", - "you *move* your *view*" - ], - "item-no-duped-items-challenge": [ - "§6No Duped Items", - "Players are *not allowed* to have", - "the *same item* in their *inventories*", - "at the same time" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "You have to keep *2 blocks* away", - "from all *mobs* or you will *get* sick" - ], - "item-only-down-challenge": [ - "§cOnly Down", - "If you go *up* by *a block*, you *die*" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Damage", - "You *take* the set amount of *damage*", - "for every new *advancement*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAll Blocks Disappear", - "With different *interactions* all", - "*blocks* of a certain type", - "disappear in the same chunk" - ], - "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", - "item-all-blocks-disappear-break-challenge": [ - "§bBy breaking", - "If you *break* a *block* all blocks", - "of the same types disappear" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBy Placing", - "If you *place* a *block* all blocks", - "of the same types disappear" - ], - "item-water-allergy-challenge": [ - "§9Water Allergy", - "You *take* the set amount of *damage*", - "while you are in *water*" - ], - "item-max-biome-time-challenge": [ - "§2Max Biome Time", - "The *time* that you may spend", - "in every *biome* is limited" - ], - "item-max-height-time-challenge": [ - "§9Max Biome Time", - "The *time* that you may spend", - "on every *height* is limited" - ], - "item-permanent-item-challenge": [ - "§cPermanent Items", - "*Items* cannot be dropped", - "or put *away*" - ], - "item-sneak-damage-challenge": [ - "§6Damage per Sneak", - "You *take* the set amount", - "of *damage* if you *sneak*" - ], - "item-jump-damage-challenge": [ - "§6Damage per Jump", - "You *take* the set amount", - "of *damage* if you *jump*" - ], - "item-random-dropping-challenge": [ - "§cRandom Item Dropping", - "Every few seconds a *random item*", - "will be *dropped* from your *inventory*" - ], - "item-random-swapping-challenge": [ - "§cRandom Item Swapping", - "Every few seconds a *random item*", - "will be *swapped* with *another item*", - "in your *inventory*" - ], - "item-random-removing-challenge": [ - "§cRandom Item Removing", - "Every few seconds a *random item*", - "will be *removed* from your *inventory*" - ], - "item-death-on-fall-challenge": [ - "§fDeath On Fall Damage", - "You *die instantly*, when", - "you take *fall damage*" - ], - "item-zero-hearts-challenge": [ - "§6Zero Hearts", - "After a *protection time* you have to", - "get *absorption permanently* else you will die" - ], - "item-random-effect-challenge": [ - "§6Random Effects", - "You get a *random potion effect*", - "in a set *interval*" - ], - "menu-random-effect-challenge-settings": "Random Effects", - "item-random-effect-time-challenge": [ - "§6Interval", - "The *interval* you get the *effect* in" - ], - "item-random-effect-length-challenge": [ - "§6Length", - "The *length* you have the *effect*" - ], - "item-random-effect-amplifier-challenge": [ - "§6Amplifier", - "The *amplifier* the effect has" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanent Effects", - "Everytime you *take damage* you get", - "a random *permanent potion effect*" - ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In a set *interval* a random", - "*challenge* will be *activated*" - ], - "item-anvil-rain-challenge": [ - "§cAnvil Rain", - "*Anvils* are falling from the *sky*" - ], - "menu-anvil-rain-challenge-settings": "Anvil Rain", - "item-anvil-rain-time-challenge": [ - "§6Interval", - "The *interval*, the *anvils* are spawning in" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "The *range* of chunks, the *anvils* are spawning in" - ], - "item-anvil-rain-count-challenge": [ - "§6Amount", - "The *amount* of anvils that", - "are spawning in one chunk" - ], - "item-anvil-rain-damage-challenge": [ - "§6Damage", - "The *damage* you take from an *anvil*" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "You have to do a *Water MLG*", - "over and over again" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Every *few minutes* you will be", - "*swapped* with a *random entity*", - "in a *200 blocks* range" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Every *few minutes* one of", - "*{0} random Events* will be activated" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "A random item will be removed from", - "your inventory for every", - "*block* / *chunk* you walk" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "The more *you jump*, the *higher* you jump" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Every *few minutes* you have to be", - "on a *certain height*, else you die" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Every *few minutes* you have to be", - "on a *certain block*, else you die" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Every *few minutes* you have to be", - "in a *certain biome*, else you die", - "The *rarer* the biome, the *more time* you have" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Every *few minutes* you have to", - "*kill* a *certain mob*, else you die" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Every *few minutes* you have to get", - "a *certain item*, else you die" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "A *random player* gets a *random item*", - "every *few seconds*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "You *cannot stop* to *walk forwards*" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "When you *pick up* an *item*", - "you will be *launched* into the air" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In a *set interval* ", - "the water rises in the *Overworld*", - "and the *lava* in the nether", - " ", - "Should be played with a *few people*!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAll Mobs To Death Point", - "If a *Mob* gets *killed* by a player", - "all mobs of the *same type* will be", - "*teleported* to its *death point*" - ], - "item-ice-floor-challenge": [ - "§bIce Floor", - "*Air* will be replaced in a", - "*3x3* area with *packed ice*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlocks Disappear After Time", - "Placed *blocks*, will *disappear*", - "after a *few seconds*" - ], - "item-missing-items-challenge": [ - "§9Items Missing", - "Every few minutes a *random item disappears* from", - "your *inventory* and you have to *guess* which it was" - ], - "item-damage-item-challenge": [ - "§cDamage Per Item", - "When you *pickup* or *click* an item", - "in your *inventory* you take the", - "*amount* of the items as *damage*" - ], - "item-damage-teleport-challenge": [ - "§cRandom Teleport On Damage", - "You'll be teleported randomly", - "when you take damage" - ], - "item-loop-challenge": [ - "§6Loop Challenge", - "Certain actions are *looped*", - "until a player *sneaks*" - ], - "item-uncraft-challenge": [ - "§6Items Crafting Back", - "*Items* in your inventory are", - "*crafting* back all few seconds" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "For each heart of *damage*, you'll be", - "*frozen* for a certain time" - ], - "item-dont-stop-running-challenge": [ - "§9Dont stop running", - "You are only allowed to stand *still*", - "a certain *time* before you *die*" - ], - "item-consume-launch-challenge": [ - "§cConsume Boost", - "When you *eat* an *item*", - "you will be *launched* into the air" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blocks", - "*Every 500 Blocks walked* players", - "will get a *64 stack* of a random item.", - "*Blocks* and *Entities* won't *drop* any items." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "The *border size* adjusts to *the player*", - "with the *most levels*." - ], - "item-chunk-effect-challenge": [ - "§3Random Chunk Effects", - "In *each chunk* you'll get", - "a random *potion effect*" - ], - "item-repeat-chunk-challenge": [ - "§2Repeated Chunk", - "Blocks that are *placed or destroyed*", - "will be placed / destroyed in *every chunk*" - ], - "item-blocks-fly-challenge": [ - "§fBlocks Fly in Air", - "*Blocks* you've *walked* on fly", - "into the air after *one second*" - ], - "item-respawn-end-challenge": [ - "§5Mobs Respawn In End", - "*Killed mobs* respawn in *end dimension*" - ], - "item-block-effect-challenge": [ - "§3Random Block Effects", - "On *each block* you'll get", - "a random *potion effect*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Got Random Effects", - "*Every Mob* has a random", - "potion effect with *max amplifier*" - ], - "item-block-mob-challenge": [ - "§cMob Blocks", - "A *random mob* spawns out of *every broken block*", - "and to *get the block* you have to *kill it*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "All mob drops are *randomly swapped*." - ], - "item-no-shared-advancements-challenge": [ - "§2No Shared Advancements", - "You're *not allowed* to get *advancements* someone else", - "*already did*. Else *you'll die*." - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Deletion", - "*Chunks* that players are in *delete*", - "completely after the given *time*" - ], - "item-dragon-goal": [ - "§5Ender Dragon", - "Kill the *Ender Dragon* to win" - ], - "item-wither-goal": [ - "§dWither", - "Kill a *Wither* to win" - ], - "item-iron-golem-goal": [ - "§bIron Golem", - "Kill an *Iron Golem* to win" - ], - "item-snow-golem-goal": [ - "§bSnowman", - "Kill a *Snowman* to win" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Kill an *Elder Guardian* to win" - ], - "item-warden-goal": [ - "§5Warden", - "Kill an *Warden* to win" - ], - "item-most-deaths-goal": [ - "§6Most Deaths", - "Who *collects* the most *different deaths* wins" - ], - "item-most-items-goal": [ - "§cMost Items", - "Who *collects* the most *different items* wins" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Who survived until the end wins" - ], - "item-mine-most-blocks-goal": [ - "§eMost Blocks", - "Who *breaks* the most *blocks* wins" - ], - "item-most-xp-goal": [ - "§aMost XP", - "Who *collects* the most *EXP* wins" - ], - "item-first-one-to-die-goal": [ - "§cFirst Death", - "Who *dies* first wins" - ], - "item-collect-wood-goal": [ - "§6Collect Wood", - "Who first collected all types of wood set wins" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Both", - "item-all-bosses-goal": [ - "§bAll Bosses", - "Each boss must has to be killed once to win" - ], - "item-all-bosses-new-goal": [ - "§5All Bosses (+ Warden)", - "Each boss must has to be killed once to win" - ], - "item-all-mobs-goal": [ - "§bAll Mobs", - "Each mob has to be killed once to win" - ], - "item-all-monster-goal": [ - "§bAll Monsters", - "Each monster has to be killed once to win" - ], - "item-all-items-goal": [ - "§2All Items", - "Find *all items* that are in *Minecraft*" - ], - "item-finish-raid-goal": [ - "§6Finish Raid", - "The first player that *finishes* a *raid* wins" - ], - "item-most-emeralds-goal": [ - "§2Most Emeralds", - "The player with the *most*", - "*emeralds* wins" - ], - "item-all-advancements-goal": [ - "§6All Advancements", - "The first player that *gets* all *advancements* wins" - ], - "item-max-height-goal": [ - "§fMaximum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-min-height-goal": [ - "§fMinimum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-race-goal": [ - "§5Race", - "The *first* player to *reach* a", - "*random* location in the overworld wins" - ], - "item-most-ores-goal": [ - "§9Most Ores", - "The player that mines the most ores wins" - ], - "item-find-elytra-goal": [ - "§fFind Elytra", - "The *player* that finds an elytra *wins*" - ], - "item-eat-cake-goal": [ - "§fEat Cake", - "The player that *eats a cake* first *wins*" - ], - "item-collect-horse-armor-goal": [ - "§bCollect Horse Armor", - "The player that *collects* every", - "horse armor first *wins*" - ], - "item-collect-ice-goal": [ - "§bCollect Ice Blocks", - "The player that *collects* every", - "ice blocks and snow first *wins*" - ], - "item-collect-swords-goal": [ - "§9Collect Swords", - "The player that *collects* every", - "sword first *wins*" - ], - "item-collect-workstations-item": [ - "§6Collect Workstations", - "The player that *collects* every", - "villager workstation first *wins*" - ], - "item-eat-most-goal": [ - "§6Eat most", - "The player that fills the mods hunger bars *wins*" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Each player gets *a random item* that", - "he has *to find*.", - "The player that *found* the *most items*, wins." - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bGive Item On Skip", - "If a player *skips* an item,", - "they will *receive* it" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Each player gets *a random mob* that", - "he has to *kill*.", - "The player that *killed* the *most mobs*, wins." - ], - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Each player gets a *random advancement*,", - "that he has to complete." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-get-full-health-goal": [ - "§aGet Full Health", - "The first player to gain full health wins." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Every player gets a *random*", - "*block*, on which he has to stand" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bGive Block On Skip", - "If a player *skips* a block,", - "they will *receive* it" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Each player gets a *random biome*,", - "that he has to *enter*." - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Each player gets a *random damage amount*,", - "that he has to *take*." - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Each player gets a *random height*,", - "that he has to *reach*." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Each player gets a *random position*,", - "that he has to *reach*." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Each player gets a *random target*,", - "that he has to reach." - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-damage-rule-none": [ - "§6General Damage", - "Sets whether you can get damage or not" - ], - "item-damage-rule-fire": [ - "§6Fire Damage", - "Sets whether you get *damage* from *Fire* and *Lava*" - ], - "item-damage-rule-attack": [ - "§3Attack Damage", - "Sets whether you get *damage* from *Melee Attacks* of entites" - ], - "item-damage-rule-projectile": [ - "§6Projectile Damage", - "Sets whether you get *damage* from *Projectiles*" - ], - "item-damage-rule-fall": [ - "§fFall Damage", - "Sets whether you get *damage* from *Fall Damage" - ], - "item-damage-rule-explosion": [ - "§cExplosion Damage", - "Sets whether you get *damage* from *Explosions" - ], - "item-damage-rule-drowning": [ - "§9Drowning Damage", - "Sets whether you get *damage* from *Drowning" - ], - "item-damage-rule-block": [ - "§eBlock Damage", - "Sets whether you get *damage* from *Falling Blocks" - ], - "item-damage-rule-magic": [ - "§5Magic Damage", - "Sets whether you get *damage* from", - "*Poison, Wither or other Potions" - ], - "item-damage-rule-freeze": [ - "§cFreeze Damage", - "Sets whether you get *damage* from *Freezing*" - ], - "item-block-material": [ - "{0}", - "Sets whether *{1}* can be used" - ], - "custom-limit": "You've reached the limit of §e{0} challenges", - "custom-not-deleted": "Challenge doesn't exist yet!", - "custom-saved": "§7Challenge §asaved §7locally", - "custom-saved-db": [ - "To save it in your database use §e/db save customs", - "§cWarning: §7Old challenges will be overwritten!" - ], - "custom-no-changes": "You haven't made any changes", - "custom-name-info": "Type the new name into the chat", - "custom-command-info": [ - "Type the command §ewithout / §7in chat", - "Allowed commands: §e{0}", - "§cOther commands can be allowed in the config" - ], - "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", - "custom-chars-max_length": "You've reached the limit of {0} characters", - "custom-not-loaded": [ - " ", - "There are no currently loaded challenges.", - "You're missing your challenges? §e/db load customs", - "You've got problems with saving them?", - "Save your challenges before leaving with §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6View Challenges", - "custom-main-create-challenge": "§aCreate Challenge", - "custom-title-trigger": "Trigger", - "custom-title-action": "Action", - "custom-title-view": "View", - "custom-sub-finish": "§aFinished", - "item-custom-info-delete": [ - "§cDelete", - "*Warning* This Action cannot be made *undone*" - ], - "item-custom-info-save": "§aSave", - "item-custom-info-trigger": [ - "§cTrigger", - "*Click here* to set what has to be happening", - "for the *action* to execute" - ], - "item-custom-info-action": [ - "§bAction", - "*Click here* to set what should happen", - "once the *trigger* is met" - ], - "item-custom-info-material": [ - "§6Display Item", - "*Click here* to change the display item" - ], - "item-custom-info-name": [ - "§6Name", - "*Click here* to change the name via chat", - "Max Characters: 50" - ], - "custom-info-currently": "§7Set §8» §e", - "custom-info-trigger": "§7Trigger", - "custom-info-action": "§7Action", - "item-custom-trigger-jump": [ - "§aPlayer Jumps" - ], - "item-custom-trigger-sneak": [ - "§aPlayer Sneaks" - ], - "item-custom-trigger-move_block": [ - "§6Player Walks A Block" - ], - "item-custom-trigger-death": [ - "§cEntity Dies" - ], - "item-custom-trigger-damage": [ - "§cEntity Takes Damage" - ], - "item-custom-trigger-damage-any": [ - "§aAny Cause" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Takes Damage By Player" - ], - "item-custom-trigger-intervall": [ - "§6Interval" - ], - "item-custom-trigger-intervall-second": [ - "§6Each Second" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Every {0} Seconds" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Every {0} Minutes" - ], - "item-custom-trigger-block_place": [ - "§aBlock Placed" - ], - "item-custom-trigger-block_break": [ - "§cBlock Destroyed" - ], - "item-custom-trigger-consume_item": [ - "§2Consume Item" - ], - "item-custom-trigger-pickup_item": [ - "§bPickup Item" - ], - "item-custom-trigger-drop_item": [ - "§9Player Dropped Item" - ], - "item-custom-trigger-advancement": [ - "§cPlayer Gets Advancement" - ], - "item-custom-trigger-hunger": [ - "§2Player Looses Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Player Moves Block Down" - ], - "item-custom-trigger-move_up": [ - "§6Player Moves Block Up" - ], - "item-custom-trigger-move_camera": [ - "§6Moves Camera" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Player Is On Specific Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Player Is Not On Specific Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Player Gets XP" - ], - "item-custom-trigger-level_up": [ - "§5Player Gets Level" - ], - "item-custom-trigger-item_craft": [ - "§6Player Crafts Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Player Is In Liquid" - ], - "item-custom-trigger-get_item": [ - "§aGet Item", - "Action will be executed *every time*", - "item is clicked or picked up" - ], - "item-custom-action-cancel": [ - "§4Cancel Trigger", - "Prevent that the trigger will be executed", - "Non preventable Trigger: *Jump*, *Sneak*, *Death*", - "*Advancement*, *Level Up*, *In Liquid*" - ], - "item-custom-action-command": [ - "§4Execute Command", - "Make players execute commands.", - "Commands are executed for players via */execute as*.", - "Allowed commands can be set in plugin config.", - "The player doesn't need the *permission* to the commands.", - "Player aren't able to execute *plugin commands*." - ], - "item-custom-action-kill": [ - "§4Kill", - "Kill entities" - ], - "item-custom-action-damage": [ - "§cDamage", - "Hurt entities" - ], - "item-custom-action-heal": [ - "§aHeal", - "Restore entity health" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Make Entities get hunger" - ], - "item-custom-action-max_health": [ - "§cChange Max Health", - "Modify the max health of players.", - "Will be reset with */gamestate reset*" - ], - "item-custom-action-max_health-offset": [ - "§cHealth Change", - "Choose how the max health should be changed" - ], - "item-custom-action-spawn_entity": [ - "§3Spawn Entity", - "Spawn an entity with a specific type" - ], - "item-custom-action-random_mob": [ - "§6Random Entity", - "Spawn a random entity" - ], - "item-custom-action-random_item": [ - "§bRandom Item", - "Give random items to players" - ], - "item-custom-action-uncraft_inventory": [ - "§eUncraft Inventory", - "Make players inventories uncraft" - ], - "item-custom-action-boost_in_air": [ - "§fBoost In Air", - "Boost entities into the air" - ], - "item-custom-action-boost_in_air-strength": [ - "§fAmplifier" - ], - "item-custom-action-potion_effect": [ - "§dPotion Effect", - "Add a potion effect to entities" - ], - "item-custom-action-permanent_effect": [ - "§6Permanent Potion Effect", - "Add a permanent potion effect to players.", - "Uses the settings of the permanent effect challenge." - ], - "item-custom-action-random_effect": [ - "§dRandom Potion Effect", - "Add a random potion effect to entities" - ], - "item-custom-action-clear_inventory": [ - "§cClear Inventory", - "Clear the inventory of players" - ], - "item-custom-action-drop_random_item": [ - "§aDrop Item From Inventory", - "Drop a random item from the inventory onto the floor" - ], - "item-custom-action-remove_random_item": [ - "§cRemove Item From Inventory", - "Remove a random item from the inventory" - ], - "item-custom-action-swap_random_item": [ - "§6Swap Items In Inventory", - "Swap two items in the inventory" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Temporarily freeze mobs", - "Uses the settings of the freeze challenge" - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invert the current health of players" - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "All players have to do a water mlg to survive" - ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "A random player has to a a jump and run", - "that gets longer everytime" - ], - "item-custom-action-win": [ - "§6Win", - "The challenge will be won *by specific players*" - ], - "item-custom-action-random_hotbar": [ - "§eRandom Hotbar", - "The inventory is emptied and the player", - "gets a full hotbar of random items" - ], - "item-custom-action-modify_border": [ - "§bModify World Border", - "Make the world border *bigger* or *tinier*" - ], - "item-custom-action-modify_border-change": [ - "§dChange" - ], - "item-custom-action-swap_mobs": [ - "§5Swap mobs", - "Swap a mob with another of the same world" - ], - "item-custom-action-place_structure": [ - "§aPlace Structure", - "Places a structure" - ], - "item-custom-action-place_structure-random": "§bRandom structure", - "item-custom-setting-target-current": [ - "§6Current Entity", - "The action will be executed for the *current entity*" - ], - "item-custom-setting-target-every_mob": [ - "§4Every Mob", - "The action will be executed for *every mob*" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Every Mob Except Current", - "The action will be executed for *every mob*", - "*except* the current one" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Every Mob Except Players", - "The action will be executed for *every mob except players*" - ], - "item-custom-setting-target-random_player": [ - "§5Random Player", - "The action will be executed for a *random player*" - ], - "item-custom-setting-target-every_player": [ - "§cEvery Player", - "The action will be executed for *every player*" - ], - "item-custom-setting-target-current_player": [ - "§aCurrent Player", - "The action will be executed for the *active player*.", - "§7§oIf the current entity is not a player nothing will be happen" - ], - "item-custom-setting-target-console": [ - "§4Console", - "The action will be executed for the *console*" - ], - "item-custom-setting-entity_type-any": "§cAny Entity", - "item-custom-setting-entity_type-player": "§aPlayer", - "item-custom-setting-block-any": "§2Any Block", - "item-custom-setting-item-any": "§2Any Item", - "custom-subsetting-target_entity": "Target Entity", - "custom-subsetting-entity_type": "Entity Type", - "custom-subsetting-liquid": "Liquid", - "custom-subsetting-time": "Time", - "custom-subsetting-damage_cause": "Damage Cause", - "custom-subsetting-amount": "Amount", - "custom-subsetting-value": "Value Editor", - "custom-subsetting-health_offset": "Change", - "custom-subsetting-length": "Length", - "custom-subsetting-amplifier": "Amplifier", - "custom-subsetting-change": "Change", - "custom-subsetting-swap_targets": "Swap Targets" + "syntax": "Please use §e/{0}", + "reload": "Challenges Plugin is reloading...", + "reload-failed": "An §cerror &7occurred while reloading the plugin", + "reload-success": "Challenges Plugin §asuccessfully §7reloaded", + "player-command": "You must be a player!", + "no-permission": "You §cdon't §7have permissions to do this", + "enabled": "§aActivated", + "disabled": "§cDeactivated", + "customize": "§6Customize", + "navigate-back": "§8« §7Back", + "navigate-next": "§8» §7Next", + "seconds": "seconds", + "second": "second", + "minutes": "minutes", + "minute": "minute", + "hours": "hours", + "hour": "hour", + "amplifier": "amplifier", + "open": "Open", + "everyone": "§5Everyone", + "player": "§6Active player", + "none": "None", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer counting §aup", + "timer-counting-down": "§8» §7Timer counting §cdown", + "timer-is-paused": "§8» §7Timer §cpaused", + "timer-is-running": "§8» §7Timer §astarted", + "confirm-reset": "Confirm reset with §e/{0}", + "no-fresh-reset": [ + "The Server §ccan't §7be reset yet", + "The Challenge §chasn't been §7started" + ], + "new-challenge": "§a§lNew!", + "feature-disabled": "This function is currently §cdeactivated", + "challenge-disabled": "This challenge is currently §cdeactivated", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", + "timer-not-started": "The timer §chasn't been started", + "timer-was-started": "The timer has been §astarted", + "timer-was-paused": "The timer has been §cpaused", + "timer-was-set": "The timer has ben set on §e§l{0}", + "timer-already-started": "The timer is §calready running", + "timer-already-paused": "The timer is §calready paused", + "timer-mode-set-down": "The timer is counting §cdown", + "timer-mode-set-up": "The timer is counting §aup", + "no-database-connection": "There is §cno §7database connection", + "fetching-data": "Data is being retrieved..", + "undefined": "undefined", + "no-such-material": "This material doesn't exist", + "not-an-item": "§e{0} §7is not an item", + "no-such-entity": "This entity doesn't exist", + "not-alive": "§e{0} §7is not a living entity", + "no-loot": "§e{0} §7doesn't have any drops", + "deprecated-plugin-version": [ + " ", + "An update for the plugin is available", + "Download: §e{0}", + " " + ], + "deprecated-config-version": [ + "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", + "You can either manually add all missing settings or delete the old one" + ], + "missing-config-settings": "There are missing config settings: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cThere are no missing config settings.", + "§cYou can manually update it to §c§l{0}" + ], + "unsuported-language": [ + "§cThe language §7(§e{0}§7) is not supported" + ], + "not-op": [ + "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" + ], + "join-message": "§e{0} §7has §ajoined §7the server", + "quit-message": "§e{0} §7has §cleft §7the server", + "timer-paused-message": [ + "The timer is §cpaused", + "Use §e/timer resume §7to start it" + ], + "cheats-detected": [ + "§e{0} §7has §ccheated", + "§cNo §7further statistics can be collected" + ], + "cheats-already-detected": [ + "On this server has been §ccheated", + "§cNo §7further statistics can be collected" + ], + "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", + "config-reset": "The §elocal §7settings were reset §asuccessfully", + "player-config-loaded": "Your settings have been loaded §asuccessfully", + "player-config-saved": "Your settings have been saved §asuccessfully", + "player-config-reset": "Your settings were reset §asuccessfully", + "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", + "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", + "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Dragons killed", + "stat-deaths": "Deaths", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Damage dealt", + "stat-damage-taken": "Damage taken", + "stat-blocks-mined": "Blocks destroyed", + "stat-blocks-placed": "Blocks placed", + "stat-blocks-traveled": "Blocks travelled", + "stat-challenges-played": "Challenges played", + "stat-jumps": "Jumps", + "stats-of": "§8» §7Stats of §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Place" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positions are §cdeactivated", + "position-other-world": "This position is in another world §8(§e{0}§8)", + "position-not-exists": "The position §e{0} §cdoesn't §7exist", + "position-already-exists": "The position {0} §calready §7exist", + "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "no-positions": [ + "There are no §epositions §7set in this world", + "Create on with §e/{0}" + ], + "no-positions-global": [ + "There are no §epositions §7set", + "Create on with §e/{0}" + ], + "command-no-target": "§cNo §7players has been found", + "command-heal-healed": "You have been §ahealed", + "command-heal-healed-others": "You healed §e{0} player/s", + "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", + "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", + "command-village-search": "A village is being searched..", + "command-village-teleport": "You have been §ateleported to a village", + "command-village-not-found": "§cNo §7new village was found", + "command-weather-set-clear": "Weather was changed to §eclear", + "command-weather-set-rain": "Weather was changed to §erainy", + "command-weather-set-thunder": "Weather was changed to §ethundery", + "command-invsee-open": "Inventory of §e{0} §7opened", + "command-enderchest-open": "You opened your §5Enderchest", + "command-difficulty-change": "Difficulty changed to {0}", + "command-difficulty-current": "Current difficulty is {0}", + "command-search-nothing": "§e{0} §7is not dropped by any special block", + "command-search-result": "§e{0} §7drops from §e{1}", + "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", + "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", + "command-searchloot-result": [ + "§e{0} §7drops the loot of §e{1}", + "The loot of §e{0} §7is dropped by §e{2}" + ], + "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", + "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", + "command-time-query": [ + "§8» §7Current ingame times", + "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Noon", + "command-time-night": "Night", + "command-time-midnight": "Midnight", + "command-time-day": "Day", + "command-fly-enabled": "You can fly §anow", + "command-fly-disabled": "You can §cno longer §7fly", + "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", + "command-feed-fed": "Your appetite was §esated", + "command-feed-others": "You satiated the appetite of §e{0} §7player/s", + "command-gamestate-reload": "The gamestate was §areloaded", + "command-gamestate-reset": "The gamestate was §areset", + "command-world-teleport": "You'll be teleported into the §e{0}", + "command-back-no-locations": "You §cweren't §7teleported yet", + "command-back-teleported": "You were teleported §e{0} §7location back", + "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", + "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", + "command-god-mode-enabled": "You are now in §aGod mode", + "command-god-mode-disabled": "You are §cno longer in God mode", + "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", + "traffic-light-challenge-fail": "§e{0} §7went over §cred", + "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", + "death-message": "§e{0} §7died", + "death-message-cause": "§e{0} §7died by §e{1}", + "health-inverted": "Your hearts have been §cinverted", + "exp-picked-up": "§e{0} §7collected §cEXP", + "unable-to-find-fortress": "§cNo fortress §7could be found", + "unable-to-find-bastion": "§cNo bastion §7could be found", + "death-collected": "Death reason §e{0} §7registered", + "item-collected": "Item §e{0} §7registered", + "items-to-collect": "§7Items to collect §8» §e{0}", + "backpacks-disabled": "Backpacks are currently §cdeactivated", + "backpack-opened": "You opened the {0}", + "top-to-overworld": "You have been teleported to the §eoverworld", + "top-to-surface": "You have been teleported to the §etop", + "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", + "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", + "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", + "snake-failed": "§e{0} §7stepped over the §9line", + "only-dirt-failed": "§e{0} §7did not stand on dirt", + "no-mouse-move-failed": "§e{0} §7moved his mouse", + "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", + "only-down-failed": "§e{0} §7went up one block", + "food-once-failed": "§e{0} §7suffocated by §e{1}", + "food-once-new-food-team": "§e{0} §7ate §e{1}", + "food-once-new-food": "§eYou §7ate §e{1}", + "sneak-damage-failed": "§e{0} §7sneaked", + "jump-damage-failed": "§e{0} §7jumped", + "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", + "all-items-skipped": "Item §e{0} §7skipped", + "all-items-already-finished": "All items has been already found", + "all-items-found": "Item §e{0} §7registered by §e{1}", + "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Swapped with §e{0}", + "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", + "force-height-success": "All players were on the §aright §7height", + "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", + "force-block-success": "All players were on the §aright §7block", + "force-biome-fail": "The biome §e{0} §chasn't been found", + "force-biome-success": "§e{0} §7found the biome §e{1}", + "force-mob-fail": "The mob §e{0} §chasn't been killed", + "force-mob-success": "§e{0} §7killed the mob §e{1}", + "force-item-fail": "Item §e{0} §chasn't been found", + "force-item-success": "§e{0} §afound §7the item §e{1}", + "new-effect": "Effect §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Which item is missing?", + "missing-items-inventory-open": "§8[§aOpen GUI§8]", + "loops-cleared": "§e{0} §7Loops cancelled", + "stopped-moving": "§e{0} §7hasn't moved for too long", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "height-reached": "§e{0} §7reached §eY = {1} §7first!", + "race-goal-reached": "§e{0} §7reached the goal!", + "points-change": "§e{0} §7Points", + "force-item-battle-found": "You've found §e{0}!", + "force-item-battle-new-item": "Item to find: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "You've killed §e{0}!", + "force-mob-battle-new-mob": "Mob to kill: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "You've completed §e{0}!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "You've found §e{0}!", + "force-block-battle-new-block": "Block to find: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display": "§eItem: {0}", + "force-battle-height-target-display": "§eHeight: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiome: {0}", + "force-battle-damage-target-display": "§eDamage: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Height to reach: §e{0}", + "extreme-force-battle-reached-height": "You've reached height §e{0}!", + "extreme-force-battle-new-biome": "Biome to find: §e{0}", + "extreme-force-battle-found-biome": "You've found the biome §e{0}!", + "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", + "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position to reach: §e{0}", + "extreme-force-battle-reached-position": "You've reached the position §e{0}!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Is it you?", + "Woahh! That's fast" + ], + "random-event-entities": [ + "Is this a zoo?", + "Where did this come from?", + "What are you doing here?" + ], + "random-event-hole": [ + "But you fell pretty deep", + "From the very top to the very bottom..", + "Where did this hole come from?" + ], + "random-event-fly": [ + "Good flight :)", + "I believe I can fly..", + "So this is what flying feels like" + ], + "random-event-webs": [ + "Have they been here for a long time?" + ], + "random-event-ores": [ + "Where did all the ores go?", + "Aren't there any ores here?", + "Was there any ore here??" + ], + "random-event-sickness": [ + "Are you sick??", + "What's going on now?!" + ], + "bossbar-timer-paused": "§8» §7The timer is §cpaused", + "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7All items found", + "bossbar-force-height-waiting": "§8» §7Waiting for next height..", + "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Waiting for next block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", + "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Waiting for next item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", + "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", + "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7seconds", + "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", + "subtitle-time-minutes": "§e{0} §7minutes", + "subtitle-launcher-description": "§7Power §e{0}", + "subtitle-blocks": "§e{0} §7Blocks", + "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Your place §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServer reset", + " ", + "§7Reset by §4§l{0}", + "§7The server is §crestarting", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cThe challenge is over!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cThe challenge is over!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7The challenge was ended!", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7The challenge was ended!", + "§7Winner: §e§l{1}", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cThe challenge is over! §6#FeelsBadMan ✞", + "§7Time wasted: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §acontinued" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpaused" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aActivated" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeactivated" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Timer is stopped.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Goal", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blocks & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eSettings", + "menu-custom": "§aCustom Challenges", + "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Activated §8» §aYes", + "lore-category-deactivated": "§7Activated §8» §cNo", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges that *couldn't be*", + "*assigned* with a category" + ], + "category-randomizer": [ + "§6Randomizer", + "Experience a *randomized gameplay*" + ], + "category-limited_time": [ + "§aLimited Time", + "Some things are timely restricted" + ], + "category-force": [ + "§3Force", + "You have to fulfill specific", + "*intermediate goals* to survive" + ], + "category-world": [ + "§4World Change", + "The world will be *modified* significant" + ], + "category-damage": [ + "§cSchaden", + "New *damage rules*" + ], + "category-effect": [ + "§5Effekte", + "Have fun with *lots of effects*" + ], + "category-inventory": [ + "§6Inventory", + "You'll have problems managing *your inventory*" + ], + "category-movement": [ + "§aBewegung", + "You're *restricted in your movements*" + ], + "category-entities": [ + "§bEntities", + "Entities will be *modified*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges that will *send*", + "you to *another world*" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Goals that *couldn't be*", + "*assigned* with a category" + ], + "category-kill_entity": [ + "§cEntities töten", + "Kill *specific entities* to win" + ], + "category-score_points": [ + "§eBest Score", + "Get the best score *to win*" + ], + "category-fastest_time": [ + "§6Fastest Time", + "Be the fastest *to win*" + ], + "category-force_battle": [ + "§bForce Battles", + "Fulfill the given *intermediate goals*", + "to earn points.", + " ", + "The player with the *most points* wins." + ], + "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", + "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", + "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Max health: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Strength: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", + "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", + "item-blocks-description": "§8» Blocks to walk: §e{0}", + "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", + "item-force-battle-goal-jokers": [ + "§6Number of jokers", + "The *amount* of *jokers*", + "hat every player has" + ], + "item-force-battle-show-scoreboard": [ + "§bShow Scoreboard" + ], + "item-force-battle-duped-targets": [ + "§cDuped Targets", + "Targets can occur *multiple times*" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "The *maximum radius*, in which the", + "positions will be located" + ], + "item-difficulty-setting": [ + "§aDifficulty", + "Sets the *Difficulty*" + ], + "item-language-setting": [ + "§bLanguage", + "Sets the *Language*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", + "item-one-life-setting": [ + "§cOne Teamlife", + "*Everyone* dies when *one player dies*" + ], + "item-respawn-setting": [ + "§4Respawn", + "When you *die*, you won't be a *spectator*" + ], + "item-death-message-setting": [ + "§6Death messages", + "Toggles *death messages*" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMax health", + "Sets the *max health*", + "for *all players*" + ], + "item-soup-setting": [ + "§cSoup healing", + "When you use a *mushroom soup*", + "you will be healed for *4 hearts*" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Damage you take will be *multiplied*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "It will be displayed in the *chat*", + "when anybody takes *damage*" + ], + "item-health-display-setting": [ + "§cHealth Display", + "The *hearts* of all players", + "will be showed in the *tablist*" + ], + "item-position-setting": [ + "§9Positions", + "Allows you to mark *positions*", + "with */pos*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Allows you to open *your backpack* or", + "the *team backpack* with */backpack*" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Different *settings* to simplify", + "the *farming* of items" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Gold ore* will be directly dropped as *Gold ingot*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Iron ore* will be directly dropped as *Iron ingot*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Coal* will be directly dropped as *torches*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* will always drop *flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Ore veins* will be directly destroyed" + ], + "item-cut-clean-inventory-setting": [ + "§6Direct Into Inventory", + "*Items* will be put *directly* into your", + "*inventory* instead of dropping" + ], + "item-cut-clean-food-setting": [ + "§cCooked Food", + "*Raw meat* will be directly dropped as *cooked meat*" + ], + "item-glow-setting": [ + "§fPlayer Glow", + "*Players* are visible through *walls*" + ], + "no-hunger-setting": [ + "§cNo Hunger", + "You don't get *hungry*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "You can *move* before", + "the game has been *started*" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "After you've *taken* damage", + "you can *get* damage *immediately* again" + ], + "item-timber-setting": [ + "§bTimber", + "You can destroy a *tree*", + "by breaking down *a single block* of the tree" + ], + "item-timber-setting-logs": "§6Logs", + "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "You don't lose any *items*", + "when you die" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monsters *can't destroy* anything" + ], + "item-no-item-damage-setting": [ + "§5No Item Damage", + "*Items* are *unbreakable*" + ], + "top-command-setting": [ + "§dTop Command", + "You can *teleport* to the *top*", + "of the world or to the *overworld*", + "with /top" + ], + "item-fortress-spawn-setting": [ + "§cFortress Spawn", + "When you go into the *nether*", + "you will always spawn in a *fortress*" + ], + "item-bastion-spawn-setting": [ + "§cBastion Spawn", + "When you go into the *nether*", + "you will always spawn in a *bastion*" + ], + "item-no-offhand-setting": [ + "§6No Offhand", + "The *second hand* will be blocked" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Sets *whether* and", + "*how* to *regenerate*" + ], + "item-regeneration-setting-not_natural": "§6Not Natural", + "item-immediate-respawn-setting": [ + "§6Direct Respawn", + "When you *die* you *respawn* automatically", + "*without* seeing the *death screen*" + ], + "item-slot-limit-setting": [ + "§4Inventory Slots", + "Sets how many *inventory*", + "*slots* are useable" + ], + "item-death-position-setting": [ + "§cDeath Position", + "When you die, */pos* creates", + "a position at your death point" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "When you execute */ec*,", + "your *Enderchest* opens" + ], + "item-split-health-setting": [ + "§cSplit Health", + "Sets whether *all players*", + "share the same *health*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "The *old 1.8 PvP System* will be used", + "There will be no *attack damage cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Death Rescue", + "If you *instant die* from a *challenge*", + "*totems* can *rescue* you" + ], + "item-traffic-light-challenge": [ + "§cTraffic Light Challenge", + "The *traffic light* switches every few minutes.", + "If you go on *red*, you die" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Each *block* drops a *random item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "If you *craft* something you will get another *random item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "When an *Entity* spawns, it spawns *twice*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Every *few minutes* every player gets *random items*" + ], + "item-damage-block-challenge": [ + "§4Damage per Block", + "You take *damage* for", + "every *block* you walk" + ], + "item-hunger-block-challenge": [ + "§6Hunger per Block", + "You lose *food* for", + "every *block* you walk" + ], + "item-stone-sight-challenge": [ + "§fStone Sight", + "*Mobs* that you look in the", + "*eyes* turn to stone" + ], + "item-no-mob-sight-challenge": [ + "§cMob Sight Damage", + "When you look into the *eyes* of an", + "*entity*, you get *damage*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Bedrock *generates* under you*", + "the whole time" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Huge *walls of bedrock*", + "are *generating* behind you" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "The *floor* is disappearing", + "to *void* behind you" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Player *inventories* are *cleared*", + "when a *player* takes damage" + ], + "item-no-trading-challenge": [ + "§2No Trading", + "You *cannot* trade", + "with villagers" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "If you *break* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "If you *place* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-no-exp-challenge": [ + "§aNo EXP", + "If you pickup *EXP* you die" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Every few minutes the *hearts are inverted*.", + "If you have *8 hearts*, you will have *2 hearts*", + "and the other way around" + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Every *few minutes* you have to do a random", + "*jump and run* which gets *harder* every time" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "The *health* of all mobs", + "is randomized" + ], + "item-snake-challenge": [ + "§9Snake", + "Each player draws a *deadly line*", + "behind them" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "If you deal damage to entites", + "you take the same damage" + ], + "item-duped-spawning-challenge": [ + "§cDuped Spawning", + "If a mob *spawns*", + "it spawns *two times*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "If you *kill* a mob", + "*two new* are spawning" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "If you kill a *mob* it", + "spawns *twice* as many", + "times as the *previous* time", + " ", + "Maximum are *512* Mobs each time" + ], + "item-floor-lava-challenge": [ + "§6The Floor Is Lava", + "*Blocks* below you transform first", + "to *magma* and then to *lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "You must stay on *dirt*", + "otherwise you will *die*" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Each *food* can be*", + "*eaten* only once" + ], + "item-food-once-challenge-player": "§6Player", + "item-food-once-challenge-everyone": "§5Everyone", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks* that players are in", + "*break* down from *above*" + ], + "item-one-durability-challenge": [ + "§4One Durability", + "Items are *destroyed* after one *use*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "The *drop chance* of each *block*", + "will be set to the defined *percentage*" + ], + "item-invisible-mobs-challenge": [ + "§fInvisible Mobs", + "All *Mobs* have an", + "*invisibility* effect" + ], + "item-mob-transformation-challenge": [ + "§cMob Transformation", + "When you hit a mob, it *turns*", + "into the last mob *you* hit" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "A *random entity* spawns", + "everytime you *jump*" + ], + "item-no-mouse-move-challenge": [ + "§cMouse Movement Damage", + "You take *damage* everytime", + "you *move* your *view*" + ], + "item-no-duped-items-challenge": [ + "§6No Duped Items", + "Players are *not allowed* to have", + "the *same item* in their *inventories*", + "at the same time" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "You have to keep *2 blocks* away", + "from all *mobs* or you will *get* sick" + ], + "item-only-down-challenge": [ + "§cOnly Down", + "If you go *up* by *a block*, you *die*" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Damage", + "You *take* the set amount of *damage*", + "for every new *advancement*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAll Blocks Disappear", + "With different *interactions* all", + "*blocks* of a certain type", + "disappear in the same chunk" + ], + "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", + "item-all-blocks-disappear-break-challenge": [ + "§bBy breaking", + "If you *break* a *block* all blocks", + "of the same types disappear" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBy Placing", + "If you *place* a *block* all blocks", + "of the same types disappear" + ], + "item-water-allergy-challenge": [ + "§9Water Allergy", + "You *take* the set amount of *damage*", + "while you are in *water*" + ], + "item-max-biome-time-challenge": [ + "§2Max Biome Time", + "The *time* that you may spend", + "in every *biome* is limited" + ], + "item-max-height-time-challenge": [ + "§9Max Biome Time", + "The *time* that you may spend", + "on every *height* is limited" + ], + "item-permanent-item-challenge": [ + "§cPermanent Items", + "*Items* cannot be dropped", + "or put *away*" + ], + "item-sneak-damage-challenge": [ + "§6Damage per Sneak", + "You *take* the set amount", + "of *damage* if you *sneak*" + ], + "item-jump-damage-challenge": [ + "§6Damage per Jump", + "You *take* the set amount", + "of *damage* if you *jump*" + ], + "item-random-dropping-challenge": [ + "§cRandom Item Dropping", + "Every few seconds a *random item*", + "will be *dropped* from your *inventory*" + ], + "item-random-swapping-challenge": [ + "§cRandom Item Swapping", + "Every few seconds a *random item*", + "will be *swapped* with *another item*", + "in your *inventory*" + ], + "item-random-removing-challenge": [ + "§cRandom Item Removing", + "Every few seconds a *random item*", + "will be *removed* from your *inventory*" + ], + "item-death-on-fall-challenge": [ + "§fDeath On Fall Damage", + "You *die instantly*, when", + "you take *fall damage*" + ], + "item-zero-hearts-challenge": [ + "§6Zero Hearts", + "After a *protection time* you have to", + "get *absorption permanently* else you will die" + ], + "item-random-effect-challenge": [ + "§6Random Effects", + "You get a *random potion effect*", + "in a set *interval*" + ], + "menu-random-effect-challenge-settings": "Random Effects", + "item-random-effect-time-challenge": [ + "§6Interval", + "The *interval* you get the *effect* in" + ], + "item-random-effect-length-challenge": [ + "§6Length", + "The *length* you have the *effect*" + ], + "item-random-effect-amplifier-challenge": [ + "§6Amplifier", + "The *amplifier* the effect has" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanent Effects", + "Everytime you *take damage* you get", + "a random *permanent potion effect*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In a set *interval* a random", + "*challenge* will be *activated*" + ], + "item-anvil-rain-challenge": [ + "§cAnvil Rain", + "*Anvils* are falling from the *sky*" + ], + "menu-anvil-rain-challenge-settings": "Anvil Rain", + "item-anvil-rain-time-challenge": [ + "§6Interval", + "The *interval*, the *anvils* are spawning in" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "The *range* of chunks, the *anvils* are spawning in" + ], + "item-anvil-rain-count-challenge": [ + "§6Amount", + "The *amount* of anvils that", + "are spawning in one chunk" + ], + "item-anvil-rain-damage-challenge": [ + "§6Damage", + "The *damage* you take from an *anvil*" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "You have to do a *Water MLG*", + "over and over again" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Every *few minutes* you will be", + "*swapped* with a *random entity*", + "in a *200 blocks* range" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Every *few minutes* one of", + "*{0} random Events* will be activated" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "A random item will be removed from", + "your inventory for every", + "*block* / *chunk* you walk" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "The more *you jump*, the *higher* you jump" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Every *few minutes* you have to be", + "on a *certain height*, else you die" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Every *few minutes* you have to be", + "on a *certain block*, else you die" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Every *few minutes* you have to be", + "in a *certain biome*, else you die", + "The *rarer* the biome, the *more time* you have" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Every *few minutes* you have to", + "*kill* a *certain mob*, else you die" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Every *few minutes* you have to get", + "a *certain item*, else you die" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "A *random player* gets a *random item*", + "every *few seconds*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "You *cannot stop* to *walk forwards*" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "When you *pick up* an *item*", + "you will be *launched* into the air" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In a *set interval* ", + "the water rises in the *Overworld*", + "and the *lava* in the nether", + " ", + "Should be played with a *few people*!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAll Mobs To Death Point", + "If a *Mob* gets *killed* by a player", + "all mobs of the *same type* will be", + "*teleported* to its *death point*" + ], + "item-ice-floor-challenge": [ + "§bIce Floor", + "*Air* will be replaced in a", + "*3x3* area with *packed ice*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlocks Disappear After Time", + "Placed *blocks*, will *disappear*", + "after a *few seconds*" + ], + "item-missing-items-challenge": [ + "§9Items Missing", + "Every few minutes a *random item disappears* from", + "your *inventory* and you have to *guess* which it was" + ], + "item-damage-item-challenge": [ + "§cDamage Per Item", + "When you *pickup* or *click* an item", + "in your *inventory* you take the", + "*amount* of the items as *damage*" + ], + "item-damage-teleport-challenge": [ + "§cRandom Teleport On Damage", + "You'll be teleported randomly", + "when you take damage" + ], + "item-loop-challenge": [ + "§6Loop Challenge", + "Certain actions are *looped*", + "until a player *sneaks*" + ], + "item-uncraft-challenge": [ + "§6Items Crafting Back", + "*Items* in your inventory are", + "*crafting* back all few seconds" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "For each heart of *damage*, you'll be", + "*frozen* for a certain time" + ], + "item-dont-stop-running-challenge": [ + "§9Dont stop running", + "You are only allowed to stand *still*", + "a certain *time* before you *die*" + ], + "item-consume-launch-challenge": [ + "§cConsume Boost", + "When you *eat* an *item*", + "you will be *launched* into the air" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blocks", + "*Every 500 Blocks walked* players", + "will get a *64 stack* of a random item.", + "*Blocks* and *Entities* won't *drop* any items." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "The *border size* adjusts to *the player*", + "with the *most levels*." + ], + "item-chunk-effect-challenge": [ + "§3Random Chunk Effects", + "In *each chunk* you'll get", + "a random *potion effect*" + ], + "item-repeat-chunk-challenge": [ + "§2Repeated Chunk", + "Blocks that are *placed or destroyed*", + "will be placed / destroyed in *every chunk*" + ], + "item-blocks-fly-challenge": [ + "§fBlocks Fly in Air", + "*Blocks* you've *walked* on fly", + "into the air after *one second*" + ], + "item-respawn-end-challenge": [ + "§5Mobs Respawn In End", + "*Killed mobs* respawn in *end dimension*" + ], + "item-block-effect-challenge": [ + "§3Random Block Effects", + "On *each block* you'll get", + "a random *potion effect*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Got Random Effects", + "*Every Mob* has a random", + "potion effect with *max amplifier*" + ], + "item-block-mob-challenge": [ + "§cMob Blocks", + "A *random mob* spawns out of *every broken block*", + "and to *get the block* you have to *kill it*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "All mob drops are *randomly swapped*." + ], + "item-no-shared-advancements-challenge": [ + "§2No Shared Advancements", + "You're *not allowed* to get *advancements* someone else", + "*already did*. Else *you'll die*." + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Deletion", + "*Chunks* that players are in *delete*", + "completely after the given *time*" + ], + "item-delay-damage-description": [ + "§4Damage delay", + "All *damage* from all *players* is", + "added up and dealt after *5 minutes*." + ], + "item-dragon-goal": [ + "§5Ender Dragon", + "Kill the *Ender Dragon* to win" + ], + "item-wither-goal": [ + "§dWither", + "Kill a *Wither* to win" + ], + "item-iron-golem-goal": [ + "§bIron Golem", + "Kill an *Iron Golem* to win" + ], + "item-snow-golem-goal": [ + "§bSnowman", + "Kill a *Snowman* to win" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Kill an *Elder Guardian* to win" + ], + "item-warden-goal": [ + "§5Warden", + "Kill an *Warden* to win" + ], + "item-most-deaths-goal": [ + "§6Most Deaths", + "Who *collects* the most *different deaths* wins" + ], + "item-most-items-goal": [ + "§cMost Items", + "Who *collects* the most *different items* wins" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Who survived until the end wins" + ], + "item-mine-most-blocks-goal": [ + "§eMost Blocks", + "Who *breaks* the most *blocks* wins" + ], + "item-most-xp-goal": [ + "§aMost XP", + "Who *collects* the most *EXP* wins" + ], + "item-first-one-to-die-goal": [ + "§cFirst Death", + "Who *dies* first wins" + ], + "item-collect-wood-goal": [ + "§6Collect Wood", + "Who first collected all types of wood set wins" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Both", + "item-all-bosses-goal": [ + "§bAll Bosses", + "Each boss must has to be killed once to win" + ], + "item-all-bosses-new-goal": [ + "§5All Bosses (+ Warden)", + "Each boss must has to be killed once to win" + ], + "item-all-mobs-goal": [ + "§bAll Mobs", + "Each mob has to be killed once to win" + ], + "item-all-monster-goal": [ + "§bAll Monsters", + "Each monster has to be killed once to win" + ], + "item-all-items-goal": [ + "§2All Items", + "Find *all items* that are in *Minecraft*" + ], + "item-finish-raid-goal": [ + "§6Finish Raid", + "The first player that *finishes* a *raid* wins" + ], + "item-most-emeralds-goal": [ + "§2Most Emeralds", + "The player with the *most*", + "*emeralds* wins" + ], + "item-all-advancements-goal": [ + "§6All Advancements", + "The first player that *gets* all *advancements* wins" + ], + "item-max-height-goal": [ + "§fMaximum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-min-height-goal": [ + "§fMinimum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-race-goal": [ + "§5Race", + "The *first* player to *reach* a", + "*random* location in the overworld wins" + ], + "item-most-ores-goal": [ + "§9Most Ores", + "The player that mines the most ores wins" + ], + "item-find-elytra-goal": [ + "§fFind Elytra", + "The *player* that finds an elytra *wins*" + ], + "item-eat-cake-goal": [ + "§fEat Cake", + "The player that *eats a cake* first *wins*" + ], + "item-collect-horse-armor-goal": [ + "§bCollect Horse Armor", + "The player that *collects* every", + "horse armor first *wins*" + ], + "item-collect-ice-goal": [ + "§bCollect Ice Blocks", + "The player that *collects* every", + "ice blocks and snow first *wins*" + ], + "item-collect-swords-goal": [ + "§9Collect Swords", + "The player that *collects* every", + "sword first *wins*" + ], + "item-collect-workstations-item": [ + "§6Collect Workstations", + "The player that *collects* every", + "villager workstation first *wins*" + ], + "item-eat-most-goal": [ + "§6Eat most", + "The player that fills the mods hunger bars *wins*" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Each player gets *a random item* that", + "he has *to find*.", + "The player that *found* the *most items*, wins." + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bGive Item On Skip", + "If a player *skips* an item,", + "they will *receive* it" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Each player gets *a random mob* that", + "he has to *kill*.", + "The player that *killed* the *most mobs*, wins." + ], + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Each player gets a *random advancement*,", + "that he has to complete." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-get-full-health-goal": [ + "§aGet Full Health", + "The first player to gain full health wins." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Every player gets a *random*", + "*block*, on which he has to stand" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bGive Block On Skip", + "If a player *skips* a block,", + "they will *receive* it" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Each player gets a *random biome*,", + "that he has to *enter*." + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Each player gets a *random damage amount*,", + "that he has to *take*." + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Each player gets a *random height*,", + "that he has to *reach*." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Each player gets a *random position*,", + "that he has to *reach*." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Each player gets a *random target*,", + "that he has to reach." + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-damage-rule-none": [ + "§6General Damage", + "Sets whether you can get damage or not" + ], + "item-damage-rule-fire": [ + "§6Fire Damage", + "Sets whether you get *damage* from *Fire* and *Lava*" + ], + "item-damage-rule-attack": [ + "§3Attack Damage", + "Sets whether you get *damage* from *Melee Attacks* of entites" + ], + "item-damage-rule-projectile": [ + "§6Projectile Damage", + "Sets whether you get *damage* from *Projectiles*" + ], + "item-damage-rule-fall": [ + "§fFall Damage", + "Sets whether you get *damage* from *Fall Damage" + ], + "item-damage-rule-explosion": [ + "§cExplosion Damage", + "Sets whether you get *damage* from *Explosions" + ], + "item-damage-rule-drowning": [ + "§9Drowning Damage", + "Sets whether you get *damage* from *Drowning" + ], + "item-damage-rule-block": [ + "§eBlock Damage", + "Sets whether you get *damage* from *Falling Blocks" + ], + "item-damage-rule-magic": [ + "§5Magic Damage", + "Sets whether you get *damage* from", + "*Poison, Wither or other Potions" + ], + "item-damage-rule-freeze": [ + "§cFreeze Damage", + "Sets whether you get *damage* from *Freezing*" + ], + "item-block-material": [ + "{0}", + "Sets whether *{1}* can be used" + ], + "custom-limit": "You've reached the limit of §e{0} challenges", + "custom-not-deleted": "Challenge doesn't exist yet!", + "custom-saved": "§7Challenge §asaved §7locally", + "custom-saved-db": [ + "To save it in your database use §e/db save customs", + "§cWarning: §7Old challenges will be overwritten!" + ], + "custom-no-changes": "You haven't made any changes", + "custom-name-info": "Type the new name into the chat", + "custom-command-info": [ + "Type the command §ewithout / §7in chat", + "Allowed commands: §e{0}", + "§cOther commands can be allowed in the config" + ], + "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", + "custom-chars-max_length": "You've reached the limit of {0} characters", + "custom-not-loaded": [ + " ", + "There are no currently loaded challenges.", + "You're missing your challenges? §e/db load customs", + "You've got problems with saving them?", + "Save your challenges before leaving with §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6View Challenges", + "custom-main-create-challenge": "§aCreate Challenge", + "custom-title-trigger": "Trigger", + "custom-title-action": "Action", + "custom-title-view": "View", + "custom-sub-finish": "§aFinished", + "item-custom-info-delete": [ + "§cDelete", + "*Warning* This Action cannot be made *undone*" + ], + "item-custom-info-save": "§aSave", + "item-custom-info-trigger": [ + "§cTrigger", + "*Click here* to set what has to be happening", + "for the *action* to execute" + ], + "item-custom-info-action": [ + "§bAction", + "*Click here* to set what should happen", + "once the *trigger* is met" + ], + "item-custom-info-material": [ + "§6Display Item", + "*Click here* to change the display item" + ], + "item-custom-info-name": [ + "§6Name", + "*Click here* to change the name via chat", + "Max Characters: 50" + ], + "custom-info-currently": "§7Set §8» §e", + "custom-info-trigger": "§7Trigger", + "custom-info-action": "§7Action", + "item-custom-trigger-jump": [ + "§aPlayer Jumps" + ], + "item-custom-trigger-sneak": [ + "§aPlayer Sneaks" + ], + "item-custom-trigger-move_block": [ + "§6Player Walks A Block" + ], + "item-custom-trigger-death": [ + "§cEntity Dies" + ], + "item-custom-trigger-damage": [ + "§cEntity Takes Damage" + ], + "item-custom-trigger-damage-any": [ + "§aAny Cause" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Takes Damage By Player" + ], + "item-custom-trigger-intervall": [ + "§6Interval" + ], + "item-custom-trigger-intervall-second": [ + "§6Each Second" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Every {0} Seconds" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Every {0} Minutes" + ], + "item-custom-trigger-block_place": [ + "§aBlock Placed" + ], + "item-custom-trigger-block_break": [ + "§cBlock Destroyed" + ], + "item-custom-trigger-consume_item": [ + "§2Consume Item" + ], + "item-custom-trigger-pickup_item": [ + "§bPickup Item" + ], + "item-custom-trigger-drop_item": [ + "§9Player Dropped Item" + ], + "item-custom-trigger-advancement": [ + "§cPlayer Gets Advancement" + ], + "item-custom-trigger-hunger": [ + "§2Player Looses Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Player Moves Block Down" + ], + "item-custom-trigger-move_up": [ + "§6Player Moves Block Up" + ], + "item-custom-trigger-move_camera": [ + "§6Moves Camera" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Player Is On Specific Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Player Is Not On Specific Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Player Gets XP" + ], + "item-custom-trigger-level_up": [ + "§5Player Gets Level" + ], + "item-custom-trigger-item_craft": [ + "§6Player Crafts Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Player Is In Liquid" + ], + "item-custom-trigger-get_item": [ + "§aGet Item", + "Action will be executed *every time*", + "item is clicked or picked up" + ], + "item-custom-action-cancel": [ + "§4Cancel Trigger", + "Prevent that the trigger will be executed", + "Non preventable Trigger: *Jump*, *Sneak*, *Death*", + "*Advancement*, *Level Up*, *In Liquid*" + ], + "item-custom-action-command": [ + "§4Execute Command", + "Make players execute commands.", + "Commands are executed for players via */execute as*.", + "Allowed commands can be set in plugin config.", + "The player doesn't need the *permission* to the commands.", + "Player aren't able to execute *plugin commands*." + ], + "item-custom-action-kill": [ + "§4Kill", + "Kill entities" + ], + "item-custom-action-damage": [ + "§cDamage", + "Hurt entities" + ], + "item-custom-action-heal": [ + "§aHeal", + "Restore entity health" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Make Entities get hunger" + ], + "item-custom-action-max_health": [ + "§cChange Max Health", + "Modify the max health of players.", + "Will be reset with */gamestate reset*" + ], + "item-custom-action-max_health-offset": [ + "§cHealth Change", + "Choose how the max health should be changed" + ], + "item-custom-action-spawn_entity": [ + "§3Spawn Entity", + "Spawn an entity with a specific type" + ], + "item-custom-action-random_mob": [ + "§6Random Entity", + "Spawn a random entity" + ], + "item-custom-action-random_item": [ + "§bRandom Item", + "Give random items to players" + ], + "item-custom-action-uncraft_inventory": [ + "§eUncraft Inventory", + "Make players inventories uncraft" + ], + "item-custom-action-boost_in_air": [ + "§fBoost In Air", + "Boost entities into the air" + ], + "item-custom-action-boost_in_air-strength": [ + "§fAmplifier" + ], + "item-custom-action-potion_effect": [ + "§dPotion Effect", + "Add a potion effect to entities" + ], + "item-custom-action-permanent_effect": [ + "§6Permanent Potion Effect", + "Add a permanent potion effect to players.", + "Uses the settings of the permanent effect challenge." + ], + "item-custom-action-random_effect": [ + "§dRandom Potion Effect", + "Add a random potion effect to entities" + ], + "item-custom-action-clear_inventory": [ + "§cClear Inventory", + "Clear the inventory of players" + ], + "item-custom-action-drop_random_item": [ + "§aDrop Item From Inventory", + "Drop a random item from the inventory onto the floor" + ], + "item-custom-action-remove_random_item": [ + "§cRemove Item From Inventory", + "Remove a random item from the inventory" + ], + "item-custom-action-swap_random_item": [ + "§6Swap Items In Inventory", + "Swap two items in the inventory" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Temporarily freeze mobs", + "Uses the settings of the freeze challenge" + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invert the current health of players" + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "All players have to do a water mlg to survive" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "A random player has to a a jump and run", + "that gets longer everytime" + ], + "item-custom-action-win": [ + "§6Win", + "The challenge will be won *by specific players*" + ], + "item-custom-action-random_hotbar": [ + "§eRandom Hotbar", + "The inventory is emptied and the player", + "gets a full hotbar of random items" + ], + "item-custom-action-modify_border": [ + "§bModify World Border", + "Make the world border *bigger* or *tinier*" + ], + "item-custom-action-modify_border-change": [ + "§dChange" + ], + "item-custom-action-swap_mobs": [ + "§5Swap mobs", + "Swap a mob with another of the same world" + ], + "item-custom-action-place_structure": [ + "§aPlace Structure", + "Places a structure" + ], + "item-custom-action-place_structure-random": "§bRandom structure", + "item-custom-setting-target-current": [ + "§6Current Entity", + "The action will be executed for the *current entity*" + ], + "item-custom-setting-target-every_mob": [ + "§4Every Mob", + "The action will be executed for *every mob*" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Every Mob Except Current", + "The action will be executed for *every mob*", + "*except* the current one" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Every Mob Except Players", + "The action will be executed for *every mob except players*" + ], + "item-custom-setting-target-random_player": [ + "§5Random Player", + "The action will be executed for a *random player*" + ], + "item-custom-setting-target-every_player": [ + "§cEvery Player", + "The action will be executed for *every player*" + ], + "item-custom-setting-target-current_player": [ + "§aCurrent Player", + "The action will be executed for the *active player*.", + "§7§oIf the current entity is not a player nothing will be happen" + ], + "item-custom-setting-target-console": [ + "§4Console", + "The action will be executed for the *console*" + ], + "item-custom-setting-entity_type-any": "§cAny Entity", + "item-custom-setting-entity_type-player": "§aPlayer", + "item-custom-setting-block-any": "§2Any Block", + "item-custom-setting-item-any": "§2Any Item", + "custom-subsetting-target_entity": "Target Entity", + "custom-subsetting-entity_type": "Entity Type", + "custom-subsetting-liquid": "Liquid", + "custom-subsetting-time": "Time", + "custom-subsetting-damage_cause": "Damage Cause", + "custom-subsetting-amount": "Amount", + "custom-subsetting-value": "Value Editor", + "custom-subsetting-health_offset": "Change", + "custom-subsetting-length": "Length", + "custom-subsetting-amplifier": "Amplifier", + "custom-subsetting-change": "Change", + "custom-subsetting-swap_targets": "Swap Targets" } diff --git a/language/languages.json b/language/languages.json index 2758e52e6..3d81dfd05 100644 --- a/language/languages.json +++ b/language/languages.json @@ -1,4 +1,4 @@ [ - "en", - "de" + "en", + "de" ] diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 6406c776f..0fcaef25e 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -7,7 +7,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 mongo-connector @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc spigot-api @@ -30,7 +37,7 @@ org.mongodb mongodb-driver - 3.12.8 + 3.12.14 @@ -45,12 +52,6 @@ ${project.version} - - com.github.anweisen.Utility - database-mongodb - ${utilities.version} - - @@ -79,7 +80,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.0 + 3.14.0 1.8 1.8 @@ -90,7 +91,7 @@ org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.1 attach-sources @@ -105,7 +106,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.0 package @@ -130,7 +131,7 @@ org.apache.maven.plugins maven-resources-plugin - 3.2.0 + 3.3.1 copy-license diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index 0ea5eb464..ee9999e4d 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -1,18 +1,15 @@ package net.codingarea.challenges.mongoconnector; -import net.anweisen.utilities.database.internal.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.plugin.java.JavaPlugin; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ + public final class MongoConnector extends JavaPlugin { - @Override - public void onLoad() { - Challenges.getInstance().getDatabaseManager().registerDatabase("mongodb", MongoDBDatabase.class, this); - } + @Override + public void onLoad() { + Challenges.getInstance().getDatabaseManager().registerDatabase("mongodb", MongoDBDatabase.class, this); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java new file mode 100644 index 000000000..f801ab556 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -0,0 +1,304 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.FileUtils; +import org.bson.BsonArray; +import org.bson.BsonValue; +import org.bson.json.JsonWriterSettings; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class BsonDocument extends AbstractDocument { + + protected org.bson.Document bsonDocument; + + public BsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public BsonDocument(@Nonnull Reader reader) { + BufferedReader buffered = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + StringBuilder content = new StringBuilder(); + buffered.lines().forEach(content::append); + bsonDocument = org.bson.Document.parse(content.toString()); + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument) { + this.bsonDocument = bsonDocument; + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.bsonDocument = bsonDocument; + } + + public BsonDocument() { + this(new org.bson.Document()); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + org.bson.Document document = bsonDocument.get(path, org.bson.Document.class); + if (document == null) { + bsonDocument.put(path, document = new org.bson.Document()); + } + + return new BsonDocument(document, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + BsonArray array = bsonDocument.get(path, BsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + for (BsonValue value : array) { + if (!value.isDocument()) continue; + String json = value.asDocument().toJson(); + org.bson.Document document = org.bson.Document.parse(json); + documents.add(new BsonDocument(document, root, this)); + } + return documents; + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = getObject(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + Object value = bsonDocument.get(path); + if (value instanceof Boolean) return (Boolean) value; + if (value instanceof String) return Boolean.parseBoolean((String) value); + } catch (Exception ex) { + } + return def; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return bsonDocument.get(path); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return bsonDocument.getList(path, String.class); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object value = bsonDocument.get(path); + if (value instanceof UUID) return (UUID) value; + if (value instanceof String) return UUID.fromString((String) value); + } catch (Exception ex) { + } + return null; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return bsonDocument.getDate(path); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof OffsetDateTime) + return (OffsetDateTime) value; + if (value instanceof Date) + return ((Date)value).toInstant().atOffset(ZoneOffset.UTC); + if (value instanceof String) + return OffsetDateTime.parse((CharSequence) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.time.OffsetDateTime"); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof Color) + return (Color) value; + if (value instanceof String) + return Color.decode((String) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.awt.Color"); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Override + public boolean contains(@Nonnull String path) { + return bsonDocument.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof org.bson.Document; + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isList(path) && !isDocument(path); + } + + @Override + public int size() { + return bsonDocument.size(); + } + + @Override + public void clear0() { + bsonDocument.clear(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + bsonDocument.put(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + bsonDocument.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + String json = bsonDocument.toString(); + writer.write(json); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(bsonDocument); + } + + @Nonnull + @Override + public Collection keys() { + return bsonDocument.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + bsonDocument.forEach(action); + } + + @Nonnull + @Override + public String toJson() { + return bsonDocument.toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return bsonDocument.toJson(JsonWriterSettings.builder().indent(true).build()); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java new file mode 100644 index 000000000..05611a0b0 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -0,0 +1,135 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.MongoClient; +import net.codingarea.commons.common.logging.ILogger; +import org.bson.*; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public final class BsonUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + + private BsonUtils() { + } + + @Nonnull + public static BsonDocument convertBsonToBsonDocument(@Nonnull Bson bson) { + return bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()); + } + + @Nullable + public static Object unpackBsonElement(@Nullable Object value) { + if (value == null || value instanceof BsonNull) { + return null; + } else if (value instanceof BsonString) { + return ((BsonString) value).getValue(); + } else if (value instanceof BsonDouble) { + return ((BsonDouble) value).getValue(); + } else if (value instanceof BsonInt32) { + return ((BsonInt32) value).getValue(); + } else if (value instanceof BsonInt64) { + return ((BsonInt64) value).getValue(); + } else if (value instanceof BsonBinary) { + return ((BsonBinary) value).getData(); + } else if (value instanceof BsonObjectId) { + return ((BsonObjectId) value).getValue(); + } else if (value instanceof BsonArray) { + return convertBsonArrayToList((BsonArray) value); + } else if (value instanceof BsonDocument) { + return convertBsonDocumentToMap((BsonDocument) value); + } else if (value instanceof Document) { + return value; + } else { + return value; + } + } + + @Nonnull + public static List convertBsonArrayToList(@Nonnull BsonArray array) { + List list = new ArrayList<>(array.size()); + for (BsonValue value : array) { + list.add(unpackBsonElement(value)); + } + return list; + } + + @Nonnull + public static Map convertBsonDocumentToMap(@Nonnull BsonDocument document) { + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + map.put(entry.getKey(), unpackBsonElement(entry.getValue())); + } + return map; + } + + @Nonnull + public static BsonValue convertObjectToBsonElement(@Nullable Object value) { + if (value == null) { + return BsonNull.VALUE; + } else if (value instanceof BsonValue) { + return (BsonValue) value; + } else if (value instanceof Bson) { + return convertBsonToBsonDocument((Bson) value); + } else if (value instanceof String) { + return new BsonString((String) value); + } else if (value instanceof Boolean) { + return new BsonBoolean((Boolean) value); + } else if (value instanceof ObjectId) { + return new BsonObjectId((ObjectId) value); + } else if (value instanceof Double) { + return new BsonDouble((Double) value); + } else if (value instanceof Float) { + return new BsonDouble((Float) value); + } else if (value instanceof Long) { + return new BsonInt64((Long) value); + } else if (value instanceof Integer) { + return new BsonInt32((Integer) value); + } else if (value instanceof Number) { + return new BsonInt32(((Number) value).intValue()); + } else if (value instanceof byte[]) { + return new BsonBinary((byte[]) value); + } else if (value instanceof Iterable) { + return convertIterableToBsonArray((Iterable) value); + } else if (value.getClass().isArray()) { + return convertArrayToBsonArray(value); + } else if (value instanceof Map) { + BsonDocument document = new BsonDocument(); + setDocumentProperties(document, (Map) value); + return document; + } else { + logger.error("Could not serialize " + value.getClass().getName() + " to BsonValue"); + return BsonNull.VALUE; + } + } + + public static void setDocumentProperties(@Nonnull BsonDocument document, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + document.put(entry.getKey(), convertObjectToBsonElement(value)); + } + } + + @Nonnull + public static BsonArray convertIterableToBsonArray(@Nonnull Iterable iterable) { + BsonArray bsonArray = new BsonArray(); + iterable.forEach(object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + + @Nonnull + public static BsonArray convertArrayToBsonArray(@Nonnull Object array) { + BsonArray bsonArray = new BsonArray(); + ReflectionUtils.forEachInArray(array, object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java new file mode 100644 index 000000000..d0c2c4a37 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Sorts; +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +public final class MongoUtils { + + private MongoUtils() { + } + + public static void applyWhere(@Nonnull FindIterable iterable, @Nonnull Map where) { + for (Entry entry : where.entrySet()) { + MongoDBWhere value = entry.getValue(); + iterable.filter(value.toBson()); + + Collation collation = value.getCollation(); + if (collation != null) + iterable.collation(collation); + } + } + + public static void applyOrder(@Nonnull FindIterable iterable, @Nullable String orderBy, @Nullable Order order) { + if (order == null || orderBy == null) return; + switch (order) { + case HIGHEST: + iterable.sort(Sorts.descending(orderBy)); + break; + case LOWEST: + iterable.sort(Sorts.ascending(orderBy)); + break; + } + } + + @Nullable + public static Object packObject(@Nullable Object value) { + if (value == null) { + return null; + } else if (value instanceof Json) { + String json = ((Json) value).toJson(); + return Document.parse(json); + } else if (BukkitReflectionSerializationUtils.isSerializable(value.getClass())) { + Map values = BukkitReflectionSerializationUtils.serializeObject(value); + if (values == null) return null; + BsonDocument bson = new BsonDocument(); + BsonUtils.setDocumentProperties(bson, values); + return bson; + } else if (value instanceof UUID) { + return ((UUID) value).toString(); + } else { + return value; + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java new file mode 100644 index 000000000..e6789feda --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java @@ -0,0 +1,148 @@ +package net.codingarea.commons.database.mongodb; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.mongodb.count.MongoDBCountEntries; +import net.codingarea.commons.database.mongodb.deletion.MongoDBDeletion; +import net.codingarea.commons.database.mongodb.insertion.MongoDBInsertion; +import net.codingarea.commons.database.mongodb.insertorupdate.MongoDBInsertionOrUpdate; +import net.codingarea.commons.database.mongodb.list.MongoDBListTables; +import net.codingarea.commons.database.mongodb.query.MongoDBQuery; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class MongoDBDatabase extends AbstractDatabase { + + static { + Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); + } + + protected MongoClient client; + protected MongoDatabase database; + + public MongoDBDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void connect0() throws Exception { + MongoCredential credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabase(), config.getPassword().toCharArray()); + MongoClientSettings settings = MongoClientSettings.builder() + .retryReads(false).retryReads(false) + .credential(credential) + .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress(config.getHost(), config.isPortSet() ? config.getPort() : ServerAddress.defaultPort())))) + .build(); + client = MongoClients.create(settings); + database = client.getDatabase(config.getDatabase()); + } + + @Override + public void disconnect0() throws Exception { + client.close(); + client = null; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + checkConnection(); + + boolean collectionExists = listTables().execute().contains(name); + if (collectionExists) return; + + try { + database.createCollection(name); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MongoDBListTables(this); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new MongoDBCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new MongoDBQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new MongoDBQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new MongoDBUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new MongoDBInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new MongoDBInsertion(this, table, new Document(values)); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Document document) { + return new MongoDBInsertion(this, table, document); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new MongoDBInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new MongoDBDeletion(this, table); + } + + @Nonnull + public MongoCollection getCollection(@Nonnull String collection) { + return database.getCollection(collection); + } + + @Nonnull + public MongoDatabase getDatabase() { + return database; + } + + @Override + public boolean isConnected() { + return client != null && database != null; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java new file mode 100644 index 000000000..e1b185de5 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.mongodb.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class MongoDBCountEntries implements DatabaseCountEntries { + + protected final MongoDBDatabase database; + protected final String table; + + public MongoDBCountEntries(@Nonnull MongoDBDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + return database.getCollection(table).countDocuments(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBCountEntries that = (MongoDBCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java new file mode 100644 index 000000000..3073dbb40 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.database.mongodb.deletion; + +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.DeleteOptions; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class MongoDBDeletion implements DatabaseDeletion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where = new HashMap<>(); + + public MongoDBDeletion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::ne)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + DeleteOptions options = new DeleteOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + collection.deleteMany(filter, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBDeletion that = (MongoDBDeletion) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java new file mode 100644 index 000000000..10e38cfc6 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.database.mongodb.insertion; + +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class MongoDBInsertion implements DatabaseInsertion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Document values; + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.values = new Document(); + } + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Document values) { + this.database = database; + this.collection = collection; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + database.getCollection(collection).insertOne(values); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBInsertion that = (MongoDBInsertion) o; + return database.equals(that.database) && collection.equals(that.collection) && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java new file mode 100644 index 000000000..295751f3d --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.mongodb.insertorupdate; + +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map.Entry; + +public class MongoDBInsertionOrUpdate extends MongoDBUpdate implements DatabaseInsertionOrUpdate { + + public MongoDBInsertionOrUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + super(database, collection); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + super.where(field, value, ignoreCase); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value) { + super.whereNot(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value) { + super.set(field, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(collection, where).execute().isSet()) { + return super.execute(); + } else { + Document document = new Document(values); + for (Entry entry : where.entrySet()) { + BsonDocument bson = BsonUtils.convertBsonToBsonDocument(entry.getValue().toBson()); + document.putAll(bson); + } + + database.insert(collection, document).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java new file mode 100644 index 000000000..987eba440 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.mongodb.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public class MongoDBListTables implements DatabaseListTables { + + protected final MongoDBDatabase database; + + public MongoDBListTables(@Nonnull MongoDBDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + return database.getDatabase().listCollectionNames().into(new ArrayList<>()); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java new file mode 100644 index 000000000..e1e11832b --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java @@ -0,0 +1,128 @@ +package net.codingarea.commons.database.mongodb.query; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public class MongoDBQuery implements DatabaseQuery { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected Order order; + protected String orderBy; + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + } + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where) { + this.database = database; + this.collection = collection; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + FindIterable iterable = database.getCollection(collection).find(); + MongoUtils.applyWhere(iterable, where); + MongoUtils.applyOrder(iterable, orderBy, order); + + List documents = iterable.into(new ArrayList<>()); + return createExecutedQuery(documents); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull List documents) { + List results = new ArrayList<>(documents.size()); + for (Document document : documents) { + results.add(new MongoDBResult(document)); + } + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBQuery that = (MongoDBQuery) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where) && order == that.order && Objects.equals(orderBy, that.orderBy); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, order, orderBy); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java new file mode 100644 index 000000000..c65457f05 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.mongodb.query; + +import net.codingarea.commons.common.config.document.BsonDocument; + +import javax.annotation.Nonnull; + +public final class MongoDBResult extends BsonDocument { + + public MongoDBResult(@Nonnull org.bson.Document bsonDocument) { + super(bsonDocument); + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java new file mode 100644 index 000000000..6e30f14f4 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.database.mongodb.update; + +import com.mongodb.BasicDBObject; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; + +public class MongoDBUpdate implements DatabaseUpdate { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected final Map values; + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.collection = collection; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + UpdateOptions options = new UpdateOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + Document newDocument = new Document(); + for (Entry entry : values.entrySet()) { + newDocument.put(entry.getKey(), MongoUtils.packObject(entry.getValue())); + } + + BasicDBObject update = new BasicDBObject(); + update.put("$set", newDocument); + + collection.updateMany(filter, update, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBUpdate that = (MongoDBUpdate) o; + return database.equals(that.database) + && collection.equals(that.collection) + && where.equals(that.where) + && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java new file mode 100644 index 000000000..64a41b89e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface MongoDBWhere { + + @Nonnull + Bson toBson(); + + @Nullable + Collation getCollation(); + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java new file mode 100644 index 000000000..84852ffb2 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import net.codingarea.commons.common.misc.MongoUtils; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.BiFunction; + +public class ObjectWhere implements MongoDBWhere { + + protected final String field; + protected final Object value; + protected final BiFunction creator; + + public ObjectWhere(@Nonnull String field, @Nullable Object value, @Nonnull BiFunction creator) { + this.field = field; + this.value = MongoUtils.packObject(value); + this.creator = creator; + } + + @Nonnull + @Override + public Bson toBson() { + return creator.apply(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return field.equals(that.field) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..d7e875f8e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.CollationStrength; +import com.mongodb.client.model.Filters; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements MongoDBWhere { + + protected final String field; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String field, @Nonnull String value) { + this.field = field; + this.value = value; + } + + @Nonnull + @Override + public Bson toBson() { + return Filters.eq(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return field.equals(that.field) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/plugin/pom.xml b/plugin/pom.xml index c30129dad..edfeaadca 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -7,7 +7,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 plugin @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc @@ -27,11 +34,6 @@ ${spigot.version} provided - - com.github.anweisen.Utility - bukkit-utils - ${utilities.version} - com.mojang authlib @@ -43,13 +45,13 @@ de.dytanic.cloudnet cloudnet-driver - 3.3.0-RELEASE + 3.4.5-RELEASE provided de.dytanic.cloudnet cloudnet-bridge - 3.3.0-RELEASE + 3.4.5-RELEASE provided @@ -59,23 +61,11 @@ provided - - - com.github.anweisen.Utility - database-api - ${utilities.version} - - - com.github.anweisen.Utility - database-sql - ${utilities.version} - - org.projectlombok lombok - 1.18.34 + 1.18.38 provided @@ -88,12 +78,6 @@ - - - jitpack.io - https://jitpack.io - - spigot-repo @@ -127,16 +111,16 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.0 + 3.14.0 - 1.8 - 1.8 + 16 + 16 utf-8 org.projectlombok lombok - 1.18.34 + 1.18.38 @@ -146,7 +130,7 @@ org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.1 attach-sources @@ -161,7 +145,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.0 package @@ -171,11 +155,7 @@ - com.github.anweisen.Utility:commons - com.github.anweisen.Utility:common-utils - com.github.anweisen.Utility:bukkit-utils - com.github.anweisen.Utility:database-api - com.github.anweisen.Utility:database-sql + net.kyori:adventure-api @@ -188,7 +168,7 @@ org.apache.maven.plugins maven-resources-plugin - 3.2.0 + 3.3.1 copy-license diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java index fee43728e..c4323fb08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java @@ -16,116 +16,112 @@ import java.util.List; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeAPI { - private ChallengeAPI() { - } - - public static boolean isStarted() { - return Challenges.getInstance().getChallengeTimer().isStarted(); - } - - public static boolean isPaused() { - return Challenges.getInstance().getChallengeTimer().isPaused(); - } - - public static TimerStatus getTimerStatus() { - return Challenges.getInstance().getChallengeTimer().getStatus(); - } - - public static void pauseTimer() { - Challenges.getInstance().getChallengeTimer().pause(true); - } - - public static void pauseTimer(boolean playInGameEffects) { - Challenges.getInstance().getChallengeTimer().pause(playInGameEffects); - } - - public static void resumeTimer() { - Challenges.getInstance().getChallengeTimer().resume(); - } - - public static void resetTimer() { - Challenges.getInstance().getChallengeTimer().reset(); - } - - public static void endChallenge(@Nonnull ChallengeEndCause endCause) { - Challenges.getInstance().getServerManager().endChallenge(endCause, null); - } - - public static void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { - Challenges.getInstance().getServerManager().endChallenge(endCause, winnerGetter); - } - - - public static boolean isWorldInUse() { - return Challenges.getInstance().getWorldManager().isWorldInUse(); - } - - public static boolean isFresh() { - return Challenges.getInstance().getServerManager().isFresh(); - } - - public static void registerScheduler(@Nonnull Object... scheduler) { - Challenges.getInstance().getScheduler().register(scheduler); - } - - public static void subscribeLoader(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - Challenges.getInstance().getLoaderRegistry().subscribe(classOfLoader, action); - } - - @Nonnull - public static List getCustomDrops(@Nonnull Material block) { - return Challenges.getInstance().getBlockDropManager().getCustomDrops(block); - } - - public static boolean getDropChance(@Nonnull Material block) { - return Challenges.getInstance().getBlockDropManager().getDropChance(block).getAsBoolean(); - } - - public static boolean getItemsDirectIntoInventory() { - return Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); - } - - @Nonnull - public static String formatTime(long seconds) { - return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); - } - - /** - * @return all players that aren't ignored by the plugin - */ - @Nonnull - public static List getIngamePlayers() { - List list = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (!AbstractChallenge.ignorePlayer(player)) { - list.add(player); - } - } - return list; - } - - public static List getGameWorlds() { - return Challenges.getInstance().getGameWorldStorage().getGameWorlds(); - } - - public static World getGameWorld(@Nullable Environment environment) { - return Challenges.getInstance().getGameWorldStorage().getWorld(environment); - } - - public static boolean isPlayerInGameWorld(@Nonnull Environment environment) { - World world = getGameWorld(environment); - for (Player player : world.getPlayers()) { - if (!AbstractChallenge.ignorePlayer(player)) { - return true; - } - } - return false; - } + private ChallengeAPI() { + } + + public static boolean isStarted() { + return Challenges.getInstance().getChallengeTimer().isStarted(); + } + + public static boolean isPaused() { + return Challenges.getInstance().getChallengeTimer().isPaused(); + } + + public static TimerStatus getTimerStatus() { + return Challenges.getInstance().getChallengeTimer().getStatus(); + } + + public static void pauseTimer() { + Challenges.getInstance().getChallengeTimer().pause(true); + } + + public static void pauseTimer(boolean playInGameEffects) { + Challenges.getInstance().getChallengeTimer().pause(playInGameEffects); + } + + public static void resumeTimer() { + Challenges.getInstance().getChallengeTimer().resume(); + } + + public static void resetTimer() { + Challenges.getInstance().getChallengeTimer().reset(); + } + + public static void endChallenge(@Nonnull ChallengeEndCause endCause) { + Challenges.getInstance().getServerManager().endChallenge(endCause, null); + } + + public static void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + Challenges.getInstance().getServerManager().endChallenge(endCause, winnerGetter); + } + + + public static boolean isWorldInUse() { + return Challenges.getInstance().getWorldManager().isWorldInUse(); + } + + public static boolean isFresh() { + return Challenges.getInstance().getServerManager().isFresh(); + } + + public static void registerScheduler(@Nonnull Object... scheduler) { + Challenges.getInstance().getScheduler().register(scheduler); + } + + public static void subscribeLoader(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + Challenges.getInstance().getLoaderRegistry().subscribe(classOfLoader, action); + } + + @Nonnull + public static List getCustomDrops(@Nonnull Material block) { + return Challenges.getInstance().getBlockDropManager().getCustomDrops(block); + } + + public static boolean getDropChance(@Nonnull Material block) { + return Challenges.getInstance().getBlockDropManager().getDropChance(block).getAsBoolean(); + } + + public static boolean getItemsDirectIntoInventory() { + return Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); + } + + @Nonnull + public static String formatTime(long seconds) { + return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); + } + + /** + * @return all players that aren't ignored by the plugin + */ + @Nonnull + public static List getIngamePlayers() { + List list = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (!AbstractChallenge.ignorePlayer(player)) { + list.add(player); + } + } + return list; + } + + public static List getGameWorlds() { + return Challenges.getInstance().getGameWorldStorage().getGameWorlds(); + } + + public static World getGameWorld(@Nullable Environment environment) { + return Challenges.getInstance().getGameWorldStorage().getWorld(environment); + } + + public static boolean isPlayerInGameWorld(@Nonnull Environment environment) { + World world = getGameWorld(environment); + for (Player player : world.getPlayers()) { + if (!AbstractChallenge.ignorePlayer(player)) { + return true; + } + } + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 67ac12569..1cec3de1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -1,10 +1,13 @@ package net.codingarea.challenges.plugin; import lombok.Getter; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; -import net.codingarea.challenges.plugin.content.loader.*; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; +import net.codingarea.challenges.plugin.content.loader.PrefixLoader; +import net.codingarea.challenges.plugin.content.loader.UpdateLoader; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager; import net.codingarea.challenges.plugin.management.bstats.MetricsLoader; import net.codingarea.challenges.plugin.management.challenges.ChallengeLoader; @@ -19,204 +22,202 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.ChallengeTimer; import net.codingarea.challenges.plugin.management.server.*; import net.codingarea.challenges.plugin.management.stats.StatsManager; +import net.codingarea.challenges.plugin.management.team.TeamProvider; import net.codingarea.challenges.plugin.spigot.command.*; import net.codingarea.challenges.plugin.spigot.listener.*; import net.codingarea.challenges.plugin.utils.bukkit.command.ForwardingCommand; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @Getter public final class Challenges extends BukkitModule { - private static Challenges instance; - private PlayerInventoryManager playerInventoryManager; - private ScoreboardManager scoreboardManager; - private ChallengeManager challengeManager; - private BlockDropManager blockDropManager; - private ChallengeLoader challengeLoader; - private CustomChallengesLoader customChallengesLoader; - private CustomSettingsLoader customSettingsLoader; - private DatabaseManager databaseManager; - private CloudSupportManager cloudSupportManager; - private ServerManager serverManager; - private ConfigManager configManager; - private ScheduleManager scheduler; - private StatsManager statsManager; - private WorldManager worldManager; - private TitleManager titleManager; - private MenuManager menuManager; - private ChallengeTimer challengeTimer; - private LoaderRegistry loaderRegistry; - private MetricsLoader metricsLoader; + private static Challenges instance; + private PlayerInventoryManager playerInventoryManager; + private ScoreboardManager scoreboardManager; + private ChallengeManager challengeManager; + private BlockDropManager blockDropManager; + private ChallengeLoader challengeLoader; + private CustomChallengesLoader customChallengesLoader; + private CustomSettingsLoader customSettingsLoader; + private DatabaseManager databaseManager; + private CloudSupportManager cloudSupportManager; + private ServerManager serverManager; + private ConfigManager configManager; + private ScheduleManager scheduler; + private StatsManager statsManager; + private WorldManager worldManager; + private TitleManager titleManager; + private MenuManager menuManager; + private ChallengeTimer challengeTimer; + private LoaderRegistry loaderRegistry; + private MetricsLoader metricsLoader; private GameWorldStorage gameWorldStorage; - private GeneratorWorldPortalManager generatorWorldPortalManager; - - @Nonnull - public static Challenges getInstance() { - return instance; - } - - @Override - protected void handleLoad() { - checkConfig(); - createManagers(); - loadManagers(); - } - - private void checkConfig() { - saveResource("hotbar-items.yml", false); - if (getConfigDocument().getVersion("config-version", Version.parse("1.0")).isOlderThan(Version.parse("2.0"))) { - saveResource("config.yml", true); - reloadConfig(); - getLogger().info("A deprecated config was found and replaced with a new one"); - } - } - - @Override - protected void handleEnable() { - enableManagers(); - - registerCommands(); - registerListeners(); - } - - private void createManagers() { - - configManager = new ConfigManager(); - configManager.loadConfigs(); - - loaderRegistry = new LoaderRegistry( - new LanguageLoader(), - new PrefixLoader(), - new UpdateLoader() - ); - - databaseManager = new DatabaseManager(); - worldManager = new WorldManager(); - serverManager = new ServerManager(); - scheduler = new ScheduleManager(); - scoreboardManager = new ScoreboardManager(); - cloudSupportManager = new CloudSupportManager(); - titleManager = new TitleManager(); - challengeTimer = new ChallengeTimer(); - blockDropManager = new BlockDropManager(); - challengeManager = new ChallengeManager(); - challengeLoader = new ChallengeLoader(); - customChallengesLoader = new CustomChallengesLoader(); - customSettingsLoader = new CustomSettingsLoader(); - menuManager = new MenuManager(); - playerInventoryManager = new PlayerInventoryManager(); - statsManager = new StatsManager(); - metricsLoader = new MetricsLoader(); - gameWorldStorage = new GameWorldStorage(); - generatorWorldPortalManager = new GeneratorWorldPortalManager(); - - } - - private void loadManagers() { - loaderRegistry.load(); - worldManager.load(); - } - - private void enableManagers() { - gameWorldStorage.enable(); - challengeLoader.enable(); - customSettingsLoader.enable(); - databaseManager.enable(); - worldManager.enable(); - challengeTimer.loadSession(); - challengeTimer.enable(); - challengeManager.enable(); - statsManager.register(); - scheduler.start(); - metricsLoader.start(); - - loaderRegistry.enable(); - } - - private void registerCommands() { - registerCommand(new HelpCommand(), "help"); - registerCommand(new ChallengesCommand(), "challenges"); - registerCommand(new TimerCommand(), "timer"); - registerCommand(new ForwardingCommand("timer start"), "start"); - registerCommand(new ForwardingCommand("timer pause"), "pause"); - registerCommand(new ResetCommand(), "reset"); - registerCommand(new StatsCommand(), "stats"); - registerCommand(new LeaderboardCommand(), "leaderboard"); - registerCommand(new DatabaseCommand(), "database"); - registerCommand(new GamestateCommand(), "gamestate"); - registerCommand(new VillageCommand(), "village"); - registerCommand(new HealCommand(), "heal"); - registerCommand(new FeedCommand(), "feed"); - registerCommand(new SearchCommand(), "search"); - registerListenerCommand(new InvseeCommand(), "invsee"); - registerCommand(new FlyCommand(), "fly"); - registerCommand(new WorldCommand(), "world"); - registerListenerCommand(new BackCommand(), "back"); - registerCommand(new GamemodeCommand(), "gamemode"); - registerCommand(new ForwardingCommand("gamemode 0", false), "gms"); - registerCommand(new ForwardingCommand("gamemode 1", false), "gmc"); - registerCommand(new ForwardingCommand("gamemode 2", false), "gma"); - registerCommand(new ForwardingCommand("gamemode 3", false), "gmsp"); - registerCommand(new WeatherCommand(), "weather"); - registerCommand(new ForwardingCommand("weather sun"), "sun"); - registerCommand(new ForwardingCommand("weather rain"), "rain"); - registerCommand(new ForwardingCommand("weather thunder"), "thunder"); - registerCommand(new TimeCommand(), "time"); - registerCommand(new ForwardingCommand("time set day"), "day"); - registerCommand(new ForwardingCommand("time set night"), "night"); - registerCommand(new ForwardingCommand("time set noon"), "noon"); - registerCommand(new ForwardingCommand("time set midnight"), "midnight"); - registerCommand(new ResultCommand(), "result"); - registerCommand(new SkipTimerCommand(), "skiptimer"); - registerListenerCommand(new GodModeCommand(), "godmode"); - } - - private void registerListeners() { - registerListener( - new PlayerConnectionListener(), - new RestrictionListener(), - new ExtraWorldRestrictionListener(), - new CheatListener(), - new BlockDropListener(), - new CustomEventListener(), - new HelpListener(), - new ChatInputListener(), - new GeneratorWorldsListener(), - new ScoreboardUpdateListener() - ); - } - - @Override - protected void handleDisable() { - boolean shutdownBecauseOfReset = worldManager != null && worldManager.isShutdownBecauseOfReset(); - boolean restoreDefaultsOnReset = getConfigDocument().getBoolean("restore-defaults-on-reset"); - - if (playerInventoryManager != null) playerInventoryManager.handleDisable(); - if (challengeTimer != null && !shutdownBecauseOfReset) challengeTimer.saveSession(false); - if (scheduler != null) scheduler.stop(); - if (loaderRegistry != null) loaderRegistry.disable(); - if (databaseManager != null) databaseManager.disconnectIfConnected(); - if (scoreboardManager != null) scoreboardManager.disable(); - - if (challengeManager != null) { - challengeManager.shutdownChallenges(); - if (shutdownBecauseOfReset && restoreDefaultsOnReset) { - challengeManager.restoreDefaults(); - } - challengeManager.saveLocalSettings(false); - challengeManager.saveLocalCustomChallenges(false); - - if (!shutdownBecauseOfReset) { - challengeManager.saveGamestate(false); - } - challengeManager.clearChallengeCache(); - } - } + private GeneratorWorldPortalManager generatorWorldPortalManager; + private TeamProvider teamProvider; + + @Nonnull + public static Challenges getInstance() { + return instance; + } + + @Override + protected void handleLoad() { + checkConfig(); + createManagers(); + loadManagers(); + } + + private void checkConfig() { + saveResource("hotbar-items.yml", false); + if (getConfigDocument().getVersion("config-version", Version.parse("1.0")).isOlderThan(Version.parse("2.0"))) { + saveResource("config.yml", true); + reloadConfig(); + getLogger().info("A deprecated config was found and replaced with a new one"); + } + } + + @Override + protected void handleEnable() { + enableManagers(); + + registerCommands(); + registerListeners(); + } + + private void createManagers() { + + configManager = new ConfigManager(); + configManager.loadConfigs(); + + loaderRegistry = new LoaderRegistry( + new LanguageLoader(), + new PrefixLoader(), + new UpdateLoader() + ); + + databaseManager = new DatabaseManager(); + worldManager = new WorldManager(); + serverManager = new ServerManager(); + scheduler = new ScheduleManager(); + scoreboardManager = new ScoreboardManager(); + cloudSupportManager = new CloudSupportManager(); + titleManager = new TitleManager(); + challengeTimer = new ChallengeTimer(); + blockDropManager = new BlockDropManager(); + teamProvider = new TeamProvider(); + challengeManager = new ChallengeManager(); + challengeLoader = new ChallengeLoader(); + customChallengesLoader = new CustomChallengesLoader(); + customSettingsLoader = new CustomSettingsLoader(); + menuManager = new MenuManager(); + playerInventoryManager = new PlayerInventoryManager(); + statsManager = new StatsManager(); + metricsLoader = new MetricsLoader(); + gameWorldStorage = new GameWorldStorage(); + generatorWorldPortalManager = new GeneratorWorldPortalManager(); + } + + private void loadManagers() { + loaderRegistry.load(); + worldManager.load(); + } + + private void enableManagers() { + gameWorldStorage.enable(); + challengeLoader.enable(); + customSettingsLoader.enable(); + databaseManager.enable(); + worldManager.enable(); + challengeTimer.loadSession(); + challengeTimer.enable(); + challengeManager.enable(); + statsManager.register(); + scheduler.start(); + metricsLoader.start(); + + loaderRegistry.enable(); + } + + private void registerCommands() { + registerCommand(new HelpCommand(), "help"); + registerCommand(new ChallengesCommand(), "challenges"); + registerCommand(new TimerCommand(), "timer"); + registerCommand(new ForwardingCommand("timer start"), "start"); + registerCommand(new ForwardingCommand("timer pause"), "pause"); + registerCommand(new ResetCommand(), "reset"); + registerCommand(new StatsCommand(), "stats"); + registerCommand(new LeaderboardCommand(), "leaderboard"); + registerCommand(new DatabaseCommand(), "database"); + registerCommand(new GamestateCommand(), "gamestate"); + registerCommand(new VillageCommand(), "village"); + registerCommand(new HealCommand(), "heal"); + registerCommand(new FeedCommand(), "feed"); + registerCommand(new SearchCommand(), "search"); + registerListenerCommand(new InvseeCommand(), "invsee"); + registerCommand(new FlyCommand(), "fly"); + registerCommand(new WorldCommand(), "world"); + registerListenerCommand(new BackCommand(), "back"); + registerCommand(new GamemodeCommand(), "gamemode"); + registerCommand(new ForwardingCommand("gamemode 0", false), "gms"); + registerCommand(new ForwardingCommand("gamemode 1", false), "gmc"); + registerCommand(new ForwardingCommand("gamemode 2", false), "gma"); + registerCommand(new ForwardingCommand("gamemode 3", false), "gmsp"); + registerCommand(new WeatherCommand(), "weather"); + registerCommand(new ForwardingCommand("weather sun"), "sun"); + registerCommand(new ForwardingCommand("weather rain"), "rain"); + registerCommand(new ForwardingCommand("weather thunder"), "thunder"); + registerCommand(new TimeCommand(), "time"); + registerCommand(new ForwardingCommand("time set day"), "day"); + registerCommand(new ForwardingCommand("time set night"), "night"); + registerCommand(new ForwardingCommand("time set noon"), "noon"); + registerCommand(new ForwardingCommand("time set midnight"), "midnight"); + registerCommand(new ResultCommand(), "result"); + registerCommand(new SkipTimerCommand(), "skiptimer"); + registerCommand(new LanguageCommand(), "setlanguage"); + registerListenerCommand(new GodModeCommand(), "godmode"); + } + + private void registerListeners() { + registerListener( + new PlayerConnectionListener(), + new RestrictionListener(), + new ExtraWorldRestrictionListener(), + new CheatListener(), + new BlockDropListener(), + new CustomEventListener(), + new HelpListener(), + new ChatInputListener(), + new GeneratorWorldsListener(), + new ScoreboardUpdateListener() + ); + } + + @Override + protected void handleDisable() { + boolean shutdownBecauseOfReset = worldManager != null && worldManager.isShutdownBecauseOfReset(); + boolean restoreDefaultsOnReset = getConfigDocument().getBoolean("restore-defaults-on-reset"); + + if (playerInventoryManager != null) playerInventoryManager.handleDisable(); + if (challengeTimer != null && !shutdownBecauseOfReset) challengeTimer.saveSession(false); + if (scheduler != null) scheduler.stop(); + if (loaderRegistry != null) loaderRegistry.disable(); + if (databaseManager != null) databaseManager.disconnectIfConnected(); + if (scoreboardManager != null) scoreboardManager.disable(); + + if (challengeManager != null) { + challengeManager.shutdownChallenges(); + if (shutdownBecauseOfReset && restoreDefaultsOnReset) { + challengeManager.restoreDefaults(); + } + challengeManager.saveLocalSettings(false); + challengeManager.saveLocalCustomChallenges(false); + + if (!shutdownBecauseOfReset) { + challengeManager.saveGamestate(false); + } + challengeManager.clearChallengeCache(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 3c1c775b6..e8a2e9237 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; @@ -24,176 +24,172 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter @ToString public class CustomChallenge extends Setting { - private final UUID uuid; - private Material material; - private String name; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - - public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType); - this.uuid = uuid; - this.material = displayItem; - this.name = displayName; - this.trigger = trigger; - this.subTriggers = subTriggers; - this.action = action; - this.subActions = subActions; - } - - @NotNull - @Override - public ItemStack getDisplayItem() { - String name = this.name; - if (name == null) { - name = "NULL"; - - } - Material material = this.material; - if (material == null) { - material = Material.BARRIER; - } - - ItemBuilder builder = new ItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); - - // ADDING CONDITION INFO - if (getTrigger() != null) { - builder.appendLore(" "); - List triggerDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); - - String triggerName = Message.forName(getTrigger().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); - builder.appendLore(triggerDisplay); - } - - // ADDING ACTION INFO - if (getAction() != null) { - builder.appendLore(" "); - List actionDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); - - String actionName = Message.forName(getAction().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); - builder.appendLore(actionDisplay); - } - - return builder.build(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER); - } - - @Override - public void playStatusUpdateTitle() { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getDisplayName()); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - - document.set("material", material == null ? null : material.name()); - document.set("name", name); - document.set("trigger", trigger == null ? null : trigger.getName()); - document.set("subTrigger", subTriggers); - document.set("action", action == null ? null : action.getName()); - document.set("subActions", subActions); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return super.getSettingsDescription(); - } - - public final void onTriggerFulfilled(ChallengeExecutionData challengeExecutionData) { - if (isEnabled()) { - - boolean triggerMet = isTriggerMet(challengeExecutionData.getTriggerData()); - if (triggerMet) { - executeAction(challengeExecutionData); - } - - } - } - - /** - * @return if the trigger is met. - * That is when every key in the subTriggers is contained by the data map and one or more value - * of the lists are equal to one another. - */ - public boolean isTriggerMet(Map> data) { - if (!subTriggers.isEmpty()) { - for (Entry entry : subTriggers.entrySet()) { - if (!data.containsKey(entry.getKey())) { - return false; - } - List list = data.get(entry.getKey()); - - boolean match = false; - for (String value : entry.getValue()) { - if (list.contains(value)) { - match = true; - break; - } - } - - if (!match) { - return false; - } - } - } - return true; - } - - public void executeAction(ChallengeExecutionData challengeExecutionData) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - action.execute(challengeExecutionData, subActions); - }); - return; - } - action.execute(challengeExecutionData, subActions); - } - - public void applySettings(@Nonnull Material material, @Nonnull String name, @Nonnull ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions) { - this.material = material; - this.name = name; - this.trigger = trigger; - this.subTriggers = subTriggers; - this.action = action; - this.subActions = subActions; - } - - public UUID getUniqueId() { - return uuid; - } - - @Nonnull - public String getDisplayName() { - return name; - } - - @NotNull - @Override - public String getUniqueName() { - return uuid.toString(); - } + private final UUID uuid; + private Material material; + private String name; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + + public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions) { + super(menuType); + this.uuid = uuid; + this.material = displayItem; + this.name = displayName; + this.trigger = trigger; + this.subTriggers = subTriggers; + this.action = action; + this.subActions = subActions; + } + + @NotNull + @Override + public ItemStack getDisplayItem() { + String name = this.name; + if (name == null) { + name = "NULL"; + + } + Material material = this.material; + if (material == null) { + material = Material.BARRIER; + } + + ItemBuilder builder = new ItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); + + // ADDING CONDITION INFO + if (getTrigger() != null) { + builder.appendLore(" "); + List triggerDisplay = InfoMenuGenerator + .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); + + String triggerName = Message.forName(getTrigger().getMessage()).asItemDescription().getName(); + builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); + builder.appendLore(triggerDisplay); + } + + // ADDING ACTION INFO + if (getAction() != null) { + builder.appendLore(" "); + List actionDisplay = InfoMenuGenerator + .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); + + String actionName = Message.forName(getAction().getMessage()).asItemDescription().getName(); + builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); + builder.appendLore(actionDisplay); + } + + return builder.build(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER); + } + + @Override + public void playStatusUpdateTitle() { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getDisplayName()); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + + document.set("material", material == null ? null : material.name()); + document.set("name", name); + document.set("trigger", trigger == null ? null : trigger.getName()); + document.set("subTrigger", subTriggers); + document.set("action", action == null ? null : action.getName()); + document.set("subActions", subActions); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return super.getSettingsDescription(); + } + + public final void onTriggerFulfilled(ChallengeExecutionData challengeExecutionData) { + if (isEnabled()) { + + boolean triggerMet = isTriggerMet(challengeExecutionData.getTriggerData()); + if (triggerMet) { + executeAction(challengeExecutionData); + } + + } + } + + /** + * @return if the trigger is met. + * That is when every key in the subTriggers is contained by the data map and one or more value + * of the lists are equal to one another. + */ + public boolean isTriggerMet(Map> data) { + if (!subTriggers.isEmpty()) { + for (Entry entry : subTriggers.entrySet()) { + if (!data.containsKey(entry.getKey())) { + return false; + } + List list = data.get(entry.getKey()); + + boolean match = false; + for (String value : entry.getValue()) { + if (list.contains(value)) { + match = true; + break; + } + } + + if (!match) { + return false; + } + } + } + return true; + } + + public void executeAction(ChallengeExecutionData challengeExecutionData) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + action.execute(challengeExecutionData, subActions); + }); + return; + } + action.execute(challengeExecutionData, subActions); + } + + public void applySettings(@Nonnull Material material, @Nonnull String name, @Nonnull ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions) { + this.material = material; + this.name = name; + this.trigger = trigger; + this.subTriggers = subTriggers; + this.action = action; + this.subActions = subActions; + } + + public UUID getUniqueId() { + return uuid; + } + + @Nonnull + public String getDisplayName() { + return name; + } + + @NotNull + @Override + public String getUniqueName() { + return uuid.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java index f1a4a31fa..0cde7dbe5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java @@ -15,84 +15,80 @@ import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ChallengeExecutionData { - @Getter - private final IChallengeTrigger trigger; - @Getter - private final Map> triggerData; - @Getter - private Entity entity; - private Runnable cancelAction; - @Getter - private int timesExecuting; - - public ChallengeExecutionData( - IChallengeTrigger trigger) { - this.trigger = trigger; - this.triggerData = new HashMap<>(); - } - - public ChallengeExecutionData data(String key, String data) { - triggerData.put(key, Collections.singletonList(data)); - return this; - } - - public ChallengeExecutionData data(String key, List data) { - triggerData.put(key, data); - return this; - } - - public ChallengeExecutionData data(String key, String... data) { - triggerData.put(key, Arrays.asList(data)); - return this; - } - - public ChallengeExecutionData block(Material material) { - return data(SubSettingsHelper.BLOCK, SubSettingsHelper.ANY, material.name()); - } - - public ChallengeExecutionData entityType(EntityType type) { - return data(SubSettingsHelper.ENTITY_TYPE, SubSettingsHelper.ANY, type.name()); - } - - public ChallengeExecutionData entity(Entity entity) { - this.entity = entity; - return this; - } - - public ChallengeExecutionData cancelAction(Runnable cancelAction) { - this.cancelAction = cancelAction; - return this; - } - - public ChallengeExecutionData event(Cancellable event) { - this.cancelAction = () -> event.setCancelled(true); - return this; - } - - public ChallengeExecutionData times(int timesExecuting) { - this.timesExecuting = timesExecuting; - return this; - } - - public void execute() { - if (ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse()) { - if (entity instanceof Player && AbstractChallenge.ignorePlayer(((Player) entity))) { - return; - } - if (cancelAction != null) { - CancelEventAction.onPreTrigger(); - } - Challenges.getInstance().getCustomChallengesLoader().executeTrigger(this); - if (cancelAction != null && CancelEventAction.shouldCancel()) { - cancelAction.run(); - } - } - } + @Getter + private final IChallengeTrigger trigger; + @Getter + private final Map> triggerData; + @Getter + private Entity entity; + private Runnable cancelAction; + @Getter + private int timesExecuting; + + public ChallengeExecutionData( + IChallengeTrigger trigger) { + this.trigger = trigger; + this.triggerData = new HashMap<>(); + } + + public ChallengeExecutionData data(String key, String data) { + triggerData.put(key, Collections.singletonList(data)); + return this; + } + + public ChallengeExecutionData data(String key, List data) { + triggerData.put(key, data); + return this; + } + + public ChallengeExecutionData data(String key, String... data) { + triggerData.put(key, Arrays.asList(data)); + return this; + } + + public ChallengeExecutionData block(Material material) { + return data(SubSettingsHelper.BLOCK, SubSettingsHelper.ANY, material.name()); + } + + public ChallengeExecutionData entityType(EntityType type) { + return data(SubSettingsHelper.ENTITY_TYPE, SubSettingsHelper.ANY, type.name()); + } + + public ChallengeExecutionData entity(Entity entity) { + this.entity = entity; + return this; + } + + public ChallengeExecutionData cancelAction(Runnable cancelAction) { + this.cancelAction = cancelAction; + return this; + } + + public ChallengeExecutionData event(Cancellable event) { + this.cancelAction = () -> event.setCancelled(true); + return this; + } + + public ChallengeExecutionData times(int timesExecuting) { + this.timesExecuting = timesExecuting; + return this; + } + + public void execute() { + if (ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse()) { + if (entity instanceof Player && AbstractChallenge.ignorePlayer(((Player) entity))) { + return; + } + if (cancelAction != null) { + CancelEventAction.onPreTrigger(); + } + Challenges.getInstance().getCustomChallengesLoader().executeTrigger(this); + if (cancelAction != null && CancelEventAction.shouldCancel()) { + cancelAction.run(); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index f9a6d09b2..6ba0be71f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -4,40 +4,36 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeSetting implements IChallengeSetting { - private final String name; - private final SubSettingsBuilder subSettingsBuilder; + private final String name; + private final SubSettingsBuilder subSettingsBuilder; - public ChallengeSetting(String name, SubSettingsBuilder subSettingsBuilder) { - this.name = name; - this.subSettingsBuilder = subSettingsBuilder.build(); - } + public ChallengeSetting(String name, SubSettingsBuilder subSettingsBuilder) { + this.name = name; + this.subSettingsBuilder = subSettingsBuilder.build(); + } - public ChallengeSetting(String name) { - this(name, SubSettingsBuilder.createEmpty()); - } + public ChallengeSetting(String name) { + this(name, SubSettingsBuilder.createEmpty()); + } - public ChallengeSetting(String name, Supplier builderSupplier) { - this(name, builderSupplier.get()); - } + public ChallengeSetting(String name, Supplier builderSupplier) { + this(name, builderSupplier.get()); + } - public String getMessageSuffix() { - return name.toLowerCase(); - } + public String getMessageSuffix() { + return name.toLowerCase(); + } - @Override - public SubSettingsBuilder getSubSettingsBuilder() { - return subSettingsBuilder; - } + @Override + public SubSettingsBuilder getSubSettingsBuilder() { + return subSettingsBuilder; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 78b161bb8..1cc84980d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.*; @@ -15,149 +15,145 @@ import java.util.LinkedHashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CustomSettingsLoader { - @Getter - private final Map triggers; - private final Map fallbackTriggers; - - @Getter - private final Map actions; - private final Map fallbackActions; - - public CustomSettingsLoader() { - actions = new LinkedHashMap<>(); - fallbackActions = new LinkedHashMap<>(); - triggers = new LinkedHashMap<>(); - fallbackTriggers = new LinkedHashMap<>(); - } - - public void enable() { - loadTrigger(); - loadActions(); - } - - private void loadTrigger() { - registerTriggers( - new IntervallTrigger("intervall"), - new PlayerJumpTrigger("jump"), - new PlayerSneakTrigger("sneak"), - new MoveBlockTrigger("move_block"), - new BreakBlockTrigger("block_break"), - new PlaceBlockTrigger("block_place"), - new EntityDeathTrigger("death"), - new EntityDamageTrigger("damage"), - new EntityDamageByPlayerTrigger("damage_by_player"), - new ConsumeItemTrigger("consume_item"), - new PickupItemTrigger("pickup_item"), - new DropItemTrigger("drop_item"), - new AdvancementTrigger("advancement"), - new HungerTrigger("hunger"), - new MoveUpTrigger("move_up"), - new MoveDownTrigger("move_down"), - new MoveCameraTrigger("move_camera"), - new StandsOnSpecificBlockTrigger("stands_on_specific_block"), - new StandsNotOnSpecificBlockTrigger("stands_not_on_specific_block"), - new GainXPTrigger("gain_xp"), - new LevelUpTrigger("level_up"), - new CraftItemTrigger("item_craft"), - new InLiquidTrigger("in_liquid"), - new GetItemTrigger("get_item") - ); - } - - private void loadActions() { - registerActions( - new CancelEventAction("cancel"), - new WinChallengeAction("win"), - new ExecuteCommandAction("command"), - new KillEntityAction("kill"), - new DamageEntityAction("damage"), - new HealEntityAction("heal"), - new ModifyMaxHealthAction("max_health"), - new HungerPlayerAction("hunger"), - new SpawnEntityAction("spawn_entity"), - new RandomMobAction("random_mob"), - new RandomItemAction("random_item"), - new UncraftInventoryAction("uncraft_inventory"), - new BoostEntityInAirAction("boost_in_air"), - new PotionEffectAction("potion_effect"), - new AddPermanentEffectAction("permanent_effect"), - new RandomPotionEffectAction("random_effect"), - new ClearInventoryAction("clear_inventory"), - new DropRandomItemAction("drop_random_item"), - new RemoveRandomItemAction("remove_random_item"), - new SwapRandomItemAction("swap_random_item"), - new FreezeAction("freeze"), - new InvertHealthAction("invert_health"), - new WaterMLGAction("water_mlg"), - new JumpAndRunAction("jnr"), - new RandomHotBarAction("random_hotbar"), - new ChangeWorldBorderAction("modify_border"), - new SwapRandomMobAction("swap_mobs"), - new PlaceStructureAction("place_structure") - ); - } - - public void registerTriggers(ChallengeTrigger... trigger) { - for (ChallengeTrigger trigger1 : trigger) { - if (trigger1.getClass().isAnnotationPresent(RequireVersion.class)) { - RequireVersion requireVersion = trigger1.getClass().getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = requireVersion.value(); - - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register trigger {}, requires version {}, server running on {}", trigger1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); - continue; - } - } - if (trigger1.getClass().isAnnotationPresent(FallbackNames.class)) { - FallbackNames fallbackName = trigger1.getClass().getAnnotation(FallbackNames.class); - String[] fallbackNames = fallbackName.value(); - - for (String name : fallbackNames) { - fallbackTriggers.put(name, trigger1); - } - } - triggers.put(trigger1.getName(), trigger1); - Bukkit.getPluginManager().registerEvents(trigger1, Challenges.getInstance()); - } - } - - public void registerActions(ChallengeAction... action) { - for (ChallengeAction action1 : action) { - if (action1.getClass().isAnnotationPresent(RequireVersion.class)) { - RequireVersion requireVersion = action1.getClass().getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = requireVersion.value(); - - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register action {}, requires version {}, server running on {}", action1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); - continue; - } - } - if (action1.getClass().isAnnotationPresent(FallbackNames.class)) { - FallbackNames fallbackName = action1.getClass().getAnnotation(FallbackNames.class); - String[] fallbackNames = fallbackName.value(); - - for (String name : fallbackNames) { - fallbackActions.put(name, action1); - } - } - actions.put(action1.getName(), action1); - } - } - - @Nullable - public ChallengeAction getActionByName(String name) { - return actions.getOrDefault(name, fallbackActions.get(name)); - } - - @Nullable - public ChallengeTrigger getTriggerByName(String name) { - return triggers.getOrDefault(name, fallbackTriggers.get(name)); - } + @Getter + private final Map triggers; + private final Map fallbackTriggers; + + @Getter + private final Map actions; + private final Map fallbackActions; + + public CustomSettingsLoader() { + actions = new LinkedHashMap<>(); + fallbackActions = new LinkedHashMap<>(); + triggers = new LinkedHashMap<>(); + fallbackTriggers = new LinkedHashMap<>(); + } + + public void enable() { + loadTrigger(); + loadActions(); + } + + private void loadTrigger() { + registerTriggers( + new IntervallTrigger("intervall"), + new PlayerJumpTrigger("jump"), + new PlayerSneakTrigger("sneak"), + new MoveBlockTrigger("move_block"), + new BreakBlockTrigger("block_break"), + new PlaceBlockTrigger("block_place"), + new EntityDeathTrigger("death"), + new EntityDamageTrigger("damage"), + new EntityDamageByPlayerTrigger("damage_by_player"), + new ConsumeItemTrigger("consume_item"), + new PickupItemTrigger("pickup_item"), + new DropItemTrigger("drop_item"), + new AdvancementTrigger("advancement"), + new HungerTrigger("hunger"), + new MoveUpTrigger("move_up"), + new MoveDownTrigger("move_down"), + new MoveCameraTrigger("move_camera"), + new StandsOnSpecificBlockTrigger("stands_on_specific_block"), + new StandsNotOnSpecificBlockTrigger("stands_not_on_specific_block"), + new GainXPTrigger("gain_xp"), + new LevelUpTrigger("level_up"), + new CraftItemTrigger("item_craft"), + new InLiquidTrigger("in_liquid"), + new GetItemTrigger("get_item") + ); + } + + private void loadActions() { + registerActions( + new CancelEventAction("cancel"), + new WinChallengeAction("win"), + new ExecuteCommandAction("command"), + new KillEntityAction("kill"), + new DamageEntityAction("damage"), + new HealEntityAction("heal"), + new ModifyMaxHealthAction("max_health"), + new HungerPlayerAction("hunger"), + new SpawnEntityAction("spawn_entity"), + new RandomMobAction("random_mob"), + new RandomItemAction("random_item"), + new UncraftInventoryAction("uncraft_inventory"), + new BoostEntityInAirAction("boost_in_air"), + new PotionEffectAction("potion_effect"), + new AddPermanentEffectAction("permanent_effect"), + new RandomPotionEffectAction("random_effect"), + new ClearInventoryAction("clear_inventory"), + new DropRandomItemAction("drop_random_item"), + new RemoveRandomItemAction("remove_random_item"), + new SwapRandomItemAction("swap_random_item"), + new FreezeAction("freeze"), + new InvertHealthAction("invert_health"), + new WaterMLGAction("water_mlg"), + new JumpAndRunAction("jnr"), + new RandomHotBarAction("random_hotbar"), + new ChangeWorldBorderAction("modify_border"), + new SwapRandomMobAction("swap_mobs"), + new PlaceStructureAction("place_structure") + ); + } + + public void registerTriggers(ChallengeTrigger... trigger) { + for (ChallengeTrigger trigger1 : trigger) { + if (trigger1.getClass().isAnnotationPresent(RequireVersion.class)) { + RequireVersion requireVersion = trigger1.getClass().getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = requireVersion.value(); + + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register trigger {}, requires version {}, server running on {}", trigger1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); + continue; + } + } + if (trigger1.getClass().isAnnotationPresent(FallbackNames.class)) { + FallbackNames fallbackName = trigger1.getClass().getAnnotation(FallbackNames.class); + String[] fallbackNames = fallbackName.value(); + + for (String name : fallbackNames) { + fallbackTriggers.put(name, trigger1); + } + } + triggers.put(trigger1.getName(), trigger1); + Bukkit.getPluginManager().registerEvents(trigger1, Challenges.getInstance()); + } + } + + public void registerActions(ChallengeAction... action) { + for (ChallengeAction action1 : action) { + if (action1.getClass().isAnnotationPresent(RequireVersion.class)) { + RequireVersion requireVersion = action1.getClass().getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = requireVersion.value(); + + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register action {}, requires version {}, server running on {}", action1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); + continue; + } + } + if (action1.getClass().isAnnotationPresent(FallbackNames.class)) { + FallbackNames fallbackName = action1.getClass().getAnnotation(FallbackNames.class); + String[] fallbackNames = fallbackName.value(); + + for (String name : fallbackNames) { + fallbackActions.put(name, action1); + } + } + actions.put(action1.getName(), action1); + } + } + + @Nullable + public ChallengeAction getActionByName(String name) { + return actions.getOrDefault(name, fallbackActions.get(name)); + } + + @Nullable + public ChallengeTrigger getTriggerByName(String name) { + return triggers.getOrDefault(name, fallbackTriggers.get(name)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java index 31e878e7b..dc64e015f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java @@ -6,15 +6,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface FallbackNames { - @Nonnull - String[] value(); + @Nonnull + String[] value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java index 03741e54e..087837cca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java @@ -3,18 +3,14 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import org.bukkit.Material; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeSetting { - SubSettingsBuilder getSubSettingsBuilder(); + SubSettingsBuilder getSubSettingsBuilder(); - String getName(); + String getName(); - Material getMaterial(); + Material getMaterial(); - String getMessage(); + String getMessage(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java index ba2cdcd26..b8c06e97c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java @@ -1,13 +1,9 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public enum SettingType { - CONDITION, - MATERIAL, - ACTION + CONDITION, + MATERIAL, + ACTION } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 10e2cb0f3..d808902a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; @@ -11,41 +11,37 @@ import java.util.LinkedHashMap; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeAction extends ChallengeSetting implements - IChallengeAction { + IChallengeAction { - protected static final IRandom random = IRandom.create(); + protected static final IRandom random = IRandom.create(); - public ChallengeAction(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public ChallengeAction(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public ChallengeAction(String name) { - super(name); - } + public ChallengeAction(String name) { + super(name); + } - public ChallengeAction(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public ChallengeAction(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); - for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); - } + for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { + map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + } - return map; - } + return map; + } - @Override - public final String getMessage() { - return "item-custom-action-" + getMessageSuffix(); - } + @Override + public final String getMessage() { + return "item-custom-action-" + getMessageSuffix(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java index b47bde891..f57c55daf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java @@ -4,23 +4,19 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class EntityTargetAction extends ChallengeAction implements IEntityTargetAction { - public EntityTargetAction(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public EntityTargetAction(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public EntityTargetAction(String name) { - super(name); - } + public EntityTargetAction(String name) { + super(name); + } - public EntityTargetAction(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public EntityTargetAction(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index 7b22dc3ae..22194c0dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -1,18 +1,14 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeAction { - IRandom random = IRandom.create(); + IRandom random = IRandom.create(); - void execute(ChallengeExecutionData executionData, Map subActions); + void execute(ChallengeExecutionData executionData, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java index 02324016d..d03ef8cf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java @@ -15,70 +15,66 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public interface IEntityTargetAction extends IChallengeAction { - static List getTargets(Entity triggerTarget, Map subActions) { - return getTargets(triggerTarget, subActions, SubSettingsHelper.TARGET_ENTITY); - } + static List getTargets(Entity triggerTarget, Map subActions) { + return getTargets(triggerTarget, subActions, SubSettingsHelper.TARGET_ENTITY); + } - static List getTargets(Entity triggerTarget, Map subActions, String key) { - if (!subActions.containsKey(key)) { - return Lists.newLinkedList(); - } - String targetEntity = subActions.get(key)[0]; + static List getTargets(Entity triggerTarget, Map subActions, String key) { + if (!subActions.containsKey(key)) { + return Lists.newLinkedList(); + } + String targetEntity = subActions.get(key)[0]; - switch (targetEntity) { - case "random_player": - List players = ChallengeAPI.getIngamePlayers(); - if (players.isEmpty()) return new LinkedList<>(); - return Collections.singletonList(players.get(random.nextInt(players.size()))); - case "every_player": - return Lists.newLinkedList(ChallengeAPI.getIngamePlayers()); - case "current_player": - return triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList(); - case "every_mob": - List everyList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - everyList.addAll(world.getLivingEntities()); - } - return everyList; - case "every_mob_except_current": - List exceptList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - exceptList.addAll(world.getLivingEntities()); - } - exceptList.remove(triggerTarget); - return exceptList; - case "every_mob_except_players": - List noPlayers = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - noPlayers.add(entity); - } - } + switch (targetEntity) { + case "random_player": + List players = ChallengeAPI.getIngamePlayers(); + if (players.isEmpty()) return new LinkedList<>(); + return Collections.singletonList(players.get(random.nextInt(players.size()))); + case "every_player": + return Lists.newLinkedList(ChallengeAPI.getIngamePlayers()); + case "current_player": + return triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList(); + case "every_mob": + List everyList = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + everyList.addAll(world.getLivingEntities()); + } + return everyList; + case "every_mob_except_current": + List exceptList = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + exceptList.addAll(world.getLivingEntities()); + } + exceptList.remove(triggerTarget); + return exceptList; + case "every_mob_except_players": + List noPlayers = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity.getType() == EntityType.PLAYER) continue; + noPlayers.add(entity); + } + } - return noPlayers; - case "console": - return Collections.singletonList(null); - } - if (triggerTarget == null) { - return Lists.newLinkedList(); - } - return Lists.newArrayList(triggerTarget); - } + return noPlayers; + case "console": + return Collections.singletonList(null); + } + if (triggerTarget == null) { + return Lists.newLinkedList(); + } + return Lists.newArrayList(triggerTarget); + } - @Override - default void execute(ChallengeExecutionData executionData, Map subActions) { - for (Entity target : getTargets(executionData.getEntity(), subActions)) { - executeFor(target, subActions); - } - } + @Override + default void execute(ChallengeExecutionData executionData, Map subActions) { + for (Entity target : getTargets(executionData.getEntity(), subActions)) { + executeFor(target, subActions); + } + } - void executeFor(Entity entity, Map subActions); + void executeFor(Entity entity, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java index 2a7530283..32fb6d6fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java @@ -7,33 +7,29 @@ import java.util.Map; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class PlayerTargetAction extends EntityTargetAction { - public PlayerTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public PlayerTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public PlayerTargetAction(String name) { - super(name); - } + public PlayerTargetAction(String name) { + super(name); + } - public PlayerTargetAction(String name, - Supplier builderSupplier) { - super(name, builderSupplier); - } + public PlayerTargetAction(String name, + Supplier builderSupplier) { + super(name, builderSupplier); + } - @Override - public void executeFor(Entity entity, Map subActions) { - // Entity is null if the target entity is the console - if (entity instanceof Player || entity == null) { - executeForPlayer(((Player) entity), subActions); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + // Entity is null if the target entity is the console + if (entity instanceof Player || entity == null) { + executeForPlayer(((Player) entity), subActions); + } + } - public abstract void executeForPlayer(Player player, Map subActions); + public abstract void executeForPlayer(Player player, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java index bb7029e57..a3d5d0dfc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java @@ -9,28 +9,24 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class AddPermanentEffectAction extends PlayerTargetAction { - PermanentEffectOnDamageChallenge instance = AbstractChallenge - .getFirstInstance(PermanentEffectOnDamageChallenge.class); + PermanentEffectOnDamageChallenge instance = AbstractChallenge + .getFirstInstance(PermanentEffectOnDamageChallenge.class); - public AddPermanentEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public AddPermanentEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.MAGMA_CREAM; - } + @Override + public Material getMaterial() { + return Material.MAGMA_CREAM; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - instance.addRandomEffect(player); - instance.updateEffects(); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + instance.addRandomEffect(player); + instance.updateEffects(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index b9f2ebc25..20915daf0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; @@ -12,41 +12,37 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BoostEntityInAirAction extends EntityTargetAction { - public BoostEntityInAirAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { - builder.addModifierSetting("strength", - new ItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), - 1, 1, 10, - value -> Message.forName("amplifier").asString(), - integer -> "" - ); - })); - } - - @Override - public Material getMaterial() { - return Material.FEATHER; - } - - @Override - public void executeFor(Entity entity, Map subActions) { - - int strength = 1; - try { - strength = Integer.parseInt(subActions.get("strength")[0]); - } catch (NumberFormatException exception) { - Logger.error("", exception); - } - - Vector velocityToAdd = new Vector(0, 1, 0).multiply(strength); - Vector newVelocity = EntityUtils.getSucceedingVelocity(entity.getVelocity()).add(velocityToAdd); - entity.setVelocity(newVelocity); - } + public BoostEntityInAirAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { + builder.addModifierSetting("strength", + new ItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), + 1, 1, 10, + value -> Message.forName("amplifier").asString(), + integer -> "" + ); + })); + } + + @Override + public Material getMaterial() { + return Material.FEATHER; + } + + @Override + public void executeFor(Entity entity, Map subActions) { + + int strength = 1; + try { + strength = Integer.parseInt(subActions.get("strength")[0]); + } catch (NumberFormatException exception) { + Logger.error("", exception); + } + + Vector velocityToAdd = new Vector(0, 1, 0).multiply(strength); + Vector newVelocity = EntityUtils.getSucceedingVelocity(entity.getVelocity()).add(velocityToAdd); + entity.setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 1266600d9..2fb034f66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -6,38 +6,34 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CancelEventAction extends ChallengeAction { - public static boolean inCanceling; - - public CancelEventAction(String name) { - super(name); - } - - public static void onPreTrigger() { - inCanceling = false; - } - - public static boolean shouldCancel() { - if (inCanceling) { - inCanceling = false; - return true; - } - return false; - } - - @Override - public Material getMaterial() { - return Material.BARRIER; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - inCanceling = true; - } + public static boolean inCanceling; + + public CancelEventAction(String name) { + super(name); + } + + public static void onPreTrigger() { + inCanceling = false; + } + + public static boolean shouldCancel() { + if (inCanceling) { + inCanceling = false; + return true; + } + return false; + } + + @Override + public Material getMaterial() { + return Material.BARRIER; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + inCanceling = true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index efc08ba00..bb6e2ecf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; @@ -13,43 +13,39 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class ChangeWorldBorderAction extends ChallengeAction { - public ChangeWorldBorderAction(String name) { - super(name, SubSettingsBuilder.createValueItem() - .addModifierSetting( - "change", - new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), - 1, -10, 10 - )); - } - - @Override - public Material getMaterial() { - return Material.STRUCTURE_VOID; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - - try { - int change = Integer.parseInt(subActions.get("change")[0]); - - for (World world : ChallengeAPI.getGameWorlds()) { - WorldBorder border = world.getWorldBorder(); - if (border.getSize() + change >= 1) { // Don't change if it gets under 1 - border.setSize(border.getSize() + change); - } - } - - } catch (NumberFormatException | IndexOutOfBoundsException ex) { - Logger.error("Error while accessing change border action values", ex); - } - - } + public ChangeWorldBorderAction(String name) { + super(name, SubSettingsBuilder.createValueItem() + .addModifierSetting( + "change", + new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), + 1, -10, 10 + )); + } + + @Override + public Material getMaterial() { + return Material.STRUCTURE_VOID; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + + try { + int change = Integer.parseInt(subActions.get("change")[0]); + + for (World world : ChallengeAPI.getGameWorlds()) { + WorldBorder border = world.getWorldBorder(); + if (border.getSize() + change >= 1) { // Don't change if it gets under 1 + border.setSize(border.getSize() + change); + } + } + + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + Logger.error("Error while accessing change border action values", ex); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java index 2b6fab87c..d5408346f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java @@ -7,24 +7,20 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ClearInventoryAction extends PlayerTargetAction { - public ClearInventoryAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public ClearInventoryAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.TRAPPED_CHEST; - } + @Override + public Material getMaterial() { + return Material.TRAPPED_CHEST; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - player.getInventory().clear(); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + player.getInventory().clear(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index 3638cf70e..290f11e2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -10,35 +10,31 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DamageEntityAction extends EntityTargetAction { - public DamageEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); - } - })); - } + public DamageEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + } + })); + } - @Override - public void executeFor(Entity entity, Map subActions) { - int amount = Integer.parseInt(subActions.get("amount")[0]); - if (entity instanceof LivingEntity) { - ((LivingEntity) entity).setNoDamageTicks(0); - ((LivingEntity) entity).damage(amount); - ((LivingEntity) entity).setNoDamageTicks(0); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + int amount = Integer.parseInt(subActions.get("amount")[0]); + if (entity instanceof LivingEntity) { + ((LivingEntity) entity).setNoDamageTicks(0); + ((LivingEntity) entity).damage(amount); + ((LivingEntity) entity).setNoDamageTicks(0); + } + } - @Override - public Material getMaterial() { - return Material.FERMENTED_SPIDER_EYE; - } + @Override + public Material getMaterial() { + return Material.FERMENTED_SPIDER_EYE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java index 6accab785..c8d0d74b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java @@ -8,24 +8,20 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DropRandomItemAction extends PlayerTargetAction { - public DropRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public DropRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.DISPENSER; - } + @Override + public Material getMaterial() { + return Material.DISPENSER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - RandomItemDroppingChallenge.dropRandomItem(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + RandomItemDroppingChallenge.dropRandomItem(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 0ac2d384b..8a2066b96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -13,52 +13,48 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class ExecuteCommandAction extends PlayerTargetAction { - // Static because cannot be accessed before super has been called - public static int maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); - private static List commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); - - public ExecuteCommandAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { - Message.forName("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); - }, event -> { - String cmd = event.getMessage().split(" ")[0].toLowerCase(); - - if (!commandsThatCanBeExecuted.contains(cmd)) { - Message.forName("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); - return false; - } - - if (event.getMessage().length() > maxCommandLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); - return false; - } - return true; - })); - // Reload from config on reload - maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); - commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - String fullCommand = subActions.get("command")[0]; - - CommandSender sender = Bukkit.getConsoleSender(); - if (player != null) { - fullCommand = "execute as " + player.getName() + " at " + player.getName() + " run " + fullCommand; - } - - Bukkit.getServer().dispatchCommand(sender, fullCommand); - } - - @Override - public Material getMaterial() { - return Material.COMMAND_BLOCK; - } + // Static because cannot be accessed before super has been called + public static int maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); + private static List commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); + + public ExecuteCommandAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { + Message.forName("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); + }, event -> { + String cmd = event.getMessage().split(" ")[0].toLowerCase(); + + if (!commandsThatCanBeExecuted.contains(cmd)) { + Message.forName("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); + return false; + } + + if (event.getMessage().length() > maxCommandLength) { + Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); + return false; + } + return true; + })); + // Reload from config on reload + maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); + commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + String fullCommand = subActions.get("command")[0]; + + CommandSender sender = Bukkit.getConsoleSender(); + if (player != null) { + fullCommand = "execute as " + player.getName() + " at " + player.getName() + " run " + fullCommand; + } + + Bukkit.getServer().dispatchCommand(sender, fullCommand); + } + + @Override + public Material getMaterial() { + return Material.COMMAND_BLOCK; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java index 2a513836d..4123e255f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java @@ -10,33 +10,29 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class FreezeAction extends EntityTargetAction { - FreezeChallenge instance = AbstractChallenge - .getFirstInstance(FreezeChallenge.class); + FreezeChallenge instance = AbstractChallenge + .getFirstInstance(FreezeChallenge.class); - public FreezeAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); - } + public FreezeAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); + } - @Override - public Material getMaterial() { - return Material.ICE; - } + @Override + public Material getMaterial() { + return Material.ICE; + } - @Override - public void executeFor(Entity entity, Map subActions) { + @Override + public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - instance.setFreeze(livingEntity, 2); - } + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + instance.setFreeze(livingEntity, 2); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 6e0f923d3..76de8e406 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,50 +2,47 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HealEntityAction extends EntityTargetAction { - public HealEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder( - MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); - } - })); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - int amount = Integer.parseInt(subActions.get("amount")[0]); - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute = livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return; - double newHealth = Math.min(livingEntity.getHealth() + amount, - attribute.getBaseValue()); - livingEntity.setHealth(newHealth); - } - } - - @Override - public Material getMaterial() { - return Material.GOLDEN_APPLE; - } + public HealEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder( + MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + } + })); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + int amount = Integer.parseInt(subActions.get("amount")[0]); + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + AttributeInstance attribute = livingEntity.getAttribute(AttributeWrapper.MAX_HEALTH); + + if (attribute == null) return; + double newHealth = Math.min(livingEntity.getHealth() + amount, + attribute.getBaseValue()); + livingEntity.setHealth(newHealth); + } + } + + @Override + public Material getMaterial() { + return Material.GOLDEN_APPLE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index 791a0aafd..3458c69f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -9,34 +9,30 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HungerPlayerAction extends PlayerTargetAction { - public HungerPlayerAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) - .createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); - } - - })); - } - - @Override - public Material getMaterial() { - return Material.ROTTEN_FLESH; - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - int newFoodLevel = player.getFoodLevel() - Integer.parseInt(subActions.get("amount")[0]); - player.setFoodLevel(Math.max(newFoodLevel, 0)); - } + public HungerPlayerAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) + .createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); + } + + })); + } + + @Override + public Material getMaterial() { + return Material.ROTTEN_FLESH; + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + int newFoodLevel = player.getFoodLevel() - Integer.parseInt(subActions.get("amount")[0]); + player.setFoodLevel(Math.max(newFoodLevel, 0)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java index 96d8ad6d4..38ed19e6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java @@ -8,25 +8,21 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class InvertHealthAction extends PlayerTargetAction { - public InvertHealthAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public InvertHealthAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.REDSTONE; - } + @Override + public Material getMaterial() { + return Material.REDSTONE; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - InvertHealthChallenge.invertHealth(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + InvertHealthChallenge.invertHealth(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java index 612798911..a2d6f33fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java @@ -8,26 +8,22 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class JumpAndRunAction extends ChallengeAction { - public JumpAndRunAction(String name) { - super(name); - } + public JumpAndRunAction(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ACACIA_STAIRS; - } + @Override + public Material getMaterial() { + return Material.ACACIA_STAIRS; + } - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge(); - } + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java index 6e34ac4e3..74b1ad670 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java @@ -10,28 +10,24 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class KillEntityAction extends EntityTargetAction { - public KillEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); - } + public KillEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof Player) { - ChallengeHelper.kill(((Player) entity)); - } else if (entity instanceof LivingEntity) { - ((LivingEntity) entity).damage(((LivingEntity) entity).getHealth()); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof Player) { + ChallengeHelper.kill(((Player) entity)); + } else if (entity instanceof LivingEntity) { + ((LivingEntity) entity).damage(((LivingEntity) entity).getHealth()); + } + } - @Override - public Material getMaterial() { - return Material.DIAMOND_SWORD; - } + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 7075c9e34..829701896 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -13,45 +13,41 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ModifyMaxHealthAction extends PlayerTargetAction { - public ModifyMaxHealthAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) - .createValueChild().fill(builder -> { - builder.addModifierSetting("health_offset", - new ItemBuilder(MinecraftNameWrapper.RED_DYE, - Message.forName("item-custom-action-max_health-offset")), - 0, -20, 20, - integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); - })); - } - - @Override - public Material getMaterial() { - return MinecraftNameWrapper.RED_DYE; - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - int healthOffset = Integer.parseInt(subActions.get("health_offset")[0]); - MaxHealthSetting instance = AbstractChallenge.getFirstInstance(MaxHealthSetting.class); - - int oldMaxHealth = instance.getMaxHealth(player); - if (oldMaxHealth <= 0) { - ChallengeHelper.kill(player); - return; - } - - instance.addHealth(player, healthOffset); - - int newMaxHealth = instance.getMaxHealth(player); - if (newMaxHealth <= 0) { - ChallengeHelper.kill(player); - } - } + public ModifyMaxHealthAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) + .createValueChild().fill(builder -> { + builder.addModifierSetting("health_offset", + new ItemBuilder(MinecraftNameWrapper.RED_DYE, + Message.forName("item-custom-action-max_health-offset")), + 0, -20, 20, + integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); + })); + } + + @Override + public Material getMaterial() { + return MinecraftNameWrapper.RED_DYE; + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + int healthOffset = Integer.parseInt(subActions.get("health_offset")[0]); + MaxHealthSetting instance = AbstractChallenge.getFirstInstance(MaxHealthSetting.class); + + int oldMaxHealth = instance.getMaxHealth(player); + if (oldMaxHealth <= 0) { + ChallengeHelper.kill(player); + return; + } + + instance.addHealth(player, healthOffset); + + int newMaxHealth = instance.getMaxHealth(player); + if (newMaxHealth <= 0) { + ChallengeHelper.kill(player); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index 02414dcf5..f370a9651 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; @@ -15,79 +15,75 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.2 - */ @RequireVersion(MinecraftVersion.V1_19) @FallbackNames({"place_random_structure"}) public class PlaceStructureAction extends EntityTargetAction { - private List structureKeys; - private List villageKeys; + private List structureKeys; + private List villageKeys; - public PlaceStructureAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); - } - - @Override - public Material getMaterial() { - return Material.STRUCTURE_BLOCK; - } + public PlaceStructureAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); + } - @Override - public void executeFor(Entity entity, Map subActions) { - String structureString = subActions.get(SubSettingsHelper.STRUCTURE)[0]; + @Override + public Material getMaterial() { + return Material.STRUCTURE_BLOCK; + } - NamespacedKey structureKey; + @Override + public void executeFor(Entity entity, Map subActions) { + String structureString = subActions.get(SubSettingsHelper.STRUCTURE)[0]; - if (structureString.equals("random_structure")) { - if (structureKeys == null) { - reloadStructureKeys(); - } + NamespacedKey structureKey; - structureKey = structureKeys.get(IRandom.singleton().nextInt(structureKeys.size())); - if (structureKey == StructureType.VILLAGE.getKey()) { - structureKey = villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); - } - } else { - StructureType structureType = StructureType.getStructureTypes().get(structureString); - structureKey = getStructureKey(structureType); - } + if (structureString.equals("random_structure")) { + if (structureKeys == null) { + reloadStructureKeys(); + } - - Location location = entity.getLocation(); - String locationString = (int) location.getX() + " " + (int) location.getY() + " " + (int) location.getZ(); - String command = String.format("minecraft:place structure %s %s", structureKey, locationString); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + structureKey = structureKeys.get(IRandom.singleton().nextInt(structureKeys.size())); + if (structureKey == StructureType.VILLAGE.getKey()) { + structureKey = villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); + } + } else { + StructureType structureType = StructureType.getStructureTypes().get(structureString); + structureKey = getStructureKey(structureType); } - private void reloadStructureKeys() { - structureKeys = StructureType.getStructureTypes().values().stream() - .map(StructureType::getKey) - .collect(Collectors.toList()); - - structureKeys.remove(StructureType.OCEAN_RUIN.getKey()); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_cold")); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_warm")); - - villageKeys = new ArrayList<>(); - villageKeys.add(NamespacedKey.minecraft("village_desert")); - villageKeys.add(NamespacedKey.minecraft("village_plains")); - villageKeys.add(NamespacedKey.minecraft("village_savanna")); - villageKeys.add(NamespacedKey.minecraft("village_snowy")); - villageKeys.add(NamespacedKey.minecraft("village_taiga")); - } - private NamespacedKey getStructureKey(StructureType structureType) { - if (structureType == StructureType.OCEAN_RUIN) { - List oceanRuins = Arrays.asList(NamespacedKey.minecraft("ocean_ruin_cold"), NamespacedKey.minecraft("ocean_ruin_warm")); - return oceanRuins.get(IRandom.singleton().nextInt(oceanRuins.size())); - } - if (structureType == StructureType.VILLAGE) { - return villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); - } - return structureType.getKey(); + Location location = entity.getLocation(); + String locationString = (int) location.getX() + " " + (int) location.getY() + " " + (int) location.getZ(); + String command = String.format("minecraft:place structure %s %s", structureKey, locationString); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + + private void reloadStructureKeys() { + structureKeys = StructureType.getStructureTypes().values().stream() + .map(StructureType::getKey) + .collect(Collectors.toList()); + + structureKeys.remove(StructureType.OCEAN_RUIN.getKey()); + structureKeys.add(NamespacedKey.minecraft("ocean_ruin_cold")); + structureKeys.add(NamespacedKey.minecraft("ocean_ruin_warm")); + + villageKeys = new ArrayList<>(); + villageKeys.add(NamespacedKey.minecraft("village_desert")); + villageKeys.add(NamespacedKey.minecraft("village_plains")); + villageKeys.add(NamespacedKey.minecraft("village_savanna")); + villageKeys.add(NamespacedKey.minecraft("village_snowy")); + villageKeys.add(NamespacedKey.minecraft("village_taiga")); + } + + private NamespacedKey getStructureKey(StructureType structureType) { + if (structureType == StructureType.OCEAN_RUIN) { + List oceanRuins = Arrays.asList(NamespacedKey.minecraft("ocean_ruin_cold"), NamespacedKey.minecraft("ocean_ruin_warm")); + return oceanRuins.get(IRandom.singleton().nextInt(oceanRuins.size())); + } + if (structureType == StructureType.VILLAGE) { + return villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); } + return structureType.getKey(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index ece861d40..bd618a663 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -11,39 +11,35 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PotionEffectAction extends EntityTargetAction { - public PotionEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( - SubSettingsHelper.createPotionSettingsBuilder(true, true))); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - try { - - PotionEffectType effectType = PotionEffectType.getByName(subActions.get("potion_type")[0]); - if (effectType == null) return; - PotionEffect effect = effectType.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, - Integer.parseInt(subActions.get("amplifier")[0])); - - livingEntity.addPotionEffect(effect); - } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Error while adding potion effect to player"); - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - @Override - public Material getMaterial() { - return Material.POTION; - } + public PotionEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( + SubSettingsHelper.createPotionSettingsBuilder(true, true))); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + try { + + PotionEffectType effectType = PotionEffectType.getByName(subActions.get("potion_type")[0]); + if (effectType == null) return; + PotionEffect effect = effectType.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, + Integer.parseInt(subActions.get("amplifier")[0])); + + livingEntity.addPotionEffect(effect); + } catch (Exception exception) { + Challenges.getInstance().getILogger().severe("Error while adding potion effect to player"); + Challenges.getInstance().getILogger().error("", exception); + } + } + } + + @Override + public Material getMaterial() { + return Material.POTION; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java index d5a8b45fa..0755dda5e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java @@ -8,24 +8,20 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class RandomHotBarAction extends PlayerTargetAction { - public RandomHotBarAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true)); - } + public RandomHotBarAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.ARMOR_STAND; - } + @Override + public Material getMaterial() { + return Material.ARMOR_STAND; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - HotBarRandomizerChallenge.addItems(player, true); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + HotBarRandomizerChallenge.addItems(player, true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index de465769b..17b682f2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -12,37 +12,33 @@ import javax.annotation.Nonnull; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomItemAction extends ChallengeAction { - public RandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } - - public static void giveRandomItemToPlayer(@Nonnull Player player) { - InventoryUtils.giveItem(player.getInventory(), - player.getLocation(), InventoryUtils.getRandomItem(true, false)); - } - - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - - for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { - if (target instanceof Player) { - Player player = (Player) target; - giveRandomItemToPlayer(player); - } - } - } - - @Override - public Material getMaterial() { - return Material.BEACON; - } + public RandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } + + public static void giveRandomItemToPlayer(@Nonnull Player player) { + InventoryUtils.giveItem(player.getInventory(), + player.getLocation(), InventoryUtils.getRandomItem(true, false)); + } + + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + + for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { + if (target instanceof Player) { + Player player = (Player) target; + giveRandomItemToPlayer(player); + } + } + } + + @Override + public Material getMaterial() { + return Material.BEACON; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java index 803a4125b..181089413 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java @@ -14,39 +14,35 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomMobAction extends EntityTargetAction { - @Getter - private static final EntityType[] spawnableMobs; - @Getter - private static final EntityType[] livingMobs; - - static { - List list = new LinkedList<>(Arrays.asList(EntityType.values())); - list = list.stream().filter(EntityType::isSpawnable).collect(Collectors.toList()); - spawnableMobs = list.toArray(new EntityType[0]); - list = list.stream().filter(EntityType::isAlive).collect(Collectors.toList()); - livingMobs = list.toArray(new EntityType[0]); - } - - public RandomMobAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity.getLocation().getWorld() == null) return; - EntityType value = ChallengeAction.random.choose(spawnableMobs); - entity.getLocation().getWorld().spawnEntity(entity.getLocation(), value); - } - - @Override - public Material getMaterial() { - return Material.BLAZE_SPAWN_EGG; - } + @Getter + private static final EntityType[] spawnableMobs; + @Getter + private static final EntityType[] livingMobs; + + static { + List list = new LinkedList<>(Arrays.asList(EntityType.values())); + list = list.stream().filter(EntityType::isSpawnable).collect(Collectors.toList()); + spawnableMobs = list.toArray(new EntityType[0]); + list = list.stream().filter(EntityType::isAlive).collect(Collectors.toList()); + livingMobs = list.toArray(new EntityType[0]); + } + + public RandomMobAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity.getLocation().getWorld() == null) return; + EntityType value = ChallengeAction.random.choose(spawnableMobs); + entity.getLocation().getWorld().spawnEntity(entity.getLocation(), value); + } + + @Override + public Material getMaterial() { + return Material.BLAZE_SPAWN_EGG; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java index c9569eaec..1cefa0e5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java @@ -11,35 +11,31 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomPotionEffectAction extends EntityTargetAction { - public RandomPotionEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( - SubSettingsHelper.createPotionSettingsBuilder(false, true))); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - PotionEffectType randomEffect = RandomPotionEffectChallenge - .getNewRandomEffect(livingEntity); - - if (randomEffect == null) return; - PotionEffect effect = randomEffect.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, - Integer.parseInt(subActions.get("amplifier")[0])); - - livingEntity.addPotionEffect(effect); - } - } - - @Override - public Material getMaterial() { - return Material.BREWING_STAND; - } + public RandomPotionEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( + SubSettingsHelper.createPotionSettingsBuilder(false, true))); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + PotionEffectType randomEffect = RandomPotionEffectChallenge + .getNewRandomEffect(livingEntity); + + if (randomEffect == null) return; + PotionEffect effect = randomEffect.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, + Integer.parseInt(subActions.get("amplifier")[0])); + + livingEntity.addPotionEffect(effect); + } + } + + @Override + public Material getMaterial() { + return Material.BREWING_STAND; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java index b64f82cd5..a1fa56280 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java @@ -8,24 +8,20 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RemoveRandomItemAction extends PlayerTargetAction { - public RemoveRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public RemoveRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.DROPPER; - } + @Override + public Material getMaterial() { + return Material.DROPPER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - InventoryUtils.removeRandomItem(player.getInventory()); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + InventoryUtils.removeRandomItem(player.getInventory()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index 9b4e274dc..f51cddf9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; @@ -10,41 +10,37 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class SpawnEntityAction extends EntityTargetAction { - public SpawnEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false).addChild(SubSettingsHelper.createEntityTypeSettingsBuilder(false, false))); - } + public SpawnEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false).addChild(SubSettingsHelper.createEntityTypeSettingsBuilder(false, false))); + } - @Override - public Material getMaterial() { - return Material.ZOMBIE_SPAWN_EGG; - } + @Override + public Material getMaterial() { + return Material.ZOMBIE_SPAWN_EGG; + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity.getLocation().getWorld() == null) return; + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity.getLocation().getWorld() == null) return; - String[] args = subActions.get(SubSettingsHelper.ENTITY_TYPE); + String[] args = subActions.get(SubSettingsHelper.ENTITY_TYPE); - for (String arg : args) { + for (String arg : args) { - try { - EntityType type = EntityType.valueOf(arg); - World world = entity.getLocation().getWorld(); - world.spawnEntity(entity.getLocation(), type); + try { + EntityType type = EntityType.valueOf(arg); + World world = entity.getLocation().getWorld(); + world.spawnEntity(entity.getLocation(), type); - } catch (Exception exception) { - Logger.error("", exception); - } + } catch (Exception exception) { + Logger.error("", exception); + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java index aa1108649..c71c793b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java @@ -8,24 +8,20 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SwapRandomItemAction extends PlayerTargetAction { - public SwapRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public SwapRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.HOPPER; - } + @Override + public Material getMaterial() { + return Material.HOPPER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - RandomItemSwappingChallenge.swapRandomItems(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + RandomItemSwappingChallenge.swapRandomItems(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index d1ced3607..1c967aab1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; @@ -16,44 +16,40 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SwapRandomMobAction extends ChallengeAction { - public SwapRandomMobAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true) - .addChild(SubSettingsHelper.createEntityTargetSettingsBuilder(true).setKey("swap_targets"))); - } - - @Override - public Material getMaterial() { - return Material.ENDER_PEARL; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - - List targets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions); - List swapTargets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"); - swapTargets.removeIf(entity -> !(entity instanceof LivingEntity)); - long seed = random.nextLong(); - Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); - Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); - for (World world : ChallengeAPI.getGameWorlds()) { - for (Entity target : targets) { - if (swapTargets.isEmpty()) break; - if (!(target instanceof LivingEntity)) continue; - if (target.getWorld() == world) { - int i = targets.indexOf(target); - int targetIndex = i + 1; - if (targetIndex >= swapTargets.size()) targetIndex = 0; - LivingEntity teleportTarget = (LivingEntity) swapTargets.remove(targetIndex); - RandomTeleportOnHitChallenge.switchEntityLocations(teleportTarget, (LivingEntity) target); - } - } - } - - } + public SwapRandomMobAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true) + .addChild(SubSettingsHelper.createEntityTargetSettingsBuilder(true).setKey("swap_targets"))); + } + + @Override + public Material getMaterial() { + return Material.ENDER_PEARL; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + + List targets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions); + List swapTargets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"); + swapTargets.removeIf(entity -> !(entity instanceof LivingEntity)); + long seed = random.nextLong(); + Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); + Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); + for (World world : ChallengeAPI.getGameWorlds()) { + for (Entity target : targets) { + if (swapTargets.isEmpty()) break; + if (!(target instanceof LivingEntity)) continue; + if (target.getWorld() == world) { + int i = targets.indexOf(target); + int targetIndex = i + 1; + if (targetIndex >= swapTargets.size()) targetIndex = 0; + LivingEntity teleportTarget = (LivingEntity) swapTargets.remove(targetIndex); + RandomTeleportOnHitChallenge.switchEntityLocations(teleportTarget, (LivingEntity) target); + } + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java index 389740395..3bd858bae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java @@ -9,27 +9,23 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class UncraftInventoryAction extends EntityTargetAction { - public UncraftInventoryAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); - } + public UncraftInventoryAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof Player) { - Player player = (Player) entity; - UncraftItemsChallenge.uncraftInventory(player); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof Player) { + Player player = (Player) entity; + UncraftItemsChallenge.uncraftInventory(player); + } + } - @Override - public Material getMaterial() { - return Material.CRAFTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.CRAFTING_TABLE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java index 77e938477..d7348fcfb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java @@ -8,26 +8,22 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class WaterMLGAction extends ChallengeAction { - public WaterMLGAction(String name) { - super(name); - } + public WaterMLGAction(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.WATER_BUCKET; - } + @Override + public Material getMaterial() { + return Material.WATER_BUCKET; + } - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge(); - } + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java index bb81ba045..8a064c9ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java @@ -12,33 +12,29 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class WinChallengeAction extends PlayerTargetAction { - private final List winner = Lists.newLinkedList(); + private final List winner = Lists.newLinkedList(); - public WinChallengeAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public WinChallengeAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.GOLDEN_HELMET; - } + @Override + public Material getMaterial() { + return Material.GOLDEN_HELMET; + } - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - super.execute(executionData, subActions); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); - winner.clear(); - } + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + super.execute(executionData, subActions); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); + winner.clear(); + } - @Override - public void executeForPlayer(Player player, Map subActions) { - winner.add(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + winner.add(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 57e40c03b..76dbdf823 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; -import net.anweisen.utilities.common.misc.StringUtils; +import lombok.Getter; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.impl.MessageManager; @@ -15,148 +16,133 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ +@Getter public abstract class SubSettingsBuilder { - private String key; - private SubSettingsBuilder parent; - private SubSettingsBuilder child; - - protected SubSettingsBuilder(String key) { - this.key = key; - parent = null; - } - - protected SubSettingsBuilder(String key, SubSettingsBuilder parent) { - this.key = key; - this.parent = parent; - } - - public static ChooseItemSubSettingsBuilder createChooseItem(String key) { - return new ChooseItemSubSettingsBuilder(key); - } - - public static ValueSubSettingsBuilder createValueItem() { - return new ValueSubSettingsBuilder(); - } - - public static ChooseMultipleItemSubSettingBuilder createChooseMultipleItem(String key) { - return new ChooseMultipleItemSubSettingBuilder(key); - } - - public static TextInputSubSettingsBuilder createTextInput(String key, - Consumer onOpen, - Predicate isValid) { - return new TextInputSubSettingsBuilder(key, onOpen, isValid); - } - - public static EmptySubSettingsBuilder createEmpty() { - return new EmptySubSettingsBuilder(); - } - - public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, String title); - - public abstract List getDisplay(Map activated); - - public abstract boolean hasSettings(); - - public SubSettingsBuilder getParent() { - return parent; - } - - public SubSettingsBuilder setParent(SubSettingsBuilder parent) { - - SubSettingsBuilder parentBuilder = getParent(); - if (parentBuilder != null) { - return parentBuilder.setParent(parent); - } else { - this.parent = parent; - return this; - } - - } - - public SubSettingsBuilder getChild() { - return child; - } - - public String getKey() { - return key; - } - - public SubSettingsBuilder setKey(String key) { - this.key = key; - return this; - } - - public String getKeyTranslation() { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); - } - - public List getAllChildren() { - LinkedList children = new LinkedList<>(Collections.singleton(this)); - - SubSettingsBuilder last = this; - - while (last != null) { - if (last.getChild() != null) { - children.add(last.getChild()); - } - last = last.getChild(); - } - - return children; - } - - /** - * @return the first parent that was created. - * Only required if first builder has one ore more children. - */ - public SubSettingsBuilder build() { - return parent == null ? this : parent.build(); - } - - /** - * Sets the highest parent of a child as the child of this builder. - * - * @param child one of the child builders that are added. - * @return the highest parent of that child - */ - public SubSettingsBuilder addChild(SubSettingsBuilder child) { - this.child = child.setParent(this); - return child; - } - - public ChooseItemSubSettingsBuilder createChooseItemChild(String key) { - ChooseItemSubSettingsBuilder builder = new ChooseItemSubSettingsBuilder(key, this); - this.child = builder; - return builder; - } - - public ValueSubSettingsBuilder createValueChild() { - ValueSubSettingsBuilder builder = new ValueSubSettingsBuilder(this); - this.child = builder; - return builder; - } - - public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) { - ChooseMultipleItemSubSettingBuilder builder = new ChooseMultipleItemSubSettingBuilder(key, this); - this.child = builder; - return builder; - } - - public TextInputSubSettingsBuilder createTextInputChild(String key, - Consumer onOpen, - Predicate isValid) { - TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, - this, onOpen, isValid); - this.child = builder; - return builder; - } + private String key; + private SubSettingsBuilder parent; + private SubSettingsBuilder child; + + protected SubSettingsBuilder(String key) { + this.key = key; + parent = null; + } + + protected SubSettingsBuilder(String key, SubSettingsBuilder parent) { + this.key = key; + this.parent = parent; + } + + public static ChooseItemSubSettingsBuilder createChooseItem(String key) { + return new ChooseItemSubSettingsBuilder(key); + } + + public static ValueSubSettingsBuilder createValueItem() { + return new ValueSubSettingsBuilder(); + } + + public static ChooseMultipleItemSubSettingBuilder createChooseMultipleItem(String key) { + return new ChooseMultipleItemSubSettingBuilder(key); + } + + public static TextInputSubSettingsBuilder createTextInput(String key, + Consumer onOpen, + Predicate isValid) { + return new TextInputSubSettingsBuilder(key, onOpen, isValid); + } + + public static EmptySubSettingsBuilder createEmpty() { + return new EmptySubSettingsBuilder(); + } + + public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, String title); + + public abstract List getDisplay(Map activated); + + public abstract boolean hasSettings(); + + public SubSettingsBuilder setParent(SubSettingsBuilder parent) { + + SubSettingsBuilder parentBuilder = getParent(); + if (parentBuilder != null) { + return parentBuilder.setParent(parent); + } else { + this.parent = parent; + return this; + } + + } + + public SubSettingsBuilder setKey(String key) { + this.key = key; + return this; + } + + public String getKeyTranslation() { + String messageName = "custom-subsetting-" + key; + return MessageManager.hasMessageInCache(messageName) + ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); + } + + public List getAllChildren() { + LinkedList children = new LinkedList<>(Collections.singleton(this)); + + SubSettingsBuilder last = this; + + while (last != null) { + if (last.getChild() != null) { + children.add(last.getChild()); + } + last = last.getChild(); + } + + return children; + } + + /** + * @return the first parent that was created. + * Only required if first builder has one ore more children. + */ + public SubSettingsBuilder build() { + return parent == null ? this : parent.build(); + } + + /** + * Sets the highest parent of a child as the child of this builder. + * + * @param child one of the child builders that are added. + * @return the highest parent of that child + */ + public SubSettingsBuilder addChild(SubSettingsBuilder child) { + this.child = child.setParent(this); + return child; + } + + public ChooseItemSubSettingsBuilder createChooseItemChild(String key) { + ChooseItemSubSettingsBuilder builder = new ChooseItemSubSettingsBuilder(key, this); + this.child = builder; + return builder; + } + + public ValueSubSettingsBuilder createValueChild() { + ValueSubSettingsBuilder builder = new ValueSubSettingsBuilder(this); + this.child = builder; + return builder; + } + + public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) { + ChooseMultipleItemSubSettingBuilder builder = new ChooseMultipleItemSubSettingBuilder(key, this); + this.child = builder; + return builder; + } + + public TextInputSubSettingsBuilder createTextInputChild(String key, + Consumer onOpen, + Predicate isValid) { + TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, + this, onOpen, isValid); + this.child = builder; + return builder; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 0cda0cae3..2ba7ab835 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,34 +1,30 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ValueSetting { - @Getter - private final String key; - private final ItemBuilder itemBuilder; + @Getter + private final String key; + private final ItemBuilder itemBuilder; - public ValueSetting(String key, ItemBuilder itemBuilder) { - this.key = key; - this.itemBuilder = itemBuilder; - } + public ValueSetting(String key, ItemBuilder itemBuilder) { + this.key = key; + this.itemBuilder = itemBuilder; + } - public ItemBuilder createDisplayItem() { - return itemBuilder; - } + public ItemBuilder createDisplayItem() { + return itemBuilder; + } - public abstract String onClick(MenuClickInfo info, String value, int slotIndex); + public abstract String onClick(MenuClickInfo info, String value, int slotIndex); - public ItemBuilder getDisplayItem(String value) { - return createDisplayItem().hideAttributes(); - } + public ItemBuilder getDisplayItem(String value) { + return createDisplayItem().hideAttributes(); + } - public abstract ItemBuilder getSettingsItem(String value); + public abstract ItemBuilder getSettingsItem(String value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 677844ee0..3ddf864c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -16,64 +16,60 @@ import java.util.Map.Entry; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ChooseItemSubSettingsBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); + protected final LinkedHashMap settings = new LinkedHashMap<>(); - public ChooseItemSubSettingsBuilder(String key) { - super(key); - } + public ChooseItemSubSettingsBuilder(String key) { + super(key); + } - public ChooseItemSubSettingsBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } + public ChooseItemSubSettingsBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); - } + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); + } - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (itemStack.getItemMeta() == null) continue; - display.add("§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName()); - } - } - } - } + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + for (String value : entry.getValue()) { + ItemStack itemStack = getSettings().get(value); + if (itemStack != null) { + if (itemStack.getItemMeta() == null) continue; + display.add("§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName()); + } + } + } + } - return display; - } + return display; + } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); - return this; - } + public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { + settings.put(key, value); + return this; + } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemBuilder value) { - settings.put(key, value.hideAttributes().build()); - return this; - } + public ChooseItemSubSettingsBuilder addSetting(String key, ItemBuilder value) { + settings.put(key, value.hideAttributes().build()); + return this; + } - public ChooseItemSubSettingsBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } + public ChooseItemSubSettingsBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } - public boolean hasSettings() { - return !settings.isEmpty(); - } + public boolean hasSettings() { + return !settings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index ea78e50f7..83ef09deb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -18,81 +18,77 @@ import java.util.Map.Entry; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ChooseMultipleItemSubSettingBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); - - public ChooseMultipleItemSubSettingBuilder(String key) { - super(key); - } - - public ChooseMultipleItemSubSettingBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } - - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); - } - - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - - int count = 0; - String firstDisplay = null; - - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (firstDisplay == null) { - if (itemStack.getItemMeta() == null) continue; - firstDisplay = "§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName(); - } else { - count++; - } - - } - } - - if (firstDisplay != null) { - String suffix = count == 0 ? "" : " §7+" + count; - display.add(firstDisplay + suffix); - } else { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + Message.forName("none").asString()); - } - - } - } - - return display; - } - - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); - return this; - } - - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemBuilder value) { - settings.put(key, value.hideAttributes().build()); - return this; - } - - public ChooseMultipleItemSubSettingBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } - - public boolean hasSettings() { - return !settings.isEmpty(); - } + protected final LinkedHashMap settings = new LinkedHashMap<>(); + + public ChooseMultipleItemSubSettingBuilder(String key) { + super(key); + } + + public ChooseMultipleItemSubSettingBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } + + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); + } + + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); + + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + + int count = 0; + String firstDisplay = null; + + for (String value : entry.getValue()) { + ItemStack itemStack = getSettings().get(value); + if (itemStack != null) { + if (firstDisplay == null) { + if (itemStack.getItemMeta() == null) continue; + firstDisplay = "§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName(); + } else { + count++; + } + + } + } + + if (firstDisplay != null) { + String suffix = count == 0 ? "" : " §7+" + count; + display.add(firstDisplay + suffix); + } else { + display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + Message.forName("none").asString()); + } + + } + } + + return display; + } + + public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack value) { + settings.put(key, value); + return this; + } + + public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemBuilder value) { + settings.put(key, value.hideAttributes().build()); + return this; + } + + public ChooseMultipleItemSubSettingBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } + + public boolean hasSettings() { + return !settings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index 460189c54..4cd85ec7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -8,29 +8,25 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EmptySubSettingsBuilder extends SubSettingsBuilder { - public EmptySubSettingsBuilder() { - super("none"); - } + public EmptySubSettingsBuilder() { + super("none"); + } - @Override - public List getDisplay(Map activated) { - return Lists.newLinkedList(); - } + @Override + public List getDisplay(Map activated) { + return Lists.newLinkedList(); + } - @Override - public boolean hasSettings() { - return false; - } + @Override + public boolean hasSettings() { + return false; + } - @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - return false; - } + @Override + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index c8626503b..27b413afc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -6,32 +6,28 @@ import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import org.bukkit.entity.Player; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public abstract class GeneratorSubSettingsBuilder extends SubSettingsBuilder { - public GeneratorSubSettingsBuilder(String key) { - super(key); - } + public GeneratorSubSettingsBuilder(String key) { + super(key); + } - public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } + public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - if (hasSettings()) { - MenuGenerator generator = getGenerator(player, parentGenerator, title + InventoryTitleManager.getTitleSplitter() + getKeyTranslation()); - if (generator == null) return false; - generator.open(player, 0); - return true; - } + if (hasSettings()) { + MenuGenerator generator = getGenerator(player, parentGenerator, title + InventoryTitleManager.getTitleSplitter() + getKeyTranslation()); + if (generator == null) return false; + generator.open(player, 0); + return true; + } - return false; - } + return false; + } - public abstract MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title); + public abstract MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index 85282033a..d9dc98472 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -17,79 +17,75 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class TextInputSubSettingsBuilder extends SubSettingsBuilder { - private final Consumer onOpen; - private final Predicate isValid; - - public TextInputSubSettingsBuilder(String key) { - this(key, null); - } - - public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent) { - this(key, parent, event -> { - }, event -> true); - } - - public TextInputSubSettingsBuilder(String key, - Consumer onOpen, - Predicate isValid) { - super(key); - this.onOpen = onOpen; - this.isValid = isValid; - } - - public TextInputSubSettingsBuilder(String key, - SubSettingsBuilder parent, - Consumer onOpen, - Predicate isValid) { - super(key, parent); - this.onOpen = onOpen; - this.isValid = isValid; - } - - @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - player.closeInventory(); - onOpen.accept(player); - - ChatInputListener.setInputAction(player, event -> { - if (!isValid.test(event)) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.decline(player); - }); - return; - } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.accept(player, null, MapUtils.createStringArrayMap(getKey(), event.getMessage())); - }); - }); - - return true; - } - - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + value); - } - } - } - - return display; - } - - @Override - public boolean hasSettings() { - return true; - } + private final Consumer onOpen; + private final Predicate isValid; + + public TextInputSubSettingsBuilder(String key) { + this(key, null); + } + + public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent) { + this(key, parent, event -> { + }, event -> true); + } + + public TextInputSubSettingsBuilder(String key, + Consumer onOpen, + Predicate isValid) { + super(key); + this.onOpen = onOpen; + this.isValid = isValid; + } + + public TextInputSubSettingsBuilder(String key, + SubSettingsBuilder parent, + Consumer onOpen, + Predicate isValid) { + super(key, parent); + this.onOpen = onOpen; + this.isValid = isValid; + } + + @Override + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + player.closeInventory(); + onOpen.accept(player); + + ChatInputListener.setInputAction(player, event -> { + if (!isValid.test(event)) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.decline(player); + }); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.accept(player, null, MapUtils.createStringArrayMap(getKey(), event.getMessage())); + }); + }); + + return true; + } + + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); + + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + for (String value : entry.getValue()) { + display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + value); + } + } + } + + return display; + } + + @Override + public boolean hasSettings() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index f86fd7cd8..5ed694708 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -2,7 +2,7 @@ import com.google.common.collect.Lists; import lombok.Getter; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; @@ -22,95 +22,91 @@ import java.util.function.Consumer; import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ValueSubSettingsBuilder extends GeneratorSubSettingsBuilder { - private final LinkedHashMap defaultSettings = new LinkedHashMap<>(); + private final LinkedHashMap defaultSettings = new LinkedHashMap<>(); - public ValueSubSettingsBuilder() { - super("value"); - } + public ValueSubSettingsBuilder() { + super("value"); + } - public ValueSubSettingsBuilder(SubSettingsBuilder parent) { - super("value", parent); - } + public ValueSubSettingsBuilder(SubSettingsBuilder parent) { + super("value", parent); + } - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); - } + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); + } - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); - for (Entry entry : activated.entrySet()) { + for (Entry entry : activated.entrySet()) { - for (ValueSetting setting : defaultSettings.keySet()) { + for (ValueSetting setting : defaultSettings.keySet()) { - if (entry.getKey().equals(setting.getKey())) { + if (entry.getKey().equals(setting.getKey())) { - ItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); - if (builder != null) { - display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); + ItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); + if (builder != null) { + display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); - } + } - } + } - } + } - } + } - return display; - } + return display; + } - public String getKeyTranslation(String key) { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); - } + public String getKeyTranslation(String key) { + String messageName = "custom-subsetting-" + key; + return MessageManager.hasMessageInCache(messageName) + ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); + } - public ValueSubSettingsBuilder addBooleanSetting(String key, ItemBuilder displayItem, - boolean defaultValue) { - defaultSettings.put(new BooleanSetting(key, displayItem), - defaultValue ? "enabled" : "disabled"); - return this; - } + public ValueSubSettingsBuilder addBooleanSetting(String key, ItemBuilder displayItem, + boolean defaultValue) { + defaultSettings.put(new BooleanSetting(key, displayItem), + defaultValue ? "enabled" : "disabled"); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max, Function prefixGetter, Function suffixGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max, Function prefixGetter, Function suffixGetter) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max, Function settingsItemGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max, Function settingsItemGetter) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } + public ValueSubSettingsBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } - public boolean hasSettings() { - return !defaultSettings.isEmpty(); - } + public boolean hasSettings() { + return !defaultSettings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index db1fa78e4..48623e544 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -1,30 +1,26 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BooleanSetting extends ValueSetting { - public BooleanSetting(String key, ItemBuilder itemBuilder) { - super(key, itemBuilder); - } + public BooleanSetting(String key, ItemBuilder itemBuilder) { + super(key, itemBuilder); + } - @Override - public String onClick(MenuClickInfo info, String value, - int slotIndex) { - return value.equals("enabled") ? "disabled" : "enabled"; - } + @Override + public String onClick(MenuClickInfo info, String value, + int slotIndex) { + return value.equals("enabled") ? "disabled" : "enabled"; + } - @Override - public ItemBuilder getSettingsItem(String value) { - return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); - } + @Override + public ItemBuilder getSettingsItem(String value) { + return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index b9dcbb68a..93269312d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.type.IModifier; @@ -10,92 +10,88 @@ import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ModifierSetting extends ValueSetting implements IModifier { - private final int min, max; - private final Function settingsItemGetter; - - private int tempValue; - - public ModifierSetting(String key, int min, int max, ItemBuilder displayItem) { - this(key, min, max, displayItem, integer -> "", integer -> ""); - } - - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { - this(key, min, max, itemBuilder, value -> - { - String prefix = prefixGetter.apply(value); - String suffix = suffixGetter.apply(value); - return DefaultItem.value(value, (prefix.isEmpty() ? "" : "§7" + prefix + " ") + "§e") - .appendName(suffix.isEmpty() ? "" : " " + "§7" + suffix); - }); - } - - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function settingsItemGetter) { - super(key, itemBuilder); - this.min = min; - this.max = max; - this.settingsItemGetter = settingsItemGetter; - } - - @Override - public String onClick(MenuClickInfo info, String value, int slotIndex) { - - int intValue = getIntValue(value); - tempValue = intValue; - - ChallengeHelper.handleModifierClick(info, this); - - intValue = tempValue; - tempValue = 0; - return String.valueOf(intValue); - } - - @Override - public int getValue() { - return tempValue; - } - - @Override - public void setValue(int value) { - tempValue = value; - } - - @Override - public int getMinValue() { - return min; - } - - @Override - public int getMaxValue() { - return max; - } - - @Override - public void playValueChangeTitle() { - } - - @Override - public ItemBuilder getSettingsItem(String value) { - int intValue = getIntValue(value); - return settingsItemGetter.apply(intValue); - } - - public int getIntValue(String value) { - - try { - return Integer.parseInt(value); - } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Something went wrong while parsing the " - + "value of subsetting " + getKey() + " with value " + value); - Challenges.getInstance().getLogger().error("", exception); - } - - return 0; - } + private final int min, max; + private final Function settingsItemGetter; + + private int tempValue; + + public ModifierSetting(String key, int min, int max, ItemBuilder displayItem) { + this(key, min, max, displayItem, integer -> "", integer -> ""); + } + + public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { + this(key, min, max, itemBuilder, value -> + { + String prefix = prefixGetter.apply(value); + String suffix = suffixGetter.apply(value); + return DefaultItem.value(value, (prefix.isEmpty() ? "" : "§7" + prefix + " ") + "§e") + .appendName(suffix.isEmpty() ? "" : " " + "§7" + suffix); + }); + } + + public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function settingsItemGetter) { + super(key, itemBuilder); + this.min = min; + this.max = max; + this.settingsItemGetter = settingsItemGetter; + } + + @Override + public String onClick(MenuClickInfo info, String value, int slotIndex) { + + int intValue = getIntValue(value); + tempValue = intValue; + + ChallengeHelper.handleModifierClick(info, this); + + intValue = tempValue; + tempValue = 0; + return String.valueOf(intValue); + } + + @Override + public int getValue() { + return tempValue; + } + + @Override + public void setValue(int value) { + tempValue = value; + } + + @Override + public int getMinValue() { + return min; + } + + @Override + public int getMaxValue() { + return max; + } + + @Override + public void playValueChangeTitle() { + } + + @Override + public ItemBuilder getSettingsItem(String value) { + int intValue = getIntValue(value); + return settingsItemGetter.apply(intValue); + } + + public int getIntValue(String value) { + + try { + return Integer.parseInt(value); + } catch (Exception exception) { + Challenges.getInstance().getILogger().severe("Something went wrong while parsing the " + + "value of subsetting " + getKey() + " with value " + value); + Challenges.getInstance().getILogger().error("", exception); + } + + return 0; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index cec2dd627..26888233f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -10,39 +10,35 @@ import java.util.LinkedHashMap; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeTrigger extends ChallengeSetting implements - IChallengeTrigger { + IChallengeTrigger { - public ChallengeTrigger(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public ChallengeTrigger(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public ChallengeTrigger(String name) { - super(name); - } + public ChallengeTrigger(String name) { + super(name); + } - public ChallengeTrigger(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public ChallengeTrigger(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); - for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); - } + for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { + map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + } - return map; - } + return map; + } - @Override - public final String getMessage() { - return "item-custom-trigger-" + getMessageSuffix(); - } + @Override + public final String getMessage() { + return "item-custom-trigger-" + getMessageSuffix(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java index 221be45d7..f31a8fbb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java @@ -3,14 +3,10 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import org.bukkit.event.Listener; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeTrigger extends Listener { - default ChallengeExecutionData createData() { - return new ChallengeExecutionData(this); - } + default ChallengeExecutionData createData() { + return new ChallengeExecutionData(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java index 4964ccce3..2fb962d42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java @@ -6,25 +6,21 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class AdvancementTrigger extends ChallengeTrigger { - public AdvancementTrigger(String name) { - super(name); - } + public AdvancementTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.KNOWLEDGE_BOOK; - } + @Override + public Material getMaterial() { + return Material.KNOWLEDGE_BOOK; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerAdvancementDoneEvent event) { - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - createData().entity(event.getPlayer()).execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerAdvancementDoneEvent event) { + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + createData().entity(event.getPlayer()).execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java index 21f259a3a..959e9a8ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java @@ -7,28 +7,24 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BreakBlockTrigger extends ChallengeTrigger { - public BreakBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } + public BreakBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.GOLDEN_PICKAXE; - } + @Override + public Material getMaterial() { + return Material.GOLDEN_PICKAXE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .block(event.getBlock().getType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .block(event.getBlock().getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index b86324d7a..b13f0e5d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -12,34 +12,30 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ConsumeItemTrigger extends ChallengeTrigger { - public ConsumeItemTrigger(String name) { - super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isEdible()) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - })); - } + public ConsumeItemTrigger(String name) { + super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isEdible()) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + })); + } - @Override - public Material getMaterial() { - return Material.COOKED_BEEF; - } + @Override + public Material getMaterial() { + return Material.COOKED_BEEF; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onConsumeItem(PlayerItemConsumeEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .data(SubSettingsHelper.ITEM, SubSettingsHelper.ANY, event.getItem().getType().name()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onConsumeItem(PlayerItemConsumeEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .data(SubSettingsHelper.ITEM, SubSettingsHelper.ANY, event.getItem().getType().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java index add46c5ff..a90c7850a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java @@ -7,29 +7,25 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.CraftItemEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CraftItemTrigger extends ChallengeTrigger { - public CraftItemTrigger(String name) { - super(name); - } + public CraftItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.CRAFTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.CRAFTING_TABLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCraft(CraftItemEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - createData() - .entity(player) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCraft(CraftItemEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + createData() + .entity(player) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java index 26d80deaa..3a87e15ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java @@ -6,27 +6,23 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerDropItemEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DropItemTrigger extends ChallengeTrigger { - public DropItemTrigger(String name) { - super(name); - } + public DropItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.DROPPER; - } + @Override + public Material getMaterial() { + return Material.DROPPER; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onItemDrop(PlayerDropItemEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onItemDrop(PlayerDropItemEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java index 953a7e21e..37f1ccab3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java @@ -9,30 +9,26 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDamageByPlayerTrigger extends ChallengeTrigger { - public EntityDamageByPlayerTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); - } + public EntityDamageByPlayerTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.WOODEN_SWORD; - } + @Override + public Material getMaterial() { + return Material.WOODEN_SWORD; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageByPlayerEvent event) { + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDamageByPlayerEvent event) { - createData() - .entity(event.getDamager()) - .event(event) - .entityType(event.getEntityType()) - .execute(); + createData() + .entity(event.getDamager()) + .event(event) + .entityType(event.getEntityType()) + .execute(); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index a17367b28..a0ca61a73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; @@ -17,50 +17,46 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDamageTrigger extends ChallengeTrigger { - public EntityDamageTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true).createChooseMultipleChild("damage_cause").fill(builder -> { - - List types = new ArrayList<>( - Arrays.asList(PotionEffectType.values())); - Collections.shuffle(types, new Random(1)); - - builder.addSetting(SubSettingsHelper.ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); - - DamageCause[] values = DamageCause.values(); - for (int i = 0; i < values.length; i++) { - DamageCause cause = values[i]; - PotionEffectType effectType = types.get(i); - - builder.addSetting(cause.name(), - new PotionBuilder(Material.TIPPED_ARROW, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(cause)) - .color(effectType.getColor()) - .build()); - - } - - })); - } - - @Override - public Material getMaterial() { - return Material.FLINT_AND_STEEL; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageEvent event) { - createData() - .entity(event.getEntity()) - .event(event) - .entityType(event.getEntityType()) - .data("damage_cause", SubSettingsHelper.ANY, event.getCause().name()) - .execute(); - } + public EntityDamageTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true).createChooseMultipleChild("damage_cause").fill(builder -> { + + List types = new ArrayList<>( + Arrays.asList(PotionEffectType.values())); + Collections.shuffle(types, new Random(1)); + + builder.addSetting(SubSettingsHelper.ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); + + DamageCause[] values = DamageCause.values(); + for (int i = 0; i < values.length; i++) { + DamageCause cause = values[i]; + PotionEffectType effectType = types.get(i); + + builder.addSetting(cause.name(), + new PotionBuilder(Material.TIPPED_ARROW, + DefaultItem.getItemPrefix() + StringUtils.getEnumName(cause)) + .color(effectType.getColor()) + .build()); + + } + + })); + } + + @Override + public Material getMaterial() { + return Material.FLINT_AND_STEEL; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDamageEvent event) { + createData() + .entity(event.getEntity()) + .event(event) + .entityType(event.getEntityType()) + .data("damage_cause", SubSettingsHelper.ANY, event.getCause().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java index c5735d0af..7cdb06121 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java @@ -9,27 +9,23 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDeathTrigger extends ChallengeTrigger { - public EntityDeathTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); - } + public EntityDeathTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.BONE; - } + @Override + public Material getMaterial() { + return Material.BONE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { - createData() - .entity(event.getEntity()) - .entityType(event.getEntityType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDeathEvent event) { + createData() + .entity(event.getEntity()) + .entityType(event.getEntityType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java index 442e676e8..dd7421c52 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java @@ -6,29 +6,25 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerExpChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GainXPTrigger extends ChallengeTrigger { - public GainXPTrigger(String name) { - super(name); - } + public GainXPTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.EXPERIENCE_BOTTLE; - } + @Override + public Material getMaterial() { + return Material.EXPERIENCE_BOTTLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onXPGain(PlayerExpChangeEvent event) { - if (event.getAmount() > 0) { - createData() - .entity(event.getPlayer()) - .cancelAction(() -> event.setAmount(0)) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onXPGain(PlayerExpChangeEvent event) { + if (event.getAmount() > 0) { + createData() + .entity(event.getPlayer()) + .cancelAction(() -> event.setAmount(0)) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java index d15859def..31d624648 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java @@ -7,38 +7,34 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class GetItemTrigger extends ChallengeTrigger { - public GetItemTrigger(String name) { - super(name, SubSettingsHelper.createItemSettingsBuilder()); - } + public GetItemTrigger(String name) { + super(name, SubSettingsHelper.createItemSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.HOPPER; - } + @Override + public Material getMaterial() { + return Material.HOPPER; + } - @EventHandler - public void onPickupItem(PlayerPickupItemEvent event) { - createData() - .entity(event.getPlayer()) - .data("item", event.getItem().getItemStack().getType().name()) - .execute(); - } + @EventHandler + public void onPickupItem(PlayerPickupItemEvent event) { + createData() + .entity(event.getPlayer()) + .data("item", event.getItem().getItemStack().getType().name()) + .execute(); + } - @EventHandler - public void onPlayerInventoryClick(PlayerInventoryClickEvent event) { - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - createData() - .entity(event.getPlayer()) - .data("item", event.getCurrentItem().getType().name()) - .execute(); - } + @EventHandler + public void onPlayerInventoryClick(PlayerInventoryClickEvent event) { + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + createData() + .entity(event.getPlayer()) + .data("item", event.getCurrentItem().getType().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java index 05aed6c46..7f04b2497 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java @@ -7,30 +7,26 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.FoodLevelChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HungerTrigger extends ChallengeTrigger { - public HungerTrigger(String name) { - super(name); - } + public HungerTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ROTTEN_FLESH; - } + @Override + public Material getMaterial() { + return Material.ROTTEN_FLESH; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (event.getFoodLevel() < ((Player) event.getEntity()).getFoodLevel()) { - createData() - .entity(event.getEntity()) - .event(event) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (event.getFoodLevel() < event.getEntity().getFoodLevel()) { + createData() + .entity(event.getEntity()) + .event(event) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index ef74275e4..cf6208b42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -15,57 +15,53 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class InLiquidTrigger extends ChallengeTrigger { - public InLiquidTrigger(String name) { - super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { - builder.addSetting("LAVA", new ItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); - builder.addSetting("WATER", new ItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); - })); - Challenges.getInstance().getScheduler().register(this); - } + public InLiquidTrigger(String name) { + super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { + builder.addSetting("LAVA", new ItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); + builder.addSetting("WATER", new ItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); + })); + Challenges.getInstance().getScheduler().register(this); + } - @Override - public Material getMaterial() { - return Material.BUCKET; - } + @Override + public Material getMaterial() { + return Material.BUCKET; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + if (event.getTo() == null) return; - Material type = event.getTo().getBlock().getType(); - Material oldType = event.getFrom().getBlock().getType(); - if ((type == Material.WATER || - type == Material.LAVA) && - oldType != Material.WATER && - oldType != Material.LAVA) { - createData() - .entity(event.getPlayer()) - .data(SubSettingsHelper.LIQUID, type.name()) - .execute(); - } + Material type = event.getTo().getBlock().getType(); + Material oldType = event.getFrom().getBlock().getType(); + if ((type == Material.WATER || + type == Material.LAVA) && + oldType != Material.WATER && + oldType != Material.LAVA) { + createData() + .entity(event.getPlayer()) + .data(SubSettingsHelper.LIQUID, type.name()) + .execute(); + } - } + } - @ScheduledTask(ticks = 5, async = false) - public void onFifthTick() { - for (Player player : Bukkit.getOnlinePlayers()) { - Material type = player.getLocation().getBlock().getType(); - if (type == Material.WATER || - type == Material.LAVA) { - createData() - .entity(player) - .data("liquid", type.name()) - .execute(); - } - } + @ScheduledTask(ticks = 5, async = false) + public void onFifthTick() { + for (Player player : Bukkit.getOnlinePlayers()) { + Material type = player.getLocation().getBlock().getType(); + if (type == Material.WATER || + type == Material.LAVA) { + createData() + .entity(player) + .data("liquid", type.name()) + .execute(); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 5d34447b9..87f91462a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -12,78 +12,74 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class IntervallTrigger extends ChallengeTrigger { - public IntervallTrigger(String name) { - super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { - builder.addSetting("1", new ItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); - String seconds = "item-custom-trigger-intervall-seconds"; - builder.addSetting("2", new ItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); - builder.addSetting("5", new ItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); - builder.addSetting("10", new ItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); - builder.addSetting("20", new ItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); - builder.addSetting("30", new ItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); - builder.addSetting("60", new ItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); - String minutes = "item-custom-trigger-intervall-minutes"; - builder.addSetting("120", new ItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); - builder.addSetting("180", new ItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); - builder.addSetting("240", new ItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); - builder.addSetting("300", new ItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); - })); - Challenges.getInstance().getScheduler().register(this); - } + public IntervallTrigger(String name) { + super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { + builder.addSetting("1", new ItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); + String seconds = "item-custom-trigger-intervall-seconds"; + builder.addSetting("2", new ItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); + builder.addSetting("5", new ItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); + builder.addSetting("10", new ItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); + builder.addSetting("20", new ItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); + builder.addSetting("30", new ItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); + builder.addSetting("60", new ItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); + String minutes = "item-custom-trigger-intervall-minutes"; + builder.addSetting("120", new ItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); + builder.addSetting("180", new ItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); + builder.addSetting("240", new ItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); + builder.addSetting("300", new ItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); + })); + Challenges.getInstance().getScheduler().register(this); + } - @Override - public Material getMaterial() { - return Material.CLOCK; - } + @Override + public Material getMaterial() { + return Material.CLOCK; + } - @ScheduledTask(ticks = 20, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onSecond() { - long currentTime = Challenges.getInstance().getChallengeTimer().getTime(); + @ScheduledTask(ticks = 20, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onSecond() { + long currentTime = Challenges.getInstance().getChallengeTimer().getTime(); - List list = new LinkedList<>(); - list.add("1"); + List list = new LinkedList<>(); + list.add("1"); - if (currentTime % 2 == 0) { - list.add("2"); - } - if (currentTime % 5 == 0) { - list.add("5"); - } - if (currentTime % 10 == 0) { - list.add("10"); - } - if (currentTime % 20 == 0) { - list.add("20"); - } - if (currentTime % 30 == 0) { - list.add("30"); - } - if (currentTime % 60 == 0) { - list.add("60"); - } - if (currentTime % 120 == 0) { - list.add("120"); - } - if (currentTime % 180 == 0) { - list.add("180"); - } - if (currentTime % 180 == 0) { - list.add("180"); - } - if (currentTime % 300 == 0) { - list.add("300"); - } + if (currentTime % 2 == 0) { + list.add("2"); + } + if (currentTime % 5 == 0) { + list.add("5"); + } + if (currentTime % 10 == 0) { + list.add("10"); + } + if (currentTime % 20 == 0) { + list.add("20"); + } + if (currentTime % 30 == 0) { + list.add("30"); + } + if (currentTime % 60 == 0) { + list.add("60"); + } + if (currentTime % 120 == 0) { + list.add("120"); + } + if (currentTime % 180 == 0) { + list.add("180"); + } + if (currentTime % 180 == 0) { + list.add("180"); + } + if (currentTime % 300 == 0) { + list.add("300"); + } - createData() - .data("time", list) - .execute(); - } + createData() + .data("time", list) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java index 7e895e6a8..784ddb0d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java @@ -6,28 +6,24 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerLevelChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class LevelUpTrigger extends ChallengeTrigger { - public LevelUpTrigger(String name) { - super(name); - } + public LevelUpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ENCHANTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.ENCHANTING_TABLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLevelUp(PlayerLevelChangeEvent event) { - if (event.getNewLevel() > event.getOldLevel()) { - createData() - .entity(event.getPlayer()) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLevelUp(PlayerLevelChangeEvent event) { + if (event.getNewLevel() > event.getOldLevel()) { + createData() + .entity(event.getPlayer()) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java index 8fb3639ac..c20e0fc76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java @@ -7,28 +7,24 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveBlockTrigger extends ChallengeTrigger { - public MoveBlockTrigger(String name) { - super(name); - } + public MoveBlockTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.LEATHER_BOOTS; - } + @Override + public Material getMaterial() { + return Material.LEATHER_BOOTS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java index 566b96d71..47d79e92c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java @@ -6,29 +6,25 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveCameraTrigger extends ChallengeTrigger { - public MoveCameraTrigger(String name) { - super(name); - } + public MoveCameraTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.COMPASS; - } + @Override + public Material getMaterial() { + return Material.COMPASS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getFrom().getDirection().equals(event.getTo().getDirection())) return; - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getFrom().getDirection().equals(event.getTo().getDirection())) return; + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java index 8623c2f49..73fd6a60c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java @@ -6,31 +6,27 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveDownTrigger extends ChallengeTrigger { - public MoveDownTrigger(String name) { - super(name); - } + public MoveDownTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.NETHER_BRICK_STAIRS; - } + @Override + public Material getMaterial() { + return Material.NETHER_BRICK_STAIRS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getTo().getBlockY() < event.getFrom().getBlockY()) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getTo().getBlockY() < event.getFrom().getBlockY()) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java index 044e12a06..0ee50a4aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java @@ -6,31 +6,27 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveUpTrigger extends ChallengeTrigger { - public MoveUpTrigger(String name) { - super(name); - } + public MoveUpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.PURPUR_STAIRS; - } + @Override + public Material getMaterial() { + return Material.PURPUR_STAIRS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getTo().getBlockY() > event.getFrom().getBlockY()) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getTo().getBlockY() > event.getFrom().getBlockY()) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java index 4db6072ce..0de86a1f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java @@ -6,27 +6,23 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PickupItemTrigger extends ChallengeTrigger { - public PickupItemTrigger(String name) { - super(name); - } + public PickupItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.STICK; - } + @Override + public Material getMaterial() { + return Material.STICK; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java index b17e482d1..21674f27f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java @@ -7,28 +7,24 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockPlaceEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PlaceBlockTrigger extends ChallengeTrigger { - public PlaceBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } + public PlaceBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.BRICKS; - } + @Override + public Material getMaterial() { + return Material.BRICKS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .block(event.getBlock().getType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .block(event.getBlock().getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java index c5c99d95e..440a0bcb1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java @@ -8,24 +8,20 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PlayerJumpTrigger extends ChallengeTrigger { - public PlayerJumpTrigger(String name) { - super(name); - } + public PlayerJumpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.RABBIT_FOOT; - } + @Override + public Material getMaterial() { + return Material.RABBIT_FOOT; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { - createData().entity(event.getPlayer()).execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + createData().entity(event.getPlayer()).execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java index 198a7f90a..75b19ba32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java @@ -8,26 +8,22 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class PlayerSneakTrigger extends ChallengeTrigger { - public PlayerSneakTrigger(String name) { - super(name); - } + public PlayerSneakTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.SANDSTONE_SLAB; - } + @Override + public Material getMaterial() { + return Material.SANDSTONE_SLAB; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerToggleSneakEvent event) { - if (event.isSneaking()) { - createData().entity(event.getPlayer()).execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onJump(@Nonnull PlayerToggleSneakEvent event) { + if (event.isSneaking()) { + createData().entity(event.getPlayer()).execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java index fd880281e..ab3afe49c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java @@ -14,44 +14,40 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class StandsNotOnSpecificBlockTrigger extends ChallengeTrigger { - public StandsNotOnSpecificBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } - - @Override - public Material getMaterial() { - return Material.MAGMA_BLOCK; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - if (event.getTo() == null) return; - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - - Material type = blockBelow.getType(); - - List materials = new LinkedList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.remove(type); - materials.removeIf(material -> !material.isBlock() || !material.isItem()); - - List names = new LinkedList<>(); - for (Material material : materials) { - names.add(material.name()); - } - - createData() - .entity(event.getPlayer()) - .event(event) - .data("block", names) - .execute(); - } + public StandsNotOnSpecificBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } + + @Override + public Material getMaterial() { + return Material.MAGMA_BLOCK; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + if (event.getTo() == null) return; + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + + Material type = blockBelow.getType(); + + List materials = new LinkedList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.remove(type); + materials.removeIf(material -> !material.isBlock() || !material.isItem()); + + List names = new LinkedList<>(); + for (Material material : materials) { + names.add(material.name()); + } + + createData() + .entity(event.getPlayer()) + .event(event) + .data("block", names) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index 86d4f9069..38606ffcd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -9,33 +9,31 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ +import java.util.Objects; + public class StandsOnSpecificBlockTrigger extends ChallengeTrigger { - public StandsOnSpecificBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } - - @Override - public Material getMaterial() { - return Material.PACKED_ICE; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - Block blockBelow = BlockUtils.getBlockBelow( - event.getTo()); - if (blockBelow == null) return; - - createData() - .entity(event.getPlayer()) - .event(event) - .block(blockBelow.getType()) - .execute(); - } + public StandsOnSpecificBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } + + @Override + public Material getMaterial() { + return Material.PACKED_ICE; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + Block blockBelow = BlockUtils.getBlockBelow( + Objects.requireNonNull(event.getTo())); + if (blockBelow == null) return; + + createData() + .entity(event.getPlayer()) + .event(event) + .block(blockBelow.getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 59c5999fa..01256bb88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,71 +18,67 @@ import javax.annotation.Nonnull; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class DamageTeleportChallenge extends SettingModifier { - private static final int PLAYER = 1, EVERYONE = 2; + private static final int PLAYER = 1, EVERYONE = 2; - public DamageTeleportChallenge() { - super(MenuType.CHALLENGES, 1, 2); - } + public DamageTeleportChallenge() { + super(MenuType.CHALLENGES, 1, 2); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); + } else { + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); + } + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; - handleDamage(((Player) event.getEntity())); - } + handleDamage(((Player) event.getEntity())); + } - private void handleDamage(@Nonnull Player player) { + private void handleDamage(@Nonnull Player player) { - Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); - location.setY(location.getY() + 1); - location.getChunk().load(true); + Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); + location.setY(location.getY() + 1); + location.getChunk().load(true); - if (getValue() == PLAYER) { - player.teleport(location); - } else { - broadcastFiltered(player1 -> player1.teleport(location)); - } + if (getValue() == PLAYER) { + player.teleport(location); + } else { + broadcastFiltered(player1 -> player1.teleport(location)); + } - } + } - public Location getRandomLocation(World world) { - double size = world.getWorldBorder().getSize() / 2; - size--; + public Location getRandomLocation(World world) { + double size = world.getWorldBorder().getSize() / 2; + size--; - final double randomX = ThreadLocalRandom.current().nextDouble(-size, size); - final double randomY = ThreadLocalRandom.current().nextDouble(-size, size); + final double randomX = ThreadLocalRandom.current().nextDouble(-size, size); + final double randomY = ThreadLocalRandom.current().nextDouble(-size, size); - return world.getWorldBorder().getCenter().add(randomX, 0, randomY); - } + return world.getWorldBorder().getCenter().add(randomX, 0, randomY); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 2226d2969..3a394f7c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.implementation.setting.MaxHealthSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -8,11 +8,11 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -25,92 +25,88 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class ZeroHeartsChallenge extends SettingModifier { - public ZeroHeartsChallenge() { - super(MenuType.CHALLENGES, 5, 30, 10); - } + public ZeroHeartsChallenge() { + super(MenuType.CHALLENGES, 5, 30, 10); + } - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(); - int maxTime = getValue() * 60; - bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(0); - }); - } + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(); + int maxTime = getValue() * 60; + bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + Bukkit.getOnlinePlayers().forEach(player -> { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(0); + }); + } - @Override - protected void onDisable() { - bossbar.hide(); - AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); - } + @Override + protected void onDisable() { + bossbar.hide(); + AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); + } - @Override - protected void onValueChange() { - bossbar.update(); - } + @Override + protected void onValueChange() { + bossbar.update(); + } - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcast(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(0); - }); - int absorptionTime = getCurrentTime(); - if (absorptionTime >= getValue() * 60) { - bossbar.hide(); - if (absorptionTime == getValue() * 60) { - removeAbsorptionEffect(); - } - return; - } - getGameStateData().set("absorption-time", absorptionTime + 1); - applyAbsorptionEffect(); - bossbar.update(); - } + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcast(player -> { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(0); + }); + int absorptionTime = getCurrentTime(); + if (absorptionTime >= getValue() * 60) { + bossbar.hide(); + if (absorptionTime == getValue() * 60) { + removeAbsorptionEffect(); + } + return; + } + getGameStateData().set("absorption-time", absorptionTime + 1); + applyAbsorptionEffect(); + bossbar.update(); + } - private int getCurrentTime() { - return getGameStateData().getInt("absorption-time"); - } + private int getCurrentTime() { + return getGameStateData().getInt("absorption-time"); + } - private void applyAbsorptionEffect() { - broadcastFiltered(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, (getValue() - getCurrentTime()) * 20 * 60, 1, true, false, false))); - } + private void applyAbsorptionEffect() { + broadcastFiltered(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, (getValue() - getCurrentTime()) * 20 * 60, 1, true, false, false))); + } - private void removeAbsorptionEffect() { - broadcastFiltered(player -> player.removePotionEffect(PotionEffectType.ABSORPTION)); - } + private void removeAbsorptionEffect() { + broadcastFiltered(player -> player.removePotionEffect(PotionEffectType.ABSORPTION)); + } - @EventHandler(priority = EventPriority.HIGH) - public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { - if (event.getAction() != Action.REMOVED) return; - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - kill(player); - Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - } + @EventHandler(priority = EventPriority.HIGH) + public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { + if (event.getAction() != Action.REMOVED) return; + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + kill(player); + Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index 36d98cd0f..827616b35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -14,42 +14,38 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class AdvancementDamageChallenge extends SettingModifier { - public AdvancementDamageChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - -} \ No newline at end of file + public AdvancementDamageChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index deea32241..aa70429fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -13,40 +13,35 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BlockBreakDamageChallenge extends SettingModifier { - public BlockBreakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - -} \ No newline at end of file + public BlockBreakDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 19400f792..b1688facf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -14,41 +14,36 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class BlockPlaceDamageChallenge extends SettingModifier { - public BlockPlaceDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler - public void onBreak(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - -} \ No newline at end of file + public BlockPlaceDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler + public void onBreak(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index 75c1cec12..ca487586a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -17,42 +17,38 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamagePerBlockChallenge extends SettingModifier { - public DamagePerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; - - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - -} \ No newline at end of file + public DamagePerBlockChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; + + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index bd3ece7ea..196888b2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -17,37 +17,37 @@ public class DamagePerItemChallenge extends Setting { - public DamagePerItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickup(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - applyDamage(event.getPlayer(), event.getItem().getItemStack().getAmount()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; // ignoreCancelled not working on own event - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAction() == InventoryAction.NOTHING) return; - if (event.getCurrentItem() == null) return; - applyDamage(event.getPlayer(), event.getCurrentItem().getAmount()); - } - - private void applyDamage(@Nonnull Player player, int amount) { - player.setNoDamageTicks(0); - player.damage(amount); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); - } - -} \ No newline at end of file + public DamagePerItemChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + applyDamage(event.getPlayer(), event.getItem().getItemStack().getAmount()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.isCancelled()) return; // ignoreCancelled not working on own event + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAction() == InventoryAction.NOTHING) return; + if (event.getCurrentItem() == null) return; + applyDamage(event.getPlayer(), event.getCurrentItem().getAmount()); + } + + private void applyDamage(@Nonnull Player player, int amount) { + player.setNoDamageTicks(0); + player.damage(amount); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index f459ecbbf..1fe1e8ac6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -15,33 +15,29 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class DeathOnFallChallenge extends Setting { - public DeathOnFallChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } + public DeathOnFallChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); + } - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (event.getCause() != DamageCause.FALL) return; - event.setDamage(player.getHealth()); - event.setCancelled(false); - } + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (event.getCause() != DamageCause.FALL) return; + event.setDamage(player.getHealth()); + event.setCancelled(false); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java new file mode 100644 index 000000000..24614d601 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -0,0 +1,85 @@ +package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; + +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageEvent; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +@Since("2.3.2") +public class DelayDamageChallenge extends TimedChallenge { + + private boolean canGetDamage = false; + private final Map damageMap = new HashMap<>(); + + public DelayDamageChallenge() { + super(MenuType.CHALLENGES, 1, 64, 4, false); + setCategory(SettingCategory.DAMAGE); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 30; + } + + @Override + protected void onTimeActivation() { + + double totalDamage = damageMap.values().stream() + .mapToDouble(Double::doubleValue) + .sum(); + + int playerCount = damageMap.size(); + + if (playerCount > 0) { + canGetDamage = true; + for (Player player : Bukkit.getOnlinePlayers()) { + player.damage(totalDamage); + Message.forName(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); + } + canGetDamage = false; + } + + damageMap.clear(); + restartTimer(); + } + + @Override + public @NotNull ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.REDSTONE, Message.forName("item-delay-damage-description")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + if (ignorePlayer((Player) event.getEntity())) return; + if (canGetDamage) return; + + double damage = event.getFinalDamage(); + Player player = (Player) event.getEntity(); + + damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); + event.setCancelled(true); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 29557fad9..5c5e8222f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -19,62 +17,61 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.potion.PotionEffect; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + @Since("2.0.2") public class FreezeChallenge extends SettingModifier { - public FreezeChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.DAMAGE); - } + public FreezeChallenge() { + super(MenuType.CHALLENGES, 5, 60, 20); + setCategory(SettingCategory.DAMAGE); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; - double damage = ChallengeHelper.getFinalDamage(event); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; + double damage = ChallengeHelper.getFinalDamage(event); - setFreeze(player, damage); - } + setFreeze(player, damage); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getTo().getY() == event.getFrom().getY() && event.getTo().getX() == event.getFrom().getX() && event.getTo().getZ() == event.getFrom().getZ()) - return; - PotionEffect effect = event.getPlayer().getPotionEffect(MinecraftNameWrapper.SLOWNESS); - if (effect == null || effect.getAmplifier() != 255) return; - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getTo().getY() == event.getFrom().getY() && event.getTo().getX() == event.getFrom().getX() && event.getTo().getZ() == event.getFrom().getZ()) + return; + PotionEffect effect = event.getPlayer().getPotionEffect(MinecraftNameWrapper.SLOWNESS); + if (effect == null || effect.getAmplifier() != 255) return; + event.setCancelled(true); + } - public void setFreeze(LivingEntity entity, double damage) { - int time = (int) (damage * getValue() * 20 / 2); - PotionEffect effect = entity.getPotionEffect(MinecraftNameWrapper.SLOWNESS); - entity.removePotionEffect(MinecraftNameWrapper.SLOWNESS); + public void setFreeze(LivingEntity entity, double damage) { + int time = (int) (damage * getValue() * 20 / 2); + PotionEffect effect = entity.getPotionEffect(MinecraftNameWrapper.SLOWNESS); + entity.removePotionEffect(MinecraftNameWrapper.SLOWNESS); - if (effect != null && effect.getAmplifier() == 255) time += effect.getDuration(); + if (effect != null && effect.getAmplifier() == 255) time += effect.getDuration(); - entity.addPotionEffect(new PotionEffect(MinecraftNameWrapper.SLOWNESS, time, 255)); - } + entity.addPotionEffect(new PotionEffect(MinecraftNameWrapper.SLOWNESS, time, 255)); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index c4b32de44..67f64d91f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -19,43 +19,39 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class JumpDamageChallenge extends SettingModifier { - public JumpDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerJumpEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - event.getPlayer().setNoDamageTicks(0); - } - -} \ No newline at end of file + public JumpDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + event.getPlayer().setNoDamageTicks(0); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index 26bbe5c40..babb068e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -12,30 +12,26 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class ReversedDamageChallenge extends Setting { - public ReversedDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } + public ReversedDamageChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getDamager())) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getDamager())) return; - double damage = event.getFinalDamage(); - event.getDamager().damage(damage); - } + double damage = event.getFinalDamage(); + event.getDamager().damage(damage); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 6b155969a..86f1b627d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -18,43 +18,39 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SneakDamageChallenge extends SettingModifier { - public SneakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.isSneaking()) return; - Message.forName("sneak-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - event.getPlayer().setNoDamageTicks(0); - } - -} \ No newline at end of file + public SneakDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.isSneaking()) return; + Message.forName("sneak-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + event.getPlayer().setNoDamageTicks(0); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 4ba093c91..39056f367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -15,44 +15,40 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class WaterAllergyChallenge extends SettingModifier { - public WaterAllergyChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @ScheduledTask(ticks = 5, async = false) - public void onFifthTick() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) return; - if (player.getLocation().getBlock().getType() == Material.WATER) { - player.damage(getValue()); - } - } - - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - -} \ No newline at end of file + public WaterAllergyChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @ScheduledTask(ticks = 5, async = false) + public void onFifthTick() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) return; + if (player.getLocation().getBlock().getType() == Material.WATER) { + player.damage(getValue()); + } + } + + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index adc63f9af..9857ad5a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -32,143 +32,139 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class BlockEffectChallenge extends Setting { - /* - * Saving potion effect to prevent the possibility that an effect remove was somehow skipped - */ - private Map currentPotionEffects = new HashMap<>(); - - public BlockEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARVED_PUMPKIN, Message.forName("item-block-effect-challenge")); - } - - @Override - protected void onEnable() { - currentPotionEffects = new HashMap<>(); - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - @TimerTask(status = TimerStatus.RUNNING) - public void onStart() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - @Override - protected void onDisable() { - broadcastFiltered(player -> { - removeEffect(player, player.getLocation(), null); - }); - currentPotionEffects = null; - } - - @EventHandler(priority = EventPriority.LOW) - public void onLeave(PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - currentPotionEffects.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isIgnored()) { - removeEffect(event.getPlayer(), event.getPlayer().getLocation(), null); - } else { - addEffect(event.getPlayer(), event.getPlayer().getLocation(), null); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); - Block toBlock = BlockUtils.getBlockBelow(event.getTo()); - if (toBlock != null && fromBlock != null) { - if (toBlock.getType() == fromBlock.getType()) return; - } - removeEffect(event.getPlayer(), event.getFrom(), fromBlock); - addEffect(event.getPlayer(), event.getTo(), toBlock); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); - Block toBlock = BlockUtils.getBlockBelow(event.getTo()); - if (toBlock != null && fromBlock != null) { - if (toBlock.getType() == fromBlock.getType()) return; - } - removeEffect(event.getPlayer(), event.getFrom(), fromBlock); - addEffect(event.getPlayer(), event.getTo(), toBlock); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - public void removeEffect(Player player, Location location, Block blockBelow) { - if (blockBelow == null) { - blockBelow = BlockUtils.getBlockBelow(location, -1); - } - if (blockBelow == null) return; - PotionEffectType type = getEffect(blockBelow.getType()).getType(); - player.removePotionEffect(type); - - removeEffectInCache(player); - } - - - public void addEffect(Player player, Location location, Block blockBelow) { - if (blockBelow == null) { - blockBelow = BlockUtils.getBlockBelow(location, -1); - } - if (blockBelow == null) return; - PotionEffect effect = getEffect(blockBelow.getType()); - PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); - if (currentEffect != null && !currentEffect.equals(effect)) { - player.removePotionEffect(currentEffect.getType()); - } else if (player.hasPotionEffect(effect.getType())) return; - player.addPotionEffect(effect); - currentPotionEffects.put(player.getUniqueId(), effect); - } - - public void removeEffectInCache(Player player) { - PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); - if (currentEffect != null) { - player.removePotionEffect(currentEffect.getType()); - } - } - - private PotionEffect getEffect(Material material) { - long seed = ChallengeAPI.getGameWorld(World.Environment.NORMAL).getSeed(); - IRandom random = new SeededRandomWrapper(seed / material.ordinal()); - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = types[random.nextInt(types.length)]; - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); - } - -} \ No newline at end of file + /* + * Saving potion effect to prevent the possibility that an effect remove was somehow skipped + */ + private Map currentPotionEffects = new HashMap<>(); + + public BlockEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CARVED_PUMPKIN, Message.forName("item-block-effect-challenge")); + } + + @Override + protected void onEnable() { + currentPotionEffects = new HashMap<>(); + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + @TimerTask(status = TimerStatus.RUNNING) + public void onStart() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + @Override + protected void onDisable() { + broadcastFiltered(player -> { + removeEffect(player, player.getLocation(), null); + }); + currentPotionEffects = null; + } + + @EventHandler(priority = EventPriority.LOW) + public void onLeave(PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + currentPotionEffects.remove(event.getPlayer().getUniqueId()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isIgnored()) { + removeEffect(event.getPlayer(), event.getPlayer().getLocation(), null); + } else { + addEffect(event.getPlayer(), event.getPlayer().getLocation(), null); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); + Block toBlock = BlockUtils.getBlockBelow(event.getTo()); + if (toBlock != null && fromBlock != null) { + if (toBlock.getType() == fromBlock.getType()) return; + } + removeEffect(event.getPlayer(), event.getFrom(), fromBlock); + addEffect(event.getPlayer(), event.getTo(), toBlock); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); + Block toBlock = BlockUtils.getBlockBelow(event.getTo()); + if (toBlock != null && fromBlock != null) { + if (toBlock.getType() == fromBlock.getType()) return; + } + removeEffect(event.getPlayer(), event.getFrom(), fromBlock); + addEffect(event.getPlayer(), event.getTo(), toBlock); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + public void removeEffect(Player player, Location location, Block blockBelow) { + if (blockBelow == null) { + blockBelow = BlockUtils.getBlockBelow(location, -1); + } + if (blockBelow == null) return; + PotionEffectType type = getEffect(blockBelow.getType()).getType(); + player.removePotionEffect(type); + + removeEffectInCache(player); + } + + + public void addEffect(Player player, Location location, Block blockBelow) { + if (blockBelow == null) { + blockBelow = BlockUtils.getBlockBelow(location, -1); + } + if (blockBelow == null) return; + PotionEffect effect = getEffect(blockBelow.getType()); + PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); + if (currentEffect != null && !currentEffect.equals(effect)) { + player.removePotionEffect(currentEffect.getType()); + } else if (player.hasPotionEffect(effect.getType())) return; + player.addPotionEffect(effect); + currentPotionEffects.put(player.getUniqueId(), effect); + } + + public void removeEffectInCache(Player player) { + PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); + if (currentEffect != null) { + player.removePotionEffect(currentEffect.getType()); + } + } + + private PotionEffect getEffect(Material material) { + long seed = ChallengeAPI.getGameWorld(World.Environment.NORMAL).getSeed(); + IRandom random = new SeededRandomWrapper(seed / material.ordinal()); + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = types[random.nextInt(types.length)]; + return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 9778b22ff..30b0a6d39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -28,120 +28,116 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class ChunkRandomEffectChallenge extends Setting { - /* - * Saving potion effect to prevent the possibility that an effect remove was somehow skipped - */ - private Map currentPotionEffects = new HashMap<>(); - - private long worldSeed; - - public ChunkRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAULDRON, Message.forName("item-chunk-effect-challenge")); - } - - @Override - protected void onEnable() { - currentPotionEffects = new HashMap<>(); - worldSeed = ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed(); - broadcastFiltered(player -> { - addEffect(player, player.getLocation()); - }); - } - - @Override - protected void onDisable() { - broadcastFiltered(player -> { - removeEffect(player, player.getLocation()); - }); - worldSeed = 0; - currentPotionEffects = null; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isIgnored()) { - removeEffect(event.getPlayer(), event.getPlayer().getLocation()); - } else { - addEffect(event.getPlayer(), event.getPlayer().getLocation()); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - removeEffect(event.getPlayer(), event.getFrom()); - addEffect(event.getPlayer(), event.getTo()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - removeEffect(event.getPlayer(), event.getFrom()); - addEffect(event.getPlayer(), event.getTo()); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation()); - }); - } - - public void removeEffect(Player player, Location location) { - PotionEffectType type = getEffect(location.getChunk()).getType(); - player.removePotionEffect(type); - - removeEffectInCache(player); - } - - public void addEffect(Player player, Location location) { - Chunk chunk = location.getChunk(); - PotionEffect effect = getEffect(chunk); - - removeEffectInCache(player); - - if (player.hasPotionEffect(effect.getType())) return; - player.addPotionEffect(effect); - currentPotionEffects.put(player.getUniqueId(), effect); - } - - public void removeEffectInCache(Player player) { - PotionEffect currentEffect = currentPotionEffects.remove(player.getUniqueId()); - if (currentEffect != null) { - player.removePotionEffect(currentEffect.getType()); - } - } - - public PotionEffect getEffect(Chunk chunk) { - - IRandom random = new SeededRandomWrapper(worldSeed * ( - (long) (chunk.getX() == 0 ? Integer.MAX_VALUE : chunk.getX()) * (chunk.getZ() == 0 ? Integer.MAX_VALUE : chunk.getZ()))); - - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = types[random.nextInt(types.length)]; - - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); - } + /* + * Saving potion effect to prevent the possibility that an effect remove was somehow skipped + */ + private Map currentPotionEffects = new HashMap<>(); + + private long worldSeed; + + public ChunkRandomEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAULDRON, Message.forName("item-chunk-effect-challenge")); + } + + @Override + protected void onEnable() { + currentPotionEffects = new HashMap<>(); + worldSeed = ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed(); + broadcastFiltered(player -> { + addEffect(player, player.getLocation()); + }); + } + + @Override + protected void onDisable() { + broadcastFiltered(player -> { + removeEffect(player, player.getLocation()); + }); + worldSeed = 0; + currentPotionEffects = null; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isIgnored()) { + removeEffect(event.getPlayer(), event.getPlayer().getLocation()); + } else { + addEffect(event.getPlayer(), event.getPlayer().getLocation()); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + removeEffect(event.getPlayer(), event.getFrom()); + addEffect(event.getPlayer(), event.getTo()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + removeEffect(event.getPlayer(), event.getFrom()); + addEffect(event.getPlayer(), event.getTo()); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation()); + }); + } + + public void removeEffect(Player player, Location location) { + PotionEffectType type = getEffect(location.getChunk()).getType(); + player.removePotionEffect(type); + + removeEffectInCache(player); + } + + public void addEffect(Player player, Location location) { + Chunk chunk = location.getChunk(); + PotionEffect effect = getEffect(chunk); + + removeEffectInCache(player); + + if (player.hasPotionEffect(effect.getType())) return; + player.addPotionEffect(effect); + currentPotionEffects.put(player.getUniqueId(), effect); + } + + public void removeEffectInCache(Player player) { + PotionEffect currentEffect = currentPotionEffects.remove(player.getUniqueId()); + if (currentEffect != null) { + player.removePotionEffect(currentEffect.getType()); + } + } + + public PotionEffect getEffect(Chunk chunk) { + + IRandom random = new SeededRandomWrapper(worldSeed * ( + (long) (chunk.getX() == 0 ? Integer.MAX_VALUE : chunk.getX()) * (chunk.getZ() == 0 ? Integer.MAX_VALUE : chunk.getZ()))); + + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = types[random.nextInt(types.length)]; + + return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 97fa07e7a..b140744a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -18,57 +18,53 @@ import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EntityRandomEffectChallenge extends Setting { - public EntityRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } + public EntityRandomEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PHANTOM_MEMBRANE, Message.forName("item-entity-effect-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PHANTOM_MEMBRANE, Message.forName("item-entity-effect-challenge")); + } - @Override - protected void onEnable() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - addRandomEffect(entity); - } - } - } + @Override + protected void onEnable() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + addRandomEffect(entity); + } + } + } - @Override - protected void onDisable() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - for (PotionEffect effect : entity.getActivePotionEffects()) { - entity.removePotionEffect(effect.getType()); - } - } - } - } + @Override + protected void onDisable() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity.getType() == EntityType.PLAYER) continue; + for (PotionEffect effect : entity.getActivePotionEffects()) { + entity.removePotionEffect(effect.getType()); + } + } + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onSpawn(EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - addRandomEffect((LivingEntity) event.getEntity()); - } + @EventHandler(priority = EventPriority.HIGH) + public void onSpawn(EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + addRandomEffect((LivingEntity) event.getEntity()); + } - public void addRandomEffect(LivingEntity entity) { - if (entity.getType() == EntityType.PLAYER) return; - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = globalRandom.choose(types); - entity.addPotionEffect(type.createEffect(Integer.MAX_VALUE, 255)); - } + public void addRandomEffect(LivingEntity entity) { + if (entity.getType() == EntityType.PLAYER) return; + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = globalRandom.choose(types); + entity.addPotionEffect(type.createEffect(Integer.MAX_VALUE, 255)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 3df770351..67ec37da2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -20,79 +20,75 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class InfectionChallenge extends Setting { - public InfectionChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } + public InfectionChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); + } - @Override - protected void onDisable() { - Bukkit.getOnlinePlayers().forEach(this::removeEffects); - } + @Override + protected void onDisable() { + Bukkit.getOnlinePlayers().forEach(this::removeEffects); + } - @ScheduledTask(ticks = 10, async = false) - public void onHalfSecond() { - if (!shouldExecuteEffect()) { - Bukkit.getOnlinePlayers().forEach(this::removeEffects); - return; - } - Bukkit.getOnlinePlayers().forEach(this::updateSickness); - } + @ScheduledTask(ticks = 10, async = false) + public void onHalfSecond() { + if (!shouldExecuteEffect()) { + Bukkit.getOnlinePlayers().forEach(this::removeEffects); + return; + } + Bukkit.getOnlinePlayers().forEach(this::updateSickness); + } - private void updateSickness(@Nonnull Player player) { - if (ignorePlayer(player)) { - removeEffects(player); - return; - } + private void updateSickness(@Nonnull Player player) { + if (ignorePlayer(player)) { + removeEffects(player); + return; + } - List entities = getNearbyTargets(player, 2); - if (entities.isEmpty()) { - player.removePotionEffect(MinecraftNameWrapper.NAUSEA); - return; - } + List entities = getNearbyTargets(player, 2); + if (entities.isEmpty()) { + player.removePotionEffect(MinecraftNameWrapper.NAUSEA); + return; + } - byte value = 1; - for (Entity currentEntity : entities) { - if (player.getLocation().distance(currentEntity.getLocation()) <= 1.5) value = 2; - } + byte value = 1; + for (Entity currentEntity : entities) { + if (player.getLocation().distance(currentEntity.getLocation()) <= 1.5) value = 2; + } - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, Integer.MAX_VALUE, 15)); - if (value == 1) { - if (!player.hasPotionEffect(PotionEffectType.WITHER)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 2)); - } - } else { - player.removePotionEffect(PotionEffectType.POISON); - player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 5 * 20, 4)); - } + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, Integer.MAX_VALUE, 15)); + if (value == 1) { + if (!player.hasPotionEffect(PotionEffectType.WITHER)) { + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 2)); + } + } else { + player.removePotionEffect(PotionEffectType.POISON); + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 5 * 20, 4)); + } - } + } - private void removeEffects(@Nonnull Player player) { - player.removePotionEffect(MinecraftNameWrapper.NAUSEA); - player.removePotionEffect(PotionEffectType.POISON); - player.removePotionEffect(PotionEffectType.WITHER); - } + private void removeEffects(@Nonnull Player player) { + player.removePotionEffect(MinecraftNameWrapper.NAUSEA); + player.removePotionEffect(PotionEffectType.POISON); + player.removePotionEffect(PotionEffectType.WITHER); + } - private List getNearbyTargets(@Nonnull Player player, double range) { - return player.getNearbyEntities(range, range, range).stream() - .filter(entity -> entity != player) - .filter(entity -> entity instanceof LivingEntity) - .filter(entity -> !(entity instanceof Player) - || (((Player) entity).getGameMode() != GameMode.CREATIVE - && ((Player) entity).getGameMode() != GameMode.SPECTATOR)).collect(Collectors.toList()); - } + private List getNearbyTargets(@Nonnull Player player, double range) { + return player.getNearbyEntities(range, range, range).stream() + .filter(entity -> entity != player) + .filter(entity -> entity instanceof LivingEntity) + .filter(entity -> !(entity instanceof Player) + || (((Player) entity).getGameMode() != GameMode.CREATIVE + && ((Player) entity).getGameMode() != GameMode.SPECTATOR)).collect(Collectors.toList()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index b24d137c2..5b7ebeaa8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,16 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -37,248 +30,248 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + @Since("2.0") public class PermanentEffectOnDamageChallenge extends SettingModifier { - private static final int GLOBAL_EFFECT = 1; - private final Random random = new Random(); - - public PermanentEffectOnDamageChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.EFFECT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); - } - - @Override - protected void onEnable() { - if (!shouldExecuteEffect()) { - clearEffects(); - return; - } - updateEffects(); - } - - @Override - protected void onDisable() { - clearEffects(); - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onTimerStart() { - if (!isEnabled()) return; - updateEffects(); - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void onTimerPause() { - if (!isEnabled()) return; - clearEffects(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getItem().getType() != Material.MILK_BUCKET) return; - Bukkit.getScheduler().runTask(plugin, this::updateEffects); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateEffects(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateEffects(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, () -> { - clearEffects(); - updateEffects(); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getFinalDamage() <= 0 && event.getDamage(DamageModifier.ABSORPTION) >= 0) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - DamageCause cause = event.getCause(); - if (cause == DamageCause.POISON || cause == DamageCause.WITHER) return; - - addRandomEffect(player); - updateEffects(); - } - - public void addRandomEffect(@Nonnull Player eventPlayer) { - PotionEffectType randomEffect = getNewRandomEffect(); - if (randomEffect == null) return; - applyNewEffect(eventPlayer, randomEffect); - } - - private void applyNewEffect(@Nonnull Player player, @Nonnull PotionEffectType potionEffectType) { - String path = player.getUniqueId().toString(); - Document effects = getGameStateData().getDocument(path); - - int amplifier = 1; - if (!effects.contains(potionEffectType.getName())) { - effects.set(potionEffectType.getName(), 1); - } else { - amplifier = effects.getInt(potionEffectType.getName()) + 1; - effects.set(potionEffectType.getName(), amplifier); - } - - if (effectsToEveryone()) { - Message.forName("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); - } else { - Message.forName("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); - } - - getGameStateData().set(path, effects); - } - - @Nullable - private PotionEffectType getNewRandomEffect() { - ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); - return possibleEffects.get(random.nextInt(possibleEffects.size())); - } - - public void updateEffects() { - forEachEffect((player, effectType, amplifier) -> { - if (effectsToEveryone()) { - broadcastFiltered(currentPlayer -> { - addEffect(currentPlayer, effectType, amplifier); - }); - } else { - if (!ignorePlayer(player)) { - addEffect(player, effectType, amplifier); - } - } - }); - } - - private void addEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType, int amplifier) { - - if (player.hasPotionEffect(effectType)) { - PotionEffect effect = player.getPotionEffect(effectType); - if (effect != null && effect.getAmplifier() == amplifier - 1) { - return; - } - } - - player.removePotionEffect(effectType); - player.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, amplifier - 1)); - } - - private void clearEffects() { - forEachEffect((player, potionEffectType, amplifier) -> { - broadcast(currentPlayer -> { - currentPlayer.removePotionEffect(potionEffectType); - }); - }); - } - - private void forEachEffect(@Nonnull TriConsumer action) { - List> effects = new ArrayList<>(); - - for (String uuid : getGameStateData().keys()) { - - Document effectsDocument = getGameStateData().getDocument(uuid); - for (String effectName : effectsDocument.keys()) { - PotionEffectType effectType = PotionEffectType.getByName(effectName); - int amplifier = effectsDocument.getInt(effectName); - if (effectType == null) continue; - - if (effectsToEveryone()) { - addEffectToList(effects, effectType, amplifier); - } else { - try { - Player player = Bukkit.getPlayer(UUID.fromString(uuid)); - action.accept(player, effectType, amplifier); - } catch (Exception ex) { - Logger.debug("UUID formation for uuid '" + uuid + "' failed in permanent effect challenge!"); - } - } - } - - } - - effects.forEach(tuple -> { - broadcastFiltered(player -> { - action.accept(player, tuple.getFirst(), tuple.getSecond()); - }); - }); - } - - private void addEffectToList(@Nonnull List> effectsList, @Nonnull PotionEffectType effectType, int amplifier) { - Tuple effectTuple = effectsList.stream().filter(tuple -> tuple.getFirst() == effectType).findFirst() - .orElse(new Tuple<>(effectType, 0)); - effectTuple.setSecond(effectTuple.getSecond() + amplifier); - - if (!effectsList.contains(effectTuple)) effectsList.add(effectTuple); - } - - private boolean effectsToEveryone() { - return GLOBAL_EFFECT == getValue(); - } - - @Override - protected void onValueChange() { - if (!shouldExecuteEffect()) return; - clearEffects(); - updateEffects(); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == GLOBAL_EFFECT) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); - return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); - } - - @Override - public void playValueChangeTitle() { - if (GLOBAL_EFFECT == getValue()) { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("everyone").asString()); - } else { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("player").asString()); - } - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - broadcast(player -> { - for (PotionEffect potionEffect : player.getActivePotionEffects()) { - player.removePotionEffect(potionEffect.getType()); - } - }); - if (shouldExecuteEffect()) { - updateEffects(); - } - } - -} \ No newline at end of file + private static final int GLOBAL_EFFECT = 1; + private final Random random = new Random(); + + public PermanentEffectOnDamageChallenge() { + super(MenuType.CHALLENGES, 1, 2); + setCategory(SettingCategory.EFFECT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); + } + + @Override + protected void onEnable() { + if (!shouldExecuteEffect()) { + clearEffects(); + return; + } + updateEffects(); + } + + @Override + protected void onDisable() { + clearEffects(); + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onTimerStart() { + if (!isEnabled()) return; + updateEffects(); + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void onTimerPause() { + if (!isEnabled()) return; + clearEffects(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getItem().getType() != Material.MILK_BUCKET) return; + Bukkit.getScheduler().runTask(plugin, this::updateEffects); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateEffects(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateEffects(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTask(plugin, () -> { + clearEffects(); + updateEffects(); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getFinalDamage() <= 0 && event.getDamage(DamageModifier.ABSORPTION) >= 0) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + DamageCause cause = event.getCause(); + if (cause == DamageCause.POISON || cause == DamageCause.WITHER) return; + + addRandomEffect(player); + updateEffects(); + } + + public void addRandomEffect(@Nonnull Player eventPlayer) { + PotionEffectType randomEffect = getNewRandomEffect(); + if (randomEffect == null) return; + applyNewEffect(eventPlayer, randomEffect); + } + + private void applyNewEffect(@Nonnull Player player, @Nonnull PotionEffectType potionEffectType) { + String path = player.getUniqueId().toString(); + Document effects = getGameStateData().getDocument(path); + + int amplifier = 1; + if (!effects.contains(potionEffectType.getName())) { + effects.set(potionEffectType.getName(), 1); + } else { + amplifier = effects.getInt(potionEffectType.getName()) + 1; + effects.set(potionEffectType.getName(), amplifier); + } + + if (effectsToEveryone()) { + Message.forName("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); + } else { + Message.forName("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); + } + + getGameStateData().set(path, effects); + } + + @Nullable + private PotionEffectType getNewRandomEffect() { + ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); + return possibleEffects.get(random.nextInt(possibleEffects.size())); + } + + public void updateEffects() { + forEachEffect((player, effectType, amplifier) -> { + if (effectsToEveryone()) { + broadcastFiltered(currentPlayer -> { + addEffect(currentPlayer, effectType, amplifier); + }); + } else { + if (!ignorePlayer(player)) { + addEffect(player, effectType, amplifier); + } + } + }); + } + + private void addEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType, int amplifier) { + + if (player.hasPotionEffect(effectType)) { + PotionEffect effect = player.getPotionEffect(effectType); + if (effect != null && effect.getAmplifier() == amplifier - 1) { + return; + } + } + + player.removePotionEffect(effectType); + player.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, amplifier - 1)); + } + + private void clearEffects() { + forEachEffect((player, potionEffectType, amplifier) -> { + broadcast(currentPlayer -> { + currentPlayer.removePotionEffect(potionEffectType); + }); + }); + } + + private void forEachEffect(@Nonnull TriConsumer action) { + List> effects = new ArrayList<>(); + + for (String uuid : getGameStateData().keys()) { + + Document effectsDocument = getGameStateData().getDocument(uuid); + for (String effectName : effectsDocument.keys()) { + PotionEffectType effectType = PotionEffectType.getByName(effectName); + int amplifier = effectsDocument.getInt(effectName); + if (effectType == null) continue; + + if (effectsToEveryone()) { + addEffectToList(effects, effectType, amplifier); + } else { + try { + Player player = Bukkit.getPlayer(UUID.fromString(uuid)); + action.accept(player, effectType, amplifier); + } catch (Exception ex) { + Logger.debug("UUID formation for uuid '" + uuid + "' failed in permanent effect challenge!"); + } + } + } + + } + + effects.forEach(tuple -> { + broadcastFiltered(player -> { + action.accept(player, tuple.getFirst(), tuple.getSecond()); + }); + }); + } + + private void addEffectToList(@Nonnull List> effectsList, @Nonnull PotionEffectType effectType, int amplifier) { + Tuple effectTuple = effectsList.stream().filter(tuple -> tuple.getFirst() == effectType).findFirst() + .orElse(new Tuple<>(effectType, 0)); + effectTuple.setSecond(effectTuple.getSecond() + amplifier); + + if (!effectsList.contains(effectTuple)) effectsList.add(effectTuple); + } + + private boolean effectsToEveryone() { + return GLOBAL_EFFECT == getValue(); + } + + @Override + protected void onValueChange() { + if (!shouldExecuteEffect()) return; + clearEffects(); + updateEffects(); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!isEnabled()) return DefaultItem.disabled(); + if (getValue() == GLOBAL_EFFECT) + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); + return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); + } + + @Override + public void playValueChangeTitle() { + if (GLOBAL_EFFECT == getValue()) { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("everyone").asString()); + } else { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("player").asString()); + } + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + broadcast(player -> { + for (PotionEffect potionEffect : player.getActivePotionEffects()) { + player.removePotionEffect(potionEffect.getType()); + } + }); + if (shouldExecuteEffect()) { + updateEffects(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 460ac6333..5b15d051e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -24,90 +24,86 @@ import java.util.Random; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { - private final Random random = new Random(); - int currentTime = 0; - - public RandomPotionEffectChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-random-effect-challenge-settings")); - setCategory(SettingCategory.EFFECT); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 60, - 30 - ) - ); - registerSetting("length", new NumberSubSetting( - () -> new ItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 20, - 10 - ) - ); - registerSetting("amplifier", new NumberSubSetting( - () -> new ItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), - value -> null, - value -> "§7" + Message.forName("amplifier") + " §e" + value, - 1, - 8, - 3 - ) - ); - - } - - @Nullable - public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); - - ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); - possibleEffects.removeAll(activeEffects); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); - return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - currentTime++; - - if (currentTime > getSetting("time").getAsInt()) { - currentTime = 0; - applyRandomEffect(); - } - - } - - private void applyRandomEffect() { - Bukkit.getOnlinePlayers().forEach(this::applyRandomEffect); - } - - private void applyRandomEffect(@Nonnull Player entity) { - PotionEffectType effect = getNewRandomEffect(entity); - if (effect == null) return; - applyEffect(entity, effect); - } - - private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType) { - PotionEffect potionEffect = new PotionEffect(effectType, (getSetting("length").getAsInt() + 1) * 20, getSetting("amplifier").getAsInt() - 1); - player.addPotionEffect(potionEffect); - } - -} \ No newline at end of file + private final Random random = new Random(); + int currentTime = 0; + + public RandomPotionEffectChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-random-effect-challenge-settings")); + setCategory(SettingCategory.EFFECT); + registerSetting("time", new NumberSubSetting( + () -> new ItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 60, + 30 + ) + ); + registerSetting("length", new NumberSubSetting( + () -> new ItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 20, + 10 + ) + ); + registerSetting("amplifier", new NumberSubSetting( + () -> new ItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), + value -> null, + value -> "§7" + Message.forName("amplifier") + " §e" + value, + 1, + 8, + 3 + ) + ); + + } + + @Nullable + public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); + + ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); + possibleEffects.removeAll(activeEffects); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); + return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + currentTime++; + + if (currentTime > getSetting("time").getAsInt()) { + currentTime = 0; + applyRandomEffect(); + } + + } + + private void applyRandomEffect() { + Bukkit.getOnlinePlayers().forEach(this::applyRandomEffect); + } + + private void applyRandomEffect(@Nonnull Player entity) { + PotionEffectType effect = getNewRandomEffect(entity); + if (effect == null) return; + applyEffect(entity, effect); + } + + private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType) { + PotionEffect potionEffect = new PotionEffect(effectType, (getSetting("length").getAsInt() + 1) * 20, getSetting("amplifier").getAsInt() - 1); + player.addPotionEffect(potionEffect); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 89b517a93..f7ed9e957 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -15,43 +15,39 @@ import javax.annotation.Nonnull; import java.util.Collection; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class AllMobsToDeathPoint extends Setting { - public AllMobsToDeathPoint() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @EventHandler - public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - if (ignorePlayer(event.getKiller())) return; - - teleportAllMobsOfType(event.getEntityType(), event.getEntity().getLocation()); - } - - private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Location location) { - if (location.getWorld() == null) return; - Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); - for (Entity entity : entities) { - if (!(entity instanceof LivingEntity)) return; - ((LivingEntity) entity).setNoDamageTicks(20); - entity.teleport(location); - } - - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); - } - -} \ No newline at end of file + public AllMobsToDeathPoint() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @EventHandler + public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + if (ignorePlayer(event.getKiller())) return; + + teleportAllMobsOfType(event.getEntityType(), event.getEntity().getLocation()); + } + + private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Location location) { + if (location.getWorld() == null) return; + Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); + for (Entity entity : entities) { + if (!(entity instanceof LivingEntity)) return; + ((LivingEntity) entity).setNoDamageTicks(20); + entity.teleport(location); + } + + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 9b8c31477..01cb2af32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -22,88 +22,86 @@ import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.Objects; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class BlockMobsChallenge extends Setting { - public BlockMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public BlockMobsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BRICKS, Message.forName("item-block-mob-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BRICKS, Message.forName("item-block-mob-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - EntityType type = globalRandom.choose(RandomMobAction.getLivingMobs()); - LivingEntity entity = (LivingEntity) event.getBlock().getWorld() - .spawnEntity(event.getBlock().getLocation().add(0.5, 0, 0.5), type); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + EntityType type = globalRandom.choose(RandomMobAction.getLivingMobs()); + LivingEntity entity = (LivingEntity) event.getBlock().getWorld() + .spawnEntity(event.getBlock().getLocation().add(0.5, 0, 0.5), type); - Collection drops = event.getBlock().getDrops(event.getPlayer().getEquipment().getItemInMainHand()); + Collection drops = event.getBlock().getDrops(Objects.requireNonNull(event.getPlayer().getEquipment()).getItemInMainHand()); - int i = 0; - // Put every stack in a different slot to make sure everything drops properly - for (ItemStack drop : drops) { + int i = 0; + // Put every stack in a different slot to make sure everything drops properly + for (ItemStack drop : drops) { - EquipmentSlot slot = EquipmentSlot.HEAD; - EntityEquipment equipment = entity.getEquipment(); + EquipmentSlot slot = EquipmentSlot.HEAD; + EntityEquipment equipment = entity.getEquipment(); - switch (i) { - case 0: - equipment.setHelmetDropChance(1); - break; - case 1: - slot = EquipmentSlot.CHEST; - equipment.setChestplateDropChance(1); - break; - case 2: - slot = EquipmentSlot.LEGS; - equipment.setLeggingsDropChance(1); - break; - case 3: - slot = EquipmentSlot.FEET; - equipment.setBootsDropChance(1); - break; - case 4: - slot = EquipmentSlot.HAND; - equipment.setItemInMainHandDropChance(1); - break; - case 5: - slot = EquipmentSlot.OFF_HAND; - equipment.setItemInOffHandDropChance(1); - break; - } - equipment.setItem(slot, drop); - i++; - } - event.setDropItems(false); - } + switch (i) { + case 0: + assert equipment != null; + equipment.setHelmetDropChance(1); + break; + case 1: + slot = EquipmentSlot.CHEST; + equipment.setChestplateDropChance(1); + break; + case 2: + slot = EquipmentSlot.LEGS; + equipment.setLeggingsDropChance(1); + break; + case 3: + slot = EquipmentSlot.FEET; + equipment.setBootsDropChance(1); + break; + case 4: + slot = EquipmentSlot.HAND; + equipment.setItemInMainHandDropChance(1); + break; + case 5: + slot = EquipmentSlot.OFF_HAND; + equipment.setItemInOffHandDropChance(1); + break; + } + equipment.setItem(slot, drop); + i++; + } + event.setDropItems(false); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index 19e3002f2..7cd6d145e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -13,41 +13,37 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DupedSpawningChallenge extends Setting { - private boolean inCustomSpawn = false; - - public DupedSpawningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity) - || event.getEntity() instanceof Player - || event.getEntity() instanceof EnderDragon - ) return; - if (inCustomSpawn) return; - inCustomSpawn = true; - Entity entity = event.getEntity().getWorld().spawnEntity(event.getLocation(), event.getEntityType()); - - if (entity instanceof Slime && event.getEntity() instanceof Slime) { - ((Slime) entity).setSize(((Slime) event.getEntity()).getSize()); - } - - inCustomSpawn = false; - } - -} \ No newline at end of file + private boolean inCustomSpawn = false; + + public DupedSpawningChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity) + || event.getEntity() instanceof Player + || event.getEntity() instanceof EnderDragon + ) return; + if (inCustomSpawn) return; + inCustomSpawn = true; + Entity entity = event.getEntity().getWorld().spawnEntity(event.getLocation(), event.getEntityType()); + + if (entity instanceof Slime && event.getEntity() instanceof Slime) { + ((Slime) entity).setSize(((Slime) event.getEntity()).getSize()); + } + + inCustomSpawn = false; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index 1231cb7e6..37d82eb9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -10,25 +10,21 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class HydraNormalChallenge extends HydraChallenge { - public HydraNormalChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public HydraNormalChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); + } - @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { - return 2; - } -} \ No newline at end of file + @Override + public int getNewMobsCount(@Nonnull EntityType entityType) { + return 2; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 98ed37433..e82b06d22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,36 +11,32 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class HydraPlusChallenge extends HydraChallenge { - private static final int limit = 512; - - public HydraPlusChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); - } - - @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { - int currentCount = getGameStateData().getInt(entityType.name()); - if (currentCount == 0) { - currentCount = 2; - } else { - currentCount *= 2; - } - getGameStateData().set(entityType.name(), Math.min(currentCount, limit)); - return currentCount; - } - -} \ No newline at end of file + private static final int limit = 512; + + public HydraPlusChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); + } + + @Override + public int getNewMobsCount(@Nonnull EntityType entityType) { + int currentCount = getGameStateData().getInt(entityType.name()); + if (currentCount == 0) { + currentCount = 2; + } else { + currentCount *= 2; + } + getGameStateData().set(entityType.name(), Math.min(currentCount, limit)); + return currentCount; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 4b1d8b2f5..0d9df9a5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -23,53 +23,49 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class InvisibleMobsChallenge extends Setting { - public InvisibleMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public InvisibleMobsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Override - protected void onEnable() { - addEffectForEveryEntity(); - } + @Override + protected void onEnable() { + addEffectForEveryEntity(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - addEffect(((LivingEntity) event.getEntity())); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + addEffect(((LivingEntity) event.getEntity())); + } - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void playEffects() { - if (!shouldExecuteEffect()) return; - addEffectForEveryEntity(); - } + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void playEffects() { + if (!shouldExecuteEffect()) return; + addEffectForEveryEntity(); + } - private void addEffectForEveryEntity() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - addEffect(entity); - } - } - } + private void addEffectForEveryEntity() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity instanceof Player) continue; + addEffect(entity); + } + } + } - private void addEffect(@Nonnull LivingEntity entity) { - entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); - } + private void addEffect(@Nonnull LivingEntity entity) { + entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 8d17dffa7..064c9b2c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -19,63 +19,59 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MobSightDamageChallenge extends SettingModifier { - public MobSightDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public MobSightDamageChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } - @ScheduledTask(ticks = 1, async = false) - public void onTick() { + @ScheduledTask(ticks = 1, async = false) + public void onTick() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; - RayTraceResult result = player.getWorld().rayTraceEntities( - player.getEyeLocation(), - player.getLocation().getDirection(), - 30, - 0.01, - entity -> !(entity instanceof Player) && entity instanceof LivingEntity - ); - if (result == null) continue; + RayTraceResult result = player.getWorld().rayTraceEntities( + player.getEyeLocation(), + player.getLocation().getDirection(), + 30, + 0.01, + entity -> !(entity instanceof Player) && entity instanceof LivingEntity + ); + if (result == null) continue; - Location location = result.getHitPosition().toLocation(player.getWorld()); - LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; + Location location = result.getHitPosition().toLocation(player.getWorld()); + LivingEntity entity = ((LivingEntity) result.getHitEntity()); + if (entity == null) continue; - double distance = entity.getEyeLocation().distance(location) * 5; + double distance = entity.getEyeLocation().distance(location) * 5; - BoundingBox box = entity.getBoundingBox(); - double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; + BoundingBox box = entity.getBoundingBox(); + double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); + if (distance > volume) continue; - player.damage(getValue()); - } + player.damage(getValue()); + } - } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 613b59218..e87867380 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -19,63 +19,59 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MobTransformationChallenge extends Setting { - public MobTransformationChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public MobTransformationChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - bossbar.setColor(BarColor.GREEN); - EntityType type = getPlayerData(player).getEnum("type", EntityType.class); - Object typeName = type == null ? "None" : type; - bossbar.setTitle(Message.forName("bossbar-mob-transformation").asString(typeName)); - }); - bossbar.show(); - } + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + bossbar.setColor(BarColor.GREEN); + EntityType type = getPlayerData(player).getEnum("type", EntityType.class); + Object typeName = type == null ? "None" : type; + bossbar.setTitle(Message.forName("bossbar-mob-transformation").asString(typeName)); + }); + bossbar.show(); + } - @Override - protected void onDisable() { - bossbar.hide(); - } + @Override + protected void onDisable() { + bossbar.hide(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof Player || !(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof EnderDragon) - return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof Player || !(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof EnderDragon) + return; - Player player = event.getDamager(); - if (ignorePlayer(player)) return; + Player player = event.getDamager(); + if (ignorePlayer(player)) return; - EntityType type = getPlayerData(player).getEnum("type", event.getEntityType()); + EntityType type = getPlayerData(player).getEnum("type", event.getEntityType()); - if (type != event.getEntityType()) { - event.getEntity().remove(); - event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), type); - } - getPlayerData(player).set("type", event.getEntityType()); - bossbar.update(player); - } + if (type != event.getEntityType()) { + event.getEntity().remove(); + event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), type); + } + getPlayerData(player).set("type", event.getEntityType()); + bossbar.update(player); + } - private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultType) { - EntityType type = getPlayerData(player).getEnum("type", EntityType.class); - if (type == null) return defaultType; - return type; - } + private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultType) { + EntityType type = getPlayerData(player).getEnum("type", EntityType.class); + if (type == null) return defaultType; + return type; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index f49715813..b11f85864 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -26,104 +26,100 @@ import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class MobsRespawnInEndChallenge extends Setting { - private final Map toSpawnEntities = new HashMap<>(); - private int totalMobsInEnd = 0; - - public MobsRespawnInEndChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-respawn-end-challenge")); - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.PURPLE); - bar.setTitle(Message.forName("bossbar-respawn-end").asString(totalMobsInEnd)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("total", totalMobsInEnd); - } - - @Override - public void loadGameState(@NotNull Document document) { - totalMobsInEnd = document.getInt("total"); - } - - private void addEntityToSpawn(EntityType type) { - if (!ChallengeAPI.isPlayerInGameWorld(World.Environment.THE_END)) { - increaseEntityToSpawnCount(type); - } else { - spawnEntityInEnd(type, 1); - } - totalMobsInEnd++; - bossbar.update(); - } - - private void spawnEntityInEnd(EntityType type, int count) { - World world = ChallengeAPI.getGameWorld(World.Environment.THE_END); - Location spawnLocation = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); - for (int i = 0; i < count; i++) { - Entity entity = world.spawnEntity(spawnLocation, type); - - if (entity instanceof LivingEntity) { - entity.setVelocity(Vector.getRandom().multiply(ThreadLocalRandom.current().nextBoolean() ? -1 : 1).setY(0)); - ((LivingEntity) entity).setNoDamageTicks(20 * 5); - } - } - } - - private void increaseEntityToSpawnCount(EntityType type) { - Integer count = toSpawnEntities.getOrDefault(type, 0); - toSpawnEntities.put(type, count + 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof Player || event.getEntity() instanceof EnderDragon) return; - if (event.getEntity().getLocation().getWorld() == null) return; - if (event.getEntity().getLocation().getWorld().getEnvironment() == World.Environment.THE_END) - return; - if (ChallengeHelper.ignoreDamager(event.getKiller())) return; - addEntityToSpawn(event.getEntityType()); - SoundSample.PLING.play((event.getKiller())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onWorldChange(PlayerTeleportEvent event) { - if (event.getTo() == null || event.getTo().getWorld() == null || event.getTo().getWorld() == event.getFrom().getWorld()) - return; - if (event.getTo().getWorld().getEnvironment() != World.Environment.THE_END) return; - - for (Map.Entry entry : toSpawnEntities.entrySet()) { - EntityType type = entry.getKey(); - Integer count = entry.getValue(); - spawnEntityInEnd(type, count); - } - toSpawnEntities.clear(); - - } + private final Map toSpawnEntities = new HashMap<>(); + private int totalMobsInEnd = 0; + + public MobsRespawnInEndChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-respawn-end-challenge")); + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + bar.setColor(BarColor.PURPLE); + bar.setTitle(Message.forName("bossbar-respawn-end").asString(totalMobsInEnd)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("total", totalMobsInEnd); + } + + @Override + public void loadGameState(@NotNull Document document) { + totalMobsInEnd = document.getInt("total"); + } + + private void addEntityToSpawn(EntityType type) { + if (!ChallengeAPI.isPlayerInGameWorld(World.Environment.THE_END)) { + increaseEntityToSpawnCount(type); + } else { + spawnEntityInEnd(type, 1); + } + totalMobsInEnd++; + bossbar.update(); + } + + private void spawnEntityInEnd(EntityType type, int count) { + World world = ChallengeAPI.getGameWorld(World.Environment.THE_END); + Location spawnLocation = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); + for (int i = 0; i < count; i++) { + Entity entity = world.spawnEntity(spawnLocation, type); + + if (entity instanceof LivingEntity) { + entity.setVelocity(Vector.getRandom().multiply(ThreadLocalRandom.current().nextBoolean() ? -1 : 1).setY(0)); + ((LivingEntity) entity).setNoDamageTicks(20 * 5); + } + } + } + + private void increaseEntityToSpawnCount(EntityType type) { + Integer count = toSpawnEntities.getOrDefault(type, 0); + toSpawnEntities.put(type, count + 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMobKill(EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof Player || event.getEntity() instanceof EnderDragon) return; + if (event.getEntity().getLocation().getWorld() == null) return; + if (event.getEntity().getLocation().getWorld().getEnvironment() == World.Environment.THE_END) + return; + if (ChallengeHelper.ignoreDamager(event.getKiller())) return; + addEntityToSpawn(event.getEntityType()); + SoundSample.PLING.play((event.getKiller())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorldChange(PlayerTeleportEvent event) { + if (event.getTo() == null || event.getTo().getWorld() == null || event.getTo().getWorld() == event.getFrom().getWorld()) + return; + if (event.getTo().getWorld().getEnvironment() != World.Environment.THE_END) return; + + for (Map.Entry entry : toSpawnEntities.entrySet()) { + EntityType type = entry.getKey(); + Integer count = entry.getValue(); + spawnEntityInEnd(type, count); + } + toSpawnEntities.clear(); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index a7c6758bd..08491be15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -18,35 +18,31 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class NewEntityOnJumpChallenge extends Setting { - public NewEntityOnJumpChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (ignorePlayer(event.getPlayer())) return; - if (!shouldExecuteEffect()) return; - spawnRandomEntity(event.getPlayer().getLocation()); - } - - private void spawnRandomEntity(@Nonnull Location location) { - if (location.getWorld() == null) return; - EntityType type = globalRandom.choose(RandomMobAction.getSpawnableMobs()); - location.getWorld().spawnEntity(location, type); - } - -} \ No newline at end of file + public NewEntityOnJumpChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (ignorePlayer(event.getPlayer())) return; + if (!shouldExecuteEffect()) return; + spawnRandomEntity(event.getPlayer().getLocation()); + } + + private void spawnRandomEntity(@Nonnull Location location) { + if (location.getWorld() == null) return; + EntityType type = globalRandom.choose(RandomMobAction.getSpawnableMobs()); + location.getWorld().spawnEntity(location, type); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 4c48c5c87..f91b95b93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -20,70 +20,66 @@ import javax.annotation.Nonnull; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class StoneSightChallenge extends Setting { - private final Random random = new Random(); - - public StoneSightChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); - } - - @ScheduledTask(ticks = 1, async = false) - public void onTick() { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - - RayTraceResult result = player.getWorld().rayTraceEntities( - player.getEyeLocation(), - player.getLocation().getDirection(), - 30, - 0.01, - entity -> !(entity instanceof Player) && !(entity instanceof EnderDragon) && entity instanceof LivingEntity - ); - if (result == null) continue; - - Location location = result.getHitPosition().toLocation(player.getWorld()); - LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; - - double distance = entity.getEyeLocation().distance(location) * 5; - - BoundingBox box = entity.getBoundingBox(); - double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; - - entity.getLocation().getBlock().setType(getRandomStone(), false); - entity.remove(); - SoundSample.BREAK.play(player); - - } - - } - - @Nonnull - private Material getRandomStone() { - Material[] materials = { - Material.STONE, - Material.STONE, - Material.STONE, - Material.COBBLESTONE, - Material.COBBLESTONE, - Material.MOSSY_COBBLESTONE - }; - return materials[random.nextInt(materials.length)]; - } - -} \ No newline at end of file + private final Random random = new Random(); + + public StoneSightChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); + } + + @ScheduledTask(ticks = 1, async = false) + public void onTick() { + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + + RayTraceResult result = player.getWorld().rayTraceEntities( + player.getEyeLocation(), + player.getLocation().getDirection(), + 30, + 0.01, + entity -> !(entity instanceof Player) && !(entity instanceof EnderDragon) && entity instanceof LivingEntity + ); + if (result == null) continue; + + Location location = result.getHitPosition().toLocation(player.getWorld()); + LivingEntity entity = ((LivingEntity) result.getHitEntity()); + if (entity == null) continue; + + double distance = entity.getEyeLocation().distance(location) * 5; + + BoundingBox box = entity.getBoundingBox(); + double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); + if (distance > volume) continue; + + entity.getLocation().getBlock().setType(getRandomStone(), false); + entity.remove(); + SoundSample.BREAK.play(player); + + } + + } + + @Nonnull + private Material getRandomStone() { + Material[] materials = { + Material.STONE, + Material.STONE, + Material.STONE, + Material.COBBLESTONE, + Material.COBBLESTONE, + Material.MOSSY_COBBLESTONE + }; + return materials[random.nextInt(materials.length)]; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index beeba0d04..bfa6fc65d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; @@ -20,7 +20,10 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -35,202 +38,198 @@ import java.util.Optional; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class JumpAndRunChallenge extends WorldDependentChallenge { - private final List lastPlayers = new ArrayList<>(); - - private int jumps = 4; - private int currentJump; - private int jumpsDone; - - private Block targetBlock; - private Block lastBlock; - - private UUID currentPlayer; - - public JumpAndRunChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void onDisable() { - if (isInExtraWorld()) - exitJumpAndRun(); - } - - @Override - protected void handleCountdown() { - switch (getSecondsLeftUntilNextActivation()) { - case 1: - Message.forName("jnr-countdown-one").broadcast(Prefix.CHALLENGES); - SoundSample.BASS_OFF.broadcast(); - break; - case 2: - case 3: - case 5: - Message.forName("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); - SoundSample.BASS_OFF.broadcast(); - break; - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onQuit(@Nonnull PlayerQuitEvent event) { - if (currentPlayer == null) return; - if (!currentPlayer.equals(event.getPlayer().getUniqueId())) return; - exitJumpAndRun(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - public void startWorldChallenge() { - startJumpAndRun(); - } - - protected void startJumpAndRun() { - currentJump = 0; - currentPlayer = getNextPlayer().getUniqueId(); - lastPlayers.add(currentPlayer); - - buildNextJump(); - teleportToWorld(true, (player, index) -> { - player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); - player.teleport(new Location(getExtraWorld(), 0.5, 101, 0.5)); - }); - } - - protected void buildNextJump() { - - if (lastBlock != null) lastBlock.setType(Material.AIR); - - lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); - lastBlock.setType(Material.GOLD_BLOCK); - - Material type = getRandomBlockType(); - targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); - targetBlock.setType(type); - - } - - @Nonnull - protected Material getRandomBlockType() { - if (currentJump == jumps - 1) return Material.EMERALD_BLOCK; - - Material[] materials = { - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.END_ROD, - Material.COBBLESTONE_WALL, - Material.SPRUCE_FENCE - }; - return globalRandom.choose(materials); - } - - @Nonnull - protected Player getNextPlayer() { - List players = new ArrayList<>(Bukkit.getOnlinePlayers()); - players.removeIf(AbstractChallenge::ignorePlayer); - players.removeIf(player -> lastPlayers.contains(player.getUniqueId())); - - if (players.isEmpty()) { - players = new ArrayList<>(Bukkit.getOnlinePlayers()); - lastPlayers.clear(); - } - return globalRandom.choose(players); - } - - protected void finishJumpAndRun() { - jumps++; - jumpsDone++; - - Message.forName("jnr-finished").broadcast(Prefix.CHALLENGES, Optional.ofNullable(currentPlayer).map(Bukkit::getPlayer).map(NameHelper::getName).orElse("?")); - exitJumpAndRun(); - SoundSample.KLING.broadcast(); - } - - protected void exitJumpAndRun() { - currentPlayer = null; - teleportBack(); - breakJumpAndRun(); - restartTimer(); - } - - protected void breakJumpAndRun() { - if (lastBlock != null) lastBlock.setType(Material.AIR); - if (targetBlock != null) targetBlock.setType(Material.AIR); - - lastBlock = null; - targetBlock = null; - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("jumps", jumps); - document.set("jumpsDone", jumpsDone); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - jumps = document.getInt("jumps", jumps); - jumpsDone = document.getInt("jumpsDone", jumpsDone); - } - - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) - public void spawnParticles() { - if (targetBlock == null) return; - ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), - MinecraftNameWrapper.INSTANT_EFFECT, 13, 0.35); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!event.getPlayer().getUniqueId().equals(currentPlayer)) return; - if (!isInExtraWorld()) return; - if (targetBlock == null) return; - if (event.getTo() == null) return; - - if (BlockUtils.isSameBlockLocation(event.getTo(), targetBlock.getLocation().add(0, 1, 0))) { - if (++currentJump >= jumps) { - finishJumpAndRun(); - } else { - SoundSample.PLOP.broadcast(); - buildNextJump(); - } - } else if (event.getTo().getBlockY() < targetBlock.getY() - 2) { - exitJumpAndRun(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } - - } + private final List lastPlayers = new ArrayList<>(); + + private int jumps = 4; + private int currentJump; + private int jumpsDone; + + private Block targetBlock; + private Block lastBlock; + + private UUID currentPlayer; + + public JumpAndRunChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.EXTRA_WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void onDisable() { + if (isInExtraWorld()) + exitJumpAndRun(); + } + + @Override + protected void handleCountdown() { + switch (getSecondsLeftUntilNextActivation()) { + case 1: + Message.forName("jnr-countdown-one").broadcast(Prefix.CHALLENGES); + SoundSample.BASS_OFF.broadcast(); + break; + case 2: + case 3: + case 5: + Message.forName("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); + SoundSample.BASS_OFF.broadcast(); + break; + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onQuit(@Nonnull PlayerQuitEvent event) { + if (currentPlayer == null) return; + if (!currentPlayer.equals(event.getPlayer().getUniqueId())) return; + exitJumpAndRun(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + public void startWorldChallenge() { + startJumpAndRun(); + } + + protected void startJumpAndRun() { + currentJump = 0; + currentPlayer = getNextPlayer().getUniqueId(); + lastPlayers.add(currentPlayer); + + buildNextJump(); + teleportToWorld(true, (player, index) -> { + player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); + player.teleport(new Location(getExtraWorld(), 0.5, 101, 0.5)); + }); + } + + protected void buildNextJump() { + + if (lastBlock != null) lastBlock.setType(Material.AIR); + + lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); + lastBlock.setType(Material.GOLD_BLOCK); + + Material type = getRandomBlockType(); + targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); + targetBlock.setType(type); + + } + + @Nonnull + protected Material getRandomBlockType() { + if (currentJump == jumps - 1) return Material.EMERALD_BLOCK; + + Material[] materials = { + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.END_ROD, + Material.COBBLESTONE_WALL, + Material.SPRUCE_FENCE + }; + return globalRandom.choose(materials); + } + + @Nonnull + protected Player getNextPlayer() { + List players = new ArrayList<>(Bukkit.getOnlinePlayers()); + players.removeIf(AbstractChallenge::ignorePlayer); + players.removeIf(player -> lastPlayers.contains(player.getUniqueId())); + + if (players.isEmpty()) { + players = new ArrayList<>(Bukkit.getOnlinePlayers()); + lastPlayers.clear(); + } + return globalRandom.choose(players); + } + + protected void finishJumpAndRun() { + jumps++; + jumpsDone++; + + Message.forName("jnr-finished").broadcast(Prefix.CHALLENGES, Optional.ofNullable(currentPlayer).map(Bukkit::getPlayer).map(NameHelper::getName).orElse("?")); + exitJumpAndRun(); + SoundSample.KLING.broadcast(); + } + + protected void exitJumpAndRun() { + currentPlayer = null; + teleportBack(); + breakJumpAndRun(); + restartTimer(); + } + + protected void breakJumpAndRun() { + if (lastBlock != null) lastBlock.setType(Material.AIR); + if (targetBlock != null) targetBlock.setType(Material.AIR); + + lastBlock = null; + targetBlock = null; + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("jumps", jumps); + document.set("jumpsDone", jumpsDone); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + jumps = document.getInt("jumps", jumps); + jumpsDone = document.getInt("jumpsDone", jumpsDone); + } + + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) + public void spawnParticles() { + if (targetBlock == null) return; + ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), + MinecraftNameWrapper.INSTANT_EFFECT, 13, 0.35); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!event.getPlayer().getUniqueId().equals(currentPlayer)) return; + if (!isInExtraWorld()) return; + if (targetBlock == null) return; + if (event.getTo() == null) return; + + if (BlockUtils.isSameBlockLocation(event.getTo(), targetBlock.getLocation().add(0, 1, 0))) { + if (++currentJump >= jumps) { + finishJumpAndRun(); + } else { + SoundSample.PLOP.broadcast(); + buildNextJump(); + } + } else if (event.getTo().getBlockY() < targetBlock.getY() - 2) { + exitJumpAndRun(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 0f66bad4d..c5b34d165 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -21,80 +21,76 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class WaterMLGChallenge extends WorldDependentChallenge { - public WaterMLGChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 10); - } - - @Override - public void startWorldChallenge() { - Location currentLocation = new Location(getExtraWorld(), 0, 150, 0); - - teleportToWorld(false, (player, index) -> { - currentLocation.add(100, 0, 0); - player.getInventory().setHeldItemSlot(4); - player.getInventory().setItem(4, new ItemStack(Material.WATER_BUCKET)); - player.teleport(currentLocation); - }); - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - teleportBack(); - restartTimer(); - }, 10 * 20); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { - if (!isInExtraWorld()) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - event.getBlock().setType(Material.AIR); - Bukkit.getScheduler().runTaskLater(plugin, () -> { - teleportBack(event.getPlayer()); - }, 40); - }, 10); - - } - - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!isInExtraWorld()) return; - - if (AbstractChallenge.getFirstInstance(OneTeamLifeSetting.class).isEnabled()) { - teleportBack(); - } else { - Player player = (Player) event.getEntity(); - teleportBack(player); - } - } - -} \ No newline at end of file + public WaterMLGChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.EXTRA_WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 10); + } + + @Override + public void startWorldChallenge() { + Location currentLocation = new Location(getExtraWorld(), 0, 150, 0); + + teleportToWorld(false, (player, index) -> { + currentLocation.add(100, 0, 0); + player.getInventory().setHeldItemSlot(4); + player.getInventory().setItem(4, new ItemStack(Material.WATER_BUCKET)); + player.teleport(currentLocation); + }); + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + teleportBack(); + restartTimer(); + }, 10 * 20); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { + if (!isInExtraWorld()) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + event.getBlock().setType(Material.AIR); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + teleportBack(event.getPlayer()); + }, 40); + }, 10); + + } + + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!isInExtraWorld()) return; + + if (AbstractChallenge.getFirstInstance(OneTeamLifeSetting.class).isEnabled()) { + teleportBack(); + } else { + Player player = (Player) event.getEntity(); + teleportBack(player); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 91d58f858..26a31ea9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -15,6 +15,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.block.Biome; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -26,126 +28,125 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; +import java.util.Objects; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class ForceBiomeChallenge extends CompletableForceChallenge { - private Biome biome; - - public ForceBiomeChallenge() { - super(MenuType.CHALLENGES, 2, 20, 5); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-biome-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-biome-instruction").asComponent(biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-biome-fail").broadcast(Prefix.CHALLENGES, BukkitStringUtils.getBiomeName(biome)); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); - } - - @Override - protected void chooseForcing() { - Biome[] biomes = Arrays.stream(Biome.values()) - .filter(biome -> !biome.name().contains("END")) - .filter(biome -> !biome.name().contains("MUSHROOM")) - .filter(biome -> !biome.name().contains("VOID")) - .filter(biome -> !biome.name().equals("CUSTOM")) - .toArray(Biome[]::new); - - biome = globalRandom.choose(biomes); - } - - @Override - protected int getForcingTime() { - return globalRandom.around(getRarity(biome) * 60 * 6, 60); - } - - private int getRarity(@Nonnull Biome biome) { - Object[][] mapping = { - {"BADLANDS", 5}, - {"JUNGLE", 4}, - {"BAMBOO", 4}, - {"MODIFIED", 3}, - {"TALL", 3}, - {"SWAMP", 2}, - }; - - for (Object[] pair : mapping) { - String key = (String) pair[0]; - if (biome.name().contains(key)) - return (int) pair[1]; - } - return 1; - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60 * 3, 60); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - if (event.getTo().getBlock().getBiome() != biome) return; - completeForcing(event.getPlayer()); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - biome = document.getEnum("target", Biome.class); - setState(biome == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", biome); - } + private Biome biome; + + public ForceBiomeChallenge() { + super(MenuType.CHALLENGES, 2, 20, 5); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-biome-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-biome-instruction").asComponent(biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-biome-fail").broadcast(Prefix.CHALLENGES, BukkitStringUtils.getBiomeName(biome)); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); + } + + @Override + protected void chooseForcing() { + Biome[] biomes = Arrays.stream(Biome.values()) + .filter(biome -> !biome.name().contains("END")) + .filter(biome -> !biome.name().contains("MUSHROOM")) + .filter(biome -> !biome.name().contains("VOID")) + .filter(biome -> !biome.name().equals("CUSTOM")) + .toArray(Biome[]::new); + + biome = globalRandom.choose(biomes); + } + + @Override + protected int getForcingTime() { + return globalRandom.around(getRarity(biome) * 60 * 6, 60); + } + + private int getRarity(@Nonnull Biome biome) { + Object[][] mapping = { + {"BADLANDS", 5}, + {"JUNGLE", 4}, + {"BAMBOO", 4}, + {"MODIFIED", 3}, + {"TALL", 3}, + {"SWAMP", 2}, + }; + + for (Object[] pair : mapping) { + String key = (String) pair[0]; + if (biome.name().contains(key)) + return (int) pair[1]; + } + return 1; + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60 * 3, 60); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + if (event.getTo().getBlock().getBiome() != biome) return; + completeForcing(event.getPlayer()); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + String biomeName = document.getString("target"); + biome = Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(biomeName).toLowerCase())); + setState(biome == null ? WAITING : COUNTDOWN); + } + } + + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", biome); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index c27761db1..85ae08737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -25,109 +25,105 @@ import java.util.Arrays; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceBlockChallenge extends EndingForceChallenge { - private Material block; - - public ForceBlockChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-block-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-block-instruction").asComponent(block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected boolean isFailing(@Nonnull Player player) { - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = -1; y <= 1; y++) { - Material type = player.getLocation().add(x, y, z).getBlock().getType(); - if (type == block) return false; - } - } - } - return true; - } - - @Override - protected void broadcastFailedMessage(@Nonnull Player player) { - Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); - } - - @Override - protected void broadcastSuccessMessage() { - Message.forName("force-block-success").broadcast(Prefix.CHALLENGES); - } - - @Override - protected void chooseForcing() { - Material[] materials = Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(Material::isBlock) - .filter(ItemUtils::isObtainableInSurvival) - .filter(material -> !BlockUtils.isTooHardToGet(material)) - .filter(material -> !material.name().contains("WALL")) - .toArray(length -> new Material[length]); - block = globalRandom.choose(materials); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(4 * 60, 6 * 60); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - block = document.getEnum("target", Material.class); - setState(block == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", block); - } + private Material block; + + public ForceBlockChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-block-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-block-instruction").asComponent(block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected boolean isFailing(@Nonnull Player player) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = -1; y <= 1; y++) { + Material type = player.getLocation().add(x, y, z).getBlock().getType(); + if (type == block) return false; + } + } + } + return true; + } + + @Override + protected void broadcastFailedMessage(@Nonnull Player player) { + Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); + } + + @Override + protected void broadcastSuccessMessage() { + Message.forName("force-block-success").broadcast(Prefix.CHALLENGES); + } + + @Override + protected void chooseForcing() { + Material[] materials = Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(Material::isBlock) + .filter(ItemUtils::isObtainableInSurvival) + .filter(material -> !BlockUtils.isTooHardToGet(material)) + .filter(material -> !material.name().contains("WALL")) + .toArray(length -> new Material[length]); + block = globalRandom.choose(materials); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(4 * 60, 6 * 60); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + block = document.getEnum("target", Material.class); + setState(block == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", block); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 5ebda733f..fd61eda4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -24,96 +24,92 @@ import javax.annotation.Nullable; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceHeightChallenge extends EndingForceChallenge { - private int height; - - public ForceHeightChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-height-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-height-instruction").asString(height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected boolean isFailing(@Nonnull Player player) { - return player.getLocation().getBlockY() != height; - } - - @Override - protected void broadcastFailedMessage(@Nonnull Player player) { - Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); - } - - @Override - protected void broadcastSuccessMessage() { - Message.forName("force-height-success").broadcast(Prefix.CHALLENGES); - } - - @Override - protected void chooseForcing() { - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(3 * 60 + 30, 5 * 60); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - height = document.getInt("target"); - setState(COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", height); - } + private int height; + + public ForceHeightChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-height-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-height-instruction").asString(height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected boolean isFailing(@Nonnull Player player) { + return player.getLocation().getBlockY() != height; + } + + @Override + protected void broadcastFailedMessage(@Nonnull Player player) { + Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); + } + + @Override + protected void broadcastSuccessMessage() { + Message.forName("force-height-success").broadcast(Prefix.CHALLENGES); + } + + @Override + protected void chooseForcing() { + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(3 * 60 + 30, 5 * 60); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + height = document.getInt("target"); + setState(COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", height); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index d34ddfb01..261f26e45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -35,121 +35,117 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class ForceItemChallenge extends CompletableForceChallenge { - private Material item; - - public ForceItemChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-item-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-item-instruction").asComponent(item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-item-fail").broadcast(Prefix.CHALLENGES, item); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); - } - - @Override - protected void chooseForcing() { - List items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - items.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - items.removeIf(material -> !material.isItem()); - items.removeIf(BlockUtils::isTooHardToGet); - - item = globalRandom.choose(items); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(5 * 60, 8 * 60); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - ItemStack item = event.getCurrentItem(); - if (item == null) return; - if (item.getType() != this.item) return; - completeForcing(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - Material material = event.getItem().getItemStack().getType(); - if (material != item) return; - completeForcing(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - Material material = item.getType(); - if (material != this.item) return; - completeForcing(event.getPlayer()); - }, 1); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - item = document.getEnum("target", Material.class); - setState(item == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", item); - } + private Material item; + + public ForceItemChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-item-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-item-instruction").asComponent(item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-item-fail").broadcast(Prefix.CHALLENGES, item); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); + } + + @Override + protected void chooseForcing() { + List items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + items.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + items.removeIf(material -> !material.isItem()); + items.removeIf(BlockUtils::isTooHardToGet); + + item = globalRandom.choose(items); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(5 * 60, 8 * 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + ItemStack item = event.getCurrentItem(); + if (item == null) return; + if (item.getType() != this.item) return; + completeForcing(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + Material material = event.getItem().getItemStack().getType(); + if (material != item) return; + completeForcing(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + Material material = item.getType(); + if (material != this.item) return; + completeForcing(event.getPlayer()); + }, 1); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + item = document.getEnum("target", Material.class); + setState(item == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", item); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index d61d44419..47074dea0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -30,104 +30,100 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceMobChallenge extends CompletableForceChallenge { - private EntityType entity; - - public ForceMobChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-mob-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-mob-instruction").asComponent(entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); - } - - @Override - protected void chooseForcing() { - List entities = new ArrayList<>(Arrays.asList(EntityType.values())); - entities.removeIf(type -> !type.isSpawnable()); - entities.removeIf(type -> !type.isAlive()); - Utils.removeEnums(entities, "ENDER_DRAGON", "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "SKELETON_HORSE", "SHULKER", "WITHER", "GIANT"); - - entity = globalRandom.choose(entities); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(5 * 60, 8 * 60); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - LivingEntity entity = event.getEntity(); - if (entity.getType() != this.entity) return; - Player killer = entity.getKiller(); - if (killer == null) return; - completeForcing(killer); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - entity = document.getEnum("target", EntityType.class); - setState(entity == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", entity); - } + private EntityType entity; + + public ForceMobChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-mob-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-mob-instruction").asComponent(entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); + } + + @Override + protected void chooseForcing() { + List entities = new ArrayList<>(Arrays.asList(EntityType.values())); + entities.removeIf(type -> !type.isSpawnable()); + entities.removeIf(type -> !type.isAlive()); + Utils.removeEnums(entities, "ENDER_DRAGON", "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "SKELETON_HORSE", "SHULKER", "WITHER", "GIANT"); + + entity = globalRandom.choose(entities); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(5 * 60, 8 * 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + LivingEntity entity = event.getEntity(); + if (entity.getType() != this.entity) return; + Player killer = entity.getKiller(); + if (killer == null) return; + completeForcing(killer); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + entity = document.getEnum("target", EntityType.class); + setState(entity == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", entity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index 01f9f84e6..ed7861ba1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -15,50 +15,46 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamageInventoryClearChallenge extends SettingModifier { - public DamageInventoryClearChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.INVENTORY); - } - - @EventHandler - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; - - if (getValue() == 1) { - Bukkit.getOnlinePlayers().forEach(player -> player.getInventory().clear()); - } else { - Player player = (Player) event.getEntity(); - player.getInventory().clear(); - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); - } - -} \ No newline at end of file + public DamageInventoryClearChallenge() { + super(MenuType.CHALLENGES, 1, 2); + setCategory(SettingCategory.INVENTORY); + } + + @EventHandler + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; + + if (getValue() == 1) { + Bukkit.getOnlinePlayers().forEach(player -> player.getInventory().clear()); + } else { + Player player = (Player) event.getEntity(); + player.getInventory().clear(); + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); + } else { + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); + } + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index b09bda1b3..8e7ad6ab9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -39,206 +39,202 @@ import java.util.function.Consumer; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MissingItemsChallenge extends TimedChallenge implements PlayerCommand { - private final Map> inventories = new HashMap<>(); - private List materials; + private final Map> inventories = new HashMap<>(); + private List materials; - public MissingItemsChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.INVENTORY); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 10); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); - } + public MissingItemsChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.INVENTORY); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 10); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); + } - @Override - protected void onEnable() { - materials = Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(Material::isItem) - .filter(ItemUtils::isObtainableInSurvival) - .collect(Collectors.toList()); - } + @Override + protected void onEnable() { + materials = Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(Material::isItem) + .filter(ItemUtils::isObtainableInSurvival) + .collect(Collectors.toList()); + } - @Override - protected void onDisable() { - materials = null; - } - - @Override - protected void onTimeActivation() { - broadcastFiltered(this::startGuessingGame); - - if (inventories.isEmpty()) { - restartTimer(); - } - - } - - private void startGuessingGame(@Nonnull Player player) { - - BukkitTask task = new BukkitRunnable() { - - int timeLeft = (int) (2.5 * 60); - - @Override - public void run() { - timeLeft--; - - if (!inventories.containsKey(player.getUniqueId())) { - cancel(); - return; - } - - if (timeLeft == 0) { - cancel(); - Tuple tuple = inventories.remove(player.getUniqueId()); - tuple.getSecond().handleClick(new MenuClickInfo(player, tuple.getFirst(), false, false, 1000)); - } else if (timeLeft <= 5) { - new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F, (float) (timeLeft - 1) / 10 + 1).play(player); - } - - } - - }.runTaskTimer(plugin, 20, 20); - - createMissingItemsInventory(player, unused -> { - if (!anyRunningGame()) { - inventories.clear(); - restartTimer(); - } - task.cancel(); - }); - - } - - private void createMissingItemsInventory(@Nonnull Player player, Consumer onFinish) { - - int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); - if (targetSlot == -1) return; - - SoundSample.PLOP.play(player); - - ItemStack targetItem = player.getInventory().getItem(targetSlot); - if (targetItem == null) return; - Tuple tuple = generateMissingItemsInventory(targetItem); - - Tuple inventoryTuple = new Tuple<>(tuple.getFirst(), menuClickInfo -> { - InventoryUtils.giveItem(player, targetItem); - inventories.remove(player.getUniqueId()); - onFinish.accept(null); - if (menuClickInfo.getSlot() == tuple.getSecond()) { - SoundSample.LEVEL_UP.play(player); - player.closeInventory(); - } else { - player.closeInventory(); - kill(player); - } - }); - inventories.put(player.getUniqueId(), inventoryTuple); - - player.getInventory().setItem(targetSlot, null); - - sendInfoText(player); - - } - - private void sendInfoText(@Nonnull Player player) { - String message = Message.forName("missing-items-inventory").asString("§7"); - String openMessage = Message.forName("missing-items-inventory-open").asString(); - - TextComponent messageComponent = new TextComponent(Prefix.CHALLENGES + message + " "); - - TextComponent clickComponent = new TextComponent(openMessage); - clickComponent.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/openmissingitems")); - clickComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Collections.singletonList(new TextComponent("§2§l✔ §8┃ §7" + Message.forName("open").asString())).toArray(new BaseComponent[0]))); - - messageComponent.addExtra(clickComponent); - player.spigot().sendMessage(messageComponent); - } + @Override + protected void onDisable() { + materials = null; + } + + @Override + protected void onTimeActivation() { + broadcastFiltered(this::startGuessingGame); + + if (inventories.isEmpty()) { + restartTimer(); + } + + } + + private void startGuessingGame(@Nonnull Player player) { + + BukkitTask task = new BukkitRunnable() { + + int timeLeft = (int) (2.5 * 60); + + @Override + public void run() { + timeLeft--; + + if (!inventories.containsKey(player.getUniqueId())) { + cancel(); + return; + } + + if (timeLeft == 0) { + cancel(); + Tuple tuple = inventories.remove(player.getUniqueId()); + tuple.getSecond().handleClick(new MenuClickInfo(player, tuple.getFirst(), false, false, 1000)); + } else if (timeLeft <= 5) { + new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F, (float) (timeLeft - 1) / 10 + 1).play(player); + } + + } + + }.runTaskTimer(plugin, 20, 20); + + createMissingItemsInventory(player, unused -> { + if (!anyRunningGame()) { + inventories.clear(); + restartTimer(); + } + task.cancel(); + }); + + } + + private void createMissingItemsInventory(@Nonnull Player player, Consumer onFinish) { + + int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); + if (targetSlot == -1) return; + + SoundSample.PLOP.play(player); + + ItemStack targetItem = player.getInventory().getItem(targetSlot); + if (targetItem == null) return; + Tuple tuple = generateMissingItemsInventory(targetItem); + + Tuple inventoryTuple = new Tuple<>(tuple.getFirst(), menuClickInfo -> { + InventoryUtils.giveItem(player, targetItem); + inventories.remove(player.getUniqueId()); + onFinish.accept(null); + if (menuClickInfo.getSlot() == tuple.getSecond()) { + SoundSample.LEVEL_UP.play(player); + player.closeInventory(); + } else { + player.closeInventory(); + kill(player); + } + }); + inventories.put(player.getUniqueId(), inventoryTuple); + + player.getInventory().setItem(targetSlot, null); + + sendInfoText(player); + + } + + private void sendInfoText(@Nonnull Player player) { + String message = Message.forName("missing-items-inventory").asString("§7"); + String openMessage = Message.forName("missing-items-inventory-open").asString(); + + TextComponent messageComponent = new TextComponent(Prefix.CHALLENGES + message + " "); + + TextComponent clickComponent = new TextComponent(openMessage); + clickComponent.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/openmissingitems")); + clickComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Collections.singletonList(new TextComponent("§2§l✔ §8┃ §7" + Message.forName("open").asString())).toArray(new BaseComponent[0]))); + + messageComponent.addExtra(clickComponent); + player.spigot().sendMessage(messageComponent); + } - private boolean openGameInventory(@Nonnull Player player) { - Tuple inventoryTuple = inventories.get(player.getUniqueId()); - if (inventoryTuple == null) return false; - player.openInventory(inventoryTuple.getFirst()); - MenuPosition.set(player, inventoryTuple.getSecond()); - return true; - } + private boolean openGameInventory(@Nonnull Player player) { + Tuple inventoryTuple = inventories.get(player.getUniqueId()); + if (inventoryTuple == null) return false; + player.openInventory(inventoryTuple.getFirst()); + MenuPosition.set(player, inventoryTuple.getSecond()); + return true; + } - private Tuple generateMissingItemsInventory(@Nonnull ItemStack itemStack) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); + private Tuple generateMissingItemsInventory(@Nonnull ItemStack itemStack) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); - int targetSlot = globalRandom.nextInt(inventory.getSize()); - inventory.setItem(targetSlot, itemStack); + int targetSlot = globalRandom.nextInt(inventory.getSize()); + inventory.setItem(targetSlot, itemStack); - for (int slot = 0; slot < inventory.getSize(); slot++) { - if (slot == targetSlot) continue; - try { - inventory.setItem(slot, getRandomItem(itemStack)); - } catch (Exception exception) { - inventory.setItem(slot, new ItemStack(Material.BARRIER)); - Challenges.getInstance().getLogger().error("", exception); - } - - } - - return new Tuple<>(inventory, targetSlot); - } - - private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { - if (materials == null) onEnable(); - - Material material = globalRandom.choose(materials); - ItemStack itemStack = new ItemStack(material); - - if (itemStack.getItemMeta() instanceof Damageable && 1 < material.getMaxDurability()) { - ((Damageable) itemStack.getItemMeta()).setDamage(globalRandom.range(1, material.getMaxDurability())); - } else if (1 < itemStack.getMaxStackSize() && globalRandom.nextInt(100) <= 20) { - itemStack.setAmount(globalRandom.range(1, itemStack.getMaxStackSize())); - } + for (int slot = 0; slot < inventory.getSize(); slot++) { + if (slot == targetSlot) continue; + try { + inventory.setItem(slot, getRandomItem(itemStack)); + } catch (Exception exception) { + inventory.setItem(slot, new ItemStack(Material.BARRIER)); + Challenges.getInstance().getILogger().error("", exception); + } + + } + + return new Tuple<>(inventory, targetSlot); + } + + private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { + if (materials == null) onEnable(); + + Material material = globalRandom.choose(materials); + ItemStack itemStack = new ItemStack(material); + + if (itemStack.getItemMeta() instanceof Damageable && 1 < material.getMaxDurability()) { + ((Damageable) itemStack.getItemMeta()).setDamage(globalRandom.range(1, material.getMaxDurability())); + } else if (1 < itemStack.getMaxStackSize() && globalRandom.nextInt(100) <= 20) { + itemStack.setAmount(globalRandom.range(1, itemStack.getMaxStackSize())); + } - if (itemStack.isSimilar(blacklisted) && itemStack.getAmount() == blacklisted.getAmount()) { - return getRandomItem(blacklisted); - } - - return itemStack; - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (openGameInventory(player)) { - SoundSample.OPEN.play(player); - } else { - SoundSample.BASS_OFF.play(player); - } - } - - private boolean anyRunningGame() { - return inventories.keySet().stream().anyMatch(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline()); - } - -} \ No newline at end of file + if (itemStack.isSimilar(blacklisted) && itemStack.getAmount() == blacklisted.getAmount()) { + return getRandomItem(blacklisted); + } + + return itemStack; + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (openGameInventory(player)) { + SoundSample.OPEN.play(player); + } else { + SoundSample.BASS_OFF.play(player); + } + } + + private boolean anyRunningGame() { + return inventories.keySet().stream().anyMatch(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index ac95eb420..3a9dbd54e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -17,54 +17,53 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MovementItemRemovingChallenge extends SettingModifier { - public static final int BLOCK = 1; + public static final int BLOCK = 1; - public MovementItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 2, 2); - setCategory(SettingCategory.INVENTORY); - } + public MovementItemRemovingChallenge() { + super(MenuType.CHALLENGES, 1, 2, 2); + setCategory(SettingCategory.INVENTORY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == BLOCK) return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); - return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!isEnabled()) return DefaultItem.disabled(); + if (getValue() == BLOCK) + return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); + return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + } - @Override - public void playValueChangeTitle() { - if (getValue() == BLOCK) ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); - else ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); - } + @Override + public void playValueChangeTitle() { + if (getValue() == BLOCK) + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); + else + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; - if (getValue() == BLOCK) { - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - } else { - if (BlockUtils.isSameChunk(event.getFrom().getChunk(), event.getTo().getChunk())) - return; - } + if (getValue() == BLOCK) { + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + } else { + if (BlockUtils.isSameChunk(event.getFrom().getChunk(), event.getTo().getChunk())) + return; + } - InventoryUtils.removeRandomItem(event.getPlayer().getInventory()); - } + InventoryUtils.removeRandomItem(event.getPlayer().getInventory()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 51da623b2..fe6b3f63c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -28,90 +28,86 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") @CanInstaKillOnEnable public class NoDupedItemsChallenge extends Setting { - public NoDupedItemsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkInventories(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkInventories(); - }, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedBlock() == null) return; - checkInventories(); - } - - private void checkInventories() { - Map> blackList = new HashMap<>(); - - for (Player player : Bukkit.getOnlinePlayers()) { - Triple result = checkInventory(player, blackList); - if (result != null) { - Message.forName("no-duped-items-failed").broadcast( - Prefix.CHALLENGES, - NameHelper.getName(result.getFirst()), - NameHelper.getName(result.getSecond()), - result.getThird() - ); - ChallengeHelper.kill(result.getFirst()); - ChallengeHelper.kill(result.getSecond()); - } - - } - - } - - private Triple checkInventory(@Nonnull Player player, Map> blacklist) { - List localBlacklist = new ArrayList<>(); - List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); - blacklist.put(player, playerBlacklist); - - for (ItemStack item : player.getInventory().getContents()) { - if (item == null) continue; - if (localBlacklist.contains(item.getType())) continue; - localBlacklist.add(item.getType()); - - for (Entry> entry : blacklist.entrySet()) { - List currentBlacklist = entry.getValue(); - if (currentBlacklist.contains(item.getType())) { - return new Triple<>(player, entry.getKey(), item.getType()); - } - - } - playerBlacklist.add(item.getType()); - } - - return null; - } - -} \ No newline at end of file + public NoDupedItemsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.INVENTORY); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkInventories(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkInventories(); + }, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedBlock() == null) return; + checkInventories(); + } + + private void checkInventories() { + Map> blackList = new HashMap<>(); + + for (Player player : Bukkit.getOnlinePlayers()) { + Triple result = checkInventory(player, blackList); + if (result != null) { + Message.forName("no-duped-items-failed").broadcast( + Prefix.CHALLENGES, + NameHelper.getName(result.getFirst()), + NameHelper.getName(result.getSecond()), + result.getThird() + ); + ChallengeHelper.kill(result.getFirst()); + ChallengeHelper.kill(result.getSecond()); + } + + } + + } + + private Triple checkInventory(@Nonnull Player player, Map> blacklist) { + List localBlacklist = new ArrayList<>(); + List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); + blacklist.put(player, playerBlacklist); + + for (ItemStack item : player.getInventory().getContents()) { + if (item == null) continue; + if (localBlacklist.contains(item.getType())) continue; + localBlacklist.add(item.getType()); + + for (Entry> entry : blacklist.entrySet()) { + List currentBlacklist = entry.getValue(); + if (currentBlacklist.contains(item.getType())) { + return new Triple<>(player, entry.getKey(), item.getType()); + } + + } + playerBlacklist.add(item.getType()); + } + + return null; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 23db0cc55..6b86b70af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -18,47 +18,43 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class PermanentItemChallenge extends Setting { - public PermanentItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - Inventory clickedInventory = event.getClickedInventory(); - if (event.getCursor() == null) return; - if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); - if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.PLAYER) { - if (event.getInventory().getType() != InventoryType.PLAYER) { - event.setCancelled(true); - } - } - - } - - @EventHandler - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - event.setCancelled(true); - } - -} \ No newline at end of file + public PermanentItemChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.INVENTORY); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + Inventory clickedInventory = event.getClickedInventory(); + if (event.getCursor() == null) return; + if (clickedInventory == null) return; + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.PLAYER) { + if (event.getInventory().getType() != InventoryType.PLAYER) { + event.setCancelled(true); + } + } + + } + + @EventHandler + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + event.setCancelled(true); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index bc6adbf8f..486f05d40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,43 +18,39 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class PickupItemLaunchChallenge extends SettingModifier { - public PickupItemLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); - setCategory(SettingCategory.INVENTORY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-pickup-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickUpItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Vector velocityToAdd = new Vector(0, getValue() / 2, 0); - Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); - event.getPlayer().setVelocity(newVelocity); - } + public PickupItemLaunchChallenge() { + super(MenuType.CHALLENGES, 1, 10, 2); + setCategory(SettingCategory.INVENTORY); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-pickup-launch-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-launcher-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerPickUpItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Vector velocityToAdd = new Vector(0, getValue() / 2, 0); + Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); + event.getPlayer().setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index ed181731a..7c3ddab89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -17,128 +17,125 @@ import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import java.util.Objects; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class UncraftItemsChallenge extends TimedChallenge { - public UncraftItemsChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.INVENTORY); - } + public UncraftItemsChallenge() { + super(MenuType.CHALLENGES, 5, 60, 20); + setCategory(SettingCategory.INVENTORY); + } - public static void uncraftInventory(@Nonnull Player player) { - - PlayerInventory inventory = player.getInventory(); + public static void uncraftInventory(@Nonnull Player player) { + + PlayerInventory inventory = player.getInventory(); - List itemsToAdd = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getContents().length; slot++) { - ItemStack item = inventory.getItem(slot); - if (item == null) continue; - List recipes = Bukkit.getRecipesFor(new ItemStack(item.getType())); - if (recipes.isEmpty()) continue; + List itemsToAdd = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getContents().length; slot++) { + ItemStack item = inventory.getItem(slot); + if (item == null) continue; + List recipes = Bukkit.getRecipesFor(new ItemStack(item.getType())); + if (recipes.isEmpty()) continue; - Recipe recipe = null; - for (Recipe currentRecipe : recipes) { + Recipe recipe = null; + for (Recipe currentRecipe : recipes) { - if (canCraft(recipes, item.getType())) { - continue; - } + if (canCraft(recipes, item.getType())) { + continue; + } - recipe = currentRecipe; - } + recipe = currentRecipe; + } - if (recipe == null) continue; + if (recipe == null) continue; - ItemStack[] ingredients = getIngredientsOfRecipe(recipe).toArray(new ItemStack[0]); + ItemStack[] ingredients = getIngredientsOfRecipe(recipe).toArray(new ItemStack[0]); - for (int i = 0; i < item.getAmount() / recipe.getResult().getAmount(); i++) { - for (ItemStack ingredient : ingredients) { - if (ingredient == null) { - continue; - } - itemsToAdd.add(ingredient); - } - } - inventory.setItem(slot, null); - } + for (int i = 0; i < item.getAmount() / recipe.getResult().getAmount(); i++) { + for (ItemStack ingredient : ingredients) { + if (ingredient == null) { + continue; + } + itemsToAdd.add(ingredient); + } + } + inventory.setItem(slot, null); + } - itemsToAdd.forEach(itemStack -> InventoryUtils.giveItem(player, itemStack)); + itemsToAdd.forEach(itemStack -> InventoryUtils.giveItem(player, itemStack)); - } + } - private static boolean canCraft(List recipes, Material material) { + private static boolean canCraft(List recipes, Material material) { - for (Recipe recipe : recipes) { - for (ItemStack ingredient : getIngredientsOfRecipe(recipe)) { - if (ingredient == null) continue; + for (Recipe recipe : recipes) { + for (ItemStack ingredient : getIngredientsOfRecipe(recipe)) { + if (ingredient == null) continue; - List ingredientRecipes = Bukkit.getRecipesFor(ingredient); + List ingredientRecipes = Bukkit.getRecipesFor(ingredient); - for (Recipe ingredientRecipe : ingredientRecipes) { - for (ItemStack itemStack : getIngredientsOfRecipe(ingredientRecipe)) { - if (itemStack == null) continue; - if (itemStack.getType() == material) { - return true; - } + for (Recipe ingredientRecipe : ingredientRecipes) { + for (ItemStack itemStack : getIngredientsOfRecipe(ingredientRecipe)) { + if (itemStack == null) continue; + if (itemStack.getType() == material) { + return true; + } - } + } - } + } - } - } - return false; - } + } + } + return false; + } - private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { - List ingredients = new ArrayList<>(); - if (recipe instanceof ShapedRecipe) { - ShapedRecipe shaped = (ShapedRecipe) recipe; - ingredients.addAll(shaped.getIngredientMap().values()); - } else if (recipe instanceof ShapelessRecipe) { - ShapelessRecipe shapeless = (ShapelessRecipe) recipe; - ingredients.addAll(shapeless.getIngredientList()); - } else if (recipe instanceof FurnaceRecipe) { - FurnaceRecipe furnace = (FurnaceRecipe) recipe; - ingredients.add(furnace.getInput()); - } else if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14) && recipe instanceof SmithingRecipe) { - SmithingRecipe smithing = (SmithingRecipe) recipe; - ingredients.add(smithing.getBase().getItemStack()); - ingredients.add(smithing.getAddition().getItemStack()); - } + private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { + List ingredients = new ArrayList<>(); + if (recipe instanceof ShapedRecipe) { + ShapedRecipe shaped = (ShapedRecipe) recipe; + ingredients.addAll(shaped.getIngredientMap().values()); + } else if (recipe instanceof ShapelessRecipe) { + ShapelessRecipe shapeless = (ShapelessRecipe) recipe; + ingredients.addAll(shapeless.getIngredientList()); + } else if (recipe instanceof FurnaceRecipe) { + FurnaceRecipe furnace = (FurnaceRecipe) recipe; + ingredients.add(furnace.getInput()); + } else if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14) && recipe instanceof SmithingRecipe) { + SmithingRecipe smithing = (SmithingRecipe) recipe; + ingredients.add(Objects.requireNonNull(smithing.getBase()).getItemStack()); + ingredients.add(Objects.requireNonNull(smithing.getAddition()).getItemStack()); + } - return ingredients; - } + return ingredients; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } - @Override - protected void onTimeActivation() { - restartTimer(); - - broadcastFiltered(UncraftItemsChallenge::uncraftInventory); - - } + @Override + protected void onTimeActivation() { + restartTimer(); + + broadcastFiltered(UncraftItemsChallenge::uncraftInventory); + + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 7eb4622a2..899c446cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -20,63 +20,59 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { - public EnderGamesChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - } + public EnderGamesChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } - @Override - protected void onTimeActivation() { - restartTimer(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - teleportRandom(player); - } - SoundSample.TELEPORT.broadcast(); - } + @Override + protected void onTimeActivation() { + restartTimer(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + teleportRandom(player); + } + SoundSample.TELEPORT.broadcast(); + } - private void teleportRandom(@Nonnull Player player) { + private void teleportRandom(@Nonnull Player player) { - List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() - .filter(entity -> !(entity instanceof Player)) - .filter(entity -> entity instanceof LivingEntity) - .collect(Collectors.toList()); + List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() + .filter(entity -> !(entity instanceof Player)) + .filter(entity -> entity instanceof LivingEntity) + .collect(Collectors.toList()); - Entity targetEntity = list.get(globalRandom.nextInt(list.size())); + Entity targetEntity = list.get(globalRandom.nextInt(list.size())); - Location playerLocation = player.getLocation().clone(); - player.teleport(targetEntity.getLocation()); - Message.forName("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); - targetEntity.teleport(playerLocation); + Location playerLocation = player.getLocation().clone(); + player.teleport(targetEntity.getLocation()); + Message.forName("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); + targetEntity.teleport(playerLocation); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index ed708272d..d43893978 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -17,42 +17,38 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class FoodLaunchChallenge extends SettingModifier { - public FoodLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-consume-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Vector velocityToAdd = new Vector(0, getValue() / 2, 0); - Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); - event.getPlayer().setVelocity(newVelocity); - } + public FoodLaunchChallenge() { + super(MenuType.CHALLENGES, 1, 10, 2); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAKE, Message.forName("item-consume-launch-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-launcher-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Vector velocityToAdd = new Vector(0, getValue() / 2, 0); + Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); + event.getPlayer().setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index b657d8573..cf3a29206 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -17,95 +17,91 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FoodOnceChallenge extends SettingModifier { - public FoodOnceChallenge() { - super(MenuType.CHALLENGES, 2); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - case 1: - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); - case 2: - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); - default: - return super.createSettingsItem(); - } - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Material type = event.getItem().getType(); - if (hasEaten(event.getPlayer(), type)) { - Message.forName("food-once-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - ChallengeHelper.kill(event.getPlayer(), 1); - } else { - addFood(event.getPlayer(), type); - if (teamFoodsActivated()) { - Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - } else { - Message.forName("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - - } - } - - } - - private void addFood(Player player, Material type) { - if (teamFoodsActivated()) { - addTeamFood(type); - } else { - addPlayerFood(player, type); - } - } - - private void addPlayerFood(@Nonnull Player player, @Nonnull Material material) { - List foods = getPlayerData(player).getEnumList("foods", Material.class); - foods.add(material); - getPlayerData(player).set("foods", foods); - } - - private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { - if (teamFoodsActivated()) { - return hasBeenEatenByTeam(material); - } - - return getPlayerData(player).getEnumList("foods", Material.class).contains(material); - } - - private void addTeamFood(@Nonnull Material material) { - List foods = getGameStateData().getEnumList("foods", Material.class); - foods.add(material); - getGameStateData().set("foods", foods); - } - - private boolean hasBeenEatenByTeam(@Nonnull Material material) { - return getGameStateData().getEnumList("foods", Material.class).contains(material); - } - - private boolean teamFoodsActivated() { - return getValue() == 2; - } - -} \ No newline at end of file + public FoodOnceChallenge() { + super(MenuType.CHALLENGES, 2); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + case 1: + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); + case 2: + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); + default: + return super.createSettingsItem(); + } + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Material type = event.getItem().getType(); + if (hasEaten(event.getPlayer(), type)) { + Message.forName("food-once-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + ChallengeHelper.kill(event.getPlayer(), 1); + } else { + addFood(event.getPlayer(), type); + if (teamFoodsActivated()) { + Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + } else { + Message.forName("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + + } + } + + } + + private void addFood(Player player, Material type) { + if (teamFoodsActivated()) { + addTeamFood(type); + } else { + addPlayerFood(player, type); + } + } + + private void addPlayerFood(@Nonnull Player player, @Nonnull Material material) { + List foods = getPlayerData(player).getEnumList("foods", Material.class); + foods.add(material); + getPlayerData(player).set("foods", foods); + } + + private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { + if (teamFoodsActivated()) { + return hasBeenEatenByTeam(material); + } + + return getPlayerData(player).getEnumList("foods", Material.class).contains(material); + } + + private void addTeamFood(@Nonnull Material material) { + List foods = getGameStateData().getEnumList("foods", Material.class); + foods.add(material); + getGameStateData().set("foods", foods); + } + + private boolean hasBeenEatenByTeam(@Nonnull Material material) { + return getGameStateData().getEnumList("foods", Material.class).contains(material); + } + + private boolean teamFoodsActivated() { + return getValue() == 2; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 99f3f1429..5c22246d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -16,58 +16,54 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class InvertHealthChallenge extends TimedChallenge { - public InvertHealthChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - } + public InvertHealthChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + } - public static void invertHealth(Player player) { - double health = player.getMaxHealth() - player.getHealth(); - if (health <= 0) { - ChallengeHelper.kill(player); - return; - } - player.setHealth(health); - } + public static void invertHealth(Player player) { + double health = player.getMaxHealth() - player.getHealth(); + if (health <= 0) { + ChallengeHelper.kill(player); + return; + } + player.setHealth(health); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } - @Override - protected void onTimeActivation() { - SoundSample.PLOP.broadcast(); - Message.forName("health-inverted").broadcast(Prefix.CHALLENGES); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - invertHealth(player); - } - restartTimer(); - } + @Override + protected void onTimeActivation() { + SoundSample.PLOP.broadcast(); + Message.forName("health-inverted").broadcast(Prefix.CHALLENGES); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + invertHealth(player); + } + restartTimer(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 9eba3fa27..5cf2c4414 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -16,55 +16,51 @@ import java.util.Arrays; import java.util.Random; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class LowDropRateChallenge extends SettingModifier { - private final Random random = new Random(); + private final Random random = new Random(); - public LowDropRateChallenge() { - super(MenuType.CHALLENGES, 9); - } + public LowDropRateChallenge() { + super(MenuType.CHALLENGES, 9); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-chance-description").asArray(getValue() * 10); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-chance-description").asArray(getValue() * 10); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() * 10 + "%"); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() * 10 + "%"); + } - @Override - protected void onValueChange() { - reloadChances(); - } + @Override + protected void onValueChange() { + reloadChances(); + } - @Override - protected void onEnable() { - reloadChances(); - } + @Override + protected void onEnable() { + reloadChances(); + } - @Override - protected void onDisable() { - Challenges.getInstance().getBlockDropManager().resetDropChance(DropPriority.CHANCE); - } + @Override + protected void onDisable() { + Challenges.getInstance().getBlockDropManager().resetDropChance(DropPriority.CHANCE); + } - protected void reloadChances() { - Arrays.stream(ExperimentalUtils.getMaterials()).filter(Material::isBlock).forEach(block -> { - Challenges.getInstance().getBlockDropManager().setDropChance(block, DropPriority.CHANCE, () -> random.nextInt(10) < getValue()); - }); - } + protected void reloadChances() { + Arrays.stream(ExperimentalUtils.getMaterials()).filter(Material::isBlock).forEach(block -> { + Challenges.getInstance().getBlockDropManager().setDropChance(block, DropPriority.CHANCE, () -> random.nextInt(10) < getValue()); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index b0e4086e0..60597c942 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -14,29 +14,25 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoExpChallenge extends Setting { - public NoExpChallenge() { - super(MenuType.CHALLENGES); - } + public NoExpChallenge() { + super(MenuType.CHALLENGES); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExp(PlayerExpChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAmount() <= 0) return; - Message.forName("exp-picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeHelper.kill(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExp(PlayerExpChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAmount() <= 0) return; + Message.forName("exp-picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeHelper.kill(event.getPlayer()); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index f85c099b0..188c7dbb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,57 +18,54 @@ import java.util.LinkedList; import java.util.List; +import java.util.Objects; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ @Since("2.2.0") public class NoSharedAdvancementsChallenge extends Setting { - private final List advancementsDone = new LinkedList<>(); + private final List advancementsDone = new LinkedList<>(); - public NoSharedAdvancementsChallenge() { - super(MenuType.CHALLENGES); - } + public NoSharedAdvancementsChallenge() { + super(MenuType.CHALLENGES); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-no-shared-advancements-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-no-shared-advancements-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onAdvancementDone(PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - if (advancementsDone.contains(event.getAdvancement())) { - ChallengeHelper.kill(event.getPlayer()); - } else { - advancementsDone.add(event.getAdvancement()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onAdvancementDone(PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + if (advancementsDone.contains(event.getAdvancement())) { + ChallengeHelper.kill(event.getPlayer()); + } else { + advancementsDone.add(event.getAdvancement()); + } + } - @Override - public void loadGameState(@NotNull Document document) { - advancementsDone.clear(); - List advancementKeys = document.getStringList("advancements"); - for (String advancementKey : advancementKeys) { - try { - advancementsDone.add(Bukkit.getAdvancement(BukkitReflectionUtils.fromString(advancementKey))); - } catch (Exception exception) { - // DON'T EXIST - } - } - } + @Override + public void loadGameState(@NotNull Document document) { + advancementsDone.clear(); + List advancementKeys = document.getStringList("advancements"); + for (String advancementKey : advancementKeys) { + try { + advancementsDone.add(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey)))); + } catch (Exception exception) { + // DON'T EXIST + } + } + } - @Override - public void writeGameState(@NotNull Document document) { - List foundItems = new LinkedList<>(); - for (Advancement advancement : advancementsDone) { - foundItems.add(advancement.getKey().toString()); - } - document.set("advancements", foundItems); - } + @Override + public void writeGameState(@NotNull Document document) { + List foundItems = new LinkedList<>(); + for (Advancement advancement : advancementsDone) { + foundItems.add(advancement.getKey().toString()); + } + document.set("advancements", foundItems); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index fe5d0aaa4..aaf281b19 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -14,40 +14,36 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoTradingChallenge extends Setting { - public NoTradingChallenge() { - super(MenuType.CHALLENGES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getRightClicked() instanceof Villager) { - event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_NO, 1F, 1F); - event.setCancelled(true); - } else if (event.getRightClicked().getType().name().equals("PIGLIN")) { - event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_PIGLIN_ADMIRING_ITEM, 1F, 1F); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntityType().name().equals("PIGLIN")) { - event.setCancelled(true); - } - } - -} \ No newline at end of file + public NoTradingChallenge() { + super(MenuType.CHALLENGES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getRightClicked() instanceof Villager) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_NO, 1F, 1F); + event.setCancelled(true); + } else if (event.getRightClicked().getType().name().equals("PIGLIN")) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_PIGLIN_ADMIRING_ITEM, 1F, 1F); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntityType().name().equals("PIGLIN")) { + event.setCancelled(true); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index 270c344d5..e2783a952 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -17,56 +17,52 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class OneDurabilityChallenge extends Setting { - public OneDurabilityChallenge() { - super(MenuType.CHALLENGES); - } + public OneDurabilityChallenge() { + super(MenuType.CHALLENGES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getWhoClicked() instanceof Player && ignorePlayer((Player) event.getWhoClicked())) - return; - if (event.getCurrentItem() != null) setDurability(event.getCurrentItem()); - if (event.getCursor() != null) setDurability(event.getCursor()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getWhoClicked() instanceof Player && ignorePlayer((Player) event.getWhoClicked())) + return; + if (event.getCurrentItem() != null) setDurability(event.getCurrentItem()); + if (event.getCursor() != null) setDurability(event.getCursor()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getItem() == null) return; - setDurability(event.getItem()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getItem() == null) return; + setDurability(event.getItem()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(EntityPickupItemEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - setDurability(event.getItem().getItemStack()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + setDurability(event.getItem().getItemStack()); + } - private void setDurability(@Nonnull ItemStack item) { - ItemMeta meta = item.getItemMeta(); - if (meta instanceof Damageable) { - meta.setUnbreakable(false); - int durability = item.getType().getMaxDurability() - 1; - ((Damageable) meta).setDamage(durability); - item.setItemMeta(meta); - } - } + private void setDurability(@Nonnull ItemStack item) { + ItemMeta meta = item.getItemMeta(); + if (meta instanceof Damageable) { + meta.setUnbreakable(false); + int durability = item.getType().getMaxDurability() - 1; + ((Damageable) meta).setDamage(durability); + item.setItemMeta(meta); + } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index ec9da640e..5f2beb3a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -14,51 +14,47 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class AlwaysRunningChallenge extends Setting { - public AlwaysRunningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); - } - - @ScheduledTask(ticks = 1) - public void setVelocity() { - broadcastFiltered(player -> { - if (player.isSprinting()) return; - - Location location = player.getLocation(); - Vector velocity = new Vector(); - - double rotX = location.getYaw(); - double xz = Math.cos(Math.toRadians(0)); - velocity.setX(-xz * Math.sin(Math.toRadians(rotX))); - velocity.setZ(xz * Math.cos(Math.toRadians(rotX))); - velocity.multiply(0.5); - - if (player.isSneaking()) - velocity.multiply(0.5); - else if (BukkitReflectionUtils.isInWater(player)) - velocity.multiply(0.5); - else if (!player.isOnGround()) - velocity.multiply(0.85); - - Vector oldVelocity = player.getVelocity(); - if (oldVelocity.getY() > 0) - oldVelocity.multiply(0.9); - velocity.setY(oldVelocity.getY()); - player.setVelocity(velocity); - }); - } + public AlwaysRunningChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); + } + + @ScheduledTask(ticks = 1) + public void setVelocity() { + broadcastFiltered(player -> { + if (player.isSprinting()) return; + + Location location = player.getLocation(); + Vector velocity = new Vector(); + + double rotX = location.getYaw(); + double xz = Math.cos(Math.toRadians(0)); + velocity.setX(-xz * Math.sin(Math.toRadians(rotX))); + velocity.setZ(xz * Math.cos(Math.toRadians(rotX))); + velocity.multiply(0.5); + + if (player.isSneaking()) + velocity.multiply(0.5); + else if (BukkitReflectionUtils.isInWater(player)) + velocity.multiply(0.5); + else if (!player.isOnGround()) + velocity.multiply(0.85); + + Vector oldVelocity = player.getVelocity(); + if (oldVelocity.getY() > 0) + oldVelocity.multiply(0.9); + velocity.setY(oldVelocity.getY()); + player.setVelocity(velocity); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 4e9ab9141..c56645114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -21,87 +21,83 @@ import java.util.HashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class DontStopRunningChallenge extends SettingModifier { - private static final int YELLOW = 5, RED = 3; - - private final Map playerStandingCount = new HashMap<>(); - - public DontStopRunningChallenge() { - super(MenuType.CHALLENGES, 3, 30, 10); - setCategory(SettingCategory.MOVEMENT); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int count = playerStandingCount.getOrDefault(player, 1); - int timeLeft = getValue() - count + 1; - - if (timeLeft <= RED) bossbar.setColor(BarColor.RED); - else if (timeLeft <= YELLOW) bossbar.setColor(BarColor.YELLOW); - else bossbar.setColor(BarColor.GREEN); - - String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); - - bossbar.setTitle(Message.forName("bossbar-dont-stop-running").asString(time)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - removeOfflinePlayers(); - countUpOrKillEveryone(); - bossbar.update(); - } - - private void removeOfflinePlayers() { - for (Player player : new ArrayList<>(playerStandingCount.keySet())) { - if (!player.isOnline() || ignorePlayer(player)) playerStandingCount.remove(player); - } - } - - private void countUpOrKillEveryone() { - - broadcastFiltered(player -> { - Integer count = playerStandingCount.getOrDefault(player, 0); - if (count >= getValue()) { - Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - playerStandingCount.remove(player); - kill(player); - return; - } - playerStandingCount.put(player, count + 1); - - }); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getX() == event.getTo().getX() && event.getFrom().getZ() == event.getTo().getZ() && event.getFrom().getY() == event.getTo().getY()) - return; - playerStandingCount.remove(event.getPlayer()); - } - -} \ No newline at end of file + private static final int YELLOW = 5, RED = 3; + + private final Map playerStandingCount = new HashMap<>(); + + public DontStopRunningChallenge() { + super(MenuType.CHALLENGES, 3, 30, 10); + setCategory(SettingCategory.MOVEMENT); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int count = playerStandingCount.getOrDefault(player, 1); + int timeLeft = getValue() - count + 1; + + if (timeLeft <= RED) bossbar.setColor(BarColor.RED); + else if (timeLeft <= YELLOW) bossbar.setColor(BarColor.YELLOW); + else bossbar.setColor(BarColor.GREEN); + + String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); + + bossbar.setTitle(Message.forName("bossbar-dont-stop-running").asString(time)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + removeOfflinePlayers(); + countUpOrKillEveryone(); + bossbar.update(); + } + + private void removeOfflinePlayers() { + for (Player player : new ArrayList<>(playerStandingCount.keySet())) { + if (!player.isOnline() || ignorePlayer(player)) playerStandingCount.remove(player); + } + } + + private void countUpOrKillEveryone() { + + broadcastFiltered(player -> { + Integer count = playerStandingCount.getOrDefault(player, 0); + if (count >= getValue()) { + Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + playerStandingCount.remove(player); + kill(player); + return; + } + playerStandingCount.put(player, count + 1); + + }); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getX() == event.getTo().getX() && event.getFrom().getZ() == event.getTo().getZ() && event.getFrom().getY() == event.getTo().getY()) + return; + playerStandingCount.remove(event.getPlayer()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index f4636b09c..25ec885dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -34,162 +34,158 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class FiveHundredBlocksChallenge extends SettingModifier { - private final Map blocksWalked = new HashMap<>(); - - public FiveHundredBlocksChallenge() { - super(MenuType.CHALLENGES, 1, 5, 5); - setCategory(SettingCategory.MOVEMENT); - - // Loot Generate Event was added in 1.15 - try { - Listener listener = new Listener() { - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLootGenerate(LootGenerateEvent event) { - if (!shouldExecuteEffect()) - return; - event.setLoot(new LinkedList<>()); - } - }; - - Challenges.getInstance().registerListener(listener); - } catch (NoClassDefFoundError noClassDefFoundError) { - Challenges.getInstance().getLogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); - } - - - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - int walked = blocksWalked.getOrDefault(player.getUniqueId(), 0); - bar.setTitle(Message.forName("bossbar-five-hundred-blocks").asString(walked, getBlocksToWalk())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MinecraftNameWrapper.SIGN, Message.forName("item-five-hundred-blocks-challenges")); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); - } - - private int getBlocksToWalk() { - return getValue() * 100; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - Player player = event.getPlayer(); - if (ignorePlayer(player)) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - - if (updateOrReset(player)) { - InventoryUtils.giveItem(player.getInventory(), player.getLocation(), InventoryUtils.getRandomItem(false, false)); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setDropItems(false); - event.setExpToDrop(0); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - event.getDrops().clear(); - event.setDroppedExp(0); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - /** - * @return if 500 blocks were reached - */ - private boolean updateOrReset(@Nonnull Player player) { - UUID uuid = player.getUniqueId(); - - int blocksWalked = this.blocksWalked.getOrDefault(uuid, 0); - - blocksWalked++; - - boolean reached = false; - if (blocksWalked >= getBlocksToWalk()) { - blocksWalked = 0; - reached = true; - } - - this.blocksWalked.put(uuid, blocksWalked); - - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - bossbar.update(player); - }); - return reached; - } - - @Override - public void loadGameState(@NotNull Document document) { - blocksWalked.clear(); - for (String key : document.keys()) { - try { - UUID uuid = UUID.fromString(key); - int blocks = document.getInt(key); - blocksWalked.put(uuid, blocks); - } catch (IllegalArgumentException exception) { - plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " - + "key '" + key + "' is not a valid uuid"); - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - @Override - public void writeGameState(@NotNull Document document) { - blocksWalked.forEach((uuid, integer) -> { - document.set(uuid.toString(), integer); - }); - } + private final Map blocksWalked = new HashMap<>(); + + public FiveHundredBlocksChallenge() { + super(MenuType.CHALLENGES, 1, 5, 5); + setCategory(SettingCategory.MOVEMENT); + + // Loot Generate Event was added in 1.15 + try { + Listener listener = new Listener() { + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLootGenerate(LootGenerateEvent event) { + if (!shouldExecuteEffect()) + return; + event.setLoot(new LinkedList<>()); + } + }; + + Challenges.getInstance().registerListener(listener); + } catch (NoClassDefFoundError noClassDefFoundError) { + Challenges.getInstance().getILogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); + } + + + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + int walked = blocksWalked.getOrDefault(player.getUniqueId(), 0); + bar.setTitle(Message.forName("bossbar-five-hundred-blocks").asString(walked, getBlocksToWalk())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(MinecraftNameWrapper.SIGN, Message.forName("item-five-hundred-blocks-challenges")); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); + } + + private int getBlocksToWalk() { + return getValue() * 100; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + Player player = event.getPlayer(); + if (ignorePlayer(player)) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + + if (updateOrReset(player)) { + InventoryUtils.giveItem(player.getInventory(), player.getLocation(), InventoryUtils.getRandomItem(false, false)); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setDropItems(false); + event.setExpToDrop(0); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDeath(EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + event.getDrops().clear(); + event.setDroppedExp(0); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + /** + * @return if 500 blocks were reached + */ + private boolean updateOrReset(@Nonnull Player player) { + UUID uuid = player.getUniqueId(); + + int blocksWalked = this.blocksWalked.getOrDefault(uuid, 0); + + blocksWalked++; + + boolean reached = false; + if (blocksWalked >= getBlocksToWalk()) { + blocksWalked = 0; + reached = true; + } + + this.blocksWalked.put(uuid, blocksWalked); + + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + bossbar.update(player); + }); + return reached; + } + + @Override + public void loadGameState(@NotNull Document document) { + blocksWalked.clear(); + for (String key : document.keys()) { + try { + UUID uuid = UUID.fromString(key); + int blocks = document.getInt(key); + blocksWalked.put(uuid, blocks); + } catch (IllegalArgumentException exception) { + plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " + + "key '" + key + "' is not a valid uuid"); + Challenges.getInstance().getILogger().error("", exception); + } + } + } + + @Override + public void writeGameState(@NotNull Document document) { + blocksWalked.forEach((uuid, integer) -> { + document.set(uuid.toString(), integer); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index cddb70054..0047eacc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -13,33 +13,29 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class HigherJumpsChallenge extends Setting { - public HigherJumpsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } + public HigherJumpsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); + } - @EventHandler(priority = EventPriority.NORMAL) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.NORMAL) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - int jumps = getPlayerData(event.getPlayer()).getInt("jumps") + 1; - getPlayerData(event.getPlayer()).set("jumps", jumps); + int jumps = getPlayerData(event.getPlayer()).getInt("jumps") + 1; + getPlayerData(event.getPlayer()).set("jumps", jumps); - float y = jumps / 7f; - event.getPlayer().setVelocity(new Vector().setY(y)); - } + float y = jumps / 7f; + event.getPlayer().setVelocity(new Vector().setY(y)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 7de505ec3..8b1b57f9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -14,31 +14,27 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class HungerPerBlockChallenge extends SettingModifier { - public HungerPerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 20, 2); - setCategory(SettingCategory.MOVEMENT); - } + public HungerPerBlockChallenge() { + super(MenuType.CHALLENGES, 1, 20, 2); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - int newFoodLevel = event.getPlayer().getFoodLevel() - getValue(); - event.getPlayer().setFoodLevel(Math.max(newFoodLevel, 0)); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + int newFoodLevel = event.getPlayer().getFoodLevel() - getValue(); + event.getPlayer().setFoodLevel(Math.max(newFoodLevel, 0)); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index faba24856..bc8eb2b81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -23,66 +23,62 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MoveMouseDamage extends SettingModifier { - private final Map> lastView = new HashMap<>(); + private final Map> lastView = new HashMap<>(); - public MoveMouseDamage() { - super(MenuType.CHALLENGES, 60); - setCategory(SettingCategory.MOVEMENT); - } + public MoveMouseDamage() { + super(MenuType.CHALLENGES, 60); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } - @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) - public void onTick() { - if (!shouldExecuteEffect()) { - lastView.clear(); - return; - } + @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) + public void onTick() { + if (!shouldExecuteEffect()) { + lastView.clear(); + return; + } - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) { - lastView.remove(player.getUniqueId()); - continue; - } - if (player.getNoDamageTicks() > 0) continue; + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) { + lastView.remove(player.getUniqueId()); + continue; + } + if (player.getNoDamageTicks() > 0) continue; - float yaw = player.getLocation().getYaw(); - float pitch = player.getLocation().getPitch(); - Entry pair = lastView.getOrDefault(player.getUniqueId(), new SimpleEntry<>(yaw, pitch)); - lastView.put(player.getUniqueId(), pair); + float yaw = player.getLocation().getYaw(); + float pitch = player.getLocation().getPitch(); + Entry pair = lastView.getOrDefault(player.getUniqueId(), new SimpleEntry<>(yaw, pitch)); + lastView.put(player.getUniqueId(), pair); - if (yaw != pair.getKey() || pitch != pair.getValue()) { - Bukkit.getScheduler().runTask(plugin, () -> { - if (player.getNoDamageTicks() > 0) return; - Message.forName("no-mouse-move-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - player.damage(getValue()); - player.setNoDamageTicks(5); - Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); - }); - } - } - } + if (yaw != pair.getKey() || pitch != pair.getValue()) { + Bukkit.getScheduler().runTask(plugin, () -> { + if (player.getNoDamageTicks() > 0) return; + Message.forName("no-mouse-move-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + player.damage(getValue()); + player.setNoDamageTicks(5); + Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); + }); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 481e9a674..779262f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -20,53 +20,49 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @CanInstaKillOnEnable public class OnlyDirtChallenge extends Setting { - public OnlyDirtChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } + public OnlyDirtChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemStack getSettingsItem() { - return super.getSettingsItem(); - } + @Nonnull + @Override + public ItemStack getSettingsItem() { + return super.getSettingsItem(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { - Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); - } + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { + Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + kill(event.getPlayer()); + } - } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { - if (!shouldExecuteEffect()) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + if (!shouldExecuteEffect()) return; - if (event.getNewState().getType() == Material.GRASS_BLOCK) { - event.setCancelled(true); - } + if (event.getNewState().getType() == Material.GRASS_BLOCK) { + event.setCancelled(true); + } - } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index a5128eb07..fb7817f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -15,32 +15,28 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class OnlyDownChallenge extends Setting { - public OnlyDownChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } + public OnlyDownChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); + } - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; - Message.forName("only-down-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeHelper.kill(event.getPlayer()); - } + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; + Message.forName("only-down-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeHelper.kill(event.getPlayer()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index c493342e1..7b3a20314 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -21,109 +21,105 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.3 - */ @Since("1.3") public class TrafficLightChallenge extends TimedChallenge { - private static final int GREEN = 0, YELLOW = 1, RED = 2; - - private int state; - - public TrafficLightChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.MOVEMENT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } - - @Override - public void onEnable() { - bossbar.setContent((bossbar, player) -> { - switch (state) { - case GREEN: - bossbar.setColor(BarColor.GREEN); - bossbar.setTitle("§8{ §a§l■■■ §8} §8{ §7§l■■■ §8} §8{ §7§l■■■ §8}"); - break; - case YELLOW: - bossbar.setColor(BarColor.YELLOW); - bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §e§l■■■ §8} §8{ §7§l■■■ §8}"); - break; - case RED: - bossbar.setColor(BarColor.RED); - bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §7§l■■■ §8} §8{ §c§l■■■ §8}"); - break; - } - }); - bossbar.show(); - } - - @Override - public void onDisable() { - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } - - @Override - protected void onTimeActivation() { - switch (state) { - case GREEN: - state = YELLOW; - restartTimer(2); - SoundSample.BASS_OFF.broadcast(); - bossbar.update(); - break; - case YELLOW: - state = RED; - restartTimer(3); - SoundSample.BASS_OFF.broadcast(); - bossbar.update(); - break; - case RED: - state = GREEN; - restartTimer(); - SoundSample.BASS_ON.broadcast(); - bossbar.update(); - break; - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (state != RED) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameLocation(event.getFrom(), event.getTo())) return; - - state = GREEN; - bossbar.update(); - restartTimer(); - - Player player = event.getPlayer(); - Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - kill(player); - } + private static final int GREEN = 0, YELLOW = 1, RED = 2; + + private int state; + + public TrafficLightChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5); + setCategory(SettingCategory.MOVEMENT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } + + @Override + public void onEnable() { + bossbar.setContent((bossbar, player) -> { + switch (state) { + case GREEN: + bossbar.setColor(BarColor.GREEN); + bossbar.setTitle("§8{ §a§l■■■ §8} §8{ §7§l■■■ §8} §8{ §7§l■■■ §8}"); + break; + case YELLOW: + bossbar.setColor(BarColor.YELLOW); + bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §e§l■■■ §8} §8{ §7§l■■■ §8}"); + break; + case RED: + bossbar.setColor(BarColor.RED); + bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §7§l■■■ §8} §8{ §c§l■■■ §8}"); + break; + } + }); + bossbar.show(); + } + + @Override + public void onDisable() { + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } + + @Override + protected void onTimeActivation() { + switch (state) { + case GREEN: + state = YELLOW; + restartTimer(2); + SoundSample.BASS_OFF.broadcast(); + bossbar.update(); + break; + case YELLOW: + state = RED; + restartTimer(3); + SoundSample.BASS_OFF.broadcast(); + bossbar.update(); + break; + case RED: + state = GREEN; + restartTimer(); + SoundSample.BASS_ON.broadcast(); + bossbar.update(); + break; + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (state != RED) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameLocation(event.getFrom(), event.getTo())) return; + + state = GREEN; + bossbar.update(); + restartTimer(); + + Player player = event.getPlayer(); + Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + kill(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java new file mode 100644 index 000000000..90b44a7e9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -0,0 +1,578 @@ +package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; +import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; +import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.challenges.plugin.utils.misc.TriFunction; +import org.bukkit.Material; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.boss.BarColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabCompleter { + + private static QuizChallenge instance; + + private final Prefix prefix = Prefix.forName("quiz", "§6Quiz"); + private final IRandom random = IRandom.create(); + + private IQuestion currentQuestion; + private Player currentQuestionedPlayer; + private int timeLeft; + + public QuizChallenge() { + super(MenuType.CHALLENGES, 1, 20, 5); + instance = this; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (currentQuestion == null) { + bossbar.setColor(BarColor.YELLOW); + bossbar.setTitle(Message.forName("bossbar-quiz-waiting").asString()); + return; + } + String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); + if (currentQuestionedPlayer != player) { + bossbar.setColor(BarColor.GREEN); + bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); + return; + } + bossbar.setColor(BarColor.RED); + bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return random.around(getValue() * 60 * 3, 60); + } + + private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { + broadcast(player1 -> { + if (currentQuestionedPlayer == player1) { + Message.forName(questionedPlayerMessage).send(player1, prefix, args); + } else { + Message.forName(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); + } + }); + } + + @Override + protected void onTimeActivation() { + + SavedStatistic[] statistics = SavedStatistic.values(); + SavedStatistic statistic = statistics[random.nextInt(statistics.length)]; + + IQuestion[] questions = statistic.getQuestions(); + currentQuestion = questions[random.nextInt(questions.length)]; + + List ingamePlayers = ChallengeHelper.getIngamePlayers(); + currentQuestionedPlayer = ingamePlayers.get(random.nextInt(ingamePlayers.size())); + + List answers = currentQuestion.createAnswers(statistic, currentQuestionedPlayer); + if (answers.isEmpty()) { + onTimeActivation(); + return; + } + Message.forName("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); + timeLeft = 60; + + bossbar.update(); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + if (currentQuestion == null) return; + if (!currentQuestionedPlayer.isOnline() || ignorePlayer(currentQuestionedPlayer)) { + Message.forName("quiz-cancel").broadcast(prefix); + cancelQuestion(); + } + + timeLeft--; + + if (timeLeft <= 0) { + Message.forName("quiz-time-up").broadcast(prefix); + cancelQuestion(); + } + + bossbar.update(); + } + + private void cancelQuestion() { + restartTimer(); + + List rightAnswers = currentQuestion.getRightAnswers(); + Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); + SoundSample.BREAK.play(currentQuestionedPlayer); + + currentQuestion = null; + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + if (attribute.getBaseValue() == 2) { + kill(currentQuestionedPlayer); + attribute.setBaseValue(20); + return; + } + + attribute.setBaseValue(attribute.getBaseValue() - 2); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (currentQuestion == null || currentQuestionedPlayer != player) { + // TODO: REMOVE RESTART TIMER HERE + restartTimer(3); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + Message.forName("syntax").send(player, prefix, "guess "); + return; + } + + String answer = StringUtils.getArrayAsString(args, " "); + if (!currentQuestion.isRightAnswer(answer)) { + broadcastMessage("quiz-wrong-answer", "quiz-wrong-answer-other", answer); + cancelQuestion(); + bossbar.update(); + return; + } + + broadcastMessage("quiz-right-answer", "quiz-right-answer-other", answer); + SoundSample.LEVEL_UP.play(player); + currentQuestion = null; + bossbar.update(); + restartTimer(); + } + + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String s, @Nonnull String[] strings) { + return new ArrayList<>(); + } + + interface IQuestion { + + List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player); + + List getRightAnswers(); + + boolean isRightAnswer(@Nonnull String answer); + + static void sendMessage(@Nonnull String question, @Nonnull List answers) { + Player player = instance.currentQuestionedPlayer; + + player.sendMessage(" "); + player.sendMessage("§e" + question); + player.sendMessage(" "); + + for (String answer : answers) { + player.sendMessage("§8-> §e" + answer); + } + + player.sendMessage(" "); + } + + class Question implements IQuestion { + + private final TriFunction, List> questionCreator; + private List currentRightAnswers; + + public Question(TriFunction, List> questionCreator) { + this.questionCreator = questionCreator; + } + + @Override + public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player) { + ArrayList answers = new ArrayList<>(); + currentRightAnswers = questionCreator.apply(statistic, player, answers); + return answers; + } + + @Override + public boolean isRightAnswer(@Nonnull String answer) { + if (currentRightAnswers == null) return false; + + for (String currentRightAnswer : currentRightAnswers) { + if (currentRightAnswer.equalsIgnoreCase(answer)) { + return true; + } + } + return false; + } + + @Override + public List getRightAnswers() { + return currentRightAnswers; + } + + } + + } + + private interface SavedStatistic { + + IntegerStatistic BLOCKS_MOVED = new IntegerStatistic("blocks-traveled", "traveled", "far", "be"); + IntegerStatistic JUMPED = new IntegerStatistic("jumped", "jumped", "often", "be"); + IntegerStatistic SNEAKED = new IntegerStatistic("sneaked", "sneaked", "often", "be"); + DocumentCountStatistic MOB_KILLED = new DocumentCountStatistic("mob-killed", "killed", "often", "have"); + DocumentCountStatistic MOB_DAMAGED = new DocumentCountStatistic("mobs-damaged", "damaged", "damage", "have"); + DocumentCountStatistic BLOCKS_PLACED = new DocumentCountStatistic("blocks-placed", "placed", "often", "have"); + DocumentCountStatistic BLOCKS_DESTROYED = new DocumentCountStatistic("blocks-destroyed", "broken", "often", "have"); + DocumentCountStatistic ITEMS_DROPPED = new DocumentCountStatistic("items-dropped", "dropped", "often", "have"); + DocumentCountStatistic DAMAGE_TAKEN = new DocumentCountStatistic("damage-taken", "suffered", "damage-taken", "have"); + + String getKey(); + + String getVerb(); + + String getQuestionVerb(); + + String getQuestionSuffix(); + + IQuestion[] getQuestions(); + + static SavedStatistic[] values() { + return new SavedStatistic[]{BLOCKS_MOVED, JUMPED, SNEAKED, MOB_DAMAGED, MOB_KILLED, BLOCKS_PLACED, BLOCKS_DESTROYED, ITEMS_DROPPED, DAMAGE_TAKEN}; + } + + default Message getVerbMessage() { + return Message.forName("quiz-verb-" + getVerb()); + } + + class IntegerStatistic implements SavedStatistic { + + private final static Question INTEGER_QUESTION = new Question((statistic, player, answers) -> { + IntegerStatistic integerStatistic = (IntegerStatistic) statistic; + int rightAnswer = integerStatistic.getStatistic(player); + + for (int i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } + + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(statistic.getVerbMessage(), ""), answers); + + return Collections.singletonList(rightAnswer + ""); + }); + + private final String key; + private final String questionVerb; + private final String questionSuffix; + private final String verb; + + public IntegerStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + this.key = key; + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } + + @Override + public String getKey() { + return key; + } + + @Override + public String getVerb() { + return verb; + } + + @Override + public String getQuestionVerb() { + return questionVerb; + } + + @Override + public String getQuestionSuffix() { + return questionSuffix; + } + + @Override + public IQuestion[] getQuestions() { + return new Question[]{INTEGER_QUESTION}; + } + + public void increaseStatistic(@Nonnull Player player) { + increaseStatistic(player, 1); + } + + public void increaseStatistic(@Nonnull Player player, int amount) { + instance.getPlayerData(player).set(key, getStatistic(player) + amount); + } + + public int getStatistic(@Nonnull Player player) { + return instance.getPlayerData(player).getInt(key); + } + + } + + abstract class DocumentStatistic implements SavedStatistic { + + private final String key; + + public DocumentStatistic(String key) { + this.key = key; + } + + @Override + public String getKey() { + return key; + } + + public Document getDocument(@Nonnull Player player) { + return instance.getPlayerData(player).getDocument(key); + } + + } + + class DocumentCountStatistic extends DocumentStatistic { + + private final static Question CHOOSE_QUESTION = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + Map entries = new HashMap<>(); + + ArrayList keysLeft = new ArrayList<>(document.keys()); + + if (keysLeft.isEmpty() || keysLeft.size() == 1) return null; + + Collections.shuffle(keysLeft); + for (byte i = 0; i < 4; i++) { + if (keysLeft.isEmpty()) break; + String key = keysLeft.remove(0); + entries.put(key, documentCountStatistic.getStatistic(player, key)); + } + + answers.addAll(entries.keySet()); + + double highestValue = -1; + List highestEntries = new ArrayList<>(); + + for (Entry entry : entries.entrySet()) { + if (highestValue == -1) { + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } else if (highestValue == entry.getValue()) { + highestEntries.add(entry.getKey()); + } else if (highestValue < entry.getValue()) { + highestEntries.clear(); + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } + } + + List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + answers.clear(); + answers.addAll(newAnswers); + + IQuestion.sendMessage(Message.forName("quiz-question-most").asString(statistic.getVerbMessage(), answers.size()), answers); + + highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + + return highestEntries; + }), + COUNT_QUESTIONS = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + ArrayList keys = new ArrayList<>(document.keys()); + + if (keys.isEmpty()) { + return null; + } + + String key = keys.get(instance.random.nextInt(keys.size())); + int rightAnswer = (int) documentCountStatistic.getStatistic(player, key); + + for (int i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } + + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(StringUtils.getEnumName(key), " " + statistic.getVerbMessage().asString()), answers); + + return new ArrayList<>(Collections.singleton(rightAnswer + "")); + }); + + private final String verb; + private final String questionSuffix; + private final String questionVerb; + + public DocumentCountStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + super(key); + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key) { + increaseStatistic(player, key, 1); + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key, double amount) { + getDocument(player).set(key, getStatistic(player, key) + amount); + } + + public double getStatistic(@Nonnull Player player, @Nonnull String key) { + return getDocument(player).getDouble(key); + } + + @Override + public String getVerb() { + return verb; + } + + @Override + public String getQuestionVerb() { + return questionVerb; + } + + @Override + public String getQuestionSuffix() { + return questionSuffix; + } + + @Override + public IQuestion[] getQuestions() { + return new IQuestion[]{CHOOSE_QUESTION, COUNT_QUESTIONS}; + } + + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.JUMPED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (!event.isSneaking()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.SNEAKED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { + if (!shouldExecuteEffect()) return; + + if (!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if (ignorePlayer(player)) return; + + if (!(event.getEntity() instanceof LivingEntity)) return; + + SavedStatistic.MOB_DAMAGED.increaseStatistic(player, event.getEntity().getType().name(), ChallengeHelper.getFinalDamage(event)); + + LivingEntity entity = (LivingEntity) event.getEntity(); + if (entity.getHealth() - ChallengeHelper.getFinalDamage(event) > 0) return; + + SavedStatistic.MOB_KILLED.increaseStatistic(player, event.getEntity().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BukkitReflectionUtils.isAir(event.getBlock().getType())) return; + SavedStatistic.BLOCKS_DESTROYED.increaseStatistic(event.getPlayer(), event.getBlock().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockIgnoreHeight(event.getFrom(), event.getTo())) return; + SavedStatistic.BLOCKS_MOVED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.ITEMS_DROPPED.increaseStatistic(event.getPlayer(), event.getItemDrop().getItemStack().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + SavedStatistic.DAMAGE_TAKEN.increaseStatistic(player, event.getCause().name(), ChallengeHelper.getFinalDamage(event)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 390eb21f8..ae3433268 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -1,10 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -12,55 +9,55 @@ import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ -public class BlockRandomizerChallenge extends RandomizerSetting { - - public BlockRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); - - List blocks = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - blocks.removeIf(material -> !ItemUtils.isObtainableInSurvival(material) || !material.isBlock() || BukkitReflectionUtils.isAir(material)); - random.shuffle(blocks); - - List drops = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - drops.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(drops); - - while (!blocks.isEmpty()) { - Material block = blocks.remove(0); - List items = new ArrayList<>(); - - int addDrops = getMatches(blocks.size(), drops.size()); - for (int i = 0; i < addDrops && !drops.isEmpty(); i++) { - items.add(drops.remove(0)); - } - manager.setCustomDrops(block, items, DropPriority.RANDOMIZER); - } +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; - } +public class BlockRandomizerChallenge extends RandomizerSetting { - @Override - protected void onDisable() { - BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); - manager.resetCustomDrops(DropPriority.RANDOMIZER); - } + public BlockRandomizerChallenge() { + super(MenuType.CHALLENGES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); + + List blocks = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + blocks.removeIf(material -> !ItemUtils.isObtainableInSurvival(material) || !material.isBlock() || BukkitReflectionUtils.isAir(material)); + random.shuffle(blocks); + + List drops = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + drops.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(drops); + + while (!blocks.isEmpty()) { + Material block = blocks.remove(0); + List items = new ArrayList<>(); + + int addDrops = getMatches(blocks.size(), drops.size()); + for (int i = 0; i < addDrops && !drops.isEmpty(); i++) { + items.add(drops.remove(0)); + } + manager.setCustomDrops(block, items, DropPriority.RANDOMIZER); + } + + } + + @Override + protected void onDisable() { + BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); + manager.resetCustomDrops(DropPriority.RANDOMIZER); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index ab20e5235..72628c416 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -15,57 +15,53 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CraftingRandomizerChallenge extends RandomizerSetting { - protected final Map randomization = new HashMap<>(); + protected final Map randomization = new HashMap<>(); - public CraftingRandomizerChallenge() { - super(MenuType.CHALLENGES); - } + public CraftingRandomizerChallenge() { + super(MenuType.CHALLENGES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); + } - @Override - protected void reloadRandomization() { + @Override + protected void reloadRandomization() { - List from = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - from.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(from); + List from = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + from.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(from); - List to = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - to.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(to); + List to = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + to.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(to); - while (!from.isEmpty()) { - Material item = from.remove(0); - Material result = to.remove(0); + while (!from.isEmpty()) { + Material item = from.remove(0); + Material result = to.remove(0); - randomization.put(item, result); - } + randomization.put(item, result); + } - } + } - @Override - protected void onDisable() { - randomization.clear(); - } + @Override + protected void onDisable() { + randomization.clear(); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onCraftItem(@Nonnull CraftItemEvent event) { - if (!isEnabled()) return; - ItemStack item = event.getCurrentItem(); - if (item == null) return; - Material result = randomization.get(item.getType()); - if (result == null) return; - event.setCurrentItem(new ItemBuilder(result).amount(item.getAmount()).build()); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onCraftItem(@Nonnull CraftItemEvent event) { + if (!isEnabled()) return; + ItemStack item = event.getCurrentItem(); + if (item == null) return; + Material result = randomization.get(item.getType()); + if (result == null) return; + event.setCurrentItem(new ItemBuilder(result).amount(item.getAmount()).build()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index 888998e35..659d6be31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -33,151 +33,151 @@ @Since("2.2.0") public class EntityLootRandomizerChallenge extends RandomizerSetting implements SenderCommand, Completer { - protected Map randomization; - - public EntityLootRandomizerChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FURNACE_MINECART, Message.forName("item-entity-loot-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - randomization = new HashMap<>(); - - List from = new ArrayList<>(Arrays.asList(EntityType.values())); - from.removeIf(entityType -> !getLootableEntities().contains(entityType)); - random.shuffle(from); - from.removeIf(Objects::isNull); - - List entityTypesToRemove = new ArrayList<>(); - List to = from.stream().map(entityType -> { - if (entityType == null) return null; - try { - return LootTables.valueOf(entityType.name()).getLootTable(); - } catch (IllegalArgumentException exception) { - entityTypesToRemove.add(entityType); - return null; - } - }).filter(Objects::nonNull).collect(Collectors.toList()); - from.removeAll(entityTypesToRemove); - random.shuffle(to); - - while (!from.isEmpty()) { - EntityType entityType = from.remove(0); - LootTable lootTable = to.remove(0); - - randomization.put(entityType, lootTable); - } - } - - public List getLootableEntities() { - return new ListBuilder<>(EntityType.values()) - .removeIf(type -> !type.isSpawnable()) - .removeIf(type -> !type.isAlive()) - .remove(EntityType.ENDER_DRAGON) - .remove(EntityType.GIANT) - .remove(EntityType.ILLUSIONER) - .remove(EntityType.ZOMBIE_HORSE) - .build(); - } - - @Override - protected void onDisable() { - randomization.clear(); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { - if (!isEnabled()) return; - LivingEntity entity = event.getEntity(); - if (!getLootableEntities().contains(entity.getType())) return; - event.getDrops().clear(); - if (!randomization.containsKey(entity.getType())) return; - - LootTable lootTable = randomization.get(entity.getType()); - LootContext.Builder builder = new LootContext.Builder(entity.getLocation()) - .lootedEntity(entity); - - if (entity.getKiller() == null) { - builder.lootingModifier(0); - } else { - builder.killer(entity.getKiller()); - } - - Collection newDrops = lootTable.populateLoot(random.asRandom(), builder.build()); - event.getDrops().addAll(newDrops); - } - - public LootTable getLootTableForEntity(EntityType entityType) { - return randomization.get(entityType); - } - - public Optional getEntityForLootTable(LootTable lootTable) { - return randomization.entrySet().stream() - .filter(entry -> entry.getValue().equals(lootTable)) - .map(Map.Entry::getKey) - .findFirst(); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (!isEnabled()) { - Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); - return; - } - - if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); - return; - } - - String input = String.join("_", args).toUpperCase(); - EntityType entityType = Utils.getEntityType(input); - - if (entityType == null) { - Message.forName("no-such-entity").send(sender, Prefix.CHALLENGES); - return; - } - if (!entityType.isAlive()) { - Message.forName("not-alive").send(sender, Prefix.CHALLENGES, entityType); - return; - } - - LootTable givenLootTable; - try { - givenLootTable = LootTables.valueOf(entityType.name()).getLootTable(); - } catch (IllegalArgumentException exception) { - Message.forName("no-loot").send(sender, Prefix.CHALLENGES, entityType); - return; - } - - Optional optionalEntity = getEntityForLootTable(givenLootTable); - LootTable droppedLootTable = getLootTableForEntity(entityType); - - if (optionalEntity.isPresent()) { - Message.forName("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); - } else { - Message.forName("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - EntityLootRandomizerChallenge instance = AbstractChallenge.getFirstInstance(EntityLootRandomizerChallenge.class); - return args.length != 1 ? null : - instance.getLootableEntities().stream() - .map(material -> material.name().toLowerCase()) - .collect(Collectors.toList() - ); - } + protected Map randomization; + + public EntityLootRandomizerChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.RANDOMIZER); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FURNACE_MINECART, Message.forName("item-entity-loot-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + randomization = new HashMap<>(); + + List from = new ArrayList<>(Arrays.asList(EntityType.values())); + from.removeIf(entityType -> !getLootableEntities().contains(entityType)); + random.shuffle(from); + from.removeIf(Objects::isNull); + + List entityTypesToRemove = new ArrayList<>(); + List to = from.stream().map(entityType -> { + if (entityType == null) return null; + try { + return LootTables.valueOf(entityType.name()).getLootTable(); + } catch (IllegalArgumentException exception) { + entityTypesToRemove.add(entityType); + return null; + } + }).filter(Objects::nonNull).collect(Collectors.toList()); + from.removeAll(entityTypesToRemove); + random.shuffle(to); + + while (!from.isEmpty()) { + EntityType entityType = from.remove(0); + LootTable lootTable = to.remove(0); + + randomization.put(entityType, lootTable); + } + } + + public List getLootableEntities() { + return new ListBuilder<>(EntityType.values()) + .removeIf(type -> !type.isSpawnable()) + .removeIf(type -> !type.isAlive()) + .remove(EntityType.ENDER_DRAGON) + .remove(EntityType.GIANT) + .remove(EntityType.ILLUSIONER) + .remove(EntityType.ZOMBIE_HORSE) + .build(); + } + + @Override + protected void onDisable() { + randomization.clear(); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityDeath(EntityDeathEvent event) { + if (!isEnabled()) return; + LivingEntity entity = event.getEntity(); + if (!getLootableEntities().contains(entity.getType())) return; + event.getDrops().clear(); + if (!randomization.containsKey(entity.getType())) return; + + LootTable lootTable = randomization.get(entity.getType()); + LootContext.Builder builder = new LootContext.Builder(entity.getLocation()) + .lootedEntity(entity); + + if (entity.getKiller() == null) { + builder.lootingModifier(0); + } else { + builder.killer(entity.getKiller()); + } + + Collection newDrops = lootTable.populateLoot(random.asRandom(), builder.build()); + event.getDrops().addAll(newDrops); + } + + public LootTable getLootTableForEntity(EntityType entityType) { + return randomization.get(entityType); + } + + public Optional getEntityForLootTable(LootTable lootTable) { + return randomization.entrySet().stream() + .filter(entry -> entry.getValue().equals(lootTable)) + .map(Map.Entry::getKey) + .findFirst(); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (!isEnabled()) { + Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); + return; + } + + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); + return; + } + + String input = String.join("_", args).toUpperCase(); + EntityType entityType = Utils.getEntityType(input); + + if (entityType == null) { + Message.forName("no-such-entity").send(sender, Prefix.CHALLENGES); + return; + } + if (!entityType.isAlive()) { + Message.forName("not-alive").send(sender, Prefix.CHALLENGES, entityType); + return; + } + + LootTable givenLootTable; + try { + givenLootTable = LootTables.valueOf(entityType.name()).getLootTable(); + } catch (IllegalArgumentException exception) { + Message.forName("no-loot").send(sender, Prefix.CHALLENGES, entityType); + return; + } + + Optional optionalEntity = getEntityForLootTable(givenLootTable); + LootTable droppedLootTable = getLootTableForEntity(entityType); + + if (optionalEntity.isPresent()) { + Message.forName("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); + } else { + Message.forName("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + EntityLootRandomizerChallenge instance = AbstractChallenge.getFirstInstance(EntityLootRandomizerChallenge.class); + return args.length != 1 ? null : + instance.getLootableEntities().stream() + .map(material -> material.name().toLowerCase()) + .collect(Collectors.toList() + ); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 3792fbbcb..32c31c8f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -30,128 +30,124 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { - public HotBarRandomizerChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.RANDOMIZER); - } - - /** - * @param force if true only sets items if inventory is empty - */ - public static void addItems(Player player, boolean force) { - - if (!force && !player.getInventory().isEmpty()) { - return; - } - - player.getInventory().clear(); - for (int i = 0; i < 9; i++) { - player.getInventory().setItem(i, InventoryUtils.getRandomItem(false, true)); - } - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER_MINECART, Message.forName("item-hotbar-randomizer-challenge")); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 60; - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-minutes-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); - } - - @Override - protected void onTimeActivation() { - - broadcastFiltered(player -> { - addItems(player, true); - }); - restartTimer(); - } - - @TimerTask(status = TimerStatus.RUNNING) - public void onStart() { - // Execute after hotbar items are removed - Bukkit.getScheduler().runTask(plugin, () -> { - broadcastFiltered(player -> { - addItems(player, false); - }); - - }); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - addItems(event.getPlayer(), false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setDropItems(false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - Inventory clickedInventory = event.getClickedInventory(); - if (event.getCursor() == null) return; - if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); - if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.PLAYER) { - if (event.getInventory().getType() != InventoryType.PLAYER) { - event.setCancelled(true); - } - } - - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + public HotBarRandomizerChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5); + setCategory(SettingCategory.RANDOMIZER); + } + + /** + * @param force if true only sets items if inventory is empty + */ + public static void addItems(Player player, boolean force) { + + if (!force && !player.getInventory().isEmpty()) { + return; + } + + player.getInventory().clear(); + for (int i = 0; i < 9; i++) { + player.getInventory().setItem(i, InventoryUtils.getRandomItem(false, true)); + } + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.HOPPER_MINECART, Message.forName("item-hotbar-randomizer-challenge")); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 60; + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-minutes-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); + } + + @Override + protected void onTimeActivation() { + + broadcastFiltered(player -> { + addItems(player, true); + }); + restartTimer(); + } + + @TimerTask(status = TimerStatus.RUNNING) + public void onStart() { + // Execute after hotbar items are removed + Bukkit.getScheduler().runTask(plugin, () -> { + broadcastFiltered(player -> { + addItems(player, false); + }); + + }); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + addItems(event.getPlayer(), false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setDropItems(false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + Inventory clickedInventory = event.getClickedInventory(); + if (event.getCursor() == null) return; + if (clickedInventory == null) return; + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.PLAYER) { + if (event.getInventory().getType() != InventoryType.PLAYER) { + event.setCancelled(true); + } + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index 6259c4eb4..aff8383d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -1,12 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; @@ -21,212 +16,207 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Drowned; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.SpawnCategory; -import org.bukkit.entity.WaterMob; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Since("2.0") public class MobRandomizerChallenge extends RandomizerSetting { - private final Map entityRandomizer = new HashMap<>(); - private final Map inverseRandomizer = new HashMap<>(); - - private boolean inSpawn = false; - private boolean initialSpawn = false; - - public MobRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @Override - protected void onEnable() { - super.onEnable(); - if (!shouldExecuteEffect()) return; - initialSpawn = true; - loadAllEntities(); - initialSpawn = false; - } - - @Override - protected void onDisable() { - super.onDisable(); - unLoadAllEntities(); - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void onPause() { - unLoadAllEntities(); - } - - private void loadAllEntities() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - if (!entityRandomizer.containsKey(entity.getType())) return; - entity.remove(); - entity.getWorld().spawnEntity(entity.getLocation(), entityRandomizer.get(entity.getType())); - }); - } - - } - } - - private void unLoadAllEntities() { - inSpawn = true; - - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (!inverseRandomizer.containsKey(entity.getType())) continue; - entity.remove(); - EntityType entityType = inverseRandomizer.get(entity.getType()); - entity.getWorld().spawnEntity(entity.getLocation(), entityType); - - } - - } - - inSpawn = false; - } - - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - List entityTypes = getSpawnAbleEntities(); - List randomEntityTypes = new ArrayList<>(entityTypes); - random.shuffle(randomEntityTypes); - - for (int i = 0; i < entityTypes.size(); i++) { - EntityType type = entityTypes.get(i); - EntityType randomType = randomEntityTypes.get(i); - entityRandomizer.put(type, randomType); - inverseRandomizer.put(randomType, type); - } - - } - - public List getSpawnAbleEntities() { - ListBuilder builder = new ListBuilder<>(ExperimentalUtils.getEntityTypes()) - .removeIf(type -> !type.isSpawnable()) - .removeIf(type -> !type.isAlive()) - .remove(EntityType.ENDER_DRAGON) - .remove(EntityType.WITHER) - .remove(EntityType.GIANT) - .remove(EntityType.ILLUSIONER); - - return builder.build(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!entityRandomizer.containsKey(event.getEntityType())) return; - if (inSpawn) return; - - event.setCancelled(true); - - EntityType type = entityRandomizer.get(event.getEntityType()); - Location location = event.getLocation(); - if (location.getWorld() == null) return; - if (!initialSpawn && !maySpawn(type, location.getWorld())) return; - inSpawn = true; - event.getEntity().getWorld().spawnEntity(location, type); - inSpawn = false; - } - - private boolean maySpawn(@Nonnull EntityType newType, @Nonnull World world) { - EntityCategory category = getEntityCategory(newType); - int currentMobCount = getCurrentMobCount(category, world); - int spawnLimit = getEntityCategory(newType).getSpawnLimit(world); - return currentMobCount < spawnLimit; - } - - private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull World world) { - - int mobCount = 0; - - for (Entity entity : world.getLivingEntities()) { - if (!(entity instanceof LivingEntity)) continue; - EntityCategory entityTypeState = getEntityCategory(entity.getType()); - if (entityState == entityTypeState) { - mobCount++; - } - - } - - return mobCount; - } - - private EntityCategory getEntityCategory(@Nonnull EntityType type) { - Class entity = type.getEntityClass(); - if (entity == null) return EntityCategory.OTHER; - - if (Animals.class.isAssignableFrom(entity)) { - return EntityCategory.ANIMAL; - } - if (Drowned.class.isAssignableFrom(entity) || Guardian.class.isAssignableFrom(entity)) { - return EntityCategory.WATER_AMBIENT; - } - if (Monster.class.isAssignableFrom(entity)) { - return EntityCategory.HOSTILE; - } - if (WaterMob.class.isAssignableFrom(entity)) { - return EntityCategory.WATER_ANIMAL; - } - - return EntityCategory.AMBIENT; - } - - public enum EntityCategory { - - HOSTILE, - AMBIENT, - ANIMAL, - WATER_ANIMAL, - WATER_AMBIENT, - OTHER; - - private int getSpawnLimit(@Nonnull World world) { - boolean useSpawnCategories = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); // World#getSpawnLimit was added in 1.19 - switch (this) { - case AMBIENT: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.AMBIENT) : world.getAmbientSpawnLimit(); - case HOSTILE: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.MONSTER) : world.getMonsterSpawnLimit(); - case ANIMAL: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.ANIMAL) : world.getAnimalSpawnLimit(); - case WATER_AMBIENT: { // getWaterAmbientSpawnLimit is not available in lower versions like 1.13, default to water animal then - try { - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); - } catch (Throwable throwable) { - Challenges.getInstance().getLogger().error("", throwable); - } - } - case WATER_ANIMAL: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_ANIMAL) : world.getWaterAnimalSpawnLimit(); - default: - return 0; - } - } - - } - -} \ No newline at end of file + private final Map entityRandomizer = new HashMap<>(); + private final Map inverseRandomizer = new HashMap<>(); + + private boolean inSpawn = false; + private boolean initialSpawn = false; + + public MobRandomizerChallenge() { + super(MenuType.CHALLENGES); + } + + @Override + protected void onEnable() { + super.onEnable(); + if (!shouldExecuteEffect()) return; + initialSpawn = true; + loadAllEntities(); + initialSpawn = false; + } + + @Override + protected void onDisable() { + super.onDisable(); + unLoadAllEntities(); + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void onPause() { + unLoadAllEntities(); + } + + private void loadAllEntities() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + if (!entityRandomizer.containsKey(entity.getType())) return; + entity.remove(); + entity.getWorld().spawnEntity(entity.getLocation(), entityRandomizer.get(entity.getType())); + }); + } + + } + } + + private void unLoadAllEntities() { + inSpawn = true; + + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (!inverseRandomizer.containsKey(entity.getType())) continue; + entity.remove(); + EntityType entityType = inverseRandomizer.get(entity.getType()); + entity.getWorld().spawnEntity(entity.getLocation(), entityType); + + } + + } + + inSpawn = false; + } + + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + List entityTypes = getSpawnAbleEntities(); + List randomEntityTypes = new ArrayList<>(entityTypes); + random.shuffle(randomEntityTypes); + + for (int i = 0; i < entityTypes.size(); i++) { + EntityType type = entityTypes.get(i); + EntityType randomType = randomEntityTypes.get(i); + entityRandomizer.put(type, randomType); + inverseRandomizer.put(randomType, type); + } + + } + + public List getSpawnAbleEntities() { + ListBuilder builder = new ListBuilder<>(ExperimentalUtils.getEntityTypes()) + .removeIf(type -> !type.isSpawnable()) + .removeIf(type -> !type.isAlive()) + .remove(EntityType.ENDER_DRAGON) + .remove(EntityType.WITHER) + .remove(EntityType.GIANT) + .remove(EntityType.ILLUSIONER); + + return builder.build(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!entityRandomizer.containsKey(event.getEntityType())) return; + if (inSpawn) return; + + event.setCancelled(true); + + EntityType type = entityRandomizer.get(event.getEntityType()); + Location location = event.getLocation(); + if (location.getWorld() == null) return; + if (!initialSpawn && !maySpawn(type, location.getWorld())) return; + inSpawn = true; + event.getEntity().getWorld().spawnEntity(location, type); + inSpawn = false; + } + + private boolean maySpawn(@Nonnull EntityType newType, @Nonnull World world) { + EntityCategory category = getEntityCategory(newType); + int currentMobCount = getCurrentMobCount(category, world); + int spawnLimit = getEntityCategory(newType).getSpawnLimit(world); + return currentMobCount < spawnLimit; + } + + private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull World world) { + + int mobCount = 0; + + for (Entity entity : world.getLivingEntities()) { + if (!(entity instanceof LivingEntity)) continue; + EntityCategory entityTypeState = getEntityCategory(entity.getType()); + if (entityState == entityTypeState) { + mobCount++; + } + + } + + return mobCount; + } + + private EntityCategory getEntityCategory(@Nonnull EntityType type) { + Class entity = type.getEntityClass(); + if (entity == null) return EntityCategory.OTHER; + + if (Animals.class.isAssignableFrom(entity)) { + return EntityCategory.ANIMAL; + } + if (Drowned.class.isAssignableFrom(entity) || Guardian.class.isAssignableFrom(entity)) { + return EntityCategory.WATER_AMBIENT; + } + if (Monster.class.isAssignableFrom(entity)) { + return EntityCategory.HOSTILE; + } + if (WaterMob.class.isAssignableFrom(entity)) { + return EntityCategory.WATER_ANIMAL; + } + + return EntityCategory.AMBIENT; + } + + public enum EntityCategory { + + HOSTILE, + AMBIENT, + ANIMAL, + WATER_ANIMAL, + WATER_AMBIENT, + OTHER; + + private int getSpawnLimit(@Nonnull World world) { + boolean useSpawnCategories = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); // World#getSpawnLimit was added in 1.19 + switch (this) { + case AMBIENT: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.AMBIENT) : world.getAmbientSpawnLimit(); + case HOSTILE: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.MONSTER) : world.getMonsterSpawnLimit(); + case ANIMAL: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.ANIMAL) : world.getAnimalSpawnLimit(); + case + WATER_AMBIENT: { // getWaterAmbientSpawnLimit is not available in lower versions like 1.13, default to water animal then + try { + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); + } catch (Throwable throwable) { + Challenges.getInstance().getILogger().error("", throwable); + } + } + case WATER_ANIMAL: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_ANIMAL) : world.getWaterAnimalSpawnLimit(); + default: + return 0; + } + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 5b37d22f5..16f8537a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; @@ -20,115 +20,111 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class RandomChallengeChallenge extends TimedChallenge { - private AbstractChallenge lastUsed; - - public RandomChallengeChallenge() { - super(MenuType.CHALLENGES, 3, 60, 6, false); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (lastUsed == null) { - bossbar.setTitle(Message.forName("bossbar-random-challenge-waiting").asString()); - return; - } - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-random-challenge-current").asString(ChallengeHelper.getColoredChallengeName(lastUsed))); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - if (lastUsed != null) { - setEnabled(lastUsed, false); - lastUsed = null; - } - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 10; - } - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - if (lastUsed != null) { - setEnabled(lastUsed, false); - lastUsed = null; - } - - List challenges = new ArrayList<>(Challenges.getInstance().getChallengeManager().getChallenges()); - challenges.remove(this); - challenges.removeIf(challenge -> challenge.getType() != MenuType.CHALLENGES); - challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); - challenges.removeIf(ChallengeHelper::canInstaKillOnEnable); - challenges.removeIf(ChallengeHelper::isExcludedFromRandomChallenges); - challenges.removeIf(IChallenge::isEnabled); - if (challenges.isEmpty()) return; - - AbstractChallenge challenge = (AbstractChallenge) globalRandom.choose(challenges); - String name = ChallengeHelper.getColoredChallengeName(challenge); - Message.forName("random-challenge-enabled").broadcast(Prefix.CHALLENGES, name); - - setEnabled(challenge, true); - lastUsed = challenge; - bossbar.update(); - - } - - private void setEnabled(@Nonnull IChallenge challenge, boolean enabled) { - if (challenge instanceof Setting) { - Setting setting = (Setting) challenge; - setting.setEnabled(enabled); - } - if (challenge instanceof SettingModifier) { - SettingModifier setting = (SettingModifier) challenge; - setting.setEnabled(enabled); - } - - if (enabled && challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; - if (timedChallenge.isTimerRunning()) { - int seconds = globalRandom.range(10, 20); - if (seconds < timedChallenge.getSecondsLeftUntilNextActivation()) - timedChallenge.shortCountDownTo(seconds); - } - } - } + private AbstractChallenge lastUsed; + + public RandomChallengeChallenge() { + super(MenuType.CHALLENGES, 3, 60, 6, false); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (lastUsed == null) { + bossbar.setTitle(Message.forName("bossbar-random-challenge-waiting").asString()); + return; + } + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-random-challenge-current").asString(ChallengeHelper.getColoredChallengeName(lastUsed))); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + if (lastUsed != null) { + setEnabled(lastUsed, false); + lastUsed = null; + } + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 10; + } + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + if (lastUsed != null) { + setEnabled(lastUsed, false); + lastUsed = null; + } + + List challenges = new ArrayList<>(Challenges.getInstance().getChallengeManager().getChallenges()); + challenges.remove(this); + challenges.removeIf(challenge -> challenge.getType() != MenuType.CHALLENGES); + challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); + challenges.removeIf(ChallengeHelper::canInstaKillOnEnable); + challenges.removeIf(ChallengeHelper::isExcludedFromRandomChallenges); + challenges.removeIf(IChallenge::isEnabled); + if (challenges.isEmpty()) return; + + AbstractChallenge challenge = (AbstractChallenge) globalRandom.choose(challenges); + String name = ChallengeHelper.getColoredChallengeName(challenge); + Message.forName("random-challenge-enabled").broadcast(Prefix.CHALLENGES, name); + + setEnabled(challenge, true); + lastUsed = challenge; + bossbar.update(); + + } + + private void setEnabled(@Nonnull IChallenge challenge, boolean enabled) { + if (challenge instanceof Setting) { + Setting setting = (Setting) challenge; + setting.setEnabled(enabled); + } + if (challenge instanceof SettingModifier) { + SettingModifier setting = (SettingModifier) challenge; + setting.setEnabled(enabled); + } + + if (enabled && challenge instanceof TimedChallenge) { + TimedChallenge timedChallenge = (TimedChallenge) challenge; + if (timedChallenge.isTimerRunning()) { + int seconds = globalRandom.range(10, 20); + if (seconds < timedChallenge.getSecondsLeftUntilNextActivation()) + timedChallenge.shortCountDownTo(seconds); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index 596ba187b..f378b2c0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -24,216 +24,212 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class RandomEventChallenge extends TimedChallenge { - private final Event[] events; - - public RandomEventChallenge() { - super(MenuType.CHALLENGES, 1, 10, 3, false); - setCategory(SettingCategory.RANDOMIZER); - events = new Event[]{ - new SpeedEvent(), - new SpawnEntitiesEvent(), - new HoleEvent(), - new FlyEvent(), - new CobWebEvent(), - new ReplaceOresEvent(), - new SicknessEvent() - }; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - Event event = globalRandom.choose(events); - Logger.debug("Running random event {}", event.getClass().getSimpleName()); - event.getActivationMessage().broadcastRandom(globalRandom, Prefix.CHALLENGES); - broadcastFiltered(event::run); - } - - public interface Event { - - @Nonnull - Message getActivationMessage(); - - void run(@Nonnull Player player); - - } - - public static class SpeedEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-speed"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10 * 20, 99)); - } - - } - - public static class HoleEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-hole"); - } - - @Override - public void run(@Nonnull Player player) { - Location location = player.getLocation().getBlock().getLocation(); - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = 1; y >= -8; y--) { - location.clone().add(x, y, z).getBlock().setType(Material.AIR, true); - } - } - } - } - - } - - public static class FlyEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-fly"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 3 * 20, 5)); - } - - } - - public static class ReplaceOresEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-ores"); - } - - @Override - public void run(@Nonnull Player player) { - Location location = player.getLocation(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - for (int x = -100; x <= 100; x++) { - for (int z = -100; z <= 100; z++) { - int finalZ = z; - int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { - if (location.getWorld() == null) return; - for (int y = BukkitReflectionUtils.getMinHeight(location.getWorld()); y < 80; y++) { - Location current = location.clone().add(finalX, 0, finalZ); - current.setY(y); - Block block = current.getBlock(); - if (block.getType().name().contains("ORE")) { - Environment environment = location.getWorld().getEnvironment(); - block.setType(environment == Environment.NETHER ? Material.NETHERRACK : environment == Environment.THE_END ? Material.END_STONE : Material.STONE, true); - } - } - }); - } - } - }); - } - - } - - public static class SicknessEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-sickness"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, 7 * 20, 0)); - player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 3 * 20, 1)); - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 1)); - } - } - - public class SpawnEntitiesEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-entities"); - } - - @Override - public void run(@Nonnull Player player) { - EntityType type = globalRandom.choose(EntityType.PIG, EntityType.CHICKEN, EntityType.CAT, EntityType.SILVERFISH, EntityType.WOLF); - - for (int i = 0; i < globalRandom.nextInt(5) + 5; i++) { - Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -10, globalRandom.nextInt(10 - 5)); - if (randomLocation.getWorld() == null) return; - while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) - randomLocation.add(0, 1, 0); - - randomLocation.getWorld().spawnEntity(randomLocation, type); - } - } - - } - - public class CobWebEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-webs"); - } - - @Override - public void run(@Nonnull Player player) { - for (int i = 0; i < 13; i++) { - Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -20, globalRandom.nextInt(10 - 5)); - if (randomLocation.getWorld() == null) return; - while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) - randomLocation.add(0, 1, 0); - - randomLocation.getBlock().setType(Material.COBWEB, false); - } - } - - } + private final Event[] events; + + public RandomEventChallenge() { + super(MenuType.CHALLENGES, 1, 10, 3, false); + setCategory(SettingCategory.RANDOMIZER); + events = new Event[]{ + new SpeedEvent(), + new SpawnEntitiesEvent(), + new HoleEvent(), + new FlyEvent(), + new CobWebEvent(), + new ReplaceOresEvent(), + new SicknessEvent() + }; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + Event event = globalRandom.choose(events); + Logger.debug("Running random event {}", event.getClass().getSimpleName()); + event.getActivationMessage().broadcastRandom(globalRandom, Prefix.CHALLENGES); + broadcastFiltered(event::run); + } + + public interface Event { + + @Nonnull + Message getActivationMessage(); + + void run(@Nonnull Player player); + + } + + public static class SpeedEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-speed"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10 * 20, 99)); + } + + } + + public static class HoleEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-hole"); + } + + @Override + public void run(@Nonnull Player player) { + Location location = player.getLocation().getBlock().getLocation(); + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = 1; y >= -8; y--) { + location.clone().add(x, y, z).getBlock().setType(Material.AIR, true); + } + } + } + } + + } + + public static class FlyEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-fly"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 3 * 20, 5)); + } + + } + + public static class ReplaceOresEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-ores"); + } + + @Override + public void run(@Nonnull Player player) { + Location location = player.getLocation(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + for (int x = -100; x <= 100; x++) { + for (int z = -100; z <= 100; z++) { + int finalZ = z; + int finalX = x; + Bukkit.getScheduler().runTask(plugin, () -> { + if (location.getWorld() == null) return; + for (int y = BukkitReflectionUtils.getMinHeight(location.getWorld()); y < 80; y++) { + Location current = location.clone().add(finalX, 0, finalZ); + current.setY(y); + Block block = current.getBlock(); + if (block.getType().name().contains("ORE")) { + Environment environment = location.getWorld().getEnvironment(); + block.setType(environment == Environment.NETHER ? Material.NETHERRACK : environment == Environment.THE_END ? Material.END_STONE : Material.STONE, true); + } + } + }); + } + } + }); + } + + } + + public static class SicknessEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-sickness"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, 7 * 20, 0)); + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 3 * 20, 1)); + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 1)); + } + } + + public static class SpawnEntitiesEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-entities"); + } + + @Override + public void run(@Nonnull Player player) { + EntityType type = globalRandom.choose(EntityType.PIG, EntityType.CHICKEN, EntityType.CAT, EntityType.SILVERFISH, EntityType.WOLF); + + for (int i = 0; i < globalRandom.nextInt(5) + 5; i++) { + Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -10, globalRandom.nextInt(10 - 5)); + if (randomLocation.getWorld() == null) return; + while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) + randomLocation.add(0, 1, 0); + + randomLocation.getWorld().spawnEntity(randomLocation, type); + } + } + + } + + public static class CobWebEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-webs"); + } + + @Override + public void run(@Nonnull Player player) { + for (int i = 0; i < 13; i++) { + Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -20, globalRandom.nextInt(10 - 5)); + if (randomLocation.getWorld() == null) return; + while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) + randomLocation.add(0, 1, 0); + + randomLocation.getBlock().setType(Material.COBWEB, false); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index cea207c72..55820aaee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomItemAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -13,44 +13,40 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemChallenge extends TimedChallenge { - public RandomItemChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30, false); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - broadcastFiltered(RandomItemAction::giveRandomItemToPlayer); - } + public RandomItemChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30, false); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + broadcastFiltered(RandomItemAction::giveRandomItemToPlayer); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index dee55863e..b7e3a964e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,66 +18,62 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemDroppingChallenge extends TimedChallenge { - public RandomItemDroppingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); - } + public RandomItemDroppingChallenge() { + super(MenuType.CHALLENGES, 1, 60, 5); + setCategory(SettingCategory.RANDOMIZER); + } - public static void dropRandomItem(Player player) { - if (player.getInventory().getContents().length <= 0) return; - dropRandomItem(player.getLocation(), player.getInventory()); - } + public static void dropRandomItem(Player player) { + if (player.getInventory().getContents().length == 0) return; + dropRandomItem(player.getLocation(), player.getInventory()); + } - public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory inventory) { - if (location.getWorld() == null) return; - int slot = InventoryUtils.getRandomFullSlot(inventory); - if (slot == -1) return; - ItemStack item = inventory.getItem(slot); - if (item == null) return; - inventory.setItem(slot, null); - InventoryUtils.dropItemByPlayer(location, item); - } + public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory inventory) { + if (location.getWorld() == null) return; + int slot = InventoryUtils.getRandomFullSlot(inventory); + if (slot == -1) return; + ItemStack item = inventory.getItem(slot); + if (item == null) return; + inventory.setItem(slot, null); + InventoryUtils.dropItemByPlayer(location, item); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } - @Override - protected void onTimeActivation() { - restartTimer(); + @Override + protected void onTimeActivation() { + restartTimer(); - Bukkit.getScheduler().runTask(plugin, () -> { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; + Bukkit.getScheduler().runTask(plugin, () -> { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; - dropRandomItem(player); - } - }); - } + dropRandomItem(player); + } + }); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index aaffe7212..cf96f92f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -15,52 +15,48 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { - public RandomItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 30, 30); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - if (player.getInventory().getContents().length <= 0) continue; - - Bukkit.getScheduler().runTask(plugin, () -> { - InventoryUtils.removeRandomItem(player.getInventory()); - }); - } - } - -} \ No newline at end of file + public RandomItemRemovingChallenge() { + super(MenuType.CHALLENGES, 1, 30, 30); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + if (player.getInventory().getContents().length == 0) continue; + + Bukkit.getScheduler().runTask(plugin, () -> { + InventoryUtils.removeRandomItem(player.getInventory()); + }); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 76963ee39..33ded8246 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -17,72 +17,68 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemSwappingChallenge extends TimedChallenge { - public RandomItemSwappingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); - } - - public static void swapRandomItems(Player player) { - if (player.getInventory().getContents().length <= 0) return; - int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); - if (slot == -1) return; - swapItemToRandomSlot( - player.getInventory(), - InventoryUtils.getRandomFullSlot(player.getInventory()), - InventoryUtils.getRandomSlot(player.getInventory()) - ); - } - - private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1, int slot2) { - if (slot1 == -1 || slot2 == -1) return; - ItemStack item1 = inventory.getItem(slot1); - ItemStack item2 = inventory.getItem(slot2); - inventory.setItem(slot1, item2); - inventory.setItem(slot2, item1); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - Bukkit.getScheduler().runTask(plugin, () -> { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - swapRandomItems(player); - } - - }); - - } - -} \ No newline at end of file + public RandomItemSwappingChallenge() { + super(MenuType.CHALLENGES, 1, 60, 5); + setCategory(SettingCategory.RANDOMIZER); + } + + public static void swapRandomItems(Player player) { + if (player.getInventory().getContents().length == 0) return; + int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); + if (slot == -1) return; + swapItemToRandomSlot( + player.getInventory(), + InventoryUtils.getRandomFullSlot(player.getInventory()), + InventoryUtils.getRandomSlot(player.getInventory()) + ); + } + + private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1, int slot2) { + if (slot1 == -1 || slot2 == -1) return; + ItemStack item1 = inventory.getItem(slot1); + ItemStack item2 = inventory.getItem(slot2); + inventory.setItem(slot1, item2); + inventory.setItem(slot2, item1); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + Bukkit.getScheduler().runTask(plugin, () -> { + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + swapRandomItems(player); + } + + }); + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index b7c22044e..cdc626c77 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -19,45 +19,41 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class RandomTeleportOnHitChallenge extends Setting { - public RandomTeleportOnHitChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); - } - - public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { - entity1.setInvisible(true); - entity2.setInvisible(false); - Location entity2Location = entity2.getLocation().clone(); - entity2.teleport(entity1.getLocation()); - entity1.teleport(entity2Location); - entity2.setInvisible(false); - entity1.setInvisible(false); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-mob-damage-teleport-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getDamager())) return; - - World world = event.getDamager().getWorld(); - List livingEntities = new ArrayList<>(world.getLivingEntities()); - livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); - LivingEntity entity = globalRandom.choose(livingEntities); - - switchEntityLocations(entity, event.getDamager()); - } + public RandomTeleportOnHitChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.RANDOMIZER); + } + + public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { + entity1.setInvisible(true); + entity2.setInvisible(false); + Location entity2Location = entity2.getLocation().clone(); + entity2.teleport(entity1.getLocation()); + entity1.teleport(entity2Location); + entity2.setInvisible(false); + entity1.setInvisible(false); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-mob-damage-teleport-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getDamager())) return; + + World world = event.getDamager().getWorld(); + List livingEntities = new ArrayList<>(world.getLivingEntities()); + livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); + LivingEntity entity = globalRandom.choose(livingEntities); + + switchEntityLocations(entity, event.getDamager()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index ef17e54dc..b1686d8a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Color; @@ -13,7 +14,6 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; @@ -29,111 +29,109 @@ import java.util.Map; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RandomizedHPChallenge extends SettingModifier { - private final Random random = new Random(); - - public RandomizedHPChallenge() { - super(MenuType.CHALLENGES, 5); - setCategory(SettingCategory.RANDOMIZER); - randomizeExistingEntityHealth(); - } - - @Override - protected void onDisable() { - resetExistingEntityHealth(); - } - - @Override - public void onEnable() { - randomizeExistingEntityHealth(); - } - - @Override - protected void onValueChange() { - randomizeExistingEntityHealth(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - LivingEntity entity = (LivingEntity) event.getEntity(); - randomizeEntityHealth(entity); - } - - private void randomizeEntityHealth(@Nonnull LivingEntity entity) { - if (entity instanceof Player) return; - if (!isEnabled()) { - entity.resetMaxHealth(); - entity.setHealth(entity.getMaxHealth()); - return; - } - int health = random.nextInt(getValue() * 100) + 1; - entity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(health); - entity.setHealth(health); - } - - private void randomizeExistingEntityHealth() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - randomizeEntityHealth(entity); - } - } - } - - private void resetExistingEntityHealth() { - Map entityDefaultHealth = new HashMap<>(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - EntityType type = entity.getType(); - double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); - entityDefaultHealth.put(type, health); - AttributeInstance attribute = entity.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(health); - entity.setHealth(health); - } - } - } - - private double getDefaultHealth(@Nonnull EntityType entityType) { - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); - entity.remove(); - if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute = ((LivingEntity) entity) - .getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return 10; - return attribute.getBaseValue(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-max-health-description").asArray(getValue() * 50); - } - -} \ No newline at end of file + private final Random random = new Random(); + + public RandomizedHPChallenge() { + super(MenuType.CHALLENGES, 5); + setCategory(SettingCategory.RANDOMIZER); + randomizeExistingEntityHealth(); + } + + @Override + protected void onDisable() { + resetExistingEntityHealth(); + } + + @Override + public void onEnable() { + randomizeExistingEntityHealth(); + } + + @Override + protected void onValueChange() { + randomizeExistingEntityHealth(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + LivingEntity entity = (LivingEntity) event.getEntity(); + randomizeEntityHealth(entity); + } + + private void randomizeEntityHealth(@Nonnull LivingEntity entity) { + if (entity instanceof Player) return; + if (!isEnabled()) { + entity.resetMaxHealth(); + entity.setHealth(entity.getMaxHealth()); + return; + } + int health = random.nextInt(getValue() * 100) + 1; + entity.setHealth(health); + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(health); + } + + private void randomizeExistingEntityHealth() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + randomizeEntityHealth(entity); + } + } + } + + private void resetExistingEntityHealth() { + Map entityDefaultHealth = new HashMap<>(); + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity instanceof Player) continue; + EntityType type = entity.getType(); + double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); + entityDefaultHealth.put(type, health); + + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(health); + entity.setHealth(health); + } + } + } + + private double getDefaultHealth(@Nonnull EntityType entityType) { + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); + entity.remove(); + if (!(entity instanceof LivingEntity)) return 0; + AttributeInstance attribute = ((LivingEntity) entity).getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return 10; + return attribute.getBaseValue(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-max-health-description").asArray(getValue() * 50); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index f83daec95..fcd1ae478 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,94 +18,90 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MaxBiomeTimeChallenge extends SettingModifier { - public MaxBiomeTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(player); - int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-biome-time-left").asComponent(getBiome(player), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected void onValueChange() { - bossbar.update(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlock().getBiome() == event.getTo().getBlock().getBiome()) return; - bossbar.update(event.getPlayer()); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - broadcast(this::updateBiomeTime); - } - - private void updateBiomeTime(@Nonnull Player player) { - if (ignorePlayer(player)) { - bossbar.update(player); - return; - } - - Biome biome = player.getLocation().getBlock().getBiome(); - int time = getCurrentTime(player) + 1; - if (time > getValue() * 60) { - kill(player); - } - if (time < getValue() * 60) { - getPlayerData(player).set(biome.name(), time); - } - bossbar.update(player); - } - - private int getCurrentTime(@Nonnull Player player) { - return getPlayerData(player).getInt(getBiome(player).name(), 0); - } - - private Biome getBiome(@Nonnull Player player) { - return player.getLocation().getBlock().getBiome(); - } - -} \ No newline at end of file + public MaxBiomeTimeChallenge() { + super(MenuType.CHALLENGES, 3, 20); + setCategory(SettingCategory.LIMITED_TIME); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(player); + int maxTime = (getValue() * 60); + bossbar.setTitle(Message.forName("bossbar-biome-time-left").asComponent(getBiome(player), maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected void onValueChange() { + bossbar.update(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); + } + + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlock().getBiome() == event.getTo().getBlock().getBiome()) return; + bossbar.update(event.getPlayer()); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + broadcast(this::updateBiomeTime); + } + + private void updateBiomeTime(@Nonnull Player player) { + if (ignorePlayer(player)) { + bossbar.update(player); + return; + } + + Biome biome = player.getLocation().getBlock().getBiome(); + int time = getCurrentTime(player) + 1; + if (time > getValue() * 60) { + kill(player); + } + if (time < getValue() * 60) { + getPlayerData(player).set(biome.name(), time); + } + bossbar.update(player); + } + + private int getCurrentTime(@Nonnull Player player) { + return getPlayerData(player).getInt(getBiome(player).name(), 0); + } + + private Biome getBiome(@Nonnull Player player) { + return player.getLocation().getBlock().getBiome(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 6c8564b9f..515636263 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -18,89 +18,85 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MaxHeightTimeChallenge extends SettingModifier { - public MaxHeightTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(player); - int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-height-time-left").asString(player.getLocation().getBlockY(), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected void onValueChange() { - bossbar.update(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlockY() == event.getTo().getBlockY()) return; - Bukkit.getScheduler().runTask(plugin, () -> bossbar.update(event.getPlayer())); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - broadcast(this::updateHeightTime); - } - - private void updateHeightTime(@Nonnull Player player) { - if (ignorePlayer(player)) { - bossbar.update(player); - return; - } - - int time = getCurrentTime(player) + 1; - if (time > getValue() * 60) { - kill(player); - } - if (time < getValue() * 60) { - getPlayerData(player).set(String.valueOf(player.getLocation().getBlockY()), time); - } - bossbar.update(player); - } - - private int getCurrentTime(@Nonnull Player player) { - return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); - } - -} \ No newline at end of file + public MaxHeightTimeChallenge() { + super(MenuType.CHALLENGES, 3, 20); + setCategory(SettingCategory.LIMITED_TIME); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(player); + int maxTime = (getValue() * 60); + bossbar.setTitle(Message.forName("bossbar-height-time-left").asString(player.getLocation().getBlockY(), maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected void onValueChange() { + bossbar.update(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); + } + + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlockY() == event.getTo().getBlockY()) return; + Bukkit.getScheduler().runTask(plugin, () -> bossbar.update(event.getPlayer())); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + broadcast(this::updateHeightTime); + } + + private void updateHeightTime(@Nonnull Player player) { + if (ignorePlayer(player)) { + bossbar.update(player); + return; + } + + int time = getCurrentTime(player) + 1; + if (time > getValue() * 60) { + kill(player); + } + if (time < getValue() * 60) { + getPlayerData(player).set(String.valueOf(player.getLocation().getBlockY()), time); + } + bossbar.update(player); + } + + private int getCurrentTime(@Nonnull Player player) { + return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 743005f34..116e3760e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; @@ -28,122 +28,118 @@ import javax.annotation.Nullable; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class AllBlocksDisappearChallenge extends MenuSetting { - private final int stackDropLimit; - - public AllBlocksDisappearChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-all-blocks-disappear-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("break", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), - true - )); - registerSetting("place", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) - )); - - Document document = ChallengeConfigHelper.getSettingsDocument(); - stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!getSetting("break").getAsBoolean()) return; - if (ignorePlayer(event.getPlayer())) return; - PlayerInventory inventory = event.getPlayer().getInventory(); - event.setDropItems(false); - breakBlocks(event.getBlock(), inventory.getItemInMainHand(), inventory); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (!getSetting("place").getAsBoolean()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getBlockAgainst().getType() == Material.BEDROCK) return; - if (event.getBlockAgainst().getType() == Material.END_PORTAL) return; - breakBlocks(event.getBlockAgainst(), null, event.getPlayer().getInventory()); - } - - private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnull Inventory inventory) { - Chunk chunk = block.getChunk(); - List blocks = getAllBlocksToBreak(chunk, block.getType()); - - List allDrops = new ArrayList<>(); - - for (Block current : blocks) { - Collection drops = Challenges.getInstance().getBlockDropManager().getDrops(current, tool); - current.setType(Material.AIR); - - for (ItemStack currentBlockDrop : drops) { - boolean containsType = false; - - for (ItemStack currentAllDrop : allDrops) { - if (currentAllDrop.getType() == currentBlockDrop.getType() && (currentAllDrop.getAmount() + currentBlockDrop.getAmount()) <= currentAllDrop.getMaxStackSize()) { - containsType = true; - currentAllDrop.setAmount(currentAllDrop.getAmount() + currentBlockDrop.getAmount()); - } - } - - if (!containsType) { - allDrops.add(currentBlockDrop); - } - - } - - } - - dropList(allDrops, block.getLocation(), inventory); - } - - private void dropList(@Nonnull Collection itemStacks, @Nonnull Location location, @Nonnull Inventory inventory) { - if (location.getWorld() == null) return; - Map stackCount = new HashMap<>(); - - for (ItemStack itemStack : itemStacks) { - if (increaseStackCount(stackCount, itemStack.getType())) { - ChallengeHelper.dropItem(itemStack, location, inventory); - location.getWorld().dropItemNaturally(location, itemStack); - } - } - } - - private boolean increaseStackCount(Map map, Material material) { - int droppedStacks = map.getOrDefault(material, 0); - if (droppedStacks >= stackDropLimit) return false; - droppedStacks++; - map.put(material, droppedStacks); - return true; - } - - protected List getAllBlocksToBreak(@Nonnull Chunk chunk, @Nonnull Material material) { - return new ListBuilder() - .fill(builder -> { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = BukkitReflectionUtils.getMinHeight(chunk.getWorld()); y < chunk.getWorld().getMaxHeight(); y++) { - Block block = chunk.getBlock(x, y, z); - if (block.getType() == material) { - builder.add(block); - } - } - } - } - }) - .build(); - } + private final int stackDropLimit; + + public AllBlocksDisappearChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-all-blocks-disappear-challenge-settings")); + setCategory(SettingCategory.WORLD); + registerSetting("break", new BooleanSubSetting( + () -> new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), + true + )); + registerSetting("place", new BooleanSubSetting( + () -> new ItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) + )); + + Document document = ChallengeConfigHelper.getSettingsDocument(); + stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!getSetting("break").getAsBoolean()) return; + if (ignorePlayer(event.getPlayer())) return; + PlayerInventory inventory = event.getPlayer().getInventory(); + event.setDropItems(false); + breakBlocks(event.getBlock(), inventory.getItemInMainHand(), inventory); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (!getSetting("place").getAsBoolean()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getBlockAgainst().getType() == Material.BEDROCK) return; + if (event.getBlockAgainst().getType() == Material.END_PORTAL) return; + breakBlocks(event.getBlockAgainst(), null, event.getPlayer().getInventory()); + } + + private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnull Inventory inventory) { + Chunk chunk = block.getChunk(); + List blocks = getAllBlocksToBreak(chunk, block.getType()); + + List allDrops = new ArrayList<>(); + + for (Block current : blocks) { + Collection drops = Challenges.getInstance().getBlockDropManager().getDrops(current, tool); + current.setType(Material.AIR); + + for (ItemStack currentBlockDrop : drops) { + boolean containsType = false; + + for (ItemStack currentAllDrop : allDrops) { + if (currentAllDrop.getType() == currentBlockDrop.getType() && (currentAllDrop.getAmount() + currentBlockDrop.getAmount()) <= currentAllDrop.getMaxStackSize()) { + containsType = true; + currentAllDrop.setAmount(currentAllDrop.getAmount() + currentBlockDrop.getAmount()); + } + } + + if (!containsType) { + allDrops.add(currentBlockDrop); + } + + } + + } + + dropList(allDrops, block.getLocation(), inventory); + } + + private void dropList(@Nonnull Collection itemStacks, @Nonnull Location location, @Nonnull Inventory inventory) { + if (location.getWorld() == null) return; + Map stackCount = new HashMap<>(); + + for (ItemStack itemStack : itemStacks) { + if (increaseStackCount(stackCount, itemStack.getType())) { + ChallengeHelper.dropItem(itemStack, location, inventory); + location.getWorld().dropItemNaturally(location, itemStack); + } + } + } + + private boolean increaseStackCount(Map map, Material material) { + int droppedStacks = map.getOrDefault(material, 0); + if (droppedStacks >= stackDropLimit) return false; + droppedStacks++; + map.put(material, droppedStacks); + return true; + } + + protected List getAllBlocksToBreak(@Nonnull Chunk chunk, @Nonnull Material material) { + return new ListBuilder() + .fill(builder -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = BukkitReflectionUtils.getMinHeight(chunk.getWorld()); y < chunk.getWorld().getMaxHeight(); y++) { + Block block = chunk.getBlock(x, y, z); + if (block.getType() == material) { + builder.add(block); + } + } + } + } + }) + .build(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index e2fb9e0f6..9ea5570da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -23,213 +23,209 @@ import java.util.List; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class AnvilRainChallenge extends MenuSetting { - private final Random random = new Random(); - int currentTime = 0; - - public AnvilRainChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-anvil-rain-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 30, - 7 - ) - ); - registerSetting("count", new NumberSubSetting( - () -> new ItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), - 1, - 30, - 8 - ) - ); - registerSetting("range", new NumberSubSetting( - () -> new ItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), - value -> null, - value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), - 1, - 3, - 2 - ) - ); - registerSetting("damage", new NumberSubSetting( - () -> new ItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), - value -> null, - value -> "§e" + Display.HEARTS.formatChat(value), - 1, - 60, - 30 - ) - ); - } - - @Override - protected void onDisable() { - removeAnvils(); - } - - @TimerTask(async = false, status = TimerStatus.PAUSED) - public void onPause() { - removeAnvils(); - } - - private void removeAnvils() { - for (World world : Bukkit.getWorlds()) { - for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { - // TODO: SWITCH CASE - String name = entity.getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) continue; - entity.remove(); - } - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - currentTime++; - - if (currentTime > getSetting("time").getAsInt()) { - currentTime = 0; - handleTimeActivation(); - } - - } - - private void handleTimeActivation() { - List chunks = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - - List targetChunks = getTargetChunks(player.getLocation().getChunk()); - for (Chunk targetChunk : targetChunks) { - if (chunks.contains(targetChunk)) continue; - chunks.add(targetChunk); - spawnAnvils(targetChunk, getHeight(player.getLocation().getBlockY())); - } - } - - } - - private void spawnAnvils(@Nonnull Chunk chunk, int height) { - for (int i = 0; i < getCount(); i++) { - Block block = getRandomBlockInChunk(chunk, height); - Location location = block.getLocation().add(0.5, 0, 0.5); - block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); - } - } - - private List getTargetChunks(@Nonnull Chunk origin) { - List chunks = new ArrayList<>(); - - int originX = origin.getX(); - int originZ = origin.getZ(); - - int range = getRange(); - for (int x = -range; x <= range; x++) { - for (int z = -range; z <= range; z++) { - Chunk chunkAt = origin.getWorld().getChunkAt(originX + x, originZ + z); - chunks.add(chunkAt); - } - - } - - return chunks; - } - - private Block getRandomBlockInChunk(@Nonnull Chunk chunk, int y) { - int x = random.nextInt(16); - int z = random.nextInt(16); - return chunk.getBlock(x, y, z); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof FallingBlock)) return; - - String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) return; - - Block block = event.getBlock().getLocation().subtract(0, 1, 0).getBlock(); - if (BukkitReflectionUtils.isAir(block.getType())) return; - - event.getBlock().setType(Material.AIR); - event.setCancelled(true); - event.getEntity().remove(); - destroyRandomBlocks(event.getBlock().getLocation()); - applyDamageToNearEntities(event.getBlock().getLocation().add(0.5, 0.5, 0.5)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDrop(@Nonnull EntityDropItemEvent event) { - if (event.getItemDrop().getItemStack().getType() != Material.ANVIL) return; - if (event.getEntityType() != EntityType.FALLING_BLOCK) return; - String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) return; - - event.setCancelled(true); - - destroyRandomBlocks(event.getEntity().getLocation()); - applyDamageToNearEntities(event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0.5, 0.5)); - } - - public void destroyRandomBlocks(@Nonnull Location origin) { - int i = random.nextInt(2); - - if (i == 0) return; - int blocks = getCount() < 16 ? 0 : 1; - while (blocks < 2 && origin.getBlockY() > 1) { - - if (origin.getBlock().getType() == Material.WATER || origin.getBlock().getType() == Material.LAVA) - return; - origin.subtract(0, 1, 0); - if (origin.getBlock().isPassable()) blocks--; - - origin.getBlock().setType(Material.AIR); - blocks++; - } - - } - - public void applyDamageToNearEntities(@Nonnull Location location) { - if (location.getWorld() == null) return; - for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { - if (!(entity instanceof LivingEntity)) continue; - LivingEntity livingEntity = (LivingEntity) entity; - livingEntity.damage(getDamage()); - } - - } - - private int getRange() { - return getSetting("range").getAsInt(); - } + private final Random random = new Random(); + int currentTime = 0; + + public AnvilRainChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-anvil-rain-challenge-settings")); + setCategory(SettingCategory.WORLD); + registerSetting("time", new NumberSubSetting( + () -> new ItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 30, + 7 + ) + ); + registerSetting("count", new NumberSubSetting( + () -> new ItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), + 1, + 30, + 8 + ) + ); + registerSetting("range", new NumberSubSetting( + () -> new ItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), + value -> null, + value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), + 1, + 3, + 2 + ) + ); + registerSetting("damage", new NumberSubSetting( + () -> new ItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), + value -> null, + value -> "§e" + Display.HEARTS.formatChat(value), + 1, + 60, + 30 + ) + ); + } + + @Override + protected void onDisable() { + removeAnvils(); + } + + @TimerTask(async = false, status = TimerStatus.PAUSED) + public void onPause() { + removeAnvils(); + } + + private void removeAnvils() { + for (World world : Bukkit.getWorlds()) { + for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { + // TODO: SWITCH CASE + String name = entity.getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) continue; + entity.remove(); + } + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + currentTime++; + + if (currentTime > getSetting("time").getAsInt()) { + currentTime = 0; + handleTimeActivation(); + } + + } + + private void handleTimeActivation() { + List chunks = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + + List targetChunks = getTargetChunks(player.getLocation().getChunk()); + for (Chunk targetChunk : targetChunks) { + if (chunks.contains(targetChunk)) continue; + chunks.add(targetChunk); + spawnAnvils(targetChunk, getHeight(player.getLocation().getBlockY())); + } + } + + } + + private void spawnAnvils(@Nonnull Chunk chunk, int height) { + for (int i = 0; i < getCount(); i++) { + Block block = getRandomBlockInChunk(chunk, height); + Location location = block.getLocation().add(0.5, 0, 0.5); + block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); + } + } + + private List getTargetChunks(@Nonnull Chunk origin) { + List chunks = new ArrayList<>(); + + int originX = origin.getX(); + int originZ = origin.getZ(); + + int range = getRange(); + for (int x = -range; x <= range; x++) { + for (int z = -range; z <= range; z++) { + Chunk chunkAt = origin.getWorld().getChunkAt(originX + x, originZ + z); + chunks.add(chunkAt); + } + + } + + return chunks; + } + + private Block getRandomBlockInChunk(@Nonnull Chunk chunk, int y) { + int x = random.nextInt(16); + int z = random.nextInt(16); + return chunk.getBlock(x, y, z); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof FallingBlock)) return; + + String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) return; + + Block block = event.getBlock().getLocation().subtract(0, 1, 0).getBlock(); + if (BukkitReflectionUtils.isAir(block.getType())) return; + + event.getBlock().setType(Material.AIR); + event.setCancelled(true); + event.getEntity().remove(); + destroyRandomBlocks(event.getBlock().getLocation()); + applyDamageToNearEntities(event.getBlock().getLocation().add(0.5, 0.5, 0.5)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDrop(@Nonnull EntityDropItemEvent event) { + if (event.getItemDrop().getItemStack().getType() != Material.ANVIL) return; + if (event.getEntityType() != EntityType.FALLING_BLOCK) return; + String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) return; + + event.setCancelled(true); + + destroyRandomBlocks(event.getEntity().getLocation()); + applyDamageToNearEntities(event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0.5, 0.5)); + } + + public void destroyRandomBlocks(@Nonnull Location origin) { + int i = random.nextInt(2); + + if (i == 0) return; + int blocks = getCount() < 16 ? 0 : 1; + while (blocks < 2 && origin.getBlockY() > 1) { + + if (origin.getBlock().getType() == Material.WATER || origin.getBlock().getType() == Material.LAVA) + return; + origin.subtract(0, 1, 0); + if (origin.getBlock().isPassable()) blocks--; + + origin.getBlock().setType(Material.AIR); + blocks++; + } + + } + + public void applyDamageToNearEntities(@Nonnull Location location) { + if (location.getWorld() == null) return; + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { + if (!(entity instanceof LivingEntity)) continue; + LivingEntity livingEntity = (LivingEntity) entity; + livingEntity.damage(getDamage()); + } + + } + + private int getRange() { + return getSetting("range").getAsInt(); + } - private int getCount() { - return getSetting("count").getAsInt(); - } + private int getCount() { + return getSetting("count").getAsInt(); + } - private int getDamage() { - return getSetting("damage").getAsInt(); - } + private int getDamage() { + return getSetting("damage").getAsInt(); + } - private int getHeight(int currentHeight) { - return currentHeight + 50; - } + private int getHeight(int currentHeight) { + return currentHeight + 50; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index cf110f0ad..20cfef5a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -15,31 +15,26 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BedrockPathChallenge extends Setting { - public BedrockPathChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } + public BedrockPathChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); + } - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; - BlockUtils.createBlockPath(event.getFrom(), event.getTo(), Material.BEDROCK); - } + BlockUtils.createBlockPath(event.getFrom(), event.getTo(), Material.BEDROCK); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 8e5e013b6..00369062f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -17,58 +17,53 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BedrockWallChallenge extends SettingModifier { - public BedrockWallChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } + public BedrockWallChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; - Location location = event.getTo(); - if (location == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; + Location location = event.getTo(); + if (location == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - World world = event.getPlayer().getWorld(); + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + World world = event.getPlayer().getWorld(); - List blocks = new ArrayList<>(); - for (int y = BukkitReflectionUtils.getMinHeight(world) + 1; y < world.getMaxHeight(); y++) { - Location blockLocation = location.clone(); - blockLocation.setY(y); - blocks.add(blockLocation.getBlock()); - } + List blocks = new ArrayList<>(); + for (int y = BukkitReflectionUtils.getMinHeight(world) + 1; y < world.getMaxHeight(); y++) { + Location blockLocation = location.clone(); + blockLocation.setY(y); + blocks.add(blockLocation.getBlock()); + } - Bukkit.getScheduler().runTask(plugin, () -> { - for (Block block : blocks) { - block.setType(Material.BEDROCK, false); - } - }); + Bukkit.getScheduler().runTask(plugin, () -> { + for (Block block : blocks) { + block.setType(Material.BEDROCK, false); + } + }); - }, getValue() * 20L); + }, getValue() * 20L); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index b304bd2dc..61a77a830 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -17,50 +17,46 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class BlockFlyInAirChallenge extends Setting { - public BlockFlyInAirChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } + public BlockFlyInAirChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FERN, Message.forName("item-blocks-fly-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FERN, Message.forName("item-blocks-fly-challenge")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - if (!blockBelow.getType().isSolid()) return; + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + if (!blockBelow.getType().isSolid()) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { - boostBlockInAir(blockBelow); - }, 20); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + boostBlockInAir(blockBelow); + }, 20); - } + } - private void boostBlockInAir(Block block) { - if (!block.getType().isSolid()) return; + private void boostBlockInAir(Block block) { + if (!block.getType().isSolid()) return; - FallingBlock fallingBlock = block.getWorld() - .spawnFallingBlock(block.getLocation().add(0.5, 0, 0.5), block.getBlockData()); - fallingBlock.setInvulnerable(true); - fallingBlock.setVelocity(new Vector(0, 1, 0)); + FallingBlock fallingBlock = block.getWorld() + .spawnFallingBlock(block.getLocation().add(0.5, 0, 0.5), block.getBlockData()); + fallingBlock.setInvulnerable(true); + fallingBlock.setVelocity(new Vector(0, 1, 0)); - block.setType(Material.AIR); - } + block.setType(Material.AIR); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f1463439c..f86204b47 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -20,54 +20,50 @@ import java.util.HashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class BlocksDisappearAfterTimeChallenge extends SettingModifier { - private final Map tasks = new HashMap<>(); + private final Map tasks = new HashMap<>(); - public BlocksDisappearAfterTimeChallenge() { - super(MenuType.CHALLENGES, 60, 300); - setCategory(SettingCategory.WORLD); - } + public BlocksDisappearAfterTimeChallenge() { + super(MenuType.CHALLENGES, 60, 300); + setCategory(SettingCategory.WORLD); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); - if (oldTask != null) oldTask.cancel(); - tasks.put(event.getBlock(), runTask(event.getBlock())); + BukkitTask oldTask = tasks.remove(event.getBlock()); + if (oldTask != null) oldTask.cancel(); + tasks.put(event.getBlock(), runTask(event.getBlock())); - } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); - if (oldTask != null) oldTask.cancel(); - } + BukkitTask oldTask = tasks.remove(event.getBlock()); + if (oldTask != null) oldTask.cancel(); + } - private BukkitTask runTask(@Nonnull Block block) { - return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); - } + private BukkitTask runTask(@Nonnull Block block) { + return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 8c766be96..2e1c5c8a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -16,96 +16,92 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class ChunkDeconstructionChallenge extends TimedChallenge { - public ChunkDeconstructionChallenge() { - super(MenuType.CHALLENGES, 1, 60, 20); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - if (ChallengeAPI.isWorldInUse()) return; - - for (Chunk chunk : getChunksToDeconstruct()) { - if (!chunk.isLoaded()) continue; - deconstructChunk(chunk); - } - - restartTimer(); - } - - private void deconstructChunk(@Nonnull Chunk chunk) { - - for (int x = 0; x < 16; x++) { - int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { - for (int z = 0; z < 16; z++) { - deconstructAtLocation(chunk.getBlock(finalX, 0, z)); - } - }); - } - - } - - private void deconstructAtLocation(@Nonnull Block block) { - Block lowestBreakableBlock = getLowestBreakableBlock(block); - if (lowestBreakableBlock == null) return; - - lowestBreakableBlock.setType(Material.AIR, true); - } - - @Nullable - private Block getLowestBreakableBlock(@Nonnull Block block) { - Location location = block.getLocation(); - location.setY(block.getWorld().getMaxHeight()); - - while (location.getY() >= BukkitReflectionUtils.getMinHeight(block.getWorld()) && !isBreakable(location.getBlock())) { - location.subtract(0, 1, 0); - } - - Block currentBlock = location.getBlock(); - return currentBlock.getType() == Material.BEDROCK || currentBlock.isLiquid() ? null : location.getBlock(); - } - - private boolean isBreakable(@Nonnull Block block) { - return block.getType() != Material.BEDROCK && !BukkitReflectionUtils.isAir(block.getType()) && !block.isLiquid(); - } - - private List getChunksToDeconstruct() { - return new ListBuilder().fill(builder -> - Bukkit.getOnlinePlayers().forEach(player -> { - if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) - return; - builder.addIfNotContains(player.getLocation().getChunk()); - }) - ).build(); - } - -} \ No newline at end of file + public ChunkDeconstructionChallenge() { + super(MenuType.CHALLENGES, 1, 60, 20); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + if (ChallengeAPI.isWorldInUse()) return; + + for (Chunk chunk : getChunksToDeconstruct()) { + if (!chunk.isLoaded()) continue; + deconstructChunk(chunk); + } + + restartTimer(); + } + + private void deconstructChunk(@Nonnull Chunk chunk) { + + for (int x = 0; x < 16; x++) { + int finalX = x; + Bukkit.getScheduler().runTask(plugin, () -> { + for (int z = 0; z < 16; z++) { + deconstructAtLocation(chunk.getBlock(finalX, 0, z)); + } + }); + } + + } + + private void deconstructAtLocation(@Nonnull Block block) { + Block lowestBreakableBlock = getLowestBreakableBlock(block); + if (lowestBreakableBlock == null) return; + + lowestBreakableBlock.setType(Material.AIR, true); + } + + @Nullable + private Block getLowestBreakableBlock(@Nonnull Block block) { + Location location = block.getLocation(); + location.setY(block.getWorld().getMaxHeight()); + + while (location.getY() >= BukkitReflectionUtils.getMinHeight(block.getWorld()) && !isBreakable(location.getBlock())) { + location.subtract(0, 1, 0); + } + + Block currentBlock = location.getBlock(); + return currentBlock.getType() == Material.BEDROCK || currentBlock.isLiquid() ? null : location.getBlock(); + } + + private boolean isBreakable(@Nonnull Block block) { + return block.getType() != Material.BEDROCK && !BukkitReflectionUtils.isAir(block.getType()) && !block.isLiquid(); + } + + private List getChunksToDeconstruct() { + return new ListBuilder().fill(builder -> + Bukkit.getOnlinePlayers().forEach(player -> { + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) + return; + builder.addIfNotContains(player.getLocation().getChunk()); + }) + ).build(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 9116bda68..b17959b79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,28 +1,26 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import de.dytanic.cloudnet.driver.event.EventListener; -import java.util.HashMap; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.HashMap; + public class ChunkDeletionChallenge extends SettingModifier { private final HashMap> chunks = new HashMap<>(); @@ -87,7 +85,7 @@ public void onSecond() { bossbar.update(); } - @EventListener + @EventHandler(priority = EventPriority.HIGH) public void onPlayerMove(PlayerMoveEvent event) { if (event.getTo() == null || !checkIfAllowed(event.getPlayer())) { return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 98450318b..94ec501fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -16,52 +16,47 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FloorIsLavaChallenge extends SettingModifier { - public FloorIsLavaChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } - - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; - if (event.getTo() == null) return; - if (!BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - createMagmaFloor(event.getTo()); - }, getValue() * 20L); - } - - private void createMagmaFloor(@Nonnull Location to) { - BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to, 0.6), Material.MAGMA_BLOCK, true); - Bukkit.getScheduler().runTaskLater(plugin, () -> { - createLavaFloor(to); - }, getValue() * 20L); - } - - private void createLavaFloor(@Nonnull Location to) { - BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - -} \ No newline at end of file + public FloorIsLavaChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } + + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; + if (event.getTo() == null) return; + if (!BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + createMagmaFloor(event.getTo()); + }, getValue() * 20L); + } + + private void createMagmaFloor(@Nonnull Location to) { + BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to, 0.6), Material.MAGMA_BLOCK, true); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + createLavaFloor(to); + }, getValue() * 20L); + } + + private void createLavaFloor(@Nonnull Location to) { + BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index ad7e2c3b1..b3c46958b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -24,87 +24,83 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class IceFloorChallenge extends Setting { - private final List ignoredPlayers = new ArrayList<>(); - - public IceFloorChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); - bossbar.setColor(ignoreIce(player) ? BarColor.RED : BarColor.GREEN); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - if (ignoredPlayers.contains(player)) return; - createIceFloorForPlayer(player); - } - - private void createIceFloorForPlayer(@Nonnull Player player) { - Block middleBlock = player.getLocation().clone().subtract(0, 1, 0).getBlock(); - createIceFloor(middleBlock); - } - - private void createIceFloor(@Nonnull Block middleBlock) { - - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - Location iceLocation = middleBlock.getLocation().add(x, 0, z); - Block iceBlock = iceLocation.getBlock(); - if (iceBlock.getType().isSolid()) continue; - if (!BukkitReflectionUtils.isAir(iceBlock.getType())) { - ChallengeHelper.breakBlock(iceBlock, new ItemStack(Material.AIR)); - } - iceBlock.setType(Material.PACKED_ICE); - } - } - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (!event.isSneaking()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ignoredPlayers.contains(event.getPlayer())) { - ignoredPlayers.remove(event.getPlayer()); - event.getPlayer().setVelocity(new Vector(0, 0, 0)); - createIceFloorForPlayer(event.getPlayer()); - } else { - ignoredPlayers.add(event.getPlayer()); - } - bossbar.update(event.getPlayer()); - } - - private boolean ignoreIce(@Nonnull Player player) { - return ignoredPlayers.contains(player); - } - -} \ No newline at end of file + private final List ignoredPlayers = new ArrayList<>(); + + public IceFloorChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); + bossbar.setColor(ignoreIce(player) ? BarColor.RED : BarColor.GREEN); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + if (ignoredPlayers.contains(player)) return; + createIceFloorForPlayer(player); + } + + private void createIceFloorForPlayer(@Nonnull Player player) { + Block middleBlock = player.getLocation().clone().subtract(0, 1, 0).getBlock(); + createIceFloor(middleBlock); + } + + private void createIceFloor(@Nonnull Block middleBlock) { + + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + Location iceLocation = middleBlock.getLocation().add(x, 0, z); + Block iceBlock = iceLocation.getBlock(); + if (iceBlock.getType().isSolid()) continue; + if (!BukkitReflectionUtils.isAir(iceBlock.getType())) { + ChallengeHelper.breakBlock(iceBlock, new ItemStack(Material.AIR)); + } + iceBlock.setType(Material.PACKED_ICE); + } + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (!event.isSneaking()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ignoredPlayers.contains(event.getPlayer())) { + ignoredPlayers.remove(event.getPlayer()); + event.getPlayer().setVelocity(new Vector(0, 0, 0)); + createIceFloorForPlayer(event.getPlayer()); + } else { + ignoredPlayers.add(event.getPlayer()); + } + bossbar.update(event.getPlayer()); + } + + private boolean ignoreIce(@Nonnull Player player) { + return ignoredPlayers.contains(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 065a821b5..e615d4b96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -33,317 +33,313 @@ import java.util.Map; import java.util.UUID; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ @Since("2.2.3") @ExcludeFromRandomChallenges public class LevelBorderChallenge extends Setting { - private final Map worldCenters = new HashMap<>(); - private final Map playerWorldBorders = new HashMap<>(); - private final Map packetBorders = new HashMap<>(); + private final Map worldCenters = new HashMap<>(); + private final Map playerWorldBorders = new HashMap<>(); + private final Map packetBorders = new HashMap<>(); - private final boolean useAPI = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); + private final boolean useAPI = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); - private UUID bestPlayerUUID = null; - private int bestPlayerLevel = 0; + private UUID bestPlayerUUID = null; + private int bestPlayerLevel = 0; - public LevelBorderChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Override - protected void onEnable() { - for (World world : ChallengeAPI.getGameWorlds()) { - if(useAPI) { - playerWorldBorders.put(world, Bukkit.createWorldBorder()); - } else { - packetBorders.put(world, NMSProvider.createPacketBorder(world)); - } - } - - bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-level-border").asString(bestPlayerLevel)); - }); - bossbar.show(); - updateBorderSize(false); - worldCenters.put(ChallengeAPI.getGameWorld(World.Environment.NORMAL), getDefaultWorldSpawn()); - } - - @Override - protected void onDisable() { - borderReset(); - bossbar.hide(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTING_TABLE, Message.forName("item-level-border-challenges")); - } - - public void checkBorderSize(boolean animate) { - Player currentBestPlayer = bestPlayerUUID != null ? Bukkit.getPlayer(bestPlayerUUID) : null; - - for (Player player : ChallengeAPI.getIngamePlayers()) { - int level = player.getLevel(); - - if (bestPlayerUUID == null || currentBestPlayer == null) { - bestPlayerLevel = level; - bestPlayerUUID = player.getUniqueId(); - // Checks if the player is better than the saved level or if online the current player level. - // Checking with the player instance is required to fix issues with dying and the level of the best player being 0. - } else if (level > bestPlayerLevel || level > currentBestPlayer.getLevel()) { - bestPlayerLevel = level; - bestPlayerUUID = player.getUniqueId(); - } else if (player.getUniqueId().equals(bestPlayerUUID)) { - bestPlayerLevel = level; - } - } - - updateBorderSize(animate); - bossbar.update(); - } + public LevelBorderChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } - @ScheduledTask(ticks = 100, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBorderSize() { - checkBorderSize(true); + @Override + protected void onEnable() { + for (World world : ChallengeAPI.getGameWorlds()) { + if (useAPI) { + playerWorldBorders.put(world, Bukkit.createWorldBorder()); + } else { + packetBorders.put(world, NMSProvider.createPacketBorder(world)); + } } - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.STARTED) - public void playerSpawnTeleport() { - broadcastFiltered(player -> { - if (player.isDead()) return; - World world = player.getWorld(); - if (isOutsideBorder(player.getLocation())) { - teleportInsideBorder(world, player); - } - }); + bossbar.setContent((bar, player) -> { + bar.setTitle(Message.forName("bossbar-level-border").asString(bestPlayerLevel)); + }); + bossbar.show(); + updateBorderSize(false); + worldCenters.put(ChallengeAPI.getGameWorld(World.Environment.NORMAL), getDefaultWorldSpawn()); + } + + @Override + protected void onDisable() { + borderReset(); + bossbar.hide(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENCHANTING_TABLE, Message.forName("item-level-border-challenges")); + } + + public void checkBorderSize(boolean animate) { + Player currentBestPlayer = bestPlayerUUID != null ? Bukkit.getPlayer(bestPlayerUUID) : null; + + for (Player player : ChallengeAPI.getIngamePlayers()) { + int level = player.getLevel(); + + if (bestPlayerUUID == null || currentBestPlayer == null) { + bestPlayerLevel = level; + bestPlayerUUID = player.getUniqueId(); + // Checks if the player is better than the saved level or if online the current player level. + // Checking with the player instance is required to fix issues with dying and the level of the best player being 0. + } else if (level > bestPlayerLevel || level > currentBestPlayer.getLevel()) { + bestPlayerLevel = level; + bestPlayerUUID = player.getUniqueId(); + } else if (player.getUniqueId().equals(bestPlayerUUID)) { + bestPlayerLevel = level; + } } - public boolean isOutsideBorder(Location location) { - double size = bestPlayerLevel + 1; - Location center = worldCenters.get(location.getWorld()); - if (center == null) return false; - double x = Math.abs(location.getX()) - Math.abs(center.getX()); - double z = Math.abs(location.getZ()) - Math.abs(center.getZ()); - return Math.abs(x) > size || Math.abs(z) > size; + updateBorderSize(animate); + bossbar.update(); + } + + @ScheduledTask(ticks = 100, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBorderSize() { + checkBorderSize(true); + } + + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.STARTED) + public void playerSpawnTeleport() { + broadcastFiltered(player -> { + if (player.isDead()) return; + World world = player.getWorld(); + if (isOutsideBorder(player.getLocation())) { + teleportInsideBorder(world, player); + } + }); + } + + public boolean isOutsideBorder(Location location) { + double size = bestPlayerLevel + 1; + Location center = worldCenters.get(location.getWorld()); + if (center == null) return false; + double x = Math.abs(location.getX()) - Math.abs(center.getX()); + double z = Math.abs(location.getZ()) - Math.abs(center.getZ()); + return Math.abs(x) > size || Math.abs(z) > size; + } + + private Location getCenter(World world) { + Location center; + if (useAPI) { + center = playerWorldBorders.get(world).getCenter().subtract(0.5, 0, 0.5); + center.setY(world.getHighestBlockYAt((int) center.getX(), (int) center.getZ())); + } else { + PacketBorder packetBorder = packetBorders.get(world); + double centerX = packetBorder.getCenterX(); + double centerZ = packetBorder.getCenterZ(); + center = new Location(world, centerX, world.getHighestBlockYAt((int) centerX, (int) centerZ), centerZ); } - - private Location getCenter(World world) { - Location center; - if (useAPI) { - center = playerWorldBorders.get(world).getCenter().subtract(0.5, 0, 0.5); - center.setY(world.getHighestBlockYAt((int) center.getX(), (int) center.getZ())); - } else { - PacketBorder packetBorder = packetBorders.get(world); - double centerX = packetBorder.getCenterX(); - double centerZ = packetBorder.getCenterZ(); - center = new Location(world, centerX, world.getHighestBlockYAt((int) centerX, (int) centerZ), centerZ); - } - return center; + return center; + } + + public void teleportInsideBorder(@NotNull World world, Player player) { + Location center = getCenter(world).clone(); + center.setWorld(world); + if (world.getEnvironment() != World.Environment.NORMAL) { + player.teleport(center); + } else { + player.teleport(center.add(0.5, 1, 0.5)); } + } - public void teleportInsideBorder(@NotNull World world, Player player) { - Location center = getCenter(world).clone(); - center.setWorld(world); - if (world.getEnvironment() != World.Environment.NORMAL) { - player.teleport(center); - } else { - player.teleport(center.add(0.5, 1, 0.5)); - } + private Location getDefaultWorldSpawn() { + World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); + if (worldCenters.containsKey(world)) { + return worldCenters.get(world); } - - private Location getDefaultWorldSpawn() { - World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); - if (worldCenters.containsKey(world)) { - return worldCenters.get(world); - } - Location location = world.getSpawnLocation(); - location.setX(location.getBlockX() + 0.5); - location.setZ(location.getBlockZ() + 0.5); - return location; + Location location = world.getSpawnLocation(); + location.setX(location.getBlockX() + 0.5); + location.setZ(location.getBlockZ() + 0.5); + return location; + } + + private void updateBorderSize(boolean animate) { + for (World world : ChallengeAPI.getGameWorlds()) { + if (world.getPlayers().isEmpty()) { + continue; + } + updateBorderSize(world, animate); } - - private void updateBorderSize(boolean animate) { - for (World world : ChallengeAPI.getGameWorlds()) { - if (world.getPlayers().isEmpty()) { - continue; - } - updateBorderSize(world, animate); - } + } + + private void updateBorderSize(@Nonnull World world, boolean animate) { + Location location = worldCenters.get(world); + if (location == null) return; + int newSize = bestPlayerLevel + 1; + updateBorder(world, location, newSize == 0 ? 1 : newSize, animate); + for (Player player : world.getPlayers()) { + sendBorder(player); } + } - private void updateBorderSize(@Nonnull World world, boolean animate) { - Location location = worldCenters.get(world); - if (location == null) return; - int newSize = bestPlayerLevel + 1; - updateBorder(world, location, newSize == 0 ? 1 : newSize, animate); - for (Player player : world.getPlayers()) { - sendBorder(player); - } + public void borderReset() { + if (useAPI) { + playerWorldBorders.values().forEach(WorldBorder::reset); + } else { + broadcast(player -> packetBorders.get(player.getWorld()).reset(player)); } - - public void borderReset() { - if (useAPI) { - playerWorldBorders.values().forEach(WorldBorder::reset); - } else { - broadcast(player -> packetBorders.get(player.getWorld()).reset(player)); - } + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onTimerStart() { + if (!isEnabled()) return; + checkBorderSize(false); + playerSpawnTeleport(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLevelChange(@Nonnull PlayerLevelChangeEvent event) { + if (!shouldExecuteEffect()) return; + checkBorderSize(true); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + playerSpawnTeleport(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + } + + /** + * Teleports the player back inside border if spawnpoint is outside of it. + * Will rarely occur by beds since minecraft blocks bed respawn outside the border but + * because of the random spawning mechanic at the world spawn. + */ + @EventHandler(priority = EventPriority.HIGH) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> { + checkBorderSize(false); + playerSpawnTeleport(); + }, 1); + } + + /** + * Execute level change event when dying instead of respawning like spigot does it + */ + @EventHandler(priority = EventPriority.HIGH) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getEntity())) return; + PlayerLevelChangeEvent lvlEvent = new PlayerLevelChangeEvent( + event.getEntity(), event.getEntity().getLevel(), 0); + event.getEntity().setLevel(0); + onLevelChange(lvlEvent); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getDamager().getType() != EntityType.PLAYER) return; + if (!event.isCancelled()) return; + if (isOutsideBorder(event.getEntity().getLocation()) && + !isOutsideBorder(event.getDamager().getLocation())) { + event.setCancelled(false); } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onTimerStart() { - if (!isEnabled()) return; - checkBorderSize(false); - playerSpawnTeleport(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(@Nonnull PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && + event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return; + World world = event.getTo().getWorld(); + if (world == null) return; + if (world == Challenges.getInstance().getWorldManager().getExtraWorld()) return; + Location location = event.getTo().getBlock().getLocation().add(0.5, 0, 0.5); + if (!worldCenters.containsKey(world)) worldCenters.put(world, location); + updateBorderSize(world, false); + } + + @Override + public void loadGameState(@NotNull Document document) { + bestPlayerLevel = document.getInt("level"); + String uuid = document.getString("uuid"); + if (uuid != null) { + bestPlayerUUID = UUID.fromString(uuid); } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLevelChange(@Nonnull PlayerLevelChangeEvent event) { - if (!shouldExecuteEffect()) return; - checkBorderSize(true); + worldCenters.clear(); + Document worlds = document.getDocument("worlds"); + for (String worldName : worlds.keys()) { + World world = Bukkit.getWorld(worldName); + if (world == null) continue; + worldCenters.put(world, worlds.getInstance(worldName, Location.class)); } - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); - playerSpawnTeleport(); + if (isEnabled()) { + checkBorderSize(false); } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("level", bestPlayerLevel); + GsonDocument doc = new GsonDocument(); + worldCenters.forEach((world, location) -> doc.set(world.getName(), location)); + document.set("worlds", doc); + document.set("uuid", bestPlayerUUID); + } + + private void updateBorder(World world, Location center, int size, boolean animate) { + if (useAPI) { + WorldBorder border = playerWorldBorders.get(world); + border.setCenter(center); + double x = center.getX(); + double z = center.getZ(); + // fix bug that causes border to be misplaced + if (world.getEnvironment() == World.Environment.NETHER) { + x *= 8; + z *= 8; + } + border.setCenter(x, z); + if (animate) { + border.setSize(size, 1); + } else { + border.setSize(size); + } + border.setWarningDistance(0); + border.setWarningTime(0); + } else { + PacketBorder border = packetBorders.get(world); + border.setCenter(center.getX(), center.getZ()); + if (animate) { + border.setSize(size, 1); + } else { + border.setSize(size); + } + border.setWarningDistance(0); + border.setWarningTime(0); } - - /** - * Teleports the player back inside border if spawnpoint is outside of it. - * Will rarely occur by beds since minecraft blocks bed respawn outside the border but - * because of the random spawning mechanic at the world spawn. - */ - @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { - checkBorderSize(false); - playerSpawnTeleport(); - }, 1); - } - - /** - * Execute level change event when dying instead of respawning like spigot does it - */ - @EventHandler(priority = EventPriority.HIGH) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getEntity())) return; - PlayerLevelChangeEvent lvlEvent = new PlayerLevelChangeEvent( - event.getEntity(), event.getEntity().getLevel(), 0); - event.getEntity().setLevel(0); - onLevelChange(lvlEvent); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getDamager().getType() != EntityType.PLAYER) return; - if (!event.isCancelled()) return; - if (isOutsideBorder(event.getEntity().getLocation()) && - !isOutsideBorder(event.getDamager().getLocation())) { - event.setCancelled(false); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && - event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return; - World world = event.getTo().getWorld(); - if (world == null) return; - if (world == Challenges.getInstance().getWorldManager().getExtraWorld()) return; - Location location = event.getTo().getBlock().getLocation().add(0.5, 0, 0.5); - if (!worldCenters.containsKey(world)) worldCenters.put(world, location); - updateBorderSize(world, false); - } - - @Override - public void loadGameState(@NotNull Document document) { - bestPlayerLevel = document.getInt("level"); - String uuid = document.getString("uuid"); - if (uuid != null) { - bestPlayerUUID = UUID.fromString(uuid); - } - worldCenters.clear(); - Document worlds = document.getDocument("worlds"); - for (String worldName : worlds.keys()) { - World world = Bukkit.getWorld(worldName); - if (world == null) continue; - worldCenters.put(world, worlds.getInstance(worldName, Location.class)); - } - - if (isEnabled()) { - checkBorderSize(false); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("level", bestPlayerLevel); - GsonDocument doc = new GsonDocument(); - worldCenters.forEach((world, location) -> doc.set(world.getName(), location)); - document.set("worlds", doc); - document.set("uuid", bestPlayerUUID); - } - - private void updateBorder(World world, Location center, int size, boolean animate) { - if (useAPI) { - WorldBorder border = playerWorldBorders.get(world); - border.setCenter(center); - double x = center.getX(); - double z = center.getZ(); - // fix bug that causes border to be misplaced - if (world.getEnvironment() == World.Environment.NETHER) { - x *= 8; - z *= 8; - } - border.setCenter(x, z); - if (animate) { - border.setSize(size, 1); - } else { - border.setSize(size); - } - border.setWarningDistance(0); - border.setWarningTime(0); - } else { - PacketBorder border = packetBorders.get(world); - border.setCenter(center.getX(), center.getZ()); - if (animate) { - border.setSize(size, 1); - } else { - border.setSize(size); - } - border.setWarningDistance(0); - border.setWarningTime(0); - } - } - - private void sendBorder(@Nonnull Player player) { - if (useAPI) { - WorldBorder border = playerWorldBorders.get(player.getWorld()); - player.setWorldBorder(border); - } else { - packetBorders.get(player.getWorld()).send(player, PacketBorder.UpdateType.values()); - } + } + + private void sendBorder(@Nonnull Player player) { + if (useAPI) { + WorldBorder border = playerWorldBorders.get(player.getWorld()); + player.setWorldBorder(border); + } else { + packetBorders.get(player.getWorld()).send(player, PacketBorder.UpdateType.values()); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index ee017e3c4..000dea1ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,6 +13,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; @@ -35,7 +36,6 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; @@ -44,329 +44,325 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class LoopChallenge extends Setting { - private static final Map loops = new HashMap<>(); - - public LoopChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); - } + private static final Map loops = new HashMap<>(); + + public LoopChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); + } - @ScheduledTask(ticks = 1, async = false) - public void onTick() { - long currentTimeMillis = System.currentTimeMillis(); + @ScheduledTask(ticks = 1, async = false) + public void onTick() { + long currentTimeMillis = System.currentTimeMillis(); - for (Entry entry : new ArrayList<>(loops.entrySet())) { - - if (entry.getValue() + 1000 <= currentTimeMillis) { - entry.getKey().execute(); - loops.put(entry.getKey(), currentTimeMillis); - } - - } - - } - - @TimerTask(status = TimerStatus.PAUSED, async = false, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onPause() { - clearLoops(); - } - - private void clearLoops() { - if (loops.isEmpty()) return; - broadcast(player -> new SoundSample().addSound(Sound.ENTITY_ITEM_BREAK, 0.5f).play(player)); - Message.forName("loops-cleared").broadcast(Prefix.CHALLENGES, loops.size()); - loops.clear(); - } - - private void createLoop(@Nonnull Loop loop) { - loops.put(loop, System.currentTimeMillis()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.isSneaking()) return; - clearLoops(); - } - - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { - if (!shouldExecuteEffect()) return; - ProjectileSource shooter = event.getEntity().getShooter(); - if (shooter == null) return; - if (shooter instanceof Player && ignorePlayer(((Player) shooter))) return; - createLoop(new ProjectileLaunchLoop(event)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - double damage = event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); - if (damage == 0) return; - createLoop(new EntityDamageLoop(((LivingEntity) event.getEntity()), event.getCause(), damage)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - createLoop(new BlockPlaceLoop(event.getBlock().getType(), event.getPlayer(), event.getBlockAgainst().getFace(event.getBlock()), event.getBlock())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - Player player = event.getPlayer(); - if (ignorePlayer(player)) return; - - - RayTraceResult result = player.getWorld().rayTraceBlocks(player.getEyeLocation(), player.getLocation().getDirection(), 5); - if (result == null) return; - if (result.getHitBlockFace() == null) return; - - - createLoop(new BlockBreakLoop(player.getInventory().getItemInMainHand(), player, result.getHitBlockFace().getOppositeFace(), event.getBlock())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - createLoop(new DropLoop(event.getItemDrop().getItemStack(), event.getPlayer())); - } - - private interface Loop { - - void execute(); - - default void cancel() { - loops.remove(this); - } - - } - - private static class ProjectileLaunchLoop implements Loop { - - private final Vector launchVelocity; - private final Location launchLocation; - private final EntityType entityType; - - public ProjectileLaunchLoop(ProjectileLaunchEvent event) { - this.launchVelocity = event.getEntity().getVelocity(); - this.launchLocation = event.getLocation(); - this.entityType = event.getEntityType(); - } - - @Override - public void execute() { - if (launchLocation.getWorld() == null) return; - Projectile projectile = (Projectile) launchLocation.getWorld().spawnEntity(launchLocation, entityType); - projectile.setVelocity(launchVelocity); - if (projectile instanceof Arrow) { - ((Arrow) projectile).setPickupStatus(PickupStatus.DISALLOWED); - } - } - - } - - private static class EntityDamageLoop implements Loop { - - private final LivingEntity entity; - private final DamageCause damageCause; - private final double damage; - - public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { - this.entity = entity; - this.damageCause = cause; - this.damage = damage; - } - - @Override - public void execute() { - if (entity.isDead()) { - cancel(); - return; - } - if (entity instanceof Player && ignorePlayer(((Player) entity))) return; - entity.damage(damage); - } - } - - private static class BlockPlaceLoop implements Loop { - - private final Material material; - private final Player player; - private final BlockFace blockFace; - private Block currentBlock; - - public BlockPlaceLoop(Material material, Player player, BlockFace blockFace, Block currentBlock) { - this.material = material; - this.player = player; - this.blockFace = blockFace; - this.currentBlock = currentBlock; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - currentBlock = currentBlock.getRelative(blockFace); - - if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { - cancel(); - return; - } else if (!BukkitReflectionUtils.isAir(currentBlock.getType()) && currentBlock.getType().isSolid()) { - return; - } else if (!decreaseMaterial()) { - cancel(); - return; - } - - currentBlock.setType(material); - } - - private boolean decreaseMaterial() { - ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.getType() == material).findFirst().orElse(null); - if (item == null) return false; - item.setAmount(item.getAmount() - 1); - return true; - } - - } - - private static class BlockBreakLoop implements Loop { - - private final Player player; - private final BlockFace blockFace; - private ItemStack itemStack; - private Block currentBlock; - - public BlockBreakLoop(ItemStack itemStack, Player player, BlockFace blockFace, Block currentBlock) { - this.itemStack = itemStack; - this.player = player; - this.blockFace = blockFace; - this.currentBlock = currentBlock; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - currentBlock = currentBlock.getRelative(blockFace); - - if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { - cancel(); - return; - } else if (BukkitReflectionUtils.isAir(currentBlock.getType())) { - return; - } else if (!decreaseDurability()) { - cancel(); - return; - } - - if (currentBlock.getType() == Material.BEDROCK) return; - - if (cantBeBroken(currentBlock, itemStack)) { - currentBlock.setType(Material.AIR); - return; - } - - - ChallengeHelper.breakBlock(currentBlock, itemStack, player.getInventory()); - } - - private boolean decreaseDurability() { - if (itemStack.getType() == Material.AIR) return true; - if (!isTool(itemStack)) return true; - - - itemStack = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); - if (itemStack == null) return false; - - if (itemStack.getItemMeta() == null) return true; - org.bukkit.inventory.meta.Damageable damageable = (org.bukkit.inventory.meta.Damageable) itemStack.getItemMeta(); - if (damageable == null) return false; - damageable.setDamage(damageable.getDamage() + 1); - itemStack.setItemMeta((ItemMeta) damageable); - - for (int slot = 0; slot < player.getInventory().getSize(); slot++) { - ItemStack item = player.getInventory().getItem(slot); - if (item == null) continue; - if (!isTool(item)) continue; - if (item.getItemMeta() == null) continue; - if (((org.bukkit.inventory.meta.Damageable) item.getItemMeta()).getDamage() >= item.getType().getMaxDurability()) { - player.getInventory().setItem(slot, null); - } - } - - return true; - } - - private boolean isTool(@Nonnull ItemStack itemStack) { - if (itemStack.getItemMeta() != null) { - try { - Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(Attribute.GENERIC_ATTACK_DAMAGE); - return attributeModifiers == null || !attributeModifiers.isEmpty(); - } catch (NullPointerException exception) { - return false; - } - } - return true; - } - - private boolean cantBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { - return block.getDrops(tool).isEmpty(); - } - - } - - private static class DropLoop implements Loop { - - private final ItemStack itemStack; - private final Player player; - - public DropLoop(ItemStack itemStack, Player player) { - itemStack = itemStack.clone(); - itemStack.setAmount(1); - this.itemStack = itemStack; - this.player = player; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - if (!decreaseItem()) { - cancel(); - return; - } - - InventoryUtils.dropItemByPlayer(player.getLocation(), itemStack); - } - - private boolean decreaseItem() { - ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); - if (item == null) return false; - item.setAmount(item.getAmount() - 1); - return true; - } - - } - -} \ No newline at end of file + for (Entry entry : new ArrayList<>(loops.entrySet())) { + + if (entry.getValue() + 1000 <= currentTimeMillis) { + entry.getKey().execute(); + loops.put(entry.getKey(), currentTimeMillis); + } + + } + + } + + @TimerTask(status = TimerStatus.PAUSED, async = false, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onPause() { + clearLoops(); + } + + private void clearLoops() { + if (loops.isEmpty()) return; + broadcast(player -> new SoundSample().addSound(Sound.ENTITY_ITEM_BREAK, 0.5f).play(player)); + Message.forName("loops-cleared").broadcast(Prefix.CHALLENGES, loops.size()); + loops.clear(); + } + + private void createLoop(@Nonnull Loop loop) { + loops.put(loop, System.currentTimeMillis()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.isSneaking()) return; + clearLoops(); + } + + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { + if (!shouldExecuteEffect()) return; + ProjectileSource shooter = event.getEntity().getShooter(); + if (shooter == null) return; + if (shooter instanceof Player && ignorePlayer(((Player) shooter))) return; + createLoop(new ProjectileLaunchLoop(event)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + double damage = event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); + if (damage == 0) return; + createLoop(new EntityDamageLoop(((LivingEntity) event.getEntity()), event.getCause(), damage)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + createLoop(new BlockPlaceLoop(event.getBlock().getType(), event.getPlayer(), event.getBlockAgainst().getFace(event.getBlock()), event.getBlock())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + Player player = event.getPlayer(); + if (ignorePlayer(player)) return; + + + RayTraceResult result = player.getWorld().rayTraceBlocks(player.getEyeLocation(), player.getLocation().getDirection(), 5); + if (result == null) return; + if (result.getHitBlockFace() == null) return; + + + createLoop(new BlockBreakLoop(player.getInventory().getItemInMainHand(), player, result.getHitBlockFace().getOppositeFace(), event.getBlock())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + createLoop(new DropLoop(event.getItemDrop().getItemStack(), event.getPlayer())); + } + + private interface Loop { + + void execute(); + + default void cancel() { + loops.remove(this); + } + + } + + private static class ProjectileLaunchLoop implements Loop { + + private final Vector launchVelocity; + private final Location launchLocation; + private final EntityType entityType; + + public ProjectileLaunchLoop(ProjectileLaunchEvent event) { + this.launchVelocity = event.getEntity().getVelocity(); + this.launchLocation = event.getLocation(); + this.entityType = event.getEntityType(); + } + + @Override + public void execute() { + if (launchLocation.getWorld() == null) return; + Projectile projectile = (Projectile) launchLocation.getWorld().spawnEntity(launchLocation, entityType); + projectile.setVelocity(launchVelocity); + if (projectile instanceof Arrow) { + ((Arrow) projectile).setPickupStatus(PickupStatus.DISALLOWED); + } + } + + } + + private static class EntityDamageLoop implements Loop { + + private final LivingEntity entity; + private final double damage; + + public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { + this.entity = entity; + this.damage = damage; + } + + @Override + public void execute() { + if (entity.isDead()) { + cancel(); + return; + } + if (entity instanceof Player && ignorePlayer(((Player) entity))) return; + entity.damage(damage); + } + } + + private static class BlockPlaceLoop implements Loop { + + private final Material material; + private final Player player; + private final BlockFace blockFace; + private Block currentBlock; + + public BlockPlaceLoop(Material material, Player player, BlockFace blockFace, Block currentBlock) { + this.material = material; + this.player = player; + this.blockFace = blockFace; + this.currentBlock = currentBlock; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + currentBlock = currentBlock.getRelative(blockFace); + + if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { + cancel(); + return; + } else if (!BukkitReflectionUtils.isAir(currentBlock.getType()) && currentBlock.getType().isSolid()) { + return; + } else if (!decreaseMaterial()) { + cancel(); + return; + } + + currentBlock.setType(material); + } + + private boolean decreaseMaterial() { + ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.getType() == material).findFirst().orElse(null); + if (item == null) return false; + item.setAmount(item.getAmount() - 1); + return true; + } + + } + + private static class BlockBreakLoop implements Loop { + + private final Player player; + private final BlockFace blockFace; + private ItemStack itemStack; + private Block currentBlock; + + public BlockBreakLoop(ItemStack itemStack, Player player, BlockFace blockFace, Block currentBlock) { + this.itemStack = itemStack; + this.player = player; + this.blockFace = blockFace; + this.currentBlock = currentBlock; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + currentBlock = currentBlock.getRelative(blockFace); + + if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { + cancel(); + return; + } else if (BukkitReflectionUtils.isAir(currentBlock.getType())) { + return; + } else if (!decreaseDurability()) { + cancel(); + return; + } + + if (currentBlock.getType() == Material.BEDROCK) return; + + if (cantBeBroken(currentBlock, itemStack)) { + currentBlock.setType(Material.AIR); + return; + } + + + ChallengeHelper.breakBlock(currentBlock, itemStack, player.getInventory()); + } + + private boolean decreaseDurability() { + if (itemStack.getType() == Material.AIR) return true; + if (!isTool(itemStack)) return true; + + + itemStack = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); + if (itemStack == null) return false; + + if (itemStack.getItemMeta() == null) return true; + org.bukkit.inventory.meta.Damageable damageable = (org.bukkit.inventory.meta.Damageable) itemStack.getItemMeta(); + if (damageable == null) return false; + damageable.setDamage(damageable.getDamage() + 1); + itemStack.setItemMeta(damageable); + + for (int slot = 0; slot < player.getInventory().getSize(); slot++) { + ItemStack item = player.getInventory().getItem(slot); + if (item == null) continue; + if (!isTool(item)) continue; + if (item.getItemMeta() == null) continue; + if (((org.bukkit.inventory.meta.Damageable) item.getItemMeta()).getDamage() >= item.getType().getMaxDurability()) { + player.getInventory().setItem(slot, null); + } + } + + return true; + } + + private boolean isTool(@Nonnull ItemStack itemStack) { + if (itemStack.getItemMeta() != null) { + try { + Attribute attribute = AttributeWrapper.MAX_HEALTH; + Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); + return attributeModifiers == null || !attributeModifiers.isEmpty(); + + } catch (NullPointerException exception) { + return false; + } + } + return true; + } + + private boolean cantBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + return block.getDrops(tool).isEmpty(); + } + + } + + private static class DropLoop implements Loop { + + private final ItemStack itemStack; + private final Player player; + + public DropLoop(ItemStack itemStack, Player player) { + itemStack = itemStack.clone(); + itemStack.setAmount(1); + this.itemStack = itemStack; + this.player = player; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + if (!decreaseItem()) { + cancel(); + return; + } + + InventoryUtils.dropItemByPlayer(player.getLocation(), itemStack); + } + + private boolean decreaseItem() { + ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); + if (item == null) return false; + item.setAmount(item.getAmount() - 1); + return true; + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index fde4a5cc4..a0b2dc226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -34,275 +34,271 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class RepeatInChunkChallenge extends Setting { - private final Map, BlockData>> changedBlocks = new HashMap<>(); - private final Set updatedChunks = new HashSet<>(); + private final Map, BlockData>> changedBlocks = new HashMap<>(); + private final Set updatedChunks = new HashSet<>(); - public RepeatInChunkChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } + public RepeatInChunkChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-repeat-chunk-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-repeat-chunk-challenge")); + } - @Override - public void writeGameState(@NotNull Document document) { + @Override + public void writeGameState(@NotNull Document document) { - GsonDocument changedDocument = new GsonDocument(); + GsonDocument changedDocument = new GsonDocument(); - for (Entry, BlockData>> entry : changedBlocks.entrySet()) { + for (Entry, BlockData>> entry : changedBlocks.entrySet()) { - List list = Lists.newLinkedList(); + List list = Lists.newLinkedList(); - for (Entry, BlockData> blockEntry : entry.getValue().entrySet()) { - GsonDocument blockDocument = new GsonDocument(); - Triple pos = blockEntry.getKey(); - blockDocument.set("x", pos.getFirst()); - blockDocument.set("y", pos.getSecond()); - blockDocument.set("z", pos.getThird()); - blockDocument.set("data", blockEntry.getValue().getAsString()); - list.add(blockDocument); - } - if (!list.isEmpty()) { - changedDocument.set(entry.getKey(), list); - } - } + for (Entry, BlockData> blockEntry : entry.getValue().entrySet()) { + GsonDocument blockDocument = new GsonDocument(); + Triple pos = blockEntry.getKey(); + blockDocument.set("x", pos.getFirst()); + blockDocument.set("y", pos.getSecond()); + blockDocument.set("z", pos.getThird()); + blockDocument.set("data", blockEntry.getValue().getAsString()); + list.add(blockDocument); + } + if (!list.isEmpty()) { + changedDocument.set(entry.getKey(), list); + } + } - document.set("changed-blocks", changedDocument); - } + document.set("changed-blocks", changedDocument); + } - @Override - public void loadGameState(@NotNull Document document) { - changedBlocks.clear(); + @Override + public void loadGameState(@NotNull Document document) { + changedBlocks.clear(); - Document changedDocument = document.getDocument("changed-blocks"); + Document changedDocument = document.getDocument("changed-blocks"); - for (World world : Bukkit.getWorlds()) { - List list = changedDocument.getDocumentList(world.getName()); - Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new HashMap<>()); - changedBlocks.putIfAbsent(world.getName(), blockMap); + for (World world : Bukkit.getWorlds()) { + List list = changedDocument.getDocumentList(world.getName()); + Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new HashMap<>()); + changedBlocks.putIfAbsent(world.getName(), blockMap); - for (Document blockDocument : list) { + for (Document blockDocument : list) { - int x = blockDocument.getInt("x"); - int y = blockDocument.getInt("y"); - int z = blockDocument.getInt("z"); + int x = blockDocument.getInt("x"); + int y = blockDocument.getInt("y"); + int z = blockDocument.getInt("z"); - if (x < 0 || z < 0) { - Logger.error("RepeatInChunkChallenge: Invalid Change Position: {}, {}, {}, {}", world.getName(), x, y, z); - continue; - } + if (x < 0 || z < 0) { + Logger.error("RepeatInChunkChallenge: Invalid Change Position: {}, {}, {}, {}", world.getName(), x, y, z); + continue; + } - Triple pos = new Triple<>(x, y, z); + Triple pos = new Triple<>(x, y, z); - String data = blockDocument.getString("data"); - BlockData blockData; - if (data != null) { - try { - blockData = Bukkit.createBlockData(data); - } catch (IllegalArgumentException exception) { - Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, data); - continue; - } - } else { - Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, null); - continue; - } + String data = blockDocument.getString("data"); + BlockData blockData; + if (data != null) { + try { + blockData = Bukkit.createBlockData(data); + } catch (IllegalArgumentException exception) { + Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, data); + continue; + } + } else { + Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, null); + continue; + } - blockMap.put(pos, blockData); - } + blockMap.put(pos, blockData); + } - } + } - } + } - @Override - protected void onEnable() { + @Override + protected void onEnable() { - for (Player player : ChallengeAPI.getIngamePlayers()) { - updateSurroundingChunks(player.getLocation().getChunk(), false); - } - } + for (Player player : ChallengeAPI.getIngamePlayers()) { + updateSurroundingChunks(player.getLocation().getChunk(), false); + } + } - private void changeBlockInEveryChunk(World world, int x, int y, int z, BlockData data, Block exception) { - updatedChunks.clear(); + private void changeBlockInEveryChunk(World world, int x, int y, int z, BlockData data, Block exception) { + updatedChunks.clear(); - Bukkit.getScheduler().runTask(plugin, () -> { + Bukkit.getScheduler().runTask(plugin, () -> { - Map, BlockData> map = changedBlocks - .getOrDefault(world.getName(), new HashMap<>()); - changedBlocks.putIfAbsent(world.getName(), map); - map.put(new Triple<>(x, y, z), data); + Map, BlockData> map = changedBlocks + .getOrDefault(world.getName(), new HashMap<>()); + changedBlocks.putIfAbsent(world.getName(), map); + map.put(new Triple<>(x, y, z), data); - for (Player player : ChallengeAPI.getIngamePlayers()) { + for (Player player : ChallengeAPI.getIngamePlayers()) { - for (Chunk chunk : getSurroundingChunks(player.getLocation().getChunk(), false)) { - Block block = chunk.getBlock(x, y, z); - if (!Objects.equals(exception, block)) { - setBlockData(block, data, true); - } - } + for (Chunk chunk : getSurroundingChunks(player.getLocation().getChunk(), false)) { + Block block = chunk.getBlock(x, y, z); + if (!Objects.equals(exception, block)) { + setBlockData(block, data, true); + } + } - } + } - }); - } + }); + } - private List getSurroundingChunks(Chunk center, boolean onlyBorder) { - int range = 8; - - int centerX = center.getX(); - int centerZ = center.getZ(); - - List chunks = Lists.newLinkedList(); - - for (int x = -range; x <= range; x++) { - - for (int z = -range; z <= range; z++) { - - if (onlyBorder) { - - if (x != -range && x != range && z != -range && z != range) { - continue; - } - - } + private List getSurroundingChunks(Chunk center, boolean onlyBorder) { + int range = 8; + + int centerX = center.getX(); + int centerZ = center.getZ(); + + List chunks = Lists.newLinkedList(); + + for (int x = -range; x <= range; x++) { + + for (int z = -range; z <= range; z++) { + + if (onlyBorder) { + + if (x != -range && x != range && z != -range && z != range) { + continue; + } + + } - Chunk chunkAt = center.getWorld().getChunkAt(centerX + x, centerZ + z); - if (updatedChunks.contains(chunkAt)) continue; - chunks.add(chunkAt); - } - } - - return chunks; - } - - private void updateSurroundingChunks(Chunk center, boolean onlyBorder) { - - for (Chunk chunk : getSurroundingChunks(center, onlyBorder)) { - updateChunk(chunk); - } - - } - - private void updateChunk(Chunk chunk) { - updatedChunks.add(chunk); - - Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new HashMap<>()); - - for (Entry, BlockData> blockEntry : dataMap.entrySet()) { - Triple pos = blockEntry.getKey(); - BlockData blockData = blockEntry.getValue(); - Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); - if (!block.getBlockData().matches(blockData)) { - setBlockData(block, blockData, false); - } - - } - - - } - - private void setBlockData(Block block, BlockData blockData, boolean update) { - if (block.getType() == Material.END_PORTAL || - block.getType() == Material.END_PORTAL_FRAME || - block.getType() == Material.END_GATEWAY) return; - block.setBlockData(blockData, update); - } - - private int getRelativeChunkCoordinate(int worldCoordinate) { - return worldCoordinate & 0xF; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Block block = event.getBlock(); - changeBlockInEveryChunk( - event.getBlock().getWorld(), - getRelativeChunkCoordinate(block.getX()), - block.getY(), - getRelativeChunkCoordinate(block.getZ()), - block.getBlockData(), - event.getBlock() - ); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Block block = event.getBlock(); - changeBlockInEveryChunk( - event.getBlock().getWorld(), - getRelativeChunkCoordinate(block.getX()), - block.getY(), - getRelativeChunkCoordinate(block.getZ()), - Bukkit.createBlockData(Material.AIR), - event.getBlock() - ); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(VehicleMoveEvent event) { - if (!shouldExecuteEffect()) return; - - boolean anyMatch = false; - for (Entity passenger : event.getVehicle().getPassengers()) { - if (passenger instanceof Player) { - anyMatch = true; - break; - } - } - if (!anyMatch) return; - - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGamemodeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isNotIgnored()) { - updateSurroundingChunks(event.getPlayer().getLocation().getChunk(), false); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onChunkUnload(ChunkUnloadEvent event) { - if (!shouldExecuteEffect()) return; - updatedChunks.remove(event.getChunk()); - } + Chunk chunkAt = center.getWorld().getChunkAt(centerX + x, centerZ + z); + if (updatedChunks.contains(chunkAt)) continue; + chunks.add(chunkAt); + } + } + + return chunks; + } + + private void updateSurroundingChunks(Chunk center, boolean onlyBorder) { + + for (Chunk chunk : getSurroundingChunks(center, onlyBorder)) { + updateChunk(chunk); + } + + } + + private void updateChunk(Chunk chunk) { + updatedChunks.add(chunk); + + Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new HashMap<>()); + + for (Entry, BlockData> blockEntry : dataMap.entrySet()) { + Triple pos = blockEntry.getKey(); + BlockData blockData = blockEntry.getValue(); + Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); + if (!block.getBlockData().matches(blockData)) { + setBlockData(block, blockData, false); + } + + } + + + } + + private void setBlockData(Block block, BlockData blockData, boolean update) { + if (block.getType() == Material.END_PORTAL || + block.getType() == Material.END_PORTAL_FRAME || + block.getType() == Material.END_GATEWAY) return; + block.setBlockData(blockData, update); + } + + private int getRelativeChunkCoordinate(int worldCoordinate) { + return worldCoordinate & 0xF; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Block block = event.getBlock(); + changeBlockInEveryChunk( + event.getBlock().getWorld(), + getRelativeChunkCoordinate(block.getX()), + block.getY(), + getRelativeChunkCoordinate(block.getZ()), + block.getBlockData(), + event.getBlock() + ); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Block block = event.getBlock(); + changeBlockInEveryChunk( + event.getBlock().getWorld(), + getRelativeChunkCoordinate(block.getX()), + block.getY(), + getRelativeChunkCoordinate(block.getZ()), + Bukkit.createBlockData(Material.AIR), + event.getBlock() + ); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(VehicleMoveEvent event) { + if (!shouldExecuteEffect()) return; + + boolean anyMatch = false; + for (Entity passenger : event.getVehicle().getPassengers()) { + if (passenger instanceof Player) { + anyMatch = true; + break; + } + } + if (!anyMatch) return; + + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGamemodeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isNotIgnored()) { + updateSurroundingChunks(event.getPlayer().getLocation().getChunk(), false); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onChunkUnload(ChunkUnloadEvent event) { + if (!shouldExecuteEffect()) return; + updatedChunks.remove(event.getChunk()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 12c9573bb..28ae22550 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -24,91 +24,82 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SnakeChallenge extends Setting { - private final ArrayList blocks = new ArrayList<>(); - - public SnakeChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); - } - - @Override - protected void onEnable() { - - } - - @Override - protected void onDisable() { - blocks.clear(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - List locations = blocks.stream().map(Block::getLocation).collect(Collectors.toList()); - document.set("blocks", locations); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return; - if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) - return; - - Block from = event.getFrom().clone().subtract(0, 1, 0).getBlock(); - Block to = event.getTo().clone().subtract(0, 0.15, 0).getBlock(); - - if (from.getType().isSolid()) { - from.setType(BlockUtils.getTerracotta(getPlayersColor(event.getPlayer())), false); - blocks.add(from); - } - - if (blocks.contains(to)) { - Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); - return; - } - - if (to.getType().isSolid()) { - to.setType(Material.BLACK_TERRACOTTA, false); - - Block block = event.getPlayer().getLocation().getBlock(); - if (!block.getType().isSolid()) { - block.breakNaturally(); - } - } - - } - - public int getPlayersColor(Player player) { - int i = 0; - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - i++; - if (i > 17) i = 0; - if (currentPlayer == player) return i; - } - return 0; - } + private final ArrayList blocks = new ArrayList<>(); + + public SnakeChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); + } + + @Override + protected void onDisable() { + blocks.clear(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + List locations = blocks.stream().map(Block::getLocation).collect(Collectors.toList()); + document.set("blocks", locations); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return; + if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) + return; + + Block from = event.getFrom().clone().subtract(0, 1, 0).getBlock(); + Block to = event.getTo().clone().subtract(0, 0.15, 0).getBlock(); + + if (from.getType().isSolid()) { + from.setType(BlockUtils.getTerracotta(getPlayersColor(event.getPlayer())), false); + blocks.add(from); + } + + if (blocks.contains(to)) { + Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + kill(event.getPlayer()); + return; + } + + if (to.getType().isSolid()) { + to.setType(Material.BLACK_TERRACOTTA, false); + + Block block = event.getPlayer().getLocation().getBlock(); + if (!block.getType().isSolid()) { + block.breakNaturally(); + } + } + + } + + public int getPlayersColor(Player player) { + int i = 0; + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + i++; + if (i > 17) i = 0; + if (currentPlayer == player) return i; + } + return 0; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 3ec66a31a..92e6e160c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -17,60 +17,55 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SurfaceHoleChallenge extends SettingModifier { - public SurfaceHoleChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } + public SurfaceHoleChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; - Location location = event.getTo(); - if (location == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; + Location location = event.getTo(); + if (location == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + if (!shouldExecuteEffect()) return; - World world = event.getPlayer().getWorld(); + World world = event.getPlayer().getWorld(); - List blocks = new ArrayList<>(); - for (int y = BukkitReflectionUtils.getMinHeight(world); y < world.getMaxHeight(); y++) { - Location blockLocation = location.clone(); - blockLocation.setY(y); - blocks.add(blockLocation.getBlock()); - } + List blocks = new ArrayList<>(); + for (int y = BukkitReflectionUtils.getMinHeight(world); y < world.getMaxHeight(); y++) { + Location blockLocation = location.clone(); + blockLocation.setY(y); + blocks.add(blockLocation.getBlock()); + } - Bukkit.getScheduler().runTask(plugin, () -> { - for (Block block : blocks) { - block.setType(Material.AIR, false); - } - }); + Bukkit.getScheduler().runTask(plugin, () -> { + for (Block block : blocks) { + block.setType(Material.AIR, false); + } + }); - }, getValue() * 20L); + }, getValue() * 20L); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index e70cc0830..127b856eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -32,208 +32,203 @@ import java.util.Map; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class TsunamiChallenge extends TimedChallenge { - public static final int RANGE = 5; - - private final List floodedChunks = new ArrayList<>(); - - private int waterHeight = Integer.MAX_VALUE, - lavaHeight = 0; - - public TsunamiChallenge() { - super(MenuType.CHALLENGES, 1, 40, 4); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 15); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 15); - } - - @Override - protected void onEnable() { - - if (waterHeight == Integer.MAX_VALUE) { - waterHeight = BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)); - } - bossbar.setContent((bossbar, player) -> { - World world = player.getWorld(); - Environment environment = world.getEnvironment(); - int height = environment == Environment.NORMAL ? waterHeight : lavaHeight; - if (height < (world.getMaxHeight() - 1)) - bossbar.setProgress(getProgress()); - - if (environment == Environment.NORMAL) { - bossbar.setColor(BarColor.BLUE); - bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); - } else if (environment == Environment.NETHER) { - bossbar.setColor(BarColor.RED); - bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); - } else { - bossbar.setVisible(false); - } - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 15; - } - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - for (World world : ChallengeAPI.getGameWorlds()) { - if (!world.getPlayers().isEmpty()) { - if (world.getEnvironment() == Environment.NORMAL) { - if (waterHeight >= (world.getMaxHeight() - 1)) continue; - waterHeight++; - } else if (world.getEnvironment() == Environment.NETHER) { - if (lavaHeight >= (world.getMaxHeight() - 1)) continue; - lavaHeight++; - } - } - } - - List previouslyFlooded = new ArrayList<>(floodedChunks); - bossbar.update(); - floodedChunks.clear(); - for (Chunk chunk : getChunksToFlood()) { - floodChunk(chunk, !previouslyFlooded.contains(chunk)); - } - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - - Chunk newChunk = event.getTo().getChunk(); - if (event.getFrom().getChunk() == newChunk) return; - - for (Chunk chunk : getChunksAroundChunk(newChunk)) { - floodChunk(chunk, true); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { - if (ignorePlayer(event.getPlayer())) return; - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - - Chunk newChunk = event.getTo().getChunk(); - if (event.getFrom().getChunk() == newChunk) return; - - bossbar.update(); - - for (Chunk chunk : getChunksAroundChunk(newChunk)) { - floodChunk(chunk, true); - } - } - - @EventHandler - public void onChunkUnload(@Nonnull ChunkUnloadEvent event) { - floodedChunks.remove(event.getChunk()); - } - - private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { - if (floodedChunks.contains(chunk)) return; - floodedChunks.add(chunk); - if (chunk.getWorld().getEnvironment() == Environment.THE_END) return; - - boolean overworld = chunk.getWorld().getEnvironment() == Environment.NORMAL; - int height = overworld ? waterHeight : lavaHeight; - floodChunk0(chunk, discovered ? null : height - 1, height, overworld, (delay, task) -> Bukkit.getScheduler().runTaskLater(plugin, task, delay)); - } - - private void floodChunk0(@Nonnull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @Nonnull BiConsumer executor) { - int startAt = givenStartAt != null ? Math.max(BukkitReflectionUtils.getMinHeight(chunk.getWorld()) + 1, givenStartAt) : BukkitReflectionUtils - .getMinHeight(chunk.getWorld()) + 1; - Map> blocksByDelay = new HashMap<>(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = startAt + 1; y <= height; y++) { - List blocks = blocksByDelay.computeIfAbsent(0, key -> new ArrayList<>(16)); - Block block = chunk.getBlock(x, y, z); - Material type = block.getType(); - if (type != Material.WATER && type != Material.LAVA && block.isPassable() || (overworld && type == Material.LAVA)) - blocks.add(block); - } - } - } - blocksByDelay.forEach((delay, blocks) -> { - executor.accept(delay, () -> { - for (Block block : blocks) { - block.setType(overworld ? Material.WATER : Material.LAVA, false); - } - }); - }); - }); - } - - private List getChunksToFlood() { - return new ListBuilder().fill(chunkListBuilder -> { - broadcastFiltered(player -> chunkListBuilder.addAllIfNotContains(getChunksAroundChunk(player.getLocation().getChunk()))); - }).build(); - } - - private List getChunksAroundChunk(@Nonnull Chunk origin) { - return new ListBuilder().fill(builder -> { - for (int x = -RANGE; x <= RANGE; x++) { - for (int z = -RANGE; z <= RANGE; z++) { - builder.addIfNotContains(origin.getWorld().getChunkAt(origin.getX() + x, origin.getZ() + z)); - } - } - }).build(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("waterHeight", waterHeight); - document.set("lavaHeight", lavaHeight); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - waterHeight = document.getInt("waterHeight"); - lavaHeight = document.getInt("lavaHeight"); - } - -} \ No newline at end of file + public static final int RANGE = 5; + + private final List floodedChunks = new ArrayList<>(); + + private int waterHeight = Integer.MAX_VALUE, + lavaHeight = 0; + + public TsunamiChallenge() { + super(MenuType.CHALLENGES, 1, 40, 4); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 15); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 15); + } + + @Override + protected void onEnable() { + + if (waterHeight == Integer.MAX_VALUE) { + waterHeight = BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)); + } + bossbar.setContent((bossbar, player) -> { + World world = player.getWorld(); + Environment environment = world.getEnvironment(); + int height = environment == Environment.NORMAL ? waterHeight : lavaHeight; + if (height < (world.getMaxHeight() - 1)) + bossbar.setProgress(getProgress()); + + if (environment == Environment.NORMAL) { + bossbar.setColor(BarColor.BLUE); + bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); + } else if (environment == Environment.NETHER) { + bossbar.setColor(BarColor.RED); + bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); + } else { + bossbar.setVisible(false); + } + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 15; + } + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + for (World world : ChallengeAPI.getGameWorlds()) { + if (!world.getPlayers().isEmpty()) { + if (world.getEnvironment() == Environment.NORMAL) { + if (waterHeight >= (world.getMaxHeight() - 1)) continue; + waterHeight++; + } else if (world.getEnvironment() == Environment.NETHER) { + if (lavaHeight >= (world.getMaxHeight() - 1)) continue; + lavaHeight++; + } + } + } + + List previouslyFlooded = new ArrayList<>(floodedChunks); + bossbar.update(); + floodedChunks.clear(); + for (Chunk chunk : getChunksToFlood()) { + floodChunk(chunk, !previouslyFlooded.contains(chunk)); + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + private void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + + Chunk newChunk = event.getTo().getChunk(); + if (event.getFrom().getChunk() == newChunk) return; + + for (Chunk chunk : getChunksAroundChunk(newChunk)) { + floodChunk(chunk, true); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(@Nonnull PlayerTeleportEvent event) { + if (ignorePlayer(event.getPlayer())) return; + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + + Chunk newChunk = event.getTo().getChunk(); + if (event.getFrom().getChunk() == newChunk) return; + + bossbar.update(); + + for (Chunk chunk : getChunksAroundChunk(newChunk)) { + floodChunk(chunk, true); + } + } + + @EventHandler + public void onChunkUnload(@Nonnull ChunkUnloadEvent event) { + floodedChunks.remove(event.getChunk()); + } + + private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { + if (floodedChunks.contains(chunk)) return; + floodedChunks.add(chunk); + if (chunk.getWorld().getEnvironment() == Environment.THE_END) return; + + boolean overworld = chunk.getWorld().getEnvironment() == Environment.NORMAL; + int height = overworld ? waterHeight : lavaHeight; + floodChunk0(chunk, discovered ? null : height - 1, height, overworld, (delay, task) -> Bukkit.getScheduler().runTaskLater(plugin, task, delay)); + } + + private void floodChunk0(@Nonnull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @Nonnull BiConsumer executor) { + int startAt = givenStartAt != null ? Math.max(BukkitReflectionUtils.getMinHeight(chunk.getWorld()) + 1, givenStartAt) : BukkitReflectionUtils + .getMinHeight(chunk.getWorld()) + 1; + Map> blocksByDelay = new HashMap<>(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = startAt + 1; y <= height; y++) { + List blocks = blocksByDelay.computeIfAbsent(0, key -> new ArrayList<>(16)); + Block block = chunk.getBlock(x, y, z); + Material type = block.getType(); + if (type != Material.WATER && type != Material.LAVA && block.isPassable() || (overworld && type == Material.LAVA)) + blocks.add(block); + } + } + } + blocksByDelay.forEach((delay, blocks) -> { + executor.accept(delay, () -> { + for (Block block : blocks) { + block.setType(overworld ? Material.WATER : Material.LAVA, false); + } + }); + }); + }); + } + + private List getChunksToFlood() { + return new ListBuilder().fill(chunkListBuilder -> { + broadcastFiltered(player -> chunkListBuilder.addAllIfNotContains(getChunksAroundChunk(player.getLocation().getChunk()))); + }).build(); + } + + private List getChunksAroundChunk(@Nonnull Chunk origin) { + return new ListBuilder().fill(builder -> { + for (int x = -RANGE; x <= RANGE; x++) { + for (int z = -RANGE; z <= RANGE; z++) { + builder.addIfNotContains(origin.getWorld().getChunkAt(origin.getX() + x, origin.getZ() + z)); + } + } + }).build(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("waterHeight", waterHeight); + document.set("lavaHeight", lavaHeight); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + waterHeight = document.getInt("waterHeight"); + lavaHeight = document.getInt("lavaHeight"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index 3aeb509e6..b8efd70c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -16,45 +16,41 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamageRuleSetting extends Setting { - private final List causes; - - private final String name; - private final ItemBuilder preset; - - public DamageRuleSetting(@Nonnull ItemBuilder preset, @Nonnull String name, @Nonnull DamageCause... causes) { - super(MenuType.DAMAGE, true); - this.causes = Arrays.asList(causes); - this.name = name; - this.preset = preset; - } - - @NotNull - @Override - public String getUniqueName() { - return super.getUniqueName() + name; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isWorldInUse()) return; - if (isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; - if (event.getCause() == DamageCause.VOID || event.getCause() == DamageCause.CUSTOM) - return; // Never ignore void or custom to prevent different issues - if (!causes.contains(event.getCause())) return; - event.setCancelled(true); - } - -} \ No newline at end of file + private final List causes; + + private final String name; + private final ItemBuilder preset; + + public DamageRuleSetting(@Nonnull ItemBuilder preset, @Nonnull String name, @Nonnull DamageCause... causes) { + super(MenuType.DAMAGE, true); + this.causes = Arrays.asList(causes); + this.name = name; + this.preset = preset; + } + + @NotNull + @Override + public String getUniqueName() { + return super.getUniqueName() + name; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isWorldInUse()) return; + if (isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() == DamageCause.VOID || event.getCause() == DamageCause.CUSTOM) + return; // Never ignore void or custom to prevent different issues + if (!causes.contains(event.getCause())) return; + event.setCancelled(true); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index fb8893fa1..ee0c8ee49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; @@ -26,104 +26,100 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class AllAdvancementGoal extends PointsGoal { - private final List allAdvancements; - private final int advancementCount; - - public AllAdvancementGoal() { - setCategory(SettingCategory.FASTEST_TIME); - allAdvancements = new LinkedList<>(); - Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { - if (!advancement.getKey().toString().contains(":recipes/")) { - allAdvancements.add(advancement); - } - }); - advancementCount = allAdvancements.size(); - } - - @Override - protected void onEnable() { - updateAdvancements(); - scoreboard.setContent(GoalHelper.createScoreboard(() -> - getPoints(new AtomicInteger(), true), player -> { - return Collections.singletonList(Message.forName("all-advancements-goal").asString(advancementCount)); - })); - scoreboard.show(); - } - - @Override - protected void onDisable() { - scoreboard.hide(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - broadcastFiltered(player -> { - if (hasWon(player)) { - winners.add(player); - } - }); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-all-advancements-goal")); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onAdvancement(PlayerAdvancementDoneEvent event) { - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateAdvancements(event.getPlayer()); - scoreboard.update(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateAdvancements(event.getPlayer()); - scoreboard.update(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onGamemodeChange(PlayerGameModeChangeEvent event) { - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, (Runnable) scoreboard::update); - } - - protected void updateAdvancements() { - broadcastFiltered(this::updateAdvancements); - } - - protected void updateAdvancements(@Nonnull Player player) { - int done = 0; - for (Advancement advancement : allAdvancements) { - AdvancementProgress progress = player.getAdvancementProgress(advancement); - if (progress.isDone()) { - done++; - } - } - setPoints(player.getUniqueId(), done); - checkForWinning(player); - } - - protected void checkForWinning(Player player) { - if (hasWon(player)) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - } - - protected boolean hasWon(@Nonnull Player player) { - return getPoints(player.getUniqueId()) >= advancementCount; - } + private final List allAdvancements; + private final int advancementCount; + + public AllAdvancementGoal() { + setCategory(SettingCategory.FASTEST_TIME); + allAdvancements = new LinkedList<>(); + Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { + if (!advancement.getKey().toString().contains(":recipes/")) { + allAdvancements.add(advancement); + } + }); + advancementCount = allAdvancements.size(); + } + + @Override + protected void onEnable() { + updateAdvancements(); + scoreboard.setContent(GoalHelper.createScoreboard(() -> + getPoints(new AtomicInteger(), true), player -> { + return Collections.singletonList(Message.forName("all-advancements-goal").asString(advancementCount)); + })); + scoreboard.show(); + } + + @Override + protected void onDisable() { + scoreboard.hide(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + broadcastFiltered(player -> { + if (hasWon(player)) { + winners.add(player); + } + }); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-all-advancements-goal")); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onAdvancement(PlayerAdvancementDoneEvent event) { + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateAdvancements(event.getPlayer()); + scoreboard.update(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateAdvancements(event.getPlayer()); + scoreboard.update(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onGamemodeChange(PlayerGameModeChangeEvent event) { + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTask(plugin, (Runnable) scoreboard::update); + } + + protected void updateAdvancements() { + broadcastFiltered(this::updateAdvancements); + } + + protected void updateAdvancements(@Nonnull Player player) { + int done = 0; + for (Advancement advancement : allAdvancements) { + AdvancementProgress progress = player.getAdvancementProgress(advancement); + if (progress.isDone()) { + done++; + } + } + setPoints(player.getUniqueId(), done); + checkForWinning(player); + } + + protected void checkForWinning(Player player) { + if (hasWon(player)) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + } + + protected boolean hasWon(@Nonnull Player player) { + return getPoints(player.getUniqueId()) >= advancementCount; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index b5ba68447..303b56631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -1,10 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import lombok.Getter; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -31,158 +32,172 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { - private final int totalItemsCount; - private SeededRandomWrapper random; - private List allItemsToFind; - private List itemsToFind; - private Material currentItem; - - public CollectAllItemsGoal() { - random = new SeededRandomWrapper(); - reloadItemsToFind(); - totalItemsCount = itemsToFind.size(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); - } - - private void reloadItemsToFind() { - allItemsToFind = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - allItemsToFind.removeIf(material -> !material.isItem()); - allItemsToFind.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - Collections.shuffle(allItemsToFind, random); - itemsToFind = new ArrayList<>(allItemsToFind); - nextItem(); - - if (isEnabled()) - bossbar.update(); - } - - private void nextItem() { - if (itemsToFind.isEmpty()) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - return; - } - currentItem = itemsToFind.remove(0); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (currentItem == null) { - bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); - return; - } - - bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent(currentItem, totalItemsCount - itemsToFind.size() + 1, totalItemsCount)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - if (currentItem == null) { - Message.forName("all-items-already-finished").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, currentItem); - SoundSample.PLING.broadcast(); - nextItem(); - bossbar.update(); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; - ItemStack item = event.getCurrentItem(); - if (item == null) return; - handleNewItem(item.getType(), event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - Material material = event.getItem().getItemStack().getType(); - handleNewItem(material, event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - Material material = item.getType(); - handleNewItem(material, event.getPlayer()); - }, 1); - } - - protected void handleNewItem(@Nullable Material material, @Nonnull Player player) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - if (currentItem != material) return; - Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, currentItem, NameHelper.getName(player)); - SoundSample.PLING.broadcast(); - nextItem(); - bossbar.update(); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - random = new SeededRandomWrapper(document.getLong("seed")); - reloadItemsToFind(); - - for (int i = 0; i < document.getInt("found"); i++) - nextItem(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("seed", random.getSeed()); - document.set("found", totalItemsCount - itemsToFind.size()); - } - - public Material getCurrentItem() { - return currentItem; - } - - public List getItemsToFind() { - return itemsToFind; - } - - public List getAllItemsToFind() { - return allItemsToFind; - } - - public int getTotalItemsCount() { - return totalItemsCount; - } - + @Getter + private final int totalItemsCount; + private SeededRandomWrapper random; + @Getter + private List allItemsToFind; + @Getter + private List itemsToFind; + @Getter + private Material currentItem; + + public CollectAllItemsGoal() { + random = new SeededRandomWrapper(); + reloadItemsToFind(); + totalItemsCount = itemsToFind.size(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); + } + + private void reloadItemsToFind() { + allItemsToFind = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + allItemsToFind.removeIf(material -> !material.isItem()); + allItemsToFind.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + Collections.shuffle(allItemsToFind, random); + itemsToFind = new ArrayList<>(allItemsToFind); + nextItem(); + + if (isEnabled()) + bossbar.update(); + } + + private void nextItem() { + if (itemsToFind.isEmpty()) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + return; + } + currentItem = itemsToFind.remove(0); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (currentItem == null) { + bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); + return; + } + bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent( + getItemDisplayName(currentItem), + totalItemsCount - itemsToFind.size() + 1, + totalItemsCount)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + if (currentItem == null) { + Message.forName("all-items-already-finished").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); + SoundSample.PLING.broadcast(); + nextItem(); + bossbar.update(); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.isCancelled()) return; + ItemStack item = event.getCurrentItem(); + if (item == null) return; + handleNewItem(item.getType(), event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + Material material = event.getItem().getItemStack().getType(); + handleNewItem(material, event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + Material material = item.getType(); + handleNewItem(material, event.getPlayer()); + }, 1); + } + + protected void handleNewItem(@Nullable Material material, @Nonnull Player player) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + if (currentItem != material) return; + Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem), NameHelper.getName(player)); + SoundSample.PLING.broadcast(); + nextItem(); + bossbar.update(); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + random = new SeededRandomWrapper(document.getLong("seed")); + reloadItemsToFind(); + + for (int i = 0; i < document.getInt("found"); i++) + nextItem(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("seed", random.getSeed()); + document.set("found", totalItemsCount - itemsToFind.size()); + } + + private String getItemDisplayName(@Nullable Material material) { + if (material == null) return "Unbekannt"; + + String name = material.name(); + + if (name.contains("SMITHING_TEMPLATE")) { + String prefix = name.replace("_SMITHING_TEMPLATE", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Smithing template"; + } + + if (name.endsWith("_BANNER_PATTERN")) { + String prefix = name.replace("_BANNER_PATTERN", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Banner Pattern"; + } + + return Arrays.stream(name.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index f1d89a5f2..ff3a3e747 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -13,33 +13,29 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectHorseAmorGoal extends ItemCollectionGoal { - public CollectHorseAmorGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - List targets = new ArrayList<>(Arrays.asList( - Material.DIAMOND_HORSE_ARMOR, - Material.GOLDEN_HORSE_ARMOR, - Material.IRON_HORSE_ARMOR - )); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - targets.add(Material.LEATHER_HORSE_ARMOR); - } - - setTarget(targets.toArray(new Object[0])); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_HORSE_ARMOR, Message.forName("item-collect-horse-armor-goal")); - } + public CollectHorseAmorGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + List targets = new ArrayList<>(Arrays.asList( + Material.DIAMOND_HORSE_ARMOR, + Material.GOLDEN_HORSE_ARMOR, + Material.IRON_HORSE_ARMOR + )); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + targets.add(Material.LEATHER_HORSE_ARMOR); + } + + setTarget(targets.toArray(new Object[0])); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_HORSE_ARMOR, Message.forName("item-collect-horse-armor-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 9b44217ec..1631103ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -8,22 +8,18 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectIceBlocksGoal extends ItemCollectionGoal { - public CollectIceBlocksGoal() { - super(Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); - setCategory(SettingCategory.FASTEST_TIME); - } + public CollectIceBlocksGoal() { + super(Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-collect-ice-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-collect-ice-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 17712f8d7..e2e7cbffe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -15,37 +15,33 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CollectMostDeathsGoal extends CollectionGoal { - public CollectMostDeathsGoal() { - super(DamageCause.values()); - setCategory(SettingCategory.SCORE_POINTS); - } + public CollectMostDeathsGoal() { + super(DamageCause.values()); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); + } - @EventHandler - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; + @EventHandler + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; - EntityDamageEvent lastCause = event.getEntity().getLastDamageCause(); - if (lastCause == null) return; + EntityDamageEvent lastCause = event.getEntity().getLastDamageCause(); + if (lastCause == null) return; - DamageCause cause = lastCause.getCause(); - if (cause == DamageCause.CUSTOM) return; + DamageCause cause = lastCause.getCause(); + if (cause == DamageCause.CUSTOM) return; - collect(event.getEntity(), cause, () -> { - Message.forName("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); - SoundSample.PLING.play(event.getEntity()); - }); - } + collect(event.getEntity(), cause, () -> { + Message.forName("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); + SoundSample.PLING.play(event.getEntity()); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 474a8099d..2e710b704 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -13,34 +13,30 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class CollectMostExpGoal extends PointsGoal { - public CollectMostExpGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExpChange(@Nonnull PlayerExpChangeEvent event) { - if (!shouldExecuteEffect()) return; - collect(event.getPlayer(), event.getAmount()); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - event.setKeepLevel(true); - } + public CollectMostExpGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExpChange(@Nonnull PlayerExpChangeEvent event) { + if (!shouldExecuteEffect()) return; + collect(event.getPlayer(), event.getAmount()); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + event.setKeepLevel(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 6eb21782a..1e28b334f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -18,51 +18,47 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CollectMostItemsGoal extends CollectionGoal { - public CollectMostItemsGoal() { - super(ExperimentalUtils.getMaterials()); - setCategory(SettingCategory.SCORE_POINTS); - } + public CollectMostItemsGoal() { + super(ExperimentalUtils.getMaterials()); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull EntityPickupItemEvent event) { - if (!isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull EntityPickupItemEvent event) { + if (!isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - ItemStack item = event.getItem().getItemStack(); - handleNewItem(item.getType(), player); - } + Player player = (Player) event.getEntity(); + ItemStack item = event.getItem().getItemStack(); + handleNewItem(item.getType(), player); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - ItemStack item = event.getCurrentItem(); - if (item == null) return; - if (!ItemUtils.isObtainableInSurvival(item.getType())) return; + Player player = (Player) event.getWhoClicked(); + ItemStack item = event.getCurrentItem(); + if (item == null) return; + if (!ItemUtils.isObtainableInSurvival(item.getType())) return; - handleNewItem(item.getType(), player); - } + handleNewItem(item.getType(), player); + } - protected void handleNewItem(@Nonnull Material material, @Nonnull Player player) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } + protected void handleNewItem(@Nonnull Material material, @Nonnull Player player) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index a319b6e39..c371f63f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -13,32 +13,28 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectSwordsGoal extends ItemCollectionGoal { - public CollectSwordsGoal() { - setCategory(SettingCategory.FASTEST_TIME); - List targets = new ArrayList<>(Arrays.asList( - Material.WOODEN_SWORD, Material.STONE_SWORD, - Material.IRON_SWORD, Material.GOLDEN_SWORD, - Material.DIAMOND_SWORD - )); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { - targets.add(Material.NETHERITE_SWORD); - } - - setTarget(targets.toArray(new Object[0])); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-collect-swords-goal")); - } + public CollectSwordsGoal() { + setCategory(SettingCategory.FASTEST_TIME); + List targets = new ArrayList<>(Arrays.asList( + Material.WOODEN_SWORD, Material.STONE_SWORD, + Material.IRON_SWORD, Material.GOLDEN_SWORD, + Material.DIAMOND_SWORD + )); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { + targets.add(Material.NETHERITE_SWORD); + } + + setTarget(targets.toArray(new Object[0])); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-collect-swords-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 4ed755a9c..d0c36d32b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -20,113 +20,109 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class CollectWoodGoal extends SettingModifierCollectionGoal { - private static final boolean newNether = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16); - private static final int - OVERWORLD = 1, - NETHER = 2, - BOTH = 3; - - public CollectWoodGoal() { - super(1, newNether ? 3 : 1); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!newNether) return DefaultItem.enabled(); - if (getValue() == OVERWORLD) - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); - if (getValue() == NETHER) - return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); - return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (!newNether && info.isLowerItemClick() && enabled) { - setEnabled(false); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } - - @Override - protected void onEnable() { - super.onEnable(); - setTarget(getWoodMaterials()); - checkCollects(); - } - - @Override - protected void onValueChange() { - setTarget(getWoodMaterials()); - checkCollects(); - } - - @Nonnull - private Object[] getWoodMaterials() { - return new ListBuilder().fill(builder -> { - for (Material material : ExperimentalUtils.getMaterials()) { - if (isSearched(material)) - builder.add(material); - } - }).build().toArray(); - } - - private boolean isLog(@Nonnull Material material) { - return material.name().contains("LOG") && !material.name().contains("STRIPPED"); - } - - private boolean isNetherLog(@Nonnull Material material) { - return material == Material.WARPED_STEM || material == Material.CRIMSON_STEM; - } - - private boolean isSearched(@Nonnull Material material) { - return getValue() == OVERWORLD && isLog(material) || - getValue() == NETHER && isNetherLog(material) || - getValue() == BOTH && (isLog(material) || isNetherLog(material)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - Material material = event.getItem().getItemStack().getType(); - Player player = event.getPlayer(); - handleCollect(player, material); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - Player player = event.getPlayer(); - Material material = event.getCurrentItem().getType(); - handleCollect(player, material); - } - - private void handleCollect(@Nonnull Player player, @Nonnull Material material) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } - -} \ No newline at end of file + private static final boolean newNether = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16); + private static final int + OVERWORLD = 1, + NETHER = 2, + BOTH = 3; + + public CollectWoodGoal() { + super(1, newNether ? 3 : 1); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!newNether) return DefaultItem.enabled(); + if (getValue() == OVERWORLD) + return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); + if (getValue() == NETHER) + return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); + return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (!newNether && info.isLowerItemClick() && enabled) { + setEnabled(false); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } + + @Override + protected void onEnable() { + super.onEnable(); + setTarget(getWoodMaterials()); + checkCollects(); + } + + @Override + protected void onValueChange() { + setTarget(getWoodMaterials()); + checkCollects(); + } + + @Nonnull + private Object[] getWoodMaterials() { + return new ListBuilder().fill(builder -> { + for (Material material : ExperimentalUtils.getMaterials()) { + if (isSearched(material)) + builder.add(material); + } + }).build().toArray(); + } + + private boolean isLog(@Nonnull Material material) { + return material.name().contains("LOG") && !material.name().contains("STRIPPED"); + } + + private boolean isNetherLog(@Nonnull Material material) { + return material == Material.WARPED_STEM || material == Material.CRIMSON_STEM; + } + + private boolean isSearched(@Nonnull Material material) { + return getValue() == OVERWORLD && isLog(material) || + getValue() == NETHER && isNetherLog(material) || + getValue() == BOTH && (isLog(material) || isNetherLog(material)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + Material material = event.getItem().getItemStack().getType(); + Player player = event.getPlayer(); + handleCollect(player, material); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isCancelled()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + Player player = event.getPlayer(); + Material material = event.getCurrentItem().getType(); + handleCollect(player, material); + } + + private void handleCollect(@Nonnull Player player, @Nonnull Material material) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 4dd1c0a07..8027dc78b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; @@ -10,28 +10,24 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") @RequireVersion(MinecraftVersion.V1_14) public class CollectWorkstationsGoal extends ItemCollectionGoal { - public CollectWorkstationsGoal() { - super( - Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, - Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, - Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, - Material.LOOM, Material.STONECUTTER, Material.BARREL - ); - setCategory(SettingCategory.FASTEST_TIME); - } + public CollectWorkstationsGoal() { + super( + Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, + Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, + Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, + Material.LOOM, Material.STONECUTTER, Material.BARREL + ); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FLETCHING_TABLE, Message.forName("item-collect-workstations-item")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FLETCHING_TABLE, Message.forName("item-collect-workstations-item")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 1b2bc328e..2fa73fcf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -18,40 +18,36 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EatCakeGoal extends SettingGoal { - public EatCakeGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-eat-cake-goal")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedBlock() == null) return; - if (event.getClickedBlock().getType() != Material.CAKE) return; - if (event.getPlayer().getFoodLevel() >= 20) return; - // Execute on next tick to prevent hunger bar not filling up - Bukkit.getScheduler().runTask(plugin, () -> { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - }); - } + public EatCakeGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAKE, Message.forName("item-eat-cake-goal")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedBlock() == null) return; + if (event.getClickedBlock().getType() != Material.CAKE) return; + if (event.getPlayer().getFoodLevel() >= 20) return; + // Execute on next tick to prevent hunger bar not filling up + Bukkit.getScheduler().runTask(plugin, () -> { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 3d6cc51e6..e84756f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -13,34 +13,30 @@ import org.bukkit.event.entity.FoodLevelChangeEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EatMostGoal extends PointsGoal { - public EatMostGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public EatMostGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKIE, Message.forName("item-eat-most-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COOKIE, Message.forName("item-eat-most-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onItemConsume(FoodLevelChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - if (ignorePlayer(((Player) event.getEntity()))) return; - int changedFoodLevel = event.getFoodLevel() - event.getEntity().getFoodLevel(); - if (changedFoodLevel > 0) { - addPoints(event.getEntity().getUniqueId(), changedFoodLevel); - Message.forName("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onItemConsume(FoodLevelChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + if (ignorePlayer(((Player) event.getEntity()))) return; + int changedFoodLevel = event.getFoodLevel() - event.getEntity().getFoodLevel(); + if (changedFoodLevel > 0) { + addPoints(event.getEntity().getUniqueId(), changedFoodLevel); + Message.forName("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index c6c48042f..00a768f51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -8,22 +8,18 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class FindElytraGoal extends FindItemGoal { - public FindElytraGoal() { - super(Material.ELYTRA); - setCategory(SettingCategory.FASTEST_TIME); - } + public FindElytraGoal() { + super(Material.ELYTRA); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELYTRA, Message.forName("item-find-elytra-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ELYTRA, Message.forName("item-find-elytra-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 09600e547..394272035 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -19,35 +19,31 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") @RequireVersion(MinecraftVersion.V1_16) public class FinishRaidGoal extends SettingGoal { - public FinishRaidGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } + public FinishRaidGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); + } - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - } + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + } - @EventHandler(priority = EventPriority.HIGH) - public void onRaidFinish(@Nonnull RaidFinishEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getRaid().getStatus() != RaidStatus.VICTORY) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); - } + @EventHandler(priority = EventPriority.HIGH) + public void onRaidFinish(@Nonnull RaidFinishEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getRaid().getStatus() != RaidStatus.VICTORY) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index 1f01aa691..bd79ebbed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -16,42 +16,38 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class FirstOneToDieGoal extends SettingGoal { - private Player winner; - - public FirstOneToDieGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - if (winner != null) - winners.add(winner); - } - - @Override - protected void onDisable() { - winner = null; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - winner = event.getEntity(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + private Player winner; + + public FirstOneToDieGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + if (winner != null) + winners.add(winner); + } + + @Override + protected void onDisable() { + winner = null; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + winner = event.getEntity(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index fda44a704..aa3ed1570 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,10 +8,10 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -22,73 +22,69 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ @Since("2.2.0") public class GetFullHealthGoal extends SettingModifierGoal { - public GetFullHealthGoal() { - super(MenuType.GOAL, 1, 20, 20); - setCategory(SettingCategory.FASTEST_TIME); - } + public GetFullHealthGoal() { + super(MenuType.GOAL, 1, 20, 20); + setCategory(SettingCategory.FASTEST_TIME); + } - @Override - protected void onEnable() { - broadcastFiltered(player -> { - player.setHealth(getValue()); - }); - } + @Override + protected void onEnable() { + broadcastFiltered(player -> { + player.setHealth(getValue()); + }); + } - @Override - protected void onValueChange() { - broadcastFiltered(player -> { - player.setHealth(getValue()); - }); - } + @Override + protected void onValueChange() { + broadcastFiltered(player -> { + player.setHealth(getValue()); + }); + } - @Override - public void getWinnersOnEnd(@NotNull List winners) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute != null) { - if (player.getHealth() >= attribute.getBaseValue()) { - winners.add(player); - } - } - } - } + @Override + public void getWinnersOnEnd(@NotNull List winners) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute != null) { + if (player.getHealth() >= attribute.getBaseValue()) { + winners.add(player); + } + } + } + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.AZURE_BLUET, Message.forName("item-get-full-health-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.AZURE_BLUET, Message.forName("item-get-full-health-goal")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-start-description").asArray(getValue() / 2f); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-start-description").asArray(getValue() / 2f); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onHealthChange(EntityRegainHealthEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer((Player) event.getEntity())) return; - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(Attribute.GENERIC_MAX_HEALTH); - Bukkit.getScheduler().runTask(plugin, () -> { - if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - }); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onHealthChange(EntityRegainHealthEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer((Player) event.getEntity())) return; + Bukkit.getScheduler().runTask(plugin, () -> { + AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index a8b5157c2..170fb80ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -11,27 +11,23 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class KillAllBossesGoal extends KillMobsGoal { - public KillAllBossesGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN)); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillAllBossesGoal() { + super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN)); + setCategory(SettingCategory.KILL_ENTITY); + } - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-bosses"); - } + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-bosses"); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 62f39ca4a..376d625c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; @@ -13,28 +13,24 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.2.0") @RequireVersion(MinecraftVersion.V1_19) public class KillAllBossesNewGoal extends KillMobsGoal { - public KillAllBossesNewGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN)); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillAllBossesNewGoal() { + super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN)); + setCategory(SettingCategory.KILL_ENTITY); + } - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-bosses"); - } + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-bosses"); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 1954cbb65..0b97d4274 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -13,37 +13,33 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class KillAllMobsGoal extends KillMobsGoal { - public KillAllMobsGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); - } - - static List getAllMobsToKill() { - LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); - list.removeIf(type -> !type.isAlive()); - list.remove(EntityType.GIANT); - list.remove(EntityType.ILLUSIONER); - list.remove(EntityType.PLAYER); - list.remove(EntityType.ARMOR_STAND); - return list; - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-all-mobs-goal")); - } - - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-mobs"); - } + public KillAllMobsGoal() { + super(getAllMobsToKill()); + setCategory(SettingCategory.KILL_ENTITY); + } + + static List getAllMobsToKill() { + LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); + list.removeIf(type -> !type.isAlive()); + list.remove(EntityType.GIANT); + list.remove(EntityType.ILLUSIONER); + list.remove(EntityType.PLAYER); + list.remove(EntityType.ARMOR_STAND); + return list; + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-all-mobs-goal")); + } + + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-mobs"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index d1f4096b7..eed2c9d87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -15,45 +15,44 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class KillAllMonsterGoal extends KillMobsGoal { - public KillAllMonsterGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); - } - - static List getAllMobsToKill() { - LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); - list.removeIf(type -> !type.isAlive()); - list.removeIf(type -> !Monster.class.isAssignableFrom(type.getEntityClass())); - list.add(EntityType.PHANTOM); - list.add(EntityType.ENDER_DRAGON); - list.add(EntityType.SHULKER); - list.add(EntityType.GHAST); - list.add(EntityType.MAGMA_CUBE); - list.add(EntityType.SLIME); - list.remove(EntityType.GIANT); - list.remove(EntityType.ILLUSIONER); - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { - list.add(EntityType.HOGLIN); - } - return list; - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ARROW, Message.forName("item-all-monster-goal")); - } - - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-monster"); - } + public KillAllMonsterGoal() { + super(getAllMobsToKill()); + setCategory(SettingCategory.KILL_ENTITY); + } + + static List getAllMobsToKill() { + LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); + list.removeIf(type -> !type.isAlive()); + list.removeIf(type -> { + assert type.getEntityClass() != null; + return !Monster.class.isAssignableFrom(type.getEntityClass()); + }); + list.add(EntityType.PHANTOM); + list.add(EntityType.ENDER_DRAGON); + list.add(EntityType.SHULKER); + list.add(EntityType.GHAST); + list.add(EntityType.MAGMA_CUBE); + list.add(EntityType.SLIME); + list.remove(EntityType.GIANT); + list.remove(EntityType.ILLUSIONER); + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { + list.add(EntityType.HOGLIN); + } + return list; + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ARROW, Message.forName("item-all-monster-goal")); + } + + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-monster"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index d6ca9b9f8..4a1cb5ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -12,28 +12,24 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class KillElderGuardianGoal extends KillEntityGoal { - public KillElderGuardianGoal() { - super(EntityType.ELDER_GUARDIAN); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillElderGuardianGoal() { + super(EntityType.ELDER_GUARDIAN); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_ELDER_GUARDIAN_CURSE, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_ELDER_GUARDIAN_CURSE, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 382fcc7f4..3aa197d2f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -12,28 +12,24 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class KillEnderDragonGoal extends KillEntityGoal { - public KillEnderDragonGoal() { - super(EntityType.ENDER_DRAGON, Environment.THE_END, true); - setCategory(SettingCategory.KILL_ENTITY); - setOneWinner(false); - } + public KillEnderDragonGoal() { + super(EntityType.ENDER_DRAGON, Environment.THE_END, true); + setCategory(SettingCategory.KILL_ENTITY); + setOneWinner(false); + } - @Nullable - @Override - public SoundSample getWinSound() { - return null; - } + @Nullable + @Override + public SoundSample getWinSound() { + return null; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index cbc79c9c9..f84395c18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -12,29 +12,25 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class KillIronGolemGoal extends KillEntityGoal { - public KillIronGolemGoal() { - super(EntityType.IRON_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); - this.killerNeeded = true; - } + public KillIronGolemGoal() { + super(EntityType.IRON_GOLEM); + setCategory(SettingCategory.KILL_ENTITY); + this.killerNeeded = true; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_IRON_GOLEM_HURT, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_IRON_GOLEM_HURT, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index cfe230402..6fd97c7be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,8 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -11,29 +10,27 @@ import org.bukkit.Material; import org.bukkit.Sound; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +import javax.annotation.Nonnull; + @Since("2.0") public class KillSnowGolemGoal extends KillEntityGoal { - public KillSnowGolemGoal() { - super(MinecraftNameWrapper.SNOW_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); - this.killerNeeded = true; - } + public KillSnowGolemGoal() { + super(MinecraftNameWrapper.SNOW_GOLEM); + setCategory(SettingCategory.KILL_ENTITY); + this.killerNeeded = true; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_SNOW_GOLEM_DEATH, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_SNOW_GOLEM_DEATH, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index ffcd2aae8..e98c71fbf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; @@ -14,29 +14,25 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.2.0") @RequireVersion(MinecraftVersion.V1_19) public class KillWardenGoal extends KillEntityGoal { - public KillWardenGoal() { - super(EntityType.WARDEN); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillWardenGoal() { + super(EntityType.WARDEN); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_WARDEN_EMERGE, 0.2f); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_WARDEN_EMERGE, 0.2f); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 11ebc2656..551b46b8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -11,27 +11,23 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class KillWitherGoal extends KillEntityGoal { - public KillWitherGoal() { - super(EntityType.WITHER); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillWitherGoal() { + super(EntityType.WITHER); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_WITHER_SPAWN, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_WITHER_SPAWN, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index fe90a8cff..0834bea22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -18,56 +18,52 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class LastManStandingGoal extends SettingGoal { - private Player winner; + private Player winner; - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); + } - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - determineWinner(); - if (winner != null) - winners.add(winner); - } + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + determineWinner(); + if (winner != null) + winners.add(winner); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!isEnabled()) return; - checkEnd(); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!isEnabled()) return; + checkEnd(); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onLeave(@Nonnull PlayerQuitEvent event) { - if (!isEnabled()) return; - checkEnd(); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onLeave(@Nonnull PlayerQuitEvent event) { + if (!isEnabled()) return; + checkEnd(); + } - protected void determineWinner() { - int playersLiving = 0; - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SPECTATOR) continue; - playersLiving++; - winner = player; - } + protected void determineWinner() { + int playersLiving = 0; + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() == GameMode.SPECTATOR) continue; + playersLiving++; + winner = player; + } - if (playersLiving != 1) - winner = null; - } + if (playersLiving != 1) + winner = null; + } - protected void checkEnd() { - determineWinner(); - if (winner == null) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + protected void checkEnd() { + determineWinner(); + if (winner == null) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 5416f0951..16a7bb90f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; @@ -10,22 +10,18 @@ import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class MaxHeightGoal extends FirstPlayerAtHeightGoal { - public MaxHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); - setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); - } + public MaxHeightGoal() { + setCategory(SettingCategory.FASTEST_TIME); + setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-max-height-goal").asItemDescription(getHeightToGetTo())); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-max-height-goal").asItemDescription(getHeightToGetTo())); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index 4b0de86e3..e27fb4c3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; @@ -11,22 +11,18 @@ import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class MinHeightGoal extends FirstPlayerAtHeightGoal { - public MinHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); - setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); - } + public MinHeightGoal() { + setCategory(SettingCategory.FASTEST_TIME); + setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-min-height-goal").asItemDescription(getHeightToGetTo())); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEDROCK, Message.forName("item-min-height-goal").asItemDescription(getHeightToGetTo())); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index ec8d2f2f6..09cfad354 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -11,28 +11,24 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class MineMostBlocksGoal extends PointsGoal { - public MineMostBlocksGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MineMostBlocksGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!isEnabled()) return; - if (event.getBlock().isPassable()) return; - collect(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!isEnabled()) return; + if (event.getBlock().isPassable()) return; + collect(event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index c5be3df63..b4405e994 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -18,70 +18,66 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class MostEmeraldsGoal extends PointsGoal { - public MostEmeraldsGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MostEmeraldsGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); + } - @Override - protected void onEnable() { - broadcastFiltered(this::updatePoints); - super.onEnable(); - } + @Override + protected void onEnable() { + broadcastFiltered(this::updatePoints); + super.onEnable(); + } - private void updatePoints(@Nonnull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> { - int count = getEmeraldsCount(player); - setPoints(player.getUniqueId(), count); - }); - } + private void updatePoints(@Nonnull Player player) { + Bukkit.getScheduler().runTask(plugin, () -> { + int count = getEmeraldsCount(player); + setPoints(player.getUniqueId(), count); + }); + } - private int getEmeraldsCount(@Nonnull Player player) { - PlayerInventory inventory = player.getInventory(); - int count = 0; - for (ItemStack itemStack : inventory.getContents()) { - if (itemStack != null && itemStack.getType() == Material.EMERALD) - count += itemStack.getAmount(); - } - if (player.getItemOnCursor().getType() == Material.EMERALD) - count += player.getItemOnCursor().getAmount(); - return count; - } + private int getEmeraldsCount(@Nonnull Player player) { + PlayerInventory inventory = player.getInventory(); + int count = 0; + for (ItemStack itemStack : inventory.getContents()) { + if (itemStack != null && itemStack.getType() == Material.EMERALD) + count += itemStack.getAmount(); + } + if (player.getItemOnCursor().getType() == Material.EMERALD) + count += player.getItemOnCursor().getAmount(); + return count; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ignorePlayer(player)) return; - updatePoints(player); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ignorePlayer(player)) return; + updatePoints(player); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updatePoints(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updatePoints(event.getPlayer()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updatePoints(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updatePoints(event.getPlayer()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 9852c3409..d63c7a93f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,73 +16,69 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class MostOresGoal extends PointsGoal { - public MostOresGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MostOresGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COAL_ORE, Message.forName("item-most-ores-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COAL_ORE, Message.forName("item-most-ores-goal")); + } - private int getPointsForOre(Material material) { - switch (material) { - case EMERALD_ORE: - case DEEPSLATE_EMERALD_ORE: - return 15; - case DIAMOND_ORE: - case DEEPSLATE_DIAMOND_ORE: - return 10; - case LAPIS_ORE: - case DEEPSLATE_LAPIS_ORE: - return 8; - case GOLD_ORE: - case DEEPSLATE_GOLD_ORE: - return 6; - case IRON_ORE: - case DEEPSLATE_IRON_ORE: - return 4; - case COAL_ORE: - case DEEPSLATE_COAL_ORE: - case REDSTONE_ORE: - case DEEPSLATE_REDSTONE_ORE: - return 2; - default: - return 0; - } - } + private int getPointsForOre(Material material) { + switch (material) { + case EMERALD_ORE: + case DEEPSLATE_EMERALD_ORE: + return 15; + case DIAMOND_ORE: + case DEEPSLATE_DIAMOND_ORE: + return 10; + case LAPIS_ORE: + case DEEPSLATE_LAPIS_ORE: + return 8; + case GOLD_ORE: + case DEEPSLATE_GOLD_ORE: + return 6; + case IRON_ORE: + case DEEPSLATE_IRON_ORE: + return 4; + case COAL_ORE: + case DEEPSLATE_COAL_ORE: + case REDSTONE_ORE: + case DEEPSLATE_REDSTONE_ORE: + return 2; + default: + return 0; + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - int points = getPointsForOre(event.getBlock().getType()); - if (points > 0) { - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); - SoundSample.PLING.play(event.getPlayer()); - addPoints(event.getPlayer().getUniqueId(), points); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + int points = getPointsForOre(event.getBlock().getType()); + if (points > 0) { + Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); + SoundSample.PLING.play(event.getPlayer()); + addPoints(event.getPlayer().getUniqueId(), points); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - int points = getPointsForOre(event.getBlock().getType()); - if (points > 0) { - SoundSample.BASS_OFF.play(event.getPlayer()); - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); - removePoints(event.getPlayer().getUniqueId(), points); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + int points = getPointsForOre(event.getBlock().getType()); + if (points > 0) { + SoundSample.BASS_OFF.play(event.getPlayer()); + Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); + removePoints(event.getPlayer().getUniqueId(), points); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index d8d5a3dcb..ed4f63bf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; @@ -18,8 +18,11 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; -import org.bukkit.*; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.Particle.DustOptions; +import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -32,144 +35,140 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class RaceGoal extends SettingModifierGoal { - protected long seed = IRandom.create().getSeed(); - - private Location goal; - - public RaceGoal() { - super(MenuType.GOAL, 1, 30, 5); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - } - - @Override - protected void onEnable() { - reloadGoalLocation(); - bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.GREEN); - if (player.getWorld() == goal.getWorld()) { - - Location relativeGoal = goal.clone(); - relativeGoal.setY(player.getLocation().getY()); - relativeGoal.add(0.5, 0, 0.5); - int distance = (int) Math.round(player.getLocation().distance(relativeGoal)); - - bar.setTitle(Message.forName("bossbar-race-goal-info") - .asString(goal.getBlockX(), goal.getBlockZ(), distance)); - } else { - bar.setTitle(Message.forName("bossbar-race-goal") - .asString(goal.getBlockX(), goal.getBlockZ())); - } - - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - goal = null; - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-range-blocks-description").asArray(getValue() * 100); - } - - - @Override - protected void onValueChange() { - reloadGoalLocation(); - bossbar.update(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRUCTURE_VOID, Message.forName("item-race-goal")); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - if (goal == null) return; - bossbar.update(); - broadcast(player -> { - Location relativeGoal = goal.clone(); - relativeGoal.setY(player.getLocation().getY()); - relativeGoal.add(0.5, 0, 0.5); - ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, new DustOptions( - Color.LIME, 1), 1, 0.5, 50); - - if (player.getWorld() != goal.getWorld()) return; - if (player.getLocation().distance(relativeGoal) > 20) return; - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), relativeGoal, - MinecraftNameWrapper.INSTANT_EFFECT, 0.75, 0.5); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - if (event.getTo().getWorld() != goal.getWorld()) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { - Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, 0.75, 2); - } - } - - private void reloadGoalLocation() { - - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - int y = 999; - - IRandom iRandom = IRandom.create(seed); - // Some more calculations to prevent the result cords to always end with the same digits. - int max = getValue() * 100 - iRandom.nextInt(getValue() - getValue() / 2); - - int x = iRandom.nextInt(max * 2) - max; - int z = iRandom.nextInt(max * 2) - max; - goal = new Location(world, x, y, z); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (!document.contains("seed")) { - seed = IRandom.create().getSeed(); - return; - } - - long seed = document.getLong("seed"); - if (this.seed == seed) return; - this.seed = seed; - - if (!isEnabled()) return; - reloadGoalLocation(); - bossbar.update(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("seed", seed); - } + protected long seed = IRandom.create().getSeed(); + + private Location goal; + + public RaceGoal() { + super(MenuType.GOAL, 1, 30, 5); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + } + + @Override + protected void onEnable() { + reloadGoalLocation(); + bossbar.setContent((bar, player) -> { + bar.setColor(BarColor.GREEN); + if (player.getWorld() == goal.getWorld()) { + + Location relativeGoal = goal.clone(); + relativeGoal.setY(player.getLocation().getY()); + relativeGoal.add(0.5, 0, 0.5); + int distance = (int) Math.round(player.getLocation().distance(relativeGoal)); + + bar.setTitle(Message.forName("bossbar-race-goal-info") + .asString(goal.getBlockX(), goal.getBlockZ(), distance)); + } else { + bar.setTitle(Message.forName("bossbar-race-goal") + .asString(goal.getBlockX(), goal.getBlockZ())); + } + + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + goal = null; + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-range-blocks-description").asArray(getValue() * 100); + } + + + @Override + protected void onValueChange() { + reloadGoalLocation(); + bossbar.update(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STRUCTURE_VOID, Message.forName("item-race-goal")); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + if (goal == null) return; + bossbar.update(); + broadcast(player -> { + Location relativeGoal = goal.clone(); + relativeGoal.setY(player.getLocation().getY()); + relativeGoal.add(0.5, 0, 0.5); + ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, new DustOptions( + Color.LIME, 1), 1, 0.5, 50); + + if (player.getWorld() != goal.getWorld()) return; + if (player.getLocation().distance(relativeGoal) > 20) return; + ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), relativeGoal, + MinecraftNameWrapper.INSTANT_EFFECT, 0.75, 0.5); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + if (event.getTo().getWorld() != goal.getWorld()) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { + Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, 0.75, 2); + } + } + + private void reloadGoalLocation() { + + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + int y = 999; + + IRandom iRandom = IRandom.create(seed); + // Some more calculations to prevent the result cords to always end with the same digits. + int max = getValue() * 100 - iRandom.nextInt(getValue() - getValue() / 2); + + int x = iRandom.nextInt(max * 2) - max; + int z = iRandom.nextInt(max * 2) - max; + goal = new Location(world, x, y, z); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (!document.contains("seed")) { + seed = IRandom.create().getSeed(); + return; + } + + long seed = document.getLong("seed"); + if (this.seed == seed) return; + this.seed = seed; + + if (!isEnabled()) return; + reloadGoalLocation(); + bossbar.update(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("seed", seed); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 56259f23e..7e8908424 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; @@ -30,262 +30,255 @@ import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.function.Function; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { - public ExtremeForceBattleGoal() { - super(Message.forName("menu-extreme-force-battle-goal-settings")); - - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-extreme-force-battle-goal")); - } - - @Override - protected ForceTarget[] getTargetsPossibleToFind() { - //Currently not needed as the setRandomTarget logic of the ForceBattleGoal class is not used - return new ForceTarget[0]; + public ExtremeForceBattleGoal() { + super(Message.forName("menu-extreme-force-battle-goal-settings")); + + registerSetting("give-item", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), + false + )); + registerSetting("give-block", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), + false + )); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-extreme-force-battle-goal")); + } + + @Override + protected ForceTarget[] getTargetsPossibleToFind() { + //Currently not needed as the setRandomTarget logic of the ForceBattleGoal class is not used + return new ForceTarget[0]; + } + + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkTargets() { + for (Map.Entry> entry : currentTarget.entrySet()) { + UUID uuid = entry.getKey(); + ForceTarget target = entry.getValue(); + Player player = Bukkit.getPlayer(uuid); + if (player == null || ignorePlayer(player)) continue; + + if (target.check(player)) { + handleTargetFound(player); + } } - - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkTargets() { - for (Map.Entry> entry : currentTarget.entrySet()) { - UUID uuid = entry.getKey(); - ForceTarget target = entry.getValue(); - Player player = Bukkit.getPlayer(uuid); - if (player == null || ignorePlayer(player)) continue; - - if (target.check(player)) { - handleTargetFound(player); - } - } + } + + @Override + public ForceTarget getTargetFromDocument(Document document, String path) { + Document targetDocument = document.getDocument(path); + String targetTypeString = targetDocument.getString("type"); + String value = targetDocument.getString("value"); + + TargetType targetType = TargetType.valueOf(targetTypeString); + return targetType.parse().apply(value); + } + + @Override + public List> getListFromDocument(Document document, String path) { + List targetDocuments = document.getDocumentList(path); + List> targets = new ArrayList<>(); + for (Document targetDocument : targetDocuments) { + String targetTypeString = targetDocument.getString("type"); + Object value = targetDocument.getObject("value"); + + TargetType targetType = TargetType.valueOf(targetTypeString); + targets.add(targetType.parse().apply(value)); } - - @Override - public ForceTarget getTargetFromDocument(Document document, String path) { - Document targetDocument = document.getDocument(path); - String targetTypeString = targetDocument.getString("type"); - String value = targetDocument.getString("value"); - - TargetType targetType = TargetType.valueOf(targetTypeString); - return targetType.parse().apply(value); + return targets; + } + + @Override + public void setTargetInDocument(Document document, String path, ForceTarget target) { + document.set(path, Document.create().set("type", target.getType().name()).set("value", target.getTargetSaveObject())); + } + + @Override + public void setFoundListInDocument(Document document, String path, List> targets) { + List documents = new ArrayList<>(); + for (ForceTarget forceTarget : targets) { + documents.add(Document.create().set("type", forceTarget.getType().name()).set("value", forceTarget.getTargetSaveObject())); } + document.set(path, documents); + } - @Override - public List> getListFromDocument(Document document, String path) { - List targetDocuments = document.getDocumentList(path); - List> targets = new ArrayList<>(); - for (Document targetDocument : targetDocuments) { - String targetTypeString = targetDocument.getString("type"); - Object value = targetDocument.getObject("value"); - - TargetType targetType = TargetType.valueOf(targetTypeString); - targets.add(targetType.parse().apply(value)); - } - return targets; - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("extreme-force-battle-leaderboard"); + } - @Override - public void setTargetInDocument(Document document, String path, ForceTarget target) { - document.set(path, Document.create().set("type", target.getType().name()).set("value", target.getTargetSaveObject())); - } + @Override + public void setRandomTarget(Player player) { + updateDisplayStand(player); - @Override - public void setFoundListInDocument(Document document, String path, List> targets) { - List documents = new ArrayList<>(); - for (ForceTarget forceTarget : targets) { - documents.add(Document.create().set("type", forceTarget.getType().name()).set("value", forceTarget.getTargetSaveObject())); - } - document.set(path, documents); - } + TargetType targetType = globalRandom.choose(TargetType.values()); + ForceTarget newTarget = targetType.getRandomTarget().apply(player); - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("extreme-force-battle-leaderboard"); + if (newTarget instanceof AdvancementTarget) { + AdvancementProgress progress = player.getAdvancementProgress(((AdvancementTarget) newTarget).getTarget()); + progress.getAwardedCriteria().forEach(progress::revokeCriteria); } - @Override - public void setRandomTarget(Player player) { - updateDisplayStand(player); - - TargetType targetType = globalRandom.choose(TargetType.values()); - ForceTarget newTarget = targetType.getRandomTarget().apply(player); - - if (newTarget instanceof AdvancementTarget) { - AdvancementProgress progress = player.getAdvancementProgress(((AdvancementTarget) newTarget).getTarget()); - progress.getAwardedCriteria().forEach(progress::revokeCriteria); - } - - currentTarget.put(player.getUniqueId(), newTarget); - getNewTargetMessage(newTarget) - .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(newTarget)); - SoundSample.PLING.play(player); - - if (scoreboard.isShown()) { - scoreboard.update(); - } + currentTarget.put(player.getUniqueId(), newTarget); + getNewTargetMessage(newTarget) + .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(newTarget)); + SoundSample.PLING.play(player); + if (scoreboard.isShown()) { + scoreboard.update(); } - @Override - protected void setScoreboardContent() { - scoreboard.setContent((board, player) -> { - List ingamePlayers = ChallengeAPI.getIngamePlayers(); - int emptyLinesAvailable = 15 - ingamePlayers.size(); - - if (emptyLinesAvailable > 0) { - board.addLine(""); - emptyLinesAvailable--; - } - - for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { - Player ingamePlayer = ingamePlayers.get(i); - ForceTarget target = currentTarget.get(ingamePlayer.getUniqueId()); - String display = target == null ? Message.forName("none").asString() : (target.getScoreboardDisplayMessage().asString(getTargetName(target))); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); - } - - if (emptyLinesAvailable > 0) { - board.addLine(""); - } - }); + } + + @Override + protected void setScoreboardContent() { + scoreboard.setContent((board, player) -> { + List ingamePlayers = ChallengeAPI.getIngamePlayers(); + int emptyLinesAvailable = 15 - ingamePlayers.size(); + + if (emptyLinesAvailable > 0) { + board.addLine(""); + emptyLinesAvailable--; + } + + for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { + Player ingamePlayer = ingamePlayers.get(i); + ForceTarget target = currentTarget.get(ingamePlayer.getUniqueId()); + String display = target == null ? Message.forName("none").asString() : (target.getScoreboardDisplayMessage().asString(getTargetName(target))); + board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); + } + + if (emptyLinesAvailable > 0) { + board.addLine(""); + } + }); + } + + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } + + @Override + public void handleJokerUse(Player player) { + ForceTarget target = currentTarget.get(player.getUniqueId()); + if (giveItemOnSkip() && target instanceof ItemTarget) { + ItemTarget itemTarget = (ItemTarget) target; + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); + } else if (giveBlockOnSkip() && target instanceof BlockTarget) { + BlockTarget blockTarget = (BlockTarget) target; + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); } - - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; + super.handleJokerUse(player); + } + + public enum TargetType { + ITEM(object -> { + return new ItemTarget(Material.valueOf((String) object)); + }, player -> { + return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems())); + }), + BLOCK(object -> { + return new BlockTarget(Material.valueOf((String) object)); + }, player -> { + return new BlockTarget(globalRandom.choose(BlockTarget.getPossibleBlocks())); + }), + HEIGHT(object -> { + return new HeightTarget(Integer.valueOf((String) object)); + }, player -> { + World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); + int height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); + return new HeightTarget(height); + }), + MOB(object -> { + return new MobTarget(EntityType.valueOf((String) object)); + }, player -> { + return new MobTarget(globalRandom.choose(MobTarget.getPossibleMobs())); + }), + BIOME(object -> { + return new BiomeTarget(Biome.valueOf((String) object)); + }, player -> { + return new BiomeTarget(globalRandom.choose(BiomeTarget.getPossibleBiomes())); + }), + DAMAGE(object -> { + return new DamageTarget(Integer.valueOf((String) object)); + }, player -> { + return new DamageTarget(globalRandom.range(1, 19)); + }), + ADVANCEMENT(object -> { + return new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(NamespacedKey.fromString((String) object)))); + }, player -> { + return new AdvancementTarget(globalRandom.choose(AdvancementTarget.getPossibleAdvancements())); + }), + POSITION(object -> { + Document document = (Document) object; + return new PositionTarget(document.getDouble("x"), document.getDouble("z")); + }, PositionTarget::new); + + private final Function> parseFunction; + private final Function> randomTargetFunction; + + TargetType(Function> parseFunction, Function> randomTargetFunction) { + this.parseFunction = parseFunction; + this.randomTargetFunction = randomTargetFunction; } - @Override - public void handleJokerUse(Player player) { - ForceTarget target = currentTarget.get(player.getUniqueId()); - if (giveItemOnSkip() && target instanceof ItemTarget) { - ItemTarget itemTarget = (ItemTarget) target; - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); - } else if (giveBlockOnSkip() && target instanceof BlockTarget) { - BlockTarget blockTarget = (BlockTarget) target; - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); - } - super.handleJokerUse(player); + public Function> parse() { + return parseFunction; } - public enum TargetType { - ITEM(object -> { - return new ItemTarget(Material.valueOf((String) object)); - }, player -> { - return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems())); - }), - BLOCK(object -> { - return new BlockTarget(Material.valueOf((String) object)); - }, player -> { - return new BlockTarget(globalRandom.choose(BlockTarget.getPossibleBlocks())); - }), - HEIGHT(object -> { - return new HeightTarget(Integer.valueOf((String) object)); - }, player -> { - World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); - int height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); - return new HeightTarget(height); - }), - MOB(object -> { - return new MobTarget(EntityType.valueOf((String) object)); - }, player -> { - return new MobTarget(globalRandom.choose(MobTarget.getPossibleMobs())); - }), - BIOME(object -> { - return new BiomeTarget(Biome.valueOf((String) object)); - }, player -> { - return new BiomeTarget(globalRandom.choose(BiomeTarget.getPossibleBiomes())); - }), - DAMAGE(object -> { - return new DamageTarget(Integer.valueOf((String) object)); - }, player -> { - return new DamageTarget(globalRandom.range(1, 19)); - }), - ADVANCEMENT(object -> { - return new AdvancementTarget(Bukkit.getAdvancement(NamespacedKey.fromString((String) object))); - }, player -> { - return new AdvancementTarget(globalRandom.choose(AdvancementTarget.getPossibleAdvancements())); - }), - POSITION(object -> { - Document document = (Document) object; - return new PositionTarget(document.getDouble("x"), document.getDouble("z")); - }, PositionTarget::new); - - private final Function> parseFunction; - private final Function> randomTargetFunction; - - TargetType(Function> parseFunction, Function> randomTargetFunction) { - this.parseFunction = parseFunction; - this.randomTargetFunction = randomTargetFunction; - } - - public Function> parse() { - return parseFunction; - } - - public Function> getRandomTarget() { - return randomTargetFunction; - } + public Function> getRandomTarget() { + return randomTargetFunction; } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - LivingEntity entity = event.getEntity(); - Player killer = entity.getKiller(); - if (killer == null) return; - if (ignorePlayer(killer)) return; - if (currentTarget.get(killer.getUniqueId()) == null) return; - if (currentTarget.get(killer.getUniqueId()) instanceof MobTarget) { - MobTarget target = (MobTarget) currentTarget.get(killer.getUniqueId()); - if (target.getTarget() != entity.getType()) return; - handleTargetFound(killer); - } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + LivingEntity entity = event.getEntity(); + Player killer = entity.getKiller(); + if (killer == null) return; + if (ignorePlayer(killer)) return; + if (currentTarget.get(killer.getUniqueId()) == null) return; + if (currentTarget.get(killer.getUniqueId()) instanceof MobTarget) { + MobTarget target = (MobTarget) currentTarget.get(killer.getUniqueId()); + if (target.getTarget() != entity.getType()) return; + handleTargetFound(killer); } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (currentTarget.get(player.getUniqueId()) == null) return; - if (currentTarget.get(player.getUniqueId()) instanceof DamageTarget) { - DamageTarget target = (DamageTarget) currentTarget.get(player.getUniqueId()); - int damage = (int) ChallengeHelper.getFinalDamage(event); - if (damage != target.getTarget()) return; - handleTargetFound(player); - } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (currentTarget.get(player.getUniqueId()) == null) return; + if (currentTarget.get(player.getUniqueId()) instanceof DamageTarget) { + DamageTarget target = (DamageTarget) currentTarget.get(player.getUniqueId()); + int damage = (int) ChallengeHelper.getFinalDamage(event); + if (damage != target.getTarget()) return; + handleTargetFound(player); } + } - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); - } + private boolean giveItemOnSkip() { + return getSetting("give-item").getAsBoolean(); + } - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); - } + private boolean giveBlockOnSkip() { + return getSetting("give-block").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index ddb3047f7..bd9a823b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; @@ -20,87 +20,86 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceAdvancementBattleGoal extends ForceBattleGoal { - public ForceAdvancementBattleGoal() { - super(Message.forName("menu-force-advancement-battle-goal-settings")); - } + public ForceAdvancementBattleGoal() { + super(Message.forName("menu-force-advancement-battle-goal-settings")); + } - private void resetAdvancementProgress(Player player, Advancement advancement) { - if (advancement == null) return; - AdvancementProgress progress = player.getAdvancementProgress(advancement); - progress.getAwardedCriteria().forEach(progress::revokeCriteria); - } + private void resetAdvancementProgress(Player player, Advancement advancement) { + if (advancement == null) return; + AdvancementProgress progress = player.getAdvancementProgress(advancement); + progress.getAwardedCriteria().forEach(progress::revokeCriteria); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-force-advancement-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-force-advancement-battle-goal")); + } - @Override - protected AdvancementTarget[] getTargetsPossibleToFind() { - List advancements = AdvancementTarget.getPossibleAdvancements(); - return advancements.stream().map(AdvancementTarget::new).toArray(AdvancementTarget[]::new); - } + @Override + protected AdvancementTarget[] getTargetsPossibleToFind() { + List advancements = AdvancementTarget.getPossibleAdvancements(); + return advancements.stream().map(AdvancementTarget::new).toArray(AdvancementTarget[]::new); + } - @Override - public AdvancementTarget getTargetFromDocument(Document document, String path) { - String advancementKey = document.getString(path); - try { - NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); - return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); - } catch (Exception exception) { - // DON'T EXIST - } - return null; - } + @Override + public AdvancementTarget getTargetFromDocument(Document document, String path) { + String advancementKey = document.getString(path); + try { + assert advancementKey != null; + NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); + assert namespacedKey != null; + return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); + } catch (Exception exception) { + // DON'T EXIST + } + return null; + } - @Override - public List getListFromDocument(Document document, String path) { - List advancementKeys = document.getStringList(path); - List advancementTargets = new ArrayList<>(); - for (String advancementKey : advancementKeys) { - try { - advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(BukkitReflectionUtils.fromString(advancementKey)))); - } catch (Exception exception) { - // DON'T EXIST - } - } - return advancementTargets; - } + @Override + public List getListFromDocument(Document document, String path) { + List advancementKeys = document.getStringList(path); + List advancementTargets = new ArrayList<>(); + for (String advancementKey : advancementKeys) { + try { + advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey))))); + } catch (Exception exception) { + // DON'T EXIST + } + } + return advancementTargets; + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-advancement-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-advancement-battle-leaderboard"); + } - @Override - public void setRandomTarget(Player player) { - super.setRandomTarget(player); - resetAdvancementProgress(player, currentTarget.get(player.getUniqueId()).getTarget()); - } + @Override + public void setRandomTarget(Player player) { + super.setRandomTarget(player); + resetAdvancementProgress(player, currentTarget.get(player.getUniqueId()).getTarget()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onAdvancement(PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Player player = event.getPlayer(); - if (event.getAdvancement() == currentTarget.get(player.getUniqueId()).getTarget()) { - handleTargetFound(player); - } - } + @EventHandler(priority = EventPriority.MONITOR) + public void onAdvancement(PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Player player = event.getPlayer(); + if (event.getAdvancement() == currentTarget.get(player.getUniqueId()).getTarget()) { + handleTargetFound(player); + } + } - @Override - public void handleTargetFound(Player player) { - super.handleTargetFound(player); - Advancement advancement = currentTarget.get(player.getUniqueId()).getTarget(); - resetAdvancementProgress(player, advancement); - } + @Override + public void handleTargetFound(Player player) { + super.handleTargetFound(player); + Advancement advancement = currentTarget.get(player.getUniqueId()).getTarget(); + resetAdvancementProgress(player, advancement); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index aed021546..783e07722 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BiomeTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; @@ -8,58 +8,62 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.block.Biome; import org.jetbrains.annotations.NotNull; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.3 - */ public class ForceBiomeBattleGoal extends ForceBattleGoal { - public ForceBiomeBattleGoal() { - super(Message.forName("menu-force-biome-battle-goal-settings")); - } + public ForceBiomeBattleGoal() { + super(Message.forName("menu-force-biome-battle-goal-settings")); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FILLED_MAP, Message.forName("item-force-biome-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FILLED_MAP, Message.forName("item-force-biome-battle-goal")); + } - @Override - protected BiomeTarget[] getTargetsPossibleToFind() { - List biomes = BiomeTarget.getPossibleBiomes(); - return biomes.stream().map(BiomeTarget::new).toArray(BiomeTarget[]::new); - } + @Override + protected BiomeTarget[] getTargetsPossibleToFind() { + List biomes = BiomeTarget.getPossibleBiomes(); + return biomes.stream().map(BiomeTarget::new).toArray(BiomeTarget[]::new); + } - @Override - public BiomeTarget getTargetFromDocument(Document document, String path) { - return new BiomeTarget(document.getEnum(path, Biome.class)); - } + @Override + public BiomeTarget getTargetFromDocument(Document document, String path) { + return new BiomeTarget(Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(document.getString(path)).toLowerCase()))); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Biome.class).stream().map(BiomeTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getStringList(path).stream() + .map(biomeName -> new BiomeTarget( + Registry.BIOME.get(NamespacedKey.minecraft(biomeName.toLowerCase())) + )) + .collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-biome-battle-leaderboard"); - } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBiomes() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - BiomeTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-biome-battle-leaderboard"); + } + + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBiomes() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + BiomeTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 0916d0227..b2764d8ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; @@ -16,70 +16,66 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { - public ForceBlockBattleGoal() { - super(Message.forName("menu-force-block-battle-goal-settings")); + public ForceBlockBattleGoal() { + super(Message.forName("menu-force-block-battle-goal-settings")); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); - } + registerSetting("give-block", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), + false + )); + } - @Override - protected BlockTarget[] getTargetsPossibleToFind() { - List materials = BlockTarget.getPossibleBlocks(); - return materials.stream().map(BlockTarget::new).toArray(BlockTarget[]::new); - } + @Override + protected BlockTarget[] getTargetsPossibleToFind() { + List materials = BlockTarget.getPossibleBlocks(); + return materials.stream().map(BlockTarget::new).toArray(BlockTarget[]::new); + } - @Override - public BlockTarget getTargetFromDocument(Document document, String path) { - return new BlockTarget(document.getEnum(path, Material.class)); - } + @Override + public BlockTarget getTargetFromDocument(Document document, String path) { + return new BlockTarget(document.getEnum(path, Material.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Material.class).stream().map(BlockTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, Material.class).stream().map(BlockTarget::new).collect(Collectors.toList()); + } - @Override - public Message getLeaderboardTitleMessage() { - return Message.forName("force-block-battle-leaderboard"); - } + @Override + public Message getLeaderboardTitleMessage() { + return Message.forName("force-block-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-force-block-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-force-block-battle-goal")); + } - @Override - public void handleJokerUse(Player player) { - super.handleJokerUse(player); - if (giveBlockOnSkip()) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); - } + @Override + public void handleJokerUse(Player player) { + super.handleJokerUse(player); + if (giveBlockOnSkip()) { + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); } + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBlocks() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - BlockTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBlocks() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + BlockTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); - } + private boolean giveBlockOnSkip() { + return getSetting("give-block").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index c3cb8dd2e..9f5519808 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.DamageTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -17,63 +17,59 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForceDamageBattleGoal extends ForceBattleGoal { - public ForceDamageBattleGoal() { - super(Message.forName("menu-force-damage-battle-goal-settings")); - } + public ForceDamageBattleGoal() { + super(Message.forName("menu-force-damage-battle-goal-settings")); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-force-damage-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-force-damage-battle-goal")); + } - @Override - protected DamageTarget[] getTargetsPossibleToFind() { - return new DamageTarget[0]; //Not used - } + @Override + protected DamageTarget[] getTargetsPossibleToFind() { + return new DamageTarget[0]; //Not used + } - @Override - protected DamageTarget getRandomTarget(Player player) { - return new DamageTarget(globalRandom.range(1, 19)); - } + @Override + protected DamageTarget getRandomTarget(Player player) { + return new DamageTarget(globalRandom.range(1, 19)); + } - @Override - public DamageTarget getTargetFromDocument(Document document, String path) { - return new DamageTarget(document.getInt(path)); - } + @Override + public DamageTarget getTargetFromDocument(Document document, String path) { + return new DamageTarget(document.getInt(path)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getIntegerList(path).stream().map(DamageTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getIntegerList(path).stream().map(DamageTarget::new).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-damage-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-damage-battle-leaderboard"); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (currentTarget.get(player.getUniqueId()) == null) return; - DamageTarget target = currentTarget.get(player.getUniqueId()); - int damage = (int) ChallengeHelper.getFinalDamage(event); - if (damage != target.getTarget()) return; - handleTargetFound(player); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (currentTarget.get(player.getUniqueId()) == null) return; + DamageTarget target = currentTarget.get(player.getUniqueId()); + int damage = (int) ChallengeHelper.getFinalDamage(event); + if (damage != target.getTarget()) return; + handleTargetFound(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index 6a85ad51b..399dbb267 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.HeightTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; @@ -16,61 +16,57 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForceHeightBattleGoal extends ForceBattleGoal { - public ForceHeightBattleGoal() { - super(Message.forName("menu-force-height-battle-goal-settings")); - } + public ForceHeightBattleGoal() { + super(Message.forName("menu-force-height-battle-goal-settings")); + } - @Override - protected HeightTarget[] getTargetsPossibleToFind() { - return new HeightTarget[0]; //Not used - } + @Override + protected HeightTarget[] getTargetsPossibleToFind() { + return new HeightTarget[0]; //Not used + } - @Override - protected HeightTarget getRandomTarget(Player player) { - World world = player.getWorld(); - return new HeightTarget(globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight())); - } + @Override + protected HeightTarget getRandomTarget(Player player) { + World world = player.getWorld(); + return new HeightTarget(globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight())); + } - @Override - public HeightTarget getTargetFromDocument(Document document, String path) { - return new HeightTarget(document.getInt(path)); - } + @Override + public HeightTarget getTargetFromDocument(Document document, String path) { + return new HeightTarget(document.getInt(path)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getIntegerList(path).stream().map(HeightTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getIntegerList(path).stream().map(HeightTarget::new).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-height-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-height-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-force-height-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-force-height-battle-goal")); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkHeights() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - HeightTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkHeights() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + HeightTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index b4238e8bd..826021f01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; @@ -18,83 +18,79 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class ForceItemBattleGoal extends ForceBattleDisplayGoal { - public ForceItemBattleGoal() { - super(Message.forName("menu-force-item-battle-goal-settings")); + public ForceItemBattleGoal() { + super(Message.forName("menu-force-item-battle-goal-settings")); - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); - } + registerSetting("give-item", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), + false + )); + } - @Override - protected ItemTarget[] getTargetsPossibleToFind() { - List materials = ItemTarget.getPossibleItems(); - return materials.stream().map(ItemTarget::new).toArray(ItemTarget[]::new); - } + @Override + protected ItemTarget[] getTargetsPossibleToFind() { + List materials = ItemTarget.getPossibleItems(); + return materials.stream().map(ItemTarget::new).toArray(ItemTarget[]::new); + } - @Override - public ItemTarget getTargetFromDocument(Document document, String path) { - return new ItemTarget(document.getEnum(path, Material.class)); - } + @Override + public ItemTarget getTargetFromDocument(Document document, String path) { + return new ItemTarget(document.getEnum(path, Material.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Material.class).stream().map(ItemTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, Material.class).stream().map(ItemTarget::new).collect(Collectors.toList()); + } - @Override - public Message getLeaderboardTitleMessage() { - return Message.forName("force-item-battle-leaderboard"); - } + @Override + public Message getLeaderboardTitleMessage() { + return Message.forName("force-item-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ITEM_FRAME, Message.forName("item-force-item-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ITEM_FRAME, Message.forName("item-force-item-battle-goal")); + } - @Override - public void handleJokerUse(Player player) { - if (giveItemOnSkip()) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); - } - super.handleJokerUse(player); - } + @Override + public void handleJokerUse(Player player) { + if (giveItemOnSkip()) { + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); + } + super.handleJokerUse(player); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedInventory() == null) return; - if (event.getCurrentItem() == null) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getCurrentItem().getType()) { - handleTargetFound(event.getPlayer()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClick(PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedInventory() == null) return; + if (event.getCurrentItem() == null) return; + Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); + if (material == null) return; + if (material == event.getCurrentItem().getType()) { + handleTargetFound(event.getPlayer()); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getItem().getItemStack().getType()) { - handleTargetFound(event.getPlayer()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); + if (material == null) return; + if (material == event.getItem().getItemStack().getType()) { + handleTargetFound(event.getPlayer()); + } + } - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); - } + private boolean giveItemOnSkip() { + return getSetting("give-item").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 573d0dd91..3325a2396 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; @@ -19,55 +19,51 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceMobBattleGoal extends ForceBattleDisplayGoal { - public ForceMobBattleGoal() { - super(Message.forName("menu-force-mob-battle-goal-settings")); - } + public ForceMobBattleGoal() { + super(Message.forName("menu-force-mob-battle-goal-settings")); + } - @Override - protected MobTarget[] getTargetsPossibleToFind() { - List entityTypes = MobTarget.getPossibleMobs(); - return entityTypes.stream().map(MobTarget::new).toArray(MobTarget[]::new); - } + @Override + protected MobTarget[] getTargetsPossibleToFind() { + List entityTypes = MobTarget.getPossibleMobs(); + return entityTypes.stream().map(MobTarget::new).toArray(MobTarget[]::new); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-mob-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-mob-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-force-mob-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-force-mob-battle-goal")); + } - @Override - public MobTarget getTargetFromDocument(Document document, String path) { - return new MobTarget(document.getEnum(path, EntityType.class)); - } + @Override + public MobTarget getTargetFromDocument(Document document, String path) { + return new MobTarget(document.getEnum(path, EntityType.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, EntityType.class).stream().map(MobTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, EntityType.class).stream().map(MobTarget::new).collect(Collectors.toList()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - LivingEntity entity = event.getEntity(); - Player killer = entity.getKiller(); - if (killer == null) return; - if (ignorePlayer(killer)) return; - if (currentTarget.get(killer.getUniqueId()) == null) return; - if (entity.getType() == currentTarget.get(killer.getUniqueId()).getTarget()) { - handleTargetFound(killer); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + LivingEntity entity = event.getEntity(); + Player killer = entity.getKiller(); + if (killer == null) return; + if (ignorePlayer(killer)) return; + if (currentTarget.get(killer.getUniqueId()) == null) return; + if (entity.getType() == currentTarget.get(killer.getUniqueId()).getTarget()) { + handleTargetFound(killer); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 6c2a881f2..5e9a2c85e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; @@ -14,74 +14,70 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForcePositionBattleGoal extends ForceBattleGoal { - public ForcePositionBattleGoal() { - super(Message.forName("menu-force-position-battle-goal-settings")); - registerSetting("radius", new NumberSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), - value -> null, - value -> "§e" + (value * 100), - 1, - 100, - 15 - )); - } + public ForcePositionBattleGoal() { + super(Message.forName("menu-force-position-battle-goal-settings")); + registerSetting("radius", new NumberSubSetting( + () -> new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), + value -> null, + value -> "§e" + (value * 100), + 1, + 100, + 15 + )); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-goal")); + } - @Override - protected PositionTarget[] getTargetsPossibleToFind() { - return new PositionTarget[0]; //Not used - } + @Override + protected PositionTarget[] getTargetsPossibleToFind() { + return new PositionTarget[0]; //Not used + } - @Override - protected PositionTarget getRandomTarget(Player player) { - return new PositionTarget(player, getRadius()); - } + @Override + protected PositionTarget getRandomTarget(Player player) { + return new PositionTarget(player, getRadius()); + } - @Override - public PositionTarget getTargetFromDocument(Document document, String path) { - return new PositionTarget( - document.getDocument(path).getDouble("x"), - document.getDocument(path).getDouble("z") - ); - } + @Override + public PositionTarget getTargetFromDocument(Document document, String path) { + return new PositionTarget( + document.getDocument(path).getDouble("x"), + document.getDocument(path).getDouble("z") + ); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getDocumentList(path).stream().map(doc -> new PositionTarget(doc.getDouble("x"), doc.getDouble("z"))).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getDocumentList(path).stream().map(doc -> new PositionTarget(doc.getDouble("x"), doc.getDouble("z"))).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-position-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-position-battle-leaderboard"); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkPositions() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - PositionTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkPositions() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + PositionTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } - protected int getRadius() { - return getSetting("radius").getAsInt() * 100; - } + protected int getRadius() { + return getSetting("radius").getAsInt() * 100; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java index 738269090..2cc333635 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java @@ -10,65 +10,61 @@ import java.util.ArrayList; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class AdvancementTarget extends ForceTarget { - public AdvancementTarget(Advancement target) { - super(target); - } + public AdvancementTarget(Advancement target) { + super(target); + } - @Override - public boolean check(Player player) { - return player.getAdvancementProgress(target).isDone(); - } + @Override + public boolean check(Player player) { + return player.getAdvancementProgress(target).isDone(); + } - public static List getPossibleAdvancements() { - List advancements = new ArrayList<>(); - Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { - String string = advancement.getKey().toString(); - if (!string.contains(":recipes/") && !string.endsWith("root")) { - advancements.add(advancement); - } - }); - return advancements; - } + public static List getPossibleAdvancements() { + List advancements = new ArrayList<>(); + Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { + String string = advancement.getKey().toString(); + if (!string.contains(":recipes/") && !string.endsWith("root")) { + advancements.add(advancement); + } + }); + return advancements; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getAdvancementTitle(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getAdvancementTitle(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-advancement-battle-new-advancement"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-advancement-battle-new-advancement"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-advancement-battle-completed"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-advancement-battle-completed"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.ADVANCEMENT; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.ADVANCEMENT; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-advancement-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-advancement-target-display"); + } - @Override - public Object getTargetSaveObject() { - return target.getKey().toString(); - } + @Override + public Object getTargetSaveObject() { + return target.getKey().toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java index 181fa0728..ddf3035f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java @@ -10,56 +10,52 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BiomeTarget extends ForceTarget { - public BiomeTarget(Biome target) { - super(target); - } - - @Override - public boolean check(Player player) { - return player.getLocation().getBlock().getBiome() == target; - } - - public static List getPossibleBiomes() { - return Arrays.stream(Biome.values()) - .filter(biome -> !biome.name().contains("VOID")) - .filter(biome -> !biome.name().equals("CUSTOM")) - .collect(Collectors.toList()); - } - - @Override - public Object toMessage() { - return target; - } - - @Override - public String getName() { - return BukkitStringUtils.getBiomeName(target).toPlainText(); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-biome"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-found-biome"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.BIOME; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-biome-target-display"); - } + public BiomeTarget(Biome target) { + super(target); + } + + @Override + public boolean check(Player player) { + return player.getLocation().getBlock().getBiome() == target; + } + + public static List getPossibleBiomes() { + return Arrays.stream(Biome.values()) + .filter(biome -> !biome.name().contains("VOID")) + .filter(biome -> !biome.name().equals("CUSTOM")) + .collect(Collectors.toList()); + } + + @Override + public Object toMessage() { + return target; + } + + @Override + public String getName() { + return BukkitStringUtils.getBiomeName(target).toPlainText(); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-biome"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-found-biome"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.BIOME; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-biome-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 585c5acb1..088da9146 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -13,60 +13,56 @@ import java.util.Arrays; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BlockTarget extends ForceTarget { - public BlockTarget(Material target) { - super(target); - } + public BlockTarget(Material target) { + super(target); + } - @Override - public boolean check(Player player) { - return EntityUtils.isStandingOnBlock(player, target); - } + @Override + public boolean check(Player player) { + return EntityUtils.isStandingOnBlock(player, target); + } - public static List getPossibleBlocks() { - List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.removeIf(material -> !ItemUtils.blockIsAvailableInSurvival(material)); - return materials; - } + public static List getPossibleBlocks() { + List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.removeIf(material -> !ItemUtils.blockIsAvailableInSurvival(material)); + return materials; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getItemName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getItemName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-block-battle-new-block"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-block-battle-new-block"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-block-battle-found"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-block-battle-found"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.BLOCK; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.BLOCK; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-block-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-block-target-display"); + } - @Override - public String toString() { - return target.name(); - } + @Override + public String toString() { + return target.name(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java index 39ab6581c..9ac2322ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java @@ -4,49 +4,45 @@ import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class DamageTarget extends ForceTarget { - public DamageTarget(Integer target) { - super(target); - } - - @Override - public boolean check(Player player) { - return false; - } - - @Override - public Object toMessage() { - return (double) target / 2; - } - - @Override - public String getName() { - return String.valueOf((double) target / 2); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-damage"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-took-damage"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.DAMAGE; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-damage-target-display"); - } + public DamageTarget(Integer target) { + super(target); + } + + @Override + public boolean check(Player player) { + return false; + } + + @Override + public Object toMessage() { + return (double) target / 2; + } + + @Override + public String getName() { + return String.valueOf((double) target / 2); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-damage"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-took-damage"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.DAMAGE; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-damage-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index 8abf1a85b..dfa948547 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; +import lombok.Getter; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Material; @@ -8,44 +9,45 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ +import java.util.Objects; + +@Getter public abstract class ForceTarget { - protected final T target; + protected final T target; - protected ForceTarget(T target) { - this.target = target; - } + protected ForceTarget(T target) { + this.target = target; + } - public abstract boolean check(Player player); - public abstract Object toMessage(); - public abstract String getName(); - public abstract Message getNewTargetMessage(); - public abstract Message getCompletedMessage(); - public abstract ExtremeForceBattleGoal.TargetType getType(); - public abstract Message getScoreboardDisplayMessage(); - - @Override - public String toString() { - return target.toString(); - } + public abstract boolean check(Player player); - public T getTarget() { - return target; - } + public abstract Object toMessage(); - public void updateDisplayStand(@NotNull ArmorStand armorStand) { - if (target instanceof Material) { - armorStand.getEquipment().setHelmet(new ItemStack((Material) target)); - } else { - armorStand.getEquipment().setHelmet(null); - } - } + public abstract String getName(); + + public abstract Message getNewTargetMessage(); - public Object getTargetSaveObject() { - return target.toString(); + public abstract Message getCompletedMessage(); + + public abstract ExtremeForceBattleGoal.TargetType getType(); + + public abstract Message getScoreboardDisplayMessage(); + + @Override + public String toString() { + return target.toString(); + } + + public void updateDisplayStand(@NotNull ArmorStand armorStand) { + if (target instanceof Material) { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack((Material) target)); + } else { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); } + } + + public Object getTargetSaveObject() { + return target.toString(); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java index 9abe837f7..efd616946 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java @@ -4,49 +4,45 @@ import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class HeightTarget extends ForceTarget { - public HeightTarget(Integer target) { - super(target); - } - - @Override - public boolean check(Player player) { - return player.getLocation().getBlockY() == target; - } - - @Override - public Object toMessage() { - return target; - } - - @Override - public String getName() { - return target.toString(); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-height"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-height"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.HEIGHT; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-height-target-display"); - } + public HeightTarget(Integer target) { + super(target); + } + + @Override + public boolean check(Player player) { + return player.getLocation().getBlockY() == target; + } + + @Override + public Object toMessage() { + return target; + } + + @Override + public String getName() { + return target.toString(); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-height"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-reached-height"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.HEIGHT; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-height-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index a407974ec..d775f5a09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -12,61 +12,57 @@ import java.util.Arrays; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ItemTarget extends ForceTarget { - public ItemTarget(Material target) { - super(target); - } + public ItemTarget(Material target) { + super(target); + } - @Override - public boolean check(Player player) { - return player.getInventory().contains(target); - } + @Override + public boolean check(Player player) { + return player.getInventory().contains(target); + } - public static List getPossibleItems() { - List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.removeIf(material -> !material.isItem()); - materials.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - return materials; - } + public static List getPossibleItems() { + List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.removeIf(material -> !material.isItem()); + materials.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + return materials; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getItemName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getItemName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-item-battle-new-item"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-item-battle-new-item"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-item-battle-found"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-item-battle-found"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.ITEM; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.ITEM; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-item-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-item-target-display"); + } - @Override - public String toString() { - return target.name(); - } + @Override + public String toString() { + return target.name(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index d5ce2cc38..ba9f60a2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -15,69 +15,66 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class MobTarget extends ForceTarget { - public MobTarget(EntityType target) { - super(target); - } + public MobTarget(EntityType target) { + super(target); + } - @Override - public boolean check(Player player) { - return false; - } + @Override + public boolean check(Player player) { + return false; + } - public static List getPossibleMobs() { - List entityTypes = new ArrayList<>(Arrays.asList(EntityType.values())); - entityTypes.removeIf(entityType -> !entityType.isSpawnable()); - entityTypes.removeIf(entityType -> !entityType.isAlive()); - Utils.removeEnums(entityTypes, "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "GIANT"); + public static List getPossibleMobs() { + List entityTypes = new ArrayList<>(Arrays.asList(EntityType.values())); + entityTypes.removeIf(entityType -> !entityType.isSpawnable()); + entityTypes.removeIf(entityType -> !entityType.isAlive()); + Utils.removeEnums(entityTypes, "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "GIANT"); - return entityTypes; - } + return entityTypes; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getEntityName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getEntityName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-mob-battle-new-mob"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-mob-battle-new-mob"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-mob-battle-killed"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-mob-battle-killed"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.MOB; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.MOB; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-mob-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-mob-target-display"); + } - @Override - public void updateDisplayStand(@NotNull ArmorStand armorStand) { - Material spawnEgg = EntityUtils.getSpawnEgg(target); - if (spawnEgg == null) { - armorStand.getEquipment().setHelmet(null); - } else { - armorStand.getEquipment().setHelmet(new ItemStack(spawnEgg)); - } + @Override + public void updateDisplayStand(@NotNull ArmorStand armorStand) { + Material spawnEgg = EntityUtils.getSpawnEgg(target); + if (spawnEgg == null) { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); + } else { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack(spawnEgg)); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 743cf7f16..524057bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,74 +1,70 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Location; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PositionTarget extends ForceTarget> { - public PositionTarget(double x, double z) { - super(Tuple.of(x, z)); - } + public PositionTarget(double x, double z) { + super(Tuple.of(x, z)); + } - public PositionTarget(Player player, int radius) { - super(Tuple.of( - player.getLocation().getBlockX() + (double) IRandom.singleton().range(-radius, radius), - player.getLocation().getBlockZ() + (double) IRandom.singleton().range(-radius, radius) - )); - } + public PositionTarget(Player player, int radius) { + super(Tuple.of( + player.getLocation().getBlockX() + (double) IRandom.singleton().range(-radius, radius), + player.getLocation().getBlockZ() + (double) IRandom.singleton().range(-radius, radius) + )); + } - public PositionTarget(Player player) { - this(player, 1500); - } + public PositionTarget(Player player) { + this(player, 1500); + } - @Override - public boolean check(Player player) { - Location playerLocation = player.getLocation().clone(); - playerLocation.setY(0); - Location targetLocation = new Location(playerLocation.getWorld(), target.getFirst(), 0, target.getSecond()); - return playerLocation.distance(targetLocation) < 5; - } + @Override + public boolean check(Player player) { + Location playerLocation = player.getLocation().clone(); + playerLocation.setY(0); + Location targetLocation = new Location(playerLocation.getWorld(), target.getFirst(), 0, target.getSecond()); + return playerLocation.distance(targetLocation) < 5; + } - @Override - public Object toMessage() { - return getName(); - } + @Override + public Object toMessage() { + return getName(); + } - @Override - public String getName() { - return Message.forName("extreme-force-battle-position").asString(target.getFirst(), target.getSecond()); - } + @Override + public String getName() { + return Message.forName("extreme-force-battle-position").asString(target.getFirst(), target.getSecond()); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-position"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-position"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-position"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-reached-position"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.POSITION; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.POSITION; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-position-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-position-target-display"); + } - @Override - public Object getTargetSaveObject() { - return Document.create().set("x", target.getFirst()).set("z", target.getSecond()); - } + @Override + public Object getTargetSaveObject() { + return Document.create().set("x", target.getFirst()).set("z", target.getSecond()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index 0e0c56653..a09668c43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -20,89 +20,85 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BlockMaterialSetting extends Setting { - private final String name; - private final ItemBuilder preset; - private final Object[] replacements; - private final Material[] materials; - - public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull Object[] replacements, @Nonnull Material... materials) { - super(MenuType.ITEMS, true); - this.name = name; - this.preset = preset; - this.replacements = replacements; - this.materials = materials; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); - } - - private boolean blockMaterial(Material material) { - return Arrays.asList(materials).contains(material); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { - if (isEnabled()) return; - if (ChallengeAPI.isWorldInUse()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!blockMaterial(event.getMaterial())) { - if (event.getClickedBlock() == null) return; - if (!blockMaterial(event.getClickedBlock().getType())) return; - event.setCancelled(true); - return; - } - event.setCancelled(true); - - dropMaterial(event.getPlayer().getLocation(), event.getPlayer().getInventory()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (isEnabled()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isWorldInUse()) return; - if (event.getCurrentItem() == null) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (!blockMaterial(event.getCurrentItem().getType())) return; - event.setCancelled(true); - - dropMaterial(event.getPlayer().getLocation(), event.getClickedInventory()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (isEnabled()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isWorldInUse()) return; - if (!blockMaterial(event.getItem().getItemStack().getType())) return; - event.setCancelled(true); - } - - public void dropMaterial(@Nonnull Location location, @Nonnull Inventory inventory) { - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item == null) continue; - if (!blockMaterial(item.getType())) continue; - InventoryUtils.dropItemByPlayer(location, item); - inventory.setItem(slot, null); - } - - } - - @NotNull - @Override - public String getUniqueName() { - return "blockmaterial" + materials[0].name().toLowerCase(); - } - -} \ No newline at end of file + private final String name; + private final ItemBuilder preset; + private final Object[] replacements; + private final Material[] materials; + + public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull Object[] replacements, @Nonnull Material... materials) { + super(MenuType.ITEMS, true); + this.name = name; + this.preset = preset; + this.replacements = replacements; + this.materials = materials; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); + } + + private boolean blockMaterial(Material material) { + return Arrays.asList(materials).contains(material); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { + if (isEnabled()) return; + if (ChallengeAPI.isWorldInUse()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!blockMaterial(event.getMaterial())) { + if (event.getClickedBlock() == null) return; + if (!blockMaterial(event.getClickedBlock().getType())) return; + event.setCancelled(true); + return; + } + event.setCancelled(true); + + dropMaterial(event.getPlayer().getLocation(), event.getPlayer().getInventory()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (isEnabled()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isWorldInUse()) return; + if (event.getCurrentItem() == null) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (!blockMaterial(event.getCurrentItem().getType())) return; + event.setCancelled(true); + + dropMaterial(event.getPlayer().getLocation(), event.getClickedInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (isEnabled()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isWorldInUse()) return; + if (!blockMaterial(event.getItem().getItemStack().getType())) return; + event.setCancelled(true); + } + + public void dropMaterial(@Nonnull Location location, @Nonnull Inventory inventory) { + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item == null) continue; + if (!blockMaterial(item.getType())) continue; + InventoryUtils.dropItemByPlayer(location, item); + inventory.setItem(slot, null); + } + + } + + @NotNull + @Override + public String getUniqueName() { + return "blockmaterial" + materials[0].name().toLowerCase(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 053947fb2..3b02b1a14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -27,143 +27,139 @@ import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class BackpackSetting extends SettingModifier implements PlayerCommand { - public static final int SHARED = 1, - PLAYER = 2; - - private final int size; - private final Map backpacks = new HashMap<>(); - private final Inventory sharedBackpack; - - public BackpackSetting() { - super(MenuType.SETTINGS, 1, 2, SHARED); - size = Math.max(Math.min(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9, 6 * 9), 9); - sharedBackpack = createInventory("§5Team Backpack"); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == SHARED) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); - } - - - @Override - public void playValueChangeTitle() { - switch (getValue()) { - case SHARED: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); - break; - case PLAYER: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); - break; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); - } - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - return; - } - - if (!isEnabled()) { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - return; - } - - if (getValue() == SHARED || getValue() == PLAYER) { - Message.forName("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); - player.openInventory(getCurrentBackpack(player)); - SoundSample.OPEN.play(player); - } else { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - } - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - loadChecked(document, "shared", sharedBackpack); - - Document players = document.getDocument("players"); - for (String key : players.keys()) { - loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), k -> createInventory("§6Backpack"))); - } - - } - - protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { - - if (document.isDocument(key)) { - loadLegacy(document.getDocument(key), inventory); - } else { - try { - String value = document.getString(key); - if (value == null) return; - BukkitSerialization.fromBase64(inventory, value); - } catch (IOException exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - - } - - protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory inventory) { - - for (String key : document.keys()) { - try { - int index = Integer.parseInt(key); - ItemStack item = document.getSerializable(key, ItemStack.class); - inventory.setItem(index, item); - } catch (Exception ignored) { - } - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - write(document, "shared", sharedBackpack); - - Document players = document.getDocument("players"); - backpacks.forEach((uuid, inventory) -> { - write(players, uuid.toString(), inventory); - }); - } - - protected void write(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { - document.set(key, BukkitSerialization.toBase64(inventory)); - } - - @Nonnull - protected Inventory createInventory(@Nonnull String title) { - return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); - } - - @Nonnull - protected Inventory getCurrentBackpack(@Nonnull Player player) { - return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); - } + public static final int SHARED = 1, + PLAYER = 2; + + private final int size; + private final Map backpacks = new HashMap<>(); + private final Inventory sharedBackpack; + + public BackpackSetting() { + super(MenuType.SETTINGS, 1, 2, SHARED); + size = Math.max(Math.min(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9, 6 * 9), 9); + sharedBackpack = createInventory("§5Team Backpack"); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == SHARED) + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); + } + + + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case SHARED: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); + break; + case PLAYER: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); + break; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + return; + } + + if (!isEnabled()) { + Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + return; + } + + if (getValue() == SHARED || getValue() == PLAYER) { + Message.forName("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); + player.openInventory(getCurrentBackpack(player)); + SoundSample.OPEN.play(player); + } else { + Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + } + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + loadChecked(document, "shared", sharedBackpack); + + Document players = document.getDocument("players"); + for (String key : players.keys()) { + loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), k -> createInventory("§6Backpack"))); + } + + } + + protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + + if (document.isDocument(key)) { + loadLegacy(document.getDocument(key), inventory); + } else { + try { + String value = document.getString(key); + if (value == null) return; + BukkitSerialization.fromBase64(inventory, value); + } catch (IOException exception) { + Challenges.getInstance().getILogger().error("", exception); + } + } + + } + + protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory inventory) { + + for (String key : document.keys()) { + try { + int index = Integer.parseInt(key); + ItemStack item = document.getSerializable(key, ItemStack.class); + inventory.setItem(index, item); + } catch (Exception ignored) { + } + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + write(document, "shared", sharedBackpack); + + Document players = document.getDocument("players"); + backpacks.forEach((uuid, inventory) -> { + write(players, uuid.toString(), inventory); + }); + } + + protected void write(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + document.set(key, BukkitSerialization.toBase64(inventory)); + } + + @Nonnull + protected Inventory createInventory(@Nonnull String title) { + return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); + } + + @Nonnull + protected Inventory getCurrentBackpack(@Nonnull Player player) { + return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 0cd7cb3a7..3c062bb33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; @@ -15,23 +15,19 @@ import java.util.Arrays; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @RequireVersion(MinecraftVersion.V1_16) public class BastionSpawnSetting extends NetherPortalSpawnSetting { - public BastionSpawnSetting() { - super(MenuType.SETTINGS, StructureType.BASTION_REMNANT, "unable-to-find-bastion", - Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); - } + public BastionSpawnSetting() { + super(MenuType.SETTINGS, StructureType.BASTION_REMNANT, "unable-to-find-bastion", + Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 0ecf32884..c30223490 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -30,209 +30,204 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class CutCleanSetting extends MenuSetting { - public CutCleanSetting() { - super(MenuType.SETTINGS, Message.forName("menu-cut-clean-setting-settings")); - registerSetting("iron->iron_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, - Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); - registerSetting("gold->gold_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, - Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); - registerSetting("coal->torch", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, - Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); - registerSetting("gravel->flint", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, - Material.FLINT, "GRAVEL")); - registerSetting("ore->veins", - new BreakOreVeinsSubSetting(() -> new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); - registerSetting("items->inventory", - new DirectIntoInventorySubSetting(() -> new ItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); - registerSetting("row->cooked", - new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); - } - - protected boolean directIntoInventory() { - return getSetting("items->inventory").getAsBoolean(); - } - - private class DirectIntoInventorySubSetting extends BooleanSubSetting { - - public DirectIntoInventorySubSetting(@Nonnull Supplier item) { - super(item); - } - - @Nonnull - @Override - public BooleanSubSetting setEnabled(boolean enabled) { - return super.setEnabled(enabled); - } - - } - - private class ConvertDropSubSetting extends BooleanSubSetting { - - protected final Material[] from; - protected final Material to; - - public ConvertDropSubSetting(@Nonnull Supplier item, boolean enabledByDefault, - @Nonnull Material to, @Nonnull String... from) { - super(item, enabledByDefault); - - List materials = new ArrayList<>(); - for (String s : from) { - Material material = Utils.getMaterial(s); - if (material != null) { - materials.add(material); - } - } - - this.from = materials.toArray(new Material[0]); - this.to = to; - } - - @Override - public void onEnable() { - if (from == null) return; - for (Material material : from) { - Challenges.getInstance().getBlockDropManager().setCustomDrops(material, to, DropPriority.CUT_CLEAN); - } - } - - @Override - public void onDisable() { - if (from == null) return; - for (Material material : from) { - Challenges.getInstance().getBlockDropManager().resetCustomDrop(material, DropPriority.CUT_CLEAN); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!directIntoInventory()) return; - if (!event.isDropItems()) return; - Material type = event.getBlock().getType(); - - for (Material material : from) { - if (type != material) continue; - List customDrops = Challenges.getInstance().getBlockDropManager().getCustomDrops(event.getBlock().getType()); - if (customDrops.isEmpty()) return; - event.setDropItems(false); - customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(event.getPlayer().getInventory(), event.getBlock().getLocation(), drop)); - } - - } - - } - - private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { - - public BreakOreVeinsSubSetting(@Nonnull Supplier item, int min, int max) { - super(item, min, max); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); - if (!canBeBroken(event.getBlock(), itemInMainHand)) return; - if (!event.getBlock().getType().name().contains("ORE")) return; - - breakBlockVein(event.getPlayer(), event.getBlock(), itemInMainHand); - } - - private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnull ItemStack tool) { - Material material = block.getType(); - - List allBlocks = new ArrayList<>(); - List nextBlocks = new ArrayList<>(); - nextBlocks.add(block); - - for (int i = 0; i < getValue(); i++) { - - if (nextBlocks.isEmpty()) break; - - List lastBlocks = new ArrayList<>(nextBlocks); - nextBlocks.clear(); - - for (Block currentMiddleBlock : lastBlocks) { - for (Block sideBlock : BlockUtils.getBlocksAroundBlock(currentMiddleBlock)) { - if (sideBlock.getType() == material && sideBlock != block && !allBlocks.contains(sideBlock) && allBlocks.size() < getValue()) { - allBlocks.add(sideBlock); - nextBlocks.add(sideBlock); - } - } - } - } - - AtomicInteger index = new AtomicInteger(); - Bukkit.getScheduler().runTaskTimer(plugin, timer -> { - - SoundSample.LOW_PLOP.play(player); - for (int i = 0; i < 2; i++) { - - if (index.get() >= allBlocks.size()) { - timer.cancel(); - return; - } - - Block currentBlock = allBlocks.get(index.get()); - if (currentBlock.getType() == material) { - ChallengeHelper.breakBlock(currentBlock, tool, player.getInventory()); - } - - index.getAndIncrement(); - } - }, 0, 2); - - } - - private boolean canBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { - return !block.getDrops(tool).isEmpty(); - } - - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); - } + public CutCleanSetting() { + super(MenuType.SETTINGS, Message.forName("menu-cut-clean-setting-settings")); + registerSetting("iron->iron_ingot", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, + Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); + registerSetting("gold->gold_ingot", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, + Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); + registerSetting("coal->torch", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, + Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); + registerSetting("gravel->flint", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, + Material.FLINT, "GRAVEL")); + registerSetting("ore->veins", + new BreakOreVeinsSubSetting(() -> new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); + registerSetting("items->inventory", + new DirectIntoInventorySubSetting(() -> new ItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); + registerSetting("row->cooked", + new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); + } + + protected boolean directIntoInventory() { + return getSetting("items->inventory").getAsBoolean(); + } + + private class DirectIntoInventorySubSetting extends BooleanSubSetting { + + public DirectIntoInventorySubSetting(@Nonnull Supplier item) { + super(item); + } + + @Nonnull + @Override + public BooleanSubSetting setEnabled(boolean enabled) { + return super.setEnabled(enabled); + } + + } + + private class ConvertDropSubSetting extends BooleanSubSetting { + + protected final Material[] from; + protected final Material to; + + public ConvertDropSubSetting(@Nonnull Supplier item, boolean enabledByDefault, + @Nonnull Material to, @Nonnull String... from) { + super(item, enabledByDefault); + + List materials = new ArrayList<>(); + for (String s : from) { + Material material = Utils.getMaterial(s); + if (material != null) { + materials.add(material); + } + } + + this.from = materials.toArray(new Material[0]); + this.to = to; + } + + @Override + public void onEnable() { + if (from == null) return; + for (Material material : from) { + Challenges.getInstance().getBlockDropManager().setCustomDrops(material, to, DropPriority.CUT_CLEAN); + } + } + + @Override + public void onDisable() { + if (from == null) return; + for (Material material : from) { + Challenges.getInstance().getBlockDropManager().resetCustomDrop(material, DropPriority.CUT_CLEAN); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!directIntoInventory()) return; + if (!event.isDropItems()) return; + Material type = event.getBlock().getType(); + + for (Material material : from) { + if (type != material) continue; + List customDrops = Challenges.getInstance().getBlockDropManager().getCustomDrops(event.getBlock().getType()); + if (customDrops.isEmpty()) return; + event.setDropItems(false); + customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(event.getPlayer().getInventory(), event.getBlock().getLocation(), drop)); + } + + } + + } + + private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { + + public BreakOreVeinsSubSetting(@Nonnull Supplier item, int min, int max) { + super(item, min, max); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); + if (!canBeBroken(event.getBlock(), itemInMainHand)) return; + if (!event.getBlock().getType().name().contains("ORE")) return; + + breakBlockVein(event.getPlayer(), event.getBlock(), itemInMainHand); + } + + private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnull ItemStack tool) { + Material material = block.getType(); + + List allBlocks = new ArrayList<>(); + List nextBlocks = new ArrayList<>(); + nextBlocks.add(block); + + for (int i = 0; i < getValue(); i++) { + + if (nextBlocks.isEmpty()) break; + + List lastBlocks = new ArrayList<>(nextBlocks); + nextBlocks.clear(); + + for (Block currentMiddleBlock : lastBlocks) { + for (Block sideBlock : BlockUtils.getBlocksAroundBlock(currentMiddleBlock)) { + if (sideBlock.getType() == material && sideBlock != block && !allBlocks.contains(sideBlock) && allBlocks.size() < getValue()) { + allBlocks.add(sideBlock); + nextBlocks.add(sideBlock); + } + } + } + } + + AtomicInteger index = new AtomicInteger(); + Bukkit.getScheduler().runTaskTimer(plugin, timer -> { + + SoundSample.LOW_PLOP.play(player); + for (int i = 0; i < 2; i++) { + + if (index.get() >= allBlocks.size()) { + timer.cancel(); + return; + } + + Block currentBlock = allBlocks.get(index.get()); + if (currentBlock.getType() == material) { + ChallengeHelper.breakBlock(currentBlock, tool, player.getInventory()); + } + + index.getAndIncrement(); + } + }, 0, 2); + + } + + private boolean canBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + return !block.getDrops(tool).isEmpty(); + } + + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); + } - } - - private class CookFoodSubSetting extends BooleanSubSetting { + } + + private class CookFoodSubSetting extends BooleanSubSetting { - public CookFoodSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { - super(item, enabledByDefault); - } + public CookFoodSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + super(item, enabledByDefault); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityKill(@Nonnull EntityDeathEvent event) { - if (!isEnabled()) return; - event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityKill(@Nonnull EntityDeathEvent event) { + if (!isEnabled()) return; + event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); - Player killer = event.getEntity().getKiller(); - if (killer != null && directIntoInventory()) { - event.getDrops().forEach(itemStack -> InventoryUtils.dropOrGiveItem(killer.getInventory(), killer.getLocation(), itemStack)); - event.getDrops().clear(); - } + Player killer = event.getEntity().getKiller(); + if (killer != null && directIntoInventory()) { + event.getDrops().forEach(itemStack -> InventoryUtils.dropOrGiveItem(killer.getInventory(), killer.getLocation(), itemStack)); + event.getDrops().clear(); + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index cc0969959..303ddf53a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -23,68 +23,64 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class DamageDisplaySetting extends Setting { - public DamageDisplaySetting() { - super(MenuType.SETTINGS, true); - } + public DamageDisplaySetting() { + super(MenuType.SETTINGS, true); + } - public static String getCause(@Nonnull EntityDamageEvent event) { + public static String getCause(@Nonnull EntityDamageEvent event) { - if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); - String cause = StringUtils.getEnumName(event.getCause()); + if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); + String cause = StringUtils.getEnumName(event.getCause()); - if (event instanceof EntityDamageByEntityEvent) { + if (event instanceof EntityDamageByEntityEvent) { - EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event; - if (damageEvent.getDamager() instanceof Player) { - Player damager = (Player) damageEvent.getDamager(); - cause += " §8(§7" + NameHelper.getName(damager) + "§8)"; - } else if (damageEvent.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) damageEvent.getDamager(); - cause = StringUtils.getEnumName(projectile.getType()); - String damager = ""; - ProjectileSource shooter = projectile.getShooter(); - if (shooter instanceof Entity) { - Entity entity = (Entity) shooter; - if (entity instanceof Player) { - Player playerDamager = (Player) entity; - damager = NameHelper.getName(playerDamager); - } else { - damager = StringUtils.getEnumName(entity.getType()); - } - } + EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event; + if (damageEvent.getDamager() instanceof Player) { + Player damager = (Player) damageEvent.getDamager(); + cause += " §8(§7" + NameHelper.getName(damager) + "§8)"; + } else if (damageEvent.getDamager() instanceof Projectile) { + Projectile projectile = (Projectile) damageEvent.getDamager(); + cause = StringUtils.getEnumName(projectile.getType()); + String damager = ""; + ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Entity) { + Entity entity = (Entity) shooter; + if (entity instanceof Player) { + Player playerDamager = (Player) entity; + damager = NameHelper.getName(playerDamager); + } else { + damager = StringUtils.getEnumName(entity.getType()); + } + } - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } else { - String damager = StringUtils.getEnumName(damageEvent.getDamager().getType()); - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } - } - return cause; - } + if (!cause.contains(damager)) + cause += " §8(§7" + damager + "§8)"; + } else { + String damager = StringUtils.getEnumName(damageEvent.getDamager().getType()); + if (!cause.contains(damager)) + cause += " §8(§7" + damager + "§8)"; + } + } + return cause; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) - return; - if (!(event.getEntity() instanceof Player)) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) + return; + if (!(event.getEntity() instanceof Player)) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; - double damage = event.getFinalDamage(); - String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); - Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); - } + double damage = event.getFinalDamage(); + String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); + Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index cf6675268..2841569f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -14,37 +14,33 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class DamageMultiplierModifier extends Modifier { - public DamageMultiplierModifier() { - super(MenuType.SETTINGS, 10); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue()).appendName("x"); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - event.setDamage(event.getDamage() * getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() + "x"); - } + public DamageMultiplierModifier() { + super(MenuType.SETTINGS, 10); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(getValue()).appendName("x"); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + event.setDamage(event.getDamage() * getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() + "x"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index a6f8d4d99..96feb5592 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -20,79 +20,75 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class DeathMessageSetting extends Modifier { - public static final int ENABLED = 2, - VANILLA = 3; + public static final int ENABLED = 2, + VANILLA = 3; - private boolean hide; + private boolean hide; - public DeathMessageSetting() { - super(MenuType.SETTINGS, 1, 3, 2); - } + public DeathMessageSetting() { + super(MenuType.SETTINGS, 1, 3, 2); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - default: - return DefaultItem.disabled(); - case ENABLED: - return DefaultItem.enabled(); - case VANILLA: - return DefaultItem.create(MinecraftNameWrapper.SIGN, Message.forName("item-death-message-setting-vanilla")); - } - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + default: + return DefaultItem.disabled(); + case ENABLED: + return DefaultItem.enabled(); + case VANILLA: + return DefaultItem.create(MinecraftNameWrapper.SIGN, Message.forName("item-death-message-setting-vanilla")); + } + } - @Override - public void playValueChangeTitle() { - switch (getValue()) { - case ENABLED: - ChallengeHelper.playToggleChallengeTitle(this, true); - return; - case VANILLA: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); - return; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); - } - } + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case ENABLED: + ChallengeHelper.playToggleChallengeTitle(this, true); + return; + case VANILLA: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); + return; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - event.setDeathMessage(null); - if (hide) return; + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + event.setDeathMessage(null); + if (hide) return; - String original = event.getDeathMessage(); - Player entity = event.getEntity(); - switch (getValue()) { - case ENABLED: - EntityDamageEvent cause = entity.getLastDamageCause(); - if (cause != null && cause.getCause() != DamageCause.CUSTOM) { - Message.forName("death-message-cause").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity), DamageDisplaySetting.getCause(cause)); - } else { - Message.forName("death-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity)); - } - return; - case VANILLA: - if (original != null) { - Bukkit.broadcastMessage(Prefix.CHALLENGES + "§7" + original); - } - } - } + String original = event.getDeathMessage(); + Player entity = event.getEntity(); + switch (getValue()) { + case ENABLED: + EntityDamageEvent cause = entity.getLastDamageCause(); + if (cause != null && cause.getCause() != DamageCause.CUSTOM) { + Message.forName("death-message-cause").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity), DamageDisplaySetting.getCause(cause)); + } else { + Message.forName("death-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity)); + } + return; + case VANILLA: + if (original != null) { + Bukkit.broadcastMessage(Prefix.CHALLENGES + "§7" + original); + } + } + } - public void setHideMessagesTemporarily(boolean hide) { - this.hide = hide; - } + public void setHideMessagesTemporarily(boolean hide) { + this.hide = hide; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 1736b6ba7..f0e163278 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -14,36 +14,32 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class DeathPositionSetting extends Setting { - private static final String POSITION_PREFIX = "death-"; + private static final String POSITION_PREFIX = "death-"; - public DeathPositionSetting() { - super(MenuType.SETTINGS); - } + public DeathPositionSetting() { + super(MenuType.SETTINGS); + } - @EventHandler(priority = EventPriority.LOWEST) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; - int index = 1; - while (AbstractChallenge.getFirstInstance(PositionSetting.class).containsPosition(POSITION_PREFIX + index)) - index++; + int index = 1; + while (AbstractChallenge.getFirstInstance(PositionSetting.class).containsPosition(POSITION_PREFIX + index)) + index++; - Player player = event.getEntity(); - player.performCommand("pos " + POSITION_PREFIX + index); + Player player = event.getEntity(); + player.performCommand("pos " + POSITION_PREFIX + index); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index aeb0167f5..f6368a423 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -30,145 +30,140 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DifficultySetting extends Modifier implements SenderCommand, TabCompleter { - public DifficultySetting() { - super(MenuType.SETTINGS, 0, 3, 2); - } - - @Override - protected void onValueChange() { - setDifficulty(getDifficultyByValue(getValue())); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - case 0: - return DefaultItem.create(Material.LIME_DYE, getDifficultyName()); - case 1: - return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()); - case 2: - return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()); - default: - return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()); - } - } - - private String getDifficultyName() { - return getDifficultyComponent().toLegacyText(); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getDifficultyName()); - } - - private void setDifficulty(Difficulty difficulty) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); - for (World world : Bukkit.getWorlds()) { - world.setDifficulty(difficulty); - } - } - - @Nonnull - private Difficulty getCurrentDifficulty() { - return Bukkit.getWorlds().isEmpty() ? Difficulty.NORMAL : ChallengeAPI.getGameWorld(Environment.NORMAL) - .getDifficulty(); - } - - @Nonnull - private Difficulty getDifficultyByValue(int value) { - Difficulty difficulty = Difficulty.values()[value]; - return difficulty == null ? Difficulty.NORMAL : difficulty; - } - - @Override - public void loadSettings(@Nonnull Document document) { - if (!document.contains("value")) - setValue(getCurrentDifficulty().ordinal()); - - super.loadSettings(document); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (args.length == 0) { - Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); - return; - } - - int difficulty = getDifficultyValue(args[0]); - if (difficulty == -1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); - return; - } - - setValue(difficulty); - Message.forName("command-difficulty-change").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); - - } - - private BaseComponent getDifficultyComponent() { - TranslatableComponent name = BukkitStringUtils.getDifficultyName(getDifficultyByValue(getValue())); - switch (getValue()) { - case 0: - name.setColor(ChatColor.GREEN); - break; - case 1: - name.setColor(ChatColor.DARK_GREEN); - break; - case 2: - name.setColor(ChatColor.GOLD); - break; - default: - name.setColor(ChatColor.RED); - break; - } - return name; - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Arrays.asList("peaceful", "easy", "normal", "hard"); - } - - private int getDifficultyValue(@Nonnull String input) { - - switch (input.toLowerCase()) { - case "peaceful": - return 0; - case "easy": - return 1; - case "normal": - return 2; - case "hard": - return 3; - } - - try { - int value = Integer.parseInt(input); - if (value < 0 || value > 3) return -1; - return value; - } catch (Exception ex) { - return -1; - } - - } + public DifficultySetting() { + super(MenuType.SETTINGS, 0, 3, 2); + } + + @Override + protected void onValueChange() { + setDifficulty(getDifficultyByValue(getValue())); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + case 0: + return DefaultItem.create(Material.LIME_DYE, getDifficultyName()); + case 1: + return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()); + case 2: + return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()); + default: + return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()); + } + } + + private String getDifficultyName() { + return getDifficultyComponent().toLegacyText(); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getDifficultyName()); + } + + private void setDifficulty(Difficulty difficulty) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); + for (World world : Bukkit.getWorlds()) { + world.setDifficulty(difficulty); + } + } + + @Nonnull + private Difficulty getCurrentDifficulty() { + return Bukkit.getWorlds().isEmpty() ? Difficulty.NORMAL : ChallengeAPI.getGameWorld(Environment.NORMAL) + .getDifficulty(); + } + + @Nonnull + private Difficulty getDifficultyByValue(int value) { + Difficulty difficulty = Difficulty.values()[value]; + return difficulty == null ? Difficulty.NORMAL : difficulty; + } + + @Override + public void loadSettings(@Nonnull Document document) { + if (!document.contains("value")) + setValue(getCurrentDifficulty().ordinal()); + + super.loadSettings(document); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (args.length == 0) { + Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); + return; + } + + int difficulty = getDifficultyValue(args[0]); + if (difficulty == -1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); + return; + } + + setValue(difficulty); + Message.forName("command-difficulty-change").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); + + } + + private BaseComponent getDifficultyComponent() { + TranslatableComponent name = BukkitStringUtils.getDifficultyName(getDifficultyByValue(getValue())); + switch (getValue()) { + case 0: + name.setColor(ChatColor.GREEN); + break; + case 1: + name.setColor(ChatColor.DARK_GREEN); + break; + case 2: + name.setColor(ChatColor.GOLD); + break; + default: + name.setColor(ChatColor.RED); + break; + } + return name; + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Arrays.asList("peaceful", "easy", "normal", "hard"); + } + + private int getDifficultyValue(@Nonnull String input) { + + switch (input.toLowerCase()) { + case "peaceful": + return 0; + case "easy": + return 1; + case "normal": + return 2; + case "hard": + return 3; + } + + try { + int value = Integer.parseInt(input); + if (value < 0 || value > 3) return -1; + return value; + } catch (Exception ex) { + return -1; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index e097f9b83..551859310 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -13,32 +13,28 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class EnderChestCommandSetting extends Setting implements PlayerCommand { - public EnderChestCommandSetting() { - super(MenuType.SETTINGS); - } + public EnderChestCommandSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); + } - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (!isEnabled() || ChallengeAPI.isWorldInUse()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - return; - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (!isEnabled() || ChallengeAPI.isWorldInUse()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + return; + } - player.openInventory(player.getEnderChest()); - Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); - } + player.openInventory(player.getEnderChest()); + Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 13ff7c093..f4abafbc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -10,21 +10,17 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { - public FortressSpawnSetting() { - super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); - } + public FortressSpawnSetting() { + super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 8be845fba..e1134eb6c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -14,86 +12,79 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.scoreboard.Criteria; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.RenderType; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.ScoreboardManager; - -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +import org.bukkit.scoreboard.*; + +import javax.annotation.Nonnull; + @Since("2.0") public class HealthDisplaySetting extends Setting { - public static final String OBJECTIVE_NAME = "health_display"; - - public HealthDisplaySetting() { - super(MenuType.SETTINGS, true); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); - } - - @Override - protected void onEnable() { - Bukkit.getOnlinePlayers().forEach(this::show); - } - - @Override - protected void onDisable() { - Bukkit.getOnlinePlayers().forEach(this::hide); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (isEnabled()) { - show(event.getPlayer()); - } else { - hide(event.getPlayer()); - } - } - - private void show(@Nonnull Player player) { - Scoreboard scoreboard = player.getScoreboard(); - ScoreboardManager manager = Bukkit.getScoreboardManager(); - if (manager == null) return; - if (player.getScoreboard() == manager.getMainScoreboard()) - player.setScoreboard(scoreboard = manager.getNewScoreboard()); - - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) - objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); - // Criteria interface only available since 1.20 - - objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); - - try { - objective.setRenderType(RenderType.HEARTS); - } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); - // In some versions of spigot RenderType does not exist - } - - } - - private void hide(@Nonnull Player player) { - - Scoreboard scoreboard = player.getScoreboard(); - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) return; - - try { - objective.unregister(); - } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Error while unregistering tablist hearts objective"); - } - - } + public static final String OBJECTIVE_NAME = "health_display"; + + public HealthDisplaySetting() { + super(MenuType.SETTINGS, true); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); + } + + @Override + protected void onEnable() { + Bukkit.getOnlinePlayers().forEach(this::show); + } + + @Override + protected void onDisable() { + Bukkit.getOnlinePlayers().forEach(this::hide); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (isEnabled()) { + show(event.getPlayer()); + } else { + hide(event.getPlayer()); + } + } + + private void show(@Nonnull Player player) { + Scoreboard scoreboard = player.getScoreboard(); + ScoreboardManager manager = Bukkit.getScoreboardManager(); + if (manager == null) return; + if (player.getScoreboard() == manager.getMainScoreboard()) + player.setScoreboard(scoreboard = manager.getNewScoreboard()); + + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) + objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); + // Criteria interface only available since 1.20 + + objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); + + try { + objective.setRenderType(RenderType.HEARTS); + } catch (Exception ex) { + Challenges.getInstance().getILogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); + // In some versions of spigot RenderType does not exist + } + + } + + private void hide(@Nonnull Player player) { + + Scoreboard scoreboard = player.getScoreboard(); + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) return; + + try { + objective.unregister(); + } catch (Exception ex) { + Challenges.getInstance().getILogger().severe("Error while unregistering tablist hearts objective"); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 2c9a9ab8b..088db39dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -15,58 +15,54 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class ImmediateRespawnSetting extends Setting { - private boolean respawnWithEvent; + private boolean respawnWithEvent; - public ImmediateRespawnSetting() { - super(MenuType.SETTINGS); - } + public ImmediateRespawnSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); + } - @Override - protected void onEnable() { - if (respawnWithEvent) { - return; - } - try { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); - } - } catch (NoSuchFieldError ignored) { - respawnWithEvent = true; - } - } + @Override + protected void onEnable() { + if (respawnWithEvent) { + return; + } + try { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); + } + } catch (NoSuchFieldError ignored) { + respawnWithEvent = true; + } + } - @Override - protected void onDisable() { - if (respawnWithEvent) { - return; - } - try { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); - } - } catch (NoSuchFieldError ignored) { - } - } + @Override + protected void onDisable() { + if (respawnWithEvent) { + return; + } + try { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); + } + } catch (NoSuchFieldError ignored) { + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!isEnabled()) return; - if (!respawnWithEvent) return; - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!isEnabled()) return; + if (!respawnWithEvent) return; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index 1f48a805a..dac4723cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -11,33 +11,29 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class KeepInventorySetting extends Setting { - public KeepInventorySetting() { - super(MenuType.SETTINGS); - } + public KeepInventorySetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); + } - @Override - protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, true); - } - } + @Override + protected void onEnable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, true); + } + } - @Override - protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, false); - } - } -} \ No newline at end of file + @Override + protected void onDisable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, false); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java new file mode 100644 index 000000000..f91ef2290 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -0,0 +1,61 @@ +package net.codingarea.challenges.plugin.challenges.implementation.setting; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.utils.item.DefaultItem; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.Material; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class LanguageSetting extends Modifier { + + public static final int ENGLISH = 1; + public static final int GERMAN = 2; + + public static final String GERMAN_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWU3ODk5YjQ4MDY4NTg2OTdlMjgzZjA4NGQ5MTczZmU0ODc4ODY0NTM3NzQ2MjZiMjRiZDhjZmVjYzc3YjNmIn19fQ", + ENGLISH_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODgzMWM3M2Y1NDY4ZTg4OGMzMDE5ZTI4NDdlNDQyZGZhYTg4ODk4ZDUwY2NmMDFmZDJmOTE0YWY1NDRkNTM2OCJ9fX0"; + + public LanguageSetting() { + super(MenuType.SETTINGS, 1, 2, ENGLISH); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; + return new ItemBuilder.SkullBuilder(DefaultItem.getItemPrefix() + Message.forName(getSettingName())).setBase64Texture(texture).hideAttributes(); + } + + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case GERMAN: + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); + break; + case ENGLISH: + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); + break; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } + + private String getSettingName() { + return getValue() == GERMAN ? "item-language-setting-german" : "item-language-setting-english"; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 2056682be..68ca3bde3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -1,126 +1,121 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.item.MaterialWrapper; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSProvider; -import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; import org.jetbrains.annotations.NotNull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ +import javax.annotation.Nonnull; + public class MaxHealthSetting extends Modifier { - /** - * Offset that can be used to modify the max health for specific players with other challenges. - * Is saved within the gamestate so it resets with a world reset. - * Saves the data with the uuid as string as the key and with an integer which defines the offset - * The health offset for every player is saved with the key "all" - */ - private Document valueOffset = new GsonDocument(); - - public MaxHealthSetting() { - super(MenuType.SETTINGS, 1, 200 * 2, 20); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("offset", valueOffset); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - valueOffset = document.contains("offset") ? document.getDocument("offset") : new GsonDocument(); - onValueChange(); - } - - @Override - public void onValueChange() { - broadcast(this::updateHealth); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { - updateHealth(event.getPlayer()); - } - - private void updateHealth(Player player) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) - return; // This should never happen because its a generic attribute, but just in case - int newMaxHealth = getMaxHealth(player); - double oldMaxHealth = attribute.getBaseValue(); - - if (newMaxHealth <= 0) { - ChallengeHelper.kill(player); - valueOffset.remove(player.getUniqueId().toString()); - return; - } - - if (oldMaxHealth != newMaxHealth) { - attribute.setBaseValue(newMaxHealth); - - if (oldMaxHealth < newMaxHealth) { - double oldHealth = player.getHealth(); - double newHealth = oldHealth + (newMaxHealth - oldMaxHealth); - player.setHealth(Math.min(Math.max(newHealth, 0), newMaxHealth)); - } - if (MinecraftVersion.current().isNewerThan(MinecraftVersion.V1_19)) { - player.sendHealthUpdate(); - } - // TODO: Versions lower than 1.19 need to update health via nms - } - } - - public int getMaxHealth(Player player) { - String key = player.getUniqueId().toString(); - return getValue() + valueOffset.getInt("all") + valueOffset.getInt(key); - } - - public void addHealth(int health) { - valueOffset.set("all", valueOffset.getInt("all") + health); - onValueChange(); - } - - public void addHealth(Player player, int health) { - String key = player.getUniqueId().toString(); - valueOffset.set(key, valueOffset.getInt(key) + health); - updateHealth(player); - } + /** + * Offset that can be used to modify the max health for specific players with other challenges. + * Is saved within the gamestate so it resets with a world reset. + * Saves the data with the uuid as string as the key and with an integer which defines the offset + * The health offset for every player is saved with the key "all" + */ + private Document valueOffset = new GsonDocument(); + + public MaxHealthSetting() { + super(MenuType.SETTINGS, 1, 200 * 2, 20); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("offset", valueOffset); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + valueOffset = document.contains("offset") ? document.getDocument("offset") : new GsonDocument(); + onValueChange(); + } + + @Override + public void onValueChange() { + broadcast(this::updateHealth); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @EventHandler + public void onJoin(@Nonnull PlayerJoinEvent event) { + updateHealth(event.getPlayer()); + } + + private void updateHealth(Player player) { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) + return; // This should never happen because its a generic attribute, but just in case + int newMaxHealth = getMaxHealth(player); + double oldMaxHealth = attribute.getBaseValue(); + + if (newMaxHealth <= 0) { + ChallengeHelper.kill(player); + valueOffset.remove(player.getUniqueId().toString()); + return; + } + + if (oldMaxHealth != newMaxHealth) { + attribute.setBaseValue(newMaxHealth); + + if (oldMaxHealth < newMaxHealth) { + double oldHealth = player.getHealth(); + double newHealth = oldHealth + (newMaxHealth - oldMaxHealth); + player.setHealth(Math.min(Math.max(newHealth, 0), newMaxHealth)); + } + if (MinecraftVersion.current().isNewerThan(MinecraftVersion.V1_19)) { + player.sendHealthUpdate(); + } + // TODO: Versions lower than 1.19 need to update health via nms + } + } + + public int getMaxHealth(Player player) { + String key = player.getUniqueId().toString(); + return getValue() + valueOffset.getInt("all") + valueOffset.getInt(key); + } + + public void addHealth(int health) { + valueOffset.set("all", valueOffset.getInt("all") + health); + onValueChange(); + } + + public void addHealth(Player player, int health) { + String key = player.getUniqueId().toString(); + valueOffset.set(key, valueOffset.getInt(key) + health); + updateHealth(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index 95e75720d..1a6180b08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -13,27 +13,27 @@ public class MobGriefingSetting extends Setting { - public MobGriefingSetting() { - super(MenuType.SETTINGS); - } + public MobGriefingSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); + } - @Override - protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, false); - } + @Override + protected void onEnable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, false); } + } - @Override - protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, true); - } + @Override + protected void onDisable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, true); } -} \ No newline at end of file + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 627e53494..7ac0f95a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -14,29 +14,25 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class NoHitDelaySetting extends Setting { - public NoHitDelaySetting() { - super(MenuType.SETTINGS); - } + public NoHitDelaySetting() { + super(MenuType.SETTINGS); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamageByEntity(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof LivingEntity)) return; - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - ((LivingEntity) event.getEntity()).setNoDamageTicks(0); - }, 1); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDamageByEntity(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof LivingEntity)) return; + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + ((LivingEntity) event.getEntity()).setNoDamageTicks(0); + }, 1); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java index 077646b53..a7e2ced01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java @@ -11,38 +11,34 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoHungerSetting extends Setting { - public NoHungerSetting() { - super(MenuType.SETTINGS); - } - - @Override - protected void onEnable() { - broadcastFiltered(this::feedPlayer); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); - } - - @EventHandler(ignoreCancelled = true) - public void onHunger(@Nonnull FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - feedPlayer(((Player) event.getEntity())); - event.setCancelled(true); - } - - private void feedPlayer(@Nonnull Player player) { - player.setFoodLevel(20); - player.setSaturation(20); - } - -} \ No newline at end of file + public NoHungerSetting() { + super(MenuType.SETTINGS); + } + + @Override + protected void onEnable() { + broadcastFiltered(this::feedPlayer); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); + } + + @EventHandler(ignoreCancelled = true) + public void onHunger(@Nonnull FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + feedPlayer(((Player) event.getEntity())); + event.setCancelled(true); + } + + private void feedPlayer(@Nonnull Player player) { + player.setFoodLevel(20); + player.setSaturation(20); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index 4573cbafd..3c57403c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -10,29 +10,25 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoItemDamageSetting extends Setting { - public NoItemDamageSetting() { - super(MenuType.SETTINGS); - } + public NoItemDamageSetting() { + super(MenuType.SETTINGS); + } - @EventHandler - public void onItemDamage(PlayerItemDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler + public void onItemDamage(PlayerItemDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - event.setCancelled(true); - event.getPlayer().updateInventory(); - } + event.setCancelled(true); + event.getPlayer().updateInventory(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index f1a3caf24..23be5b36a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -17,51 +17,47 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class NoOffhandSetting extends Setting { - public NoOffhandSetting() { - super(MenuType.SETTINGS); - } - - @Override - protected void onEnable() { - for (Player player : Bukkit.getOnlinePlayers()) { - ItemStack itemInOffHand = player.getInventory().getItemInOffHand(); - if (itemInOffHand.getType() == Material.AIR) return; - player.getWorld().dropItemNaturally(player.getLocation(), itemInOffHand); - player.getInventory().setItemInOffHand(null); - player.updateInventory(); - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ignorePlayer(player)) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; - if (event.getSlot() != 40) return; - event.setCancelled(true); - } - -} \ No newline at end of file + public NoOffhandSetting() { + super(MenuType.SETTINGS); + } + + @Override + protected void onEnable() { + for (Player player : Bukkit.getOnlinePlayers()) { + ItemStack itemInOffHand = player.getInventory().getItemInOffHand(); + if (itemInOffHand.getType() == Material.AIR) return; + player.getWorld().dropItemNaturally(player.getLocation(), itemInOffHand); + player.getInventory().setItemInOffHand(null); + player.updateInventory(); + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ignorePlayer(player)) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; + if (event.getSlot() != 40) return; + event.setCancelled(true); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 14202e27b..054dd292d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -18,62 +18,58 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class OldPvPSetting extends Setting { - public static final double DISABLED = 32, NORMAL = 4; // Values copied from BackToTheRoots + public static final double DISABLED = 32, NORMAL = 4; // Values copied from BackToTheRoots - public OldPvPSetting() { - super(MenuType.SETTINGS); - } + public OldPvPSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); + } - @Override - protected void onDisable() { - broadcast(player -> setAttackSpeed(player, NORMAL)); - } + @Override + protected void onDisable() { + broadcast(player -> setAttackSpeed(player, NORMAL)); + } - @Override - protected void onEnable() { - broadcast(player -> setAttackSpeed(player, DISABLED)); - } + @Override + protected void onEnable() { + broadcast(player -> setAttackSpeed(player, DISABLED)); + } - @EventHandler - public void onChangeWorldEvent(@Nonnull PlayerChangedWorldEvent event) { - if (!isEnabled()) return; - setAttackSpeed(event.getPlayer(), DISABLED); - } + @EventHandler + public void onChangeWorldEvent(@Nonnull PlayerChangedWorldEvent event) { + if (!isEnabled()) return; + setAttackSpeed(event.getPlayer(), DISABLED); + } - @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (!isEnabled()) return; - setAttackSpeed(event.getPlayer(), DISABLED); - } + @EventHandler + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (!isEnabled()) return; + setAttackSpeed(event.getPlayer(), DISABLED); + } - @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { - setAttackSpeed(event.getPlayer(), NORMAL); - } + @EventHandler + public void onQuit(@Nonnull PlayerQuitEvent event) { + setAttackSpeed(event.getPlayer(), NORMAL); + } - @EventHandler - public void onSweepDamage(@Nonnull EntityDamageEvent event) { - if (!isEnabled()) return; - if (event.getCause() != DamageCause.ENTITY_SWEEP_ATTACK) return; - event.setCancelled(true); - } + @EventHandler + public void onSweepDamage(@Nonnull EntityDamageEvent event) { + if (!isEnabled()) return; + if (event.getCause() != DamageCause.ENTITY_SWEEP_ATTACK) return; + event.setCancelled(true); + } - protected void setAttackSpeed(@Nonnull Player player, double value) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_ATTACK_SPEED); - if (attribute == null) return; - attribute.setBaseValue(value); - } + protected void setAttackSpeed(@Nonnull Player player, double value) { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); + if (attribute == null) return; + attribute.setBaseValue(value); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index f306b11a7..5daa22b3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -15,41 +15,37 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class OneTeamLifeSetting extends Setting { - private boolean isKilling = false; + private boolean isKilling = false; - public OneTeamLifeSetting() { - super(MenuType.SETTINGS, true); - } + public OneTeamLifeSetting() { + super(MenuType.SETTINGS, true); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (isKilling) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (isKilling) return; - Bukkit.getScheduler().runTask(plugin, () -> { - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = true); - for (Player player : Bukkit.getOnlinePlayers()) { - if (player == event.getEntity()) continue; - if (ignorePlayer(player)) continue; - ChallengeHelper.kill(player); - } + Bukkit.getScheduler().runTask(plugin, () -> { + AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = true); + for (Player player : Bukkit.getOnlinePlayers()) { + if (player == event.getEntity()) continue; + if (ignorePlayer(player)) continue; + ChallengeHelper.kill(player); + } - AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = false); - }); + AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); + AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = false); + }); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index 1dea9c84c..2d2a688b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -16,46 +16,42 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class PlayerGlowSetting extends Setting { - public PlayerGlowSetting() { - super(MenuType.SETTINGS); - } - - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); - } - - @Override - protected void onEnable() { - updateEffects(); - } - - @Override - protected void onDisable() { - updateEffects(); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}, async = false) - @ScheduledTask(ticks = 50, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void updateEffects() { - if (!shouldExecuteEffect()) { - broadcast(player -> player.removePotionEffect(PotionEffectType.GLOWING)); - return; - } - broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, Integer.MAX_VALUE, 1, true, false, false))); - } - - @EventHandler - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - updateEffects(); - } + public PlayerGlowSetting() { + super(MenuType.SETTINGS); + } + + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); + } + + @Override + protected void onEnable() { + updateEffects(); + } + + @Override + protected void onDisable() { + updateEffects(); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}, async = false) + @ScheduledTask(ticks = 50, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void updateEffects() { + if (!shouldExecuteEffect()) { + broadcast(player -> player.removePotionEffect(PotionEffectType.GLOWING)); + return; + } + broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, Integer.MAX_VALUE, 1, true, false, false))); + } + + @EventHandler + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + updateEffects(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 78a4b5c5b..c1b1ce733 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -29,288 +29,284 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PositionSetting extends Setting implements PlayerCommand, TabCompleter { - private final Map positions = new HashMap<>(); - private final boolean particleLines; - - public PositionSetting() { - super(MenuType.SETTINGS, true); - particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); - Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); - Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); - } - - public static Environment getWorldEnvironment(@Nonnull String name) { - switch (name.toLowerCase()) { - default: - return null; - case "overworld": - return Environment.NORMAL; - case "nether": - return Environment.NETHER; - case "end": - return Environment.THE_END; - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length == 0) { - if (positions.entrySet().stream().noneMatch(entry -> player.getWorld() == entry.getValue().getWorld())) { - Message.forName("no-positions").send(player, Prefix.POSITION, "position "); - return; - } - - positions.entrySet().stream() - .filter(entry -> player.getWorld() == entry.getValue().getWorld()) - .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) - .forEach(entry -> { - - Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); - }); - } else if (args.length == 1) { - String name = args[0].toLowerCase(); - Location position = positions.get(name); - if (position != null) { - if (position.getWorld() != player.getLocation().getWorld()) { - Message.forName("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); - SoundSample.BASS_OFF.play(player); - return; - } - Message.forName("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); - playParticleLine(player, position); - } else if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - } else { - positions.put(name, position = player.getLocation()); - Message.forName("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); - SoundSample.BASS_ON.play(player); - broadcastParticleLine(position); - } - - } else { - Message.forName("syntax").send(player, Prefix.POSITION, "position [name]"); - } - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); - } - - public String getWorldName(@Nonnull Location location) { - if (location.getWorld() == null) return "?"; - switch (location.getWorld().getEnvironment()) { - default: - return "Overworld"; - case NETHER: - return "Nether"; - case THE_END: - return "End"; - } - } - - public boolean containsPosition(@Nonnull String name) { - return positions.containsKey(name); - } - - private void broadcastParticleLine(@Nonnull Location location) { - broadcast(player -> playParticleLine(player, location)); - } - - private void playParticleLine(@Nonnull Player player, @Nonnull Location position) { - if (!particleLines) return; - if (player.getWorld() != position.getWorld()) return; - - // Defining target location to - Location target = position.clone().add(0, 0.3, 0); - - final int[] current = {0}; - Bukkit.getScheduler().runTaskTimer(plugin, task -> { - current[0]++; - if (current[0] >= 10) task.cancel(); - ParticleUtils.drawLine(player, player.getLocation(), target, - MinecraftNameWrapper.REDSTONE_DUST, new DustOptions(Color.LIME, 1), 1, 0.5, 50); - }, 0, 10); - } - - @Override - public void loadGameState(@Nonnull Document document) { - positions.clear(); - for (String name : document.keys()) { - positions.put(name, document.getSerializable(name, Location.class)); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - for (String key : document.keys()) { - document.remove(key); - } - positions.forEach(document::set); - } - - public class DelPosCommand implements PlayerCommand, TabCompleter { - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length == 0) { - if (positions.isEmpty()) { - Message.forName("no-positions-global").send(player, Prefix.POSITION, "position "); - return; - } - - positions.entrySet().stream() - .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) - .forEach(entry -> { - Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); - }); - } else if (args.length == 1) { - String name = args[0].toLowerCase(); - Location position = positions.get(name); - if (position != null) { - positions.remove(name); - Message.forName("position-deleted").broadcast(Prefix.POSITION, - position.getBlockX(), position.getBlockY(), position.getBlockZ(), - getWorldName(position), name, NameHelper.getName(player)); - } else { - Message.forName("position-not-exists").send(player, Prefix.POSITION); - } - - } else { - Message.forName("syntax").send(player, Prefix.POSITION, "delposition "); - } - - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); - } - - } - - public class SetPosCommand implements PlayerCommand, TabCompleter { - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length < 5) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); - return; - } - - String name = args[0].toLowerCase(); - - if (positions.containsKey(name)) { - Message.forName("position-already-exists").send(player, Prefix.POSITION, name); - return; - } - - String worldName = args[1]; - String x = args[2]; - String y = args[3]; - String z = args[4]; - - try { - Environment environment = getWorldEnvironment(worldName); - World world = ChallengeAPI.getGameWorld(environment); - if (world == null) throw new IllegalArgumentException(); - double doubleX = Double.parseDouble(x); - double doubleY = Double.parseDouble(y); - double doubleZ = Double.parseDouble(z); - - Location position = new Location(world, doubleX, doubleY, doubleZ); - positions.put(name, position); - Message.forName("position-set") - .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), - position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); - SoundSample.BASS_ON.play(player); - broadcastParticleLine(position); - - } catch (Exception exception) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); - } - - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (!(sender instanceof Player)) return new LinkedList<>(); - Player player = (Player) sender; - if (args.length > 5) return new LinkedList<>(); - - if (args.length > 2) { - int arg = args.length - 2; - - double cord; - Location location = player.getLocation(); - switch (arg) { - case 1: - cord = location.getBlockX() + 0.5; - break; - case 2: - cord = location.getBlockY(); - break; - default: - cord = location.getBlockZ() + 0.5; - } - - return Collections.singletonList(String.valueOf(cord)); - - } else if (args.length > 1) { - return Arrays.asList("Overworld", "Nether", "End"); - } - - return new LinkedList<>(); - } - - } + private final Map positions = new HashMap<>(); + private final boolean particleLines; + + public PositionSetting() { + super(MenuType.SETTINGS, true); + particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); + Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); + Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); + } + + public static Environment getWorldEnvironment(@Nonnull String name) { + switch (name.toLowerCase()) { + default: + return null; + case "overworld": + return Environment.NORMAL; + case "nether": + return Environment.NETHER; + case "end": + return Environment.THE_END; + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + if (positions.entrySet().stream().noneMatch(entry -> player.getWorld() == entry.getValue().getWorld())) { + Message.forName("no-positions").send(player, Prefix.POSITION, "position "); + return; + } + + positions.entrySet().stream() + .filter(entry -> player.getWorld() == entry.getValue().getWorld()) + .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) + .forEach(entry -> { + + Location location = entry.getValue(); + Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + }); + } else if (args.length == 1) { + String name = args[0].toLowerCase(); + Location position = positions.get(name); + if (position != null) { + if (position.getWorld() != player.getLocation().getWorld()) { + Message.forName("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); + SoundSample.BASS_OFF.play(player); + return; + } + Message.forName("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); + playParticleLine(player, position); + } else if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + } else { + positions.put(name, position = player.getLocation()); + Message.forName("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + SoundSample.BASS_ON.play(player); + broadcastParticleLine(position); + } + + } else { + Message.forName("syntax").send(player, Prefix.POSITION, "position [name]"); + } + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); + } + + public String getWorldName(@Nonnull Location location) { + if (location.getWorld() == null) return "?"; + switch (location.getWorld().getEnvironment()) { + default: + return "Overworld"; + case NETHER: + return "Nether"; + case THE_END: + return "End"; + } + } + + public boolean containsPosition(@Nonnull String name) { + return positions.containsKey(name); + } + + private void broadcastParticleLine(@Nonnull Location location) { + broadcast(player -> playParticleLine(player, location)); + } + + private void playParticleLine(@Nonnull Player player, @Nonnull Location position) { + if (!particleLines) return; + if (player.getWorld() != position.getWorld()) return; + + // Defining target location to + Location target = position.clone().add(0, 0.3, 0); + + final int[] current = {0}; + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + current[0]++; + if (current[0] >= 10) task.cancel(); + ParticleUtils.drawLine(player, player.getLocation(), target, + MinecraftNameWrapper.REDSTONE_DUST, new DustOptions(Color.LIME, 1), 1, 0.5, 50); + }, 0, 10); + } + + @Override + public void loadGameState(@Nonnull Document document) { + positions.clear(); + for (String name : document.keys()) { + positions.put(name, document.getSerializable(name, Location.class)); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + for (String key : document.keys()) { + document.remove(key); + } + positions.forEach(document::set); + } + + public class DelPosCommand implements PlayerCommand, TabCompleter { + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + if (!ChallengeAPI.isStarted()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + if (positions.isEmpty()) { + Message.forName("no-positions-global").send(player, Prefix.POSITION, "position "); + return; + } + + positions.entrySet().stream() + .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) + .forEach(entry -> { + Location location = entry.getValue(); + Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + }); + } else if (args.length == 1) { + String name = args[0].toLowerCase(); + Location position = positions.get(name); + if (position != null) { + positions.remove(name); + Message.forName("position-deleted").broadcast(Prefix.POSITION, + position.getBlockX(), position.getBlockY(), position.getBlockZ(), + getWorldName(position), name, NameHelper.getName(player)); + } else { + Message.forName("position-not-exists").send(player, Prefix.POSITION); + } + + } else { + Message.forName("syntax").send(player, Prefix.POSITION, "delposition "); + } + + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); + } + + } + + public class SetPosCommand implements PlayerCommand, TabCompleter { + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + if (!ChallengeAPI.isStarted()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length < 5) { + Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + return; + } + + String name = args[0].toLowerCase(); + + if (positions.containsKey(name)) { + Message.forName("position-already-exists").send(player, Prefix.POSITION, name); + return; + } + + String worldName = args[1]; + String x = args[2]; + String y = args[3]; + String z = args[4]; + + try { + Environment environment = getWorldEnvironment(worldName); + World world = ChallengeAPI.getGameWorld(environment); + if (world == null) throw new IllegalArgumentException(); + double doubleX = Double.parseDouble(x); + double doubleY = Double.parseDouble(y); + double doubleZ = Double.parseDouble(z); + + Location position = new Location(world, doubleX, doubleY, doubleZ); + positions.put(name, position); + Message.forName("position-set") + .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), + position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + SoundSample.BASS_ON.play(player); + broadcastParticleLine(position); + + } catch (Exception exception) { + Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + } + + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { + if (!(sender instanceof Player)) return new LinkedList<>(); + Player player = (Player) sender; + if (args.length > 5) return new LinkedList<>(); + + if (args.length > 2) { + int arg = args.length - 2; + + double cord; + Location location = player.getLocation(); + switch (arg) { + case 1: + cord = location.getBlockX() + 0.5; + break; + case 2: + cord = location.getBlockY(); + break; + default: + cord = location.getBlockZ() + 0.5; + } + + return Collections.singletonList(String.valueOf(cord)); + + } else if (args.length > 1) { + return Arrays.asList("Overworld", "Nether", "End"); + } + + return new LinkedList<>(); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index 4e0df21f4..16f50d30a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -14,49 +14,44 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class PregameMovementSetting extends Setting { - public PregameMovementSetting() { - super(MenuType.SETTINGS, true); - } - - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (ChallengeAPI.isStarted() || isEnabled()) return; - if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) - return; - - Location to = event.getTo(); - if (to == null) return; - if (BlockUtils.isSameLocationIgnoreHeight(event.getFrom(), to)) return; - - Location target = event.getFrom().clone(); - target.setY(target.getBlockY()); - findNearestBlock(target); - target.add(0, 1, 0); - - target.setPitch(to.getPitch()); - target.setYaw(to.getYaw()); - target.setDirection(to.getDirection()); - event.setTo(target); - - Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); - } - - private void findNearestBlock(@Nonnull Location location) { - for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) - ; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); - } - -} \ No newline at end of file + public PregameMovementSetting() { + super(MenuType.SETTINGS, true); + } + + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (ChallengeAPI.isStarted() || isEnabled()) return; + if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) + return; + + Location to = event.getTo(); + if (to == null) return; + if (BlockUtils.isSameLocationIgnoreHeight(event.getFrom(), to)) return; + + Location target = event.getFrom().clone(); + target.setY(target.getBlockY()); + findNearestBlock(target); + target.add(0, 1, 0); + + target.setPitch(to.getPitch()); + target.setYaw(to.getYaw()); + target.setDirection(to.getDirection()); + event.setTo(target); + + Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); + } + + private void findNearestBlock(@Nonnull Location location) { + for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) + ; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index c317e1e7b..5e301e89f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -11,27 +11,23 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PvPSetting extends Setting { - public PvPSetting() { - super(MenuType.SETTINGS, true); - } + public PvPSetting() { + super(MenuType.SETTINGS, true); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); + } - @EventHandler - public void onDamage(@Nonnull EntityDamageByPlayerEvent event) { - if (isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; - event.setCancelled(true); - } + @EventHandler + public void onDamage(@Nonnull EntityDamageByPlayerEvent event) { + if (isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; + event.setCancelled(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 0625540a5..c4a3b67b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -17,59 +17,55 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RegenerationSetting extends Modifier { - public RegenerationSetting() { - super(MenuType.SETTINGS, 1, 3, 2); - } + public RegenerationSetting() { + super(MenuType.SETTINGS, 1, 3, 2); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.disabled(); - } else if (getValue() == 2) { - return DefaultItem.enabled(); - } - return DefaultItem.create(Material.ORANGE_DYE, Message.forName("item-regeneration-setting-not_natural")); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.disabled(); + } else if (getValue() == 2) { + return DefaultItem.enabled(); + } + return DefaultItem.create(Material.ORANGE_DYE, Message.forName("item-regeneration-setting-not_natural")); + } - @Override - public void playValueChangeTitle() { - if (getValue() == 1) { - ChallengeHelper.playToggleChallengeTitle(this, false); - return; - } - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); - } + @Override + public void playValueChangeTitle() { + if (getValue() == 1) { + ChallengeHelper.playToggleChallengeTitle(this, false); + return; + } + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityRegainHealth(EntityRegainHealthEvent event) { - if (!(event.getEntity() instanceof Player)) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityRegainHealth(EntityRegainHealthEvent event) { + if (!(event.getEntity() instanceof Player)) return; - if (getValue() == 1) { - event.setAmount(0); - event.setCancelled(true); - return; - } + if (getValue() == 1) { + event.setAmount(0); + event.setCancelled(true); + return; + } - if (getValue() == 3) { - if (event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { - event.setAmount(0); - event.setCancelled(true); - } - } + if (getValue() == 3) { + if (event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { + event.setAmount(0); + event.setCancelled(true); + } + } - } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index fa4fd7d3f..4be83995e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,9 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -22,58 +19,58 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + public class RespawnSetting extends Setting { - private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); + private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); - public RespawnSetting() { - super(MenuType.SETTINGS); - } + public RespawnSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - Player player = event.getEntity(); - if (isEnabled()) { - SoundSample.DEATH.play(player); - } else { - locationsBeforeRespawn.put(player, player.getLocation()); - player.setGameMode(GameMode.SPECTATOR); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + Player player = event.getEntity(); + if (isEnabled()) { + SoundSample.DEATH.play(player); + } else { + locationsBeforeRespawn.put(player, player.getLocation()); + player.setGameMode(GameMode.SPECTATOR); - if (ChallengeAPI.isStarted()) - checkAllPlayersDead(); - } + if (ChallengeAPI.isStarted()) + checkAllPlayersDead(); + } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), - MinecraftNameWrapper.WITCH_EFFECT, 17, 1, 2); - } + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + MinecraftNameWrapper.WITCH_EFFECT, 17, 1, 2); + } - public void checkAllPlayersDead() { - int playersAlive = ChallengeAPI.getIngamePlayers().size(); - if (playersAlive == 0) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } - } + public void checkAllPlayersDead() { + int playersAlive = ChallengeAPI.getIngamePlayers().size(); + if (playersAlive == 0) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - if (isEnabled()) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + if (isEnabled()) return; - Player player = event.getPlayer(); - Location locationBeforeRespawn = locationsBeforeRespawn.remove(player); - if (locationBeforeRespawn == null) return; - if (locationBeforeRespawn.getY() < 0) - return; // If the player dies in the void (y <= 0), we dont want him to spawn there, he would die again - event.setRespawnLocation(locationBeforeRespawn); - } + Player player = event.getPlayer(); + Location locationBeforeRespawn = locationsBeforeRespawn.remove(player); + if (locationBeforeRespawn == null) return; + if (locationBeforeRespawn.getY() < 0) + return; // If the player dies in the void (y <= 0), we dont want him to spawn there, he would die again + event.setRespawnLocation(locationBeforeRespawn); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 88c66b02d..6b3f76e71 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.content.Message; @@ -25,142 +25,138 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class SlotLimitSetting extends Modifier { - public SlotLimitSetting() { - super(MenuType.SETTINGS, 1, 36, 36); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); - } - - @Override - protected void onValueChange() { - update(); - } - - @TimerTask(status = { TimerStatus.RUNNING }) - public void updateDelayed() { - Bukkit.getScheduler().runTaskLater(plugin, this::update, 1); - } - - @TimerTask(status = { TimerStatus.PAUSED }, async = false) - public void update() { - Bukkit.getOnlinePlayers().forEach(this::updateSlots); - } - - private void updateSlots(@Nonnull Player player) { - for (int i = 0; i < 36; i++) { - if (ignorePlayer(player)) { - unBlockSlot(player, i); - continue; - } - if (isBlocked(i) && ChallengeAPI.isStarted()) { - blockSlot(player, i); - } else { - unBlockSlot(player, i); - } - } - } - - private boolean isBlocked(int slot) { - if (slot > 35) return false; - - int value = getValue() - 1; - - if (slot >= 9 && slot <= 17) { - slot += 9 * 2; - } else if (slot >= 27) { - slot -= 9 * 2; - } - - return slot > value; - } - - private void blockSlot(@Nonnull Player player, int slot) { - if (ignorePlayer(player)) return; - - ItemStack item = player.getInventory().getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> { - player.getWorld().dropItemNaturally(player.getLocation(), item); - }); - } else { - player.getWorld().dropItemNaturally(player.getLocation(), item); - } - } - player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); - } - - private void unBlockSlot(@Nonnull Player player, int slot) { - ItemStack item = player.getInventory().getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - player.getInventory().setItem(slot, null); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; - if (isBlocked(event.getSlot())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { - event.setCancelled(true); - } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(PlayerRespawnEvent event) { - updateSlots(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(plugin, () -> { - updateSlots(event.getPlayer()); - }); - } - -} \ No newline at end of file + public SlotLimitSetting() { + super(MenuType.SETTINGS, 1, 36, 36); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); + } + + @Override + protected void onValueChange() { + update(); + } + + @TimerTask(status = {TimerStatus.RUNNING}) + public void updateDelayed() { + Bukkit.getScheduler().runTaskLater(plugin, this::update, 1); + } + + @TimerTask(status = {TimerStatus.PAUSED}, async = false) + public void update() { + Bukkit.getOnlinePlayers().forEach(this::updateSlots); + } + + private void updateSlots(@Nonnull Player player) { + for (int i = 0; i < 36; i++) { + if (ignorePlayer(player)) { + unBlockSlot(player, i); + continue; + } + if (isBlocked(i) && ChallengeAPI.isStarted()) { + blockSlot(player, i); + } else { + unBlockSlot(player, i); + } + } + } + + private boolean isBlocked(int slot) { + if (slot > 35) return false; + + int value = getValue() - 1; + + if (slot >= 9 && slot <= 17) { + slot += 9 * 2; + } else if (slot >= 27) { + slot -= 9 * 2; + } + + return slot > value; + } + + private void blockSlot(@Nonnull Player player, int slot) { + if (ignorePlayer(player)) return; + + ItemStack item = player.getInventory().getItem(slot); + if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> { + player.getWorld().dropItemNaturally(player.getLocation(), item); + }); + } else { + player.getWorld().dropItemNaturally(player.getLocation(), item); + } + } + player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); + } + + private void unBlockSlot(@Nonnull Player player, int slot) { + ItemStack item = player.getInventory().getItem(slot); + if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + player.getInventory().setItem(slot, null); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; + if (isBlocked(event.getSlot())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClick(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + event.setCancelled(true); + } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onRespawn(PlayerRespawnEvent event) { + updateSlots(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { + Bukkit.getScheduler().runTask(plugin, () -> { + updateSlots(event.getPlayer()); + }); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index ab5ea73de..3881c0cc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -15,39 +14,37 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.potion.PotionEffect; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ +import javax.annotation.Nonnull; + public class SoupSetting extends Setting { - public SoupSetting() { - super(MenuType.SETTINGS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); - } - - @EventHandler - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) - return; - if (event.getItem() == null) return; - if (event.getItem().getType() != Material.MUSHROOM_STEW) return; - - Player player = event.getPlayer(); - if (player.getGameMode() == GameMode.CREATIVE) return; - if (player.getHealth() == player.getMaxHealth()) return; - - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.INSTANT_HEALTH, 1, 1)); - player.getInventory().setItemInMainHand(new ItemBuilder(Material.BOWL).build()); - player.updateInventory(); - SoundSample.EAT.play(player); - - } + public SoupSetting() { + super(MenuType.SETTINGS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + if (event.getItem() == null) return; + if (event.getItem().getType() != Material.MUSHROOM_STEW) return; + + Player player = event.getPlayer(); + if (player.getGameMode() == GameMode.CREATIVE) return; + if (player.getHealth() == player.getMaxHealth()) return; + + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.INSTANT_HEALTH, 1, 1)); + player.getInventory().setItemInMainHand(new ItemBuilder(Material.BOWL).build()); + player.updateInventory(); + SoundSample.EAT.play(player); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 8b0bf4581..da91a8eef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,12 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -21,90 +21,86 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SplitHealthSetting extends Setting { - public SplitHealthSetting() { - super(MenuType.SETTINGS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); - } - - @Override - protected void onEnable() { - setHealth(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> setHealth(player, null), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> setHealth(player, event), 1); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (ignorePlayer(event.getPlayer())) return; - setHealth(); - } - - /** - * Calls {@link SplitHealthSetting#setHealth(Player, EntityDamageEvent)} for the player with the lowest health - */ - private void setHealth() { - Player player = null; - - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - if (player == null || player.getHealth() > currentPlayer.getHealth()) { - player = currentPlayer; - } - - } - if (player == null) return; - setHealth(player, null); - } - - public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damageEvent) { - if (!shouldExecuteEffect()) return; - - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(currentPlayer)) continue; - if (currentPlayer.equals(player)) continue; - - double health = player.getHealth(); - AttributeInstance attribute = currentPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) return; - if (health > attribute.getValue()) { - health = attribute.getValue(); - } - - if (health <= 0 && damageEvent != null) { - currentPlayer.setLastDamageCause(damageEvent); - } - - currentPlayer.setHealth(health); - } - - } - -} \ No newline at end of file + public SplitHealthSetting() { + super(MenuType.SETTINGS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); + } + + @Override + protected void onEnable() { + setHealth(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> setHealth(player, null), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> setHealth(player, event), 1); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (ignorePlayer(event.getPlayer())) return; + setHealth(); + } + + /** + * Calls {@link SplitHealthSetting#setHealth(Player, EntityDamageEvent)} for the player with the lowest health + */ + private void setHealth() { + Player player = null; + + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + if (player == null || player.getHealth() > currentPlayer.getHealth()) { + player = currentPlayer; + } + + } + if (player == null) return; + setHealth(player, null); + } + + public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damageEvent) { + if (!shouldExecuteEffect()) return; + + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(currentPlayer)) continue; + if (currentPlayer.equals(player)) continue; + + double health = player.getHealth(); + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + if (health > attribute.getValue()) { + health = attribute.getValue(); + } + + if (health <= 0 && damageEvent != null) { + currentPlayer.setLastDamageCause(damageEvent); + } + + currentPlayer.setHealth(health); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 3fa3c49ac..c4bc864bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -21,129 +21,125 @@ import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; +import java.util.Objects; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class TimberSetting extends SettingModifier { - public static final int LOGS_LEAVES = 2; + public static final int LOGS_LEAVES = 2; - - public TimberSetting() { - super(MenuType.SETTINGS, 2); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == LOGS_LEAVES) - return DefaultItem.create(Material.OAK_LEAVES, Message.forName("item-timber-setting-logs-and-leaves")); - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-timber-setting-logs")); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!isLog(event.getBlock().getType())) return; - - List treeBlocks = getAllTreeBlocks(event.getBlock(), getValue() == LOGS_LEAVES); - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - - final int[] index = {0}; - - boolean damageItem = !item.getItemMeta().isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); - - Bukkit.getScheduler().runTaskTimer(plugin, timer -> { - for (int i = 0; i < 2 && !treeBlocks.isEmpty(); i++) { - Block block = treeBlocks.get(index[0]); - breakBlock(block, item, damageItem); - - index[0]++; - if (index[0] >= treeBlocks.size()) { - timer.cancel(); - return; - } - } - }, 0, 1); - - } - - private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean damageItem) { - if (isLog(block.getType())) { - ChallengeHelper.breakBlock(block, item); - if (damageItem) { - ItemUtils.damageItem(item); - } - } else if (isLeaves(block.getType())) { - ChallengeHelper.breakBlock(block, item); - } - } - - private List getAllTreeBlocks(@Nonnull Block block, boolean leaves) { - List allBlocks = new ArrayList<>(); - - List currentBlocks = new ArrayList<>(); - currentBlocks.add(block); - - for (int i = 0; i < 8; i++) { - - ArrayList lastBlocks = new ArrayList<>(currentBlocks); - currentBlocks.clear(); - - for (Block currentBlock : lastBlocks) { - for (Block blockAround : BlockUtils.getBlocksAroundBlock(currentBlock)) { - if (BukkitReflectionUtils.isAir(blockAround.getType())) continue; - if (allBlocks.contains(blockAround)) continue; - - if (currentBlock.getType() == blockAround.getType() || (leaves && isLeaveMaterial(currentBlock.getType(), blockAround.getType()))) { - allBlocks.add(blockAround); - currentBlocks.add(blockAround); - } - } - } - - if (currentBlocks.isEmpty()) - break; - - } - - return allBlocks; - } - - private boolean isLog(Material material) { - String name = material.name(); - return name.contains("LOG") || name.contains("STEM"); - } - - private boolean isLeaves(Material material) { - return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); - } - - public boolean isLeaveMaterial(@Nonnull Material logMaterial, @Nonnull Material leaveMaterial) { - // Exceptions like nether wood - if (logMaterial.name().equals("CRIMSON_STEM")) - return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); - if (logMaterial.name().equals("WARPED_STEM")) - return leaveMaterial.name().equals("WARPED_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); - - int firstUnderscore = logMaterial.name().indexOf("_"); - if (firstUnderscore == -1) return false; - String logPrefix = logMaterial.name().substring(0, firstUnderscore); - return leaveMaterial.name().startsWith(logPrefix) && leaveMaterial.name().endsWith("LEAVES"); - } + + public TimberSetting() { + super(MenuType.SETTINGS, 2); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == LOGS_LEAVES) + return DefaultItem.create(Material.OAK_LEAVES, Message.forName("item-timber-setting-logs-and-leaves")); + return DefaultItem.create(Material.OAK_LOG, Message.forName("item-timber-setting-logs")); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!isLog(event.getBlock().getType())) return; + + List treeBlocks = getAllTreeBlocks(event.getBlock(), getValue() == LOGS_LEAVES); + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + + final int[] index = {0}; + + boolean damageItem = !Objects.requireNonNull(item.getItemMeta()).isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); + + Bukkit.getScheduler().runTaskTimer(plugin, timer -> { + for (int i = 0; i < 2 && !treeBlocks.isEmpty(); i++) { + Block block = treeBlocks.get(index[0]); + breakBlock(block, item, damageItem); + + index[0]++; + if (index[0] >= treeBlocks.size()) { + timer.cancel(); + return; + } + } + }, 0, 1); + + } + + private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean damageItem) { + if (isLog(block.getType())) { + ChallengeHelper.breakBlock(block, item); + if (damageItem) { + ItemUtils.damageItem(item); + } + } else if (isLeaves(block.getType())) { + ChallengeHelper.breakBlock(block, item); + } + } + + private List getAllTreeBlocks(@Nonnull Block block, boolean leaves) { + List allBlocks = new ArrayList<>(); + + List currentBlocks = new ArrayList<>(); + currentBlocks.add(block); + + for (int i = 0; i < 8; i++) { + + ArrayList lastBlocks = new ArrayList<>(currentBlocks); + currentBlocks.clear(); + + for (Block currentBlock : lastBlocks) { + for (Block blockAround : BlockUtils.getBlocksAroundBlock(currentBlock)) { + if (BukkitReflectionUtils.isAir(blockAround.getType())) continue; + if (allBlocks.contains(blockAround)) continue; + + if (currentBlock.getType() == blockAround.getType() || (leaves && isLeaveMaterial(currentBlock.getType(), blockAround.getType()))) { + allBlocks.add(blockAround); + currentBlocks.add(blockAround); + } + } + } + + if (currentBlocks.isEmpty()) + break; + + } + + return allBlocks; + } + + private boolean isLog(Material material) { + String name = material.name(); + return name.contains("LOG") || name.contains("STEM"); + } + + private boolean isLeaves(Material material) { + return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); + } + + public boolean isLeaveMaterial(@Nonnull Material logMaterial, @Nonnull Material leaveMaterial) { + // Exceptions like nether wood + if (logMaterial.name().equals("CRIMSON_STEM")) + return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + if (logMaterial.name().equals("WARPED_STEM")) + return leaveMaterial.name().equals("WARPED_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + + int firstUnderscore = logMaterial.name().indexOf("_"); + if (firstUnderscore == -1) return false; + String logPrefix = logMaterial.name().substring(0, firstUnderscore); + return leaveMaterial.name().startsWith(logPrefix) && leaveMaterial.name().endsWith("LEAVES"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 3f3e08384..627bd099e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -16,64 +16,60 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class TopCommandSetting extends Setting implements PlayerCommand { - public TopCommandSetting() { - super(MenuType.SETTINGS); - } + public TopCommandSetting() { + super(MenuType.SETTINGS); + } - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } - World world = player.getWorld(); - Environment environment = world.getEnvironment(); - Location playerLocation = player.getLocation(); - if (environment == Environment.NORMAL) { - Message.forName("top-to-surface").send(player, Prefix.CHALLENGES); + World world = player.getWorld(); + Environment environment = world.getEnvironment(); + Location playerLocation = player.getLocation(); + if (environment == Environment.NORMAL) { + Message.forName("top-to-surface").send(player, Prefix.CHALLENGES); - Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); - location.setYaw(playerLocation.getYaw()); - location.setPitch(playerLocation.getPitch()); - player.setFallDistance(0); - player.teleport(location); + Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); + location.setYaw(playerLocation.getYaw()); + location.setPitch(playerLocation.getPitch()); + player.setFallDistance(0); + player.teleport(location); - } else { - Message.forName("top-to-overworld").send(player, Prefix.CHALLENGES); + } else { + Message.forName("top-to-overworld").send(player, Prefix.CHALLENGES); - if (environment == Environment.NETHER) { - Location location = playerLocation.clone(); - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - location.setWorld(world); - location.multiply(8); - location = world.getHighestBlockAt(location).getLocation().add(0.5, 1, 0.5); - player.setFallDistance(0); - player.teleport(location); - } else { - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - Location location = player.getBedSpawnLocation(); - if (location == null) location = world.getSpawnLocation(); - player.setFallDistance(0); - player.teleport(location); - } + if (environment == Environment.NETHER) { + Location location = playerLocation.clone(); + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + location.setWorld(world); + location.multiply(8); + location = world.getHighestBlockAt(location).getLocation().add(0.5, 1, 0.5); + player.setFallDistance(0); + player.teleport(location); + } else { + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + Location location = player.getBedSpawnLocation(); + if (location == null) location = world.getSpawnLocation(); + player.setFallDistance(0); + player.teleport(location); + } - } - SoundSample.TELEPORT.play(player); + } + SoundSample.TELEPORT.play(player); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index bd0739af2..74bd86114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,28 +13,24 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class TotemSaveDeathSetting extends Setting { - public TotemSaveDeathSetting() { - super(MenuType.SETTINGS); - } + public TotemSaveDeathSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { - if (ChallengeHelper.isInInstantKill() && !isEnabled()) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { + if (ChallengeHelper.isInInstantKill() && !isEnabled()) { + event.setCancelled(true); + } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index 143f6e1d0..4ef7440cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; @@ -13,92 +13,88 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EmptyChallenge implements IChallenge { - private final MenuType menuType; + private final MenuType menuType; - public EmptyChallenge(@Nonnull MenuType menuType) { - this.menuType = menuType; - } + public EmptyChallenge(@Nonnull MenuType menuType) { + this.menuType = menuType; + } - @Override - public boolean isEnabled() { - return false; - } + @Override + public boolean isEnabled() { + return false; + } - @Override - public void restoreDefaults() { + @Override + public void restoreDefaults() { - } + } - @Override - public void handleShutdown() { + @Override + public void handleShutdown() { - } + } - @NotNull - @Override - public String getUniqueGamestateName() { - return getUniqueName(); - } + @NotNull + @Override + public String getUniqueGamestateName() { + return getUniqueName(); + } - @NotNull - @Override - public String getUniqueName() { - return "empty"; - } + @NotNull + @Override + public String getUniqueName() { + return "empty"; + } - @NotNull - @Override - public MenuType getType() { - return menuType; - } + @NotNull + @Override + public MenuType getType() { + return menuType; + } - @Nullable - @Override - public SettingCategory getCategory() { - return null; - } + @Nullable + @Override + public SettingCategory getCategory() { + return null; + } - @NotNull - @Override - public ItemStack getDisplayItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } + @NotNull + @Override + public ItemStack getDisplayItem() { + return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); + } - @NotNull - @Override - public ItemStack getSettingsItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } + @NotNull + @Override + public ItemStack getSettingsItem() { + return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); + } - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - SoundSample.CLICK.play(info.getPlayer()); - } + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } - @Override - public void writeSettings(@NotNull Document document) { + @Override + public void writeSettings(@NotNull Document document) { - } + } - @Override - public void loadSettings(@NotNull Document document) { + @Override + public void loadSettings(@NotNull Document document) { - } + } - @Override - public void writeGameState(@NotNull Document document) { + @Override + public void writeGameState(@NotNull Document document) { - } + } - @Override - public void loadGameState(@NotNull Document document) { + @Override + public void loadGameState(@NotNull Document document) { - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 2492c1023..506d29f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,73 +11,68 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @see ChallengeManager - * @since 2.0 - */ public interface IChallenge extends GamestateSaveable { - /** - * Returns if this challenge is enabled. - * This value is used in checks and policies like {@link net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy} which are used for tasks. - * If this challenge does not have clear boolean value, you may always return {@code true} - * - * @return if this challenge is enabled - */ - boolean isEnabled(); + /** + * Returns if this challenge is enabled. + * This value is used in checks and policies like {@link net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy} which are used for tasks. + * If this challenge does not have clear boolean value, you may always return {@code true} + * + * @return if this challenge is enabled + */ + boolean isEnabled(); - /** - * Restores the default settings of this challenge. - * This will be executed when the /config reset command is executed. - * - * @see ChallengeManager#restoreDefaults() - */ - void restoreDefaults(); + /** + * Restores the default settings of this challenge. + * This will be executed when the /config reset command is executed. + * + * @see ChallengeManager#restoreDefaults() + */ + void restoreDefaults(); - /** - * This method will be executed when the challenges plugin is being disabled. - * This will occur when the server is shutdown or reloaded. - * This method is intended for removing temporarily content or calling disable logic. - * - * @see ChallengeManager#shutdownChallenges() - */ - void handleShutdown(); + /** + * This method will be executed when the challenges plugin is being disabled. + * This will occur when the server is shutdown or reloaded. + * This method is intended for removing temporarily content or calling disable logic. + * + * @see ChallengeManager#shutdownChallenges() + */ + void handleShutdown(); - /** - * Returns the internal name of this challenges. - * This name will be used for saving and assigning the right settings or gamestate. - * If multiple instances of class are registered, they must not return the same value. - * Multiple challenges should not have the same name. - * - * @return the internal name of this challenge - */ - @Nonnull - String getUniqueName(); + /** + * Returns the internal name of this challenges. + * This name will be used for saving and assigning the right settings or gamestate. + * If multiple instances of class are registered, they must not return the same value. + * Multiple challenges should not have the same name. + * + * @return the internal name of this challenge + */ + @Nonnull + String getUniqueName(); - /** - * This challenge will be displayed in the menu for the given {@link MenuType}. - * This has to always return the same value. - * If {@link MenuType#isUsable()} is {@code false}, an {@link IllegalArgumentException} will be thrown when registering this challenge. - * - * @return the target menu for the challenge - */ - @Nonnull - MenuType getType(); + /** + * This challenge will be displayed in the menu for the given {@link MenuType}. + * This has to always return the same value. + * If {@link MenuType#isUsable()} is {@code false}, an {@link IllegalArgumentException} will be thrown when registering this challenge. + * + * @return the target menu for the challenge + */ + @Nonnull + MenuType getType(); - @Nullable - SettingCategory getCategory(); + @Nullable + SettingCategory getCategory(); - @Nonnull - ItemStack getDisplayItem(); + @Nonnull + ItemStack getDisplayItem(); - @Nonnull - ItemStack getSettingsItem(); + @Nonnull + ItemStack getSettingsItem(); - void handleClick(@Nonnull ChallengeMenuClickInfo info); + void handleClick(@Nonnull ChallengeMenuClickInfo info); - void writeSettings(@Nonnull Document document); + void writeSettings(@Nonnull Document document); - void loadSettings(@Nonnull Document document); + void loadSettings(@Nonnull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index 455333bd4..6f597140d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -10,46 +10,41 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @see ChallengeManager - * @since 2.0 - */ public interface IGoal extends IChallenge { - /** - * Enabled / disabled this goal. - * This must call {@link ChallengeManager#setCurrentGoal(IGoal)} with - * {@code this} if {@code enabled} is {@code true} or {@code null} if {@code enabled} is {@code false} and this goal is the current. - * This can be checked by comparing {@link ChallengeManager#getCurrentGoal()} to {@code this}. - * You may just call {@link GoalHelper#handleSetEnabled(IGoal, boolean)} with {@code this}, {@code enabled} - */ - void setEnabled(boolean enabled); - - /** - * This sound will be played when the timer is started and the plugin setting "enable-specific-start-sounds" is enabled. - * If not the standard sound will be played. - * - * @return the sound to play - */ - @Nonnull - SoundSample getStartSound(); - - /** - * This sound will be played when the challenge is won and the plugin setting "enabled-win-sounds" is enabled. - * If this returns {@code null} no sound will be played. - * - * @return the sound to play - */ - @Nullable - SoundSample getWinSound(); - - /** - * This method will be called, when the challenges are being ended with a winnable cause ({@link ChallengeEndCause#isWinnable()}) and when there is no player supplier given in order to determine the winner of this challenge run. - * If no players are added to the winners list, the {@link ChallengeEndCause#getNoWinnerMessage()} will be shown instead of the {@link ChallengeEndCause#getWinnerMessage()}. - * - * @param winners the list to which the winners should be added - */ - void getWinnersOnEnd(@Nonnull List winners); + /** + * Enabled / disabled this goal. + * This must call {@link ChallengeManager#setCurrentGoal(IGoal)} with + * {@code this} if {@code enabled} is {@code true} or {@code null} if {@code enabled} is {@code false} and this goal is the current. + * This can be checked by comparing {@link ChallengeManager#getCurrentGoal()} to {@code this}. + * You may just call {@link GoalHelper#handleSetEnabled(IGoal, boolean)} with {@code this}, {@code enabled} + */ + void setEnabled(boolean enabled); + + /** + * This sound will be played when the timer is started and the plugin setting "enable-specific-start-sounds" is enabled. + * If not the standard sound will be played. + * + * @return the sound to play + */ + @Nonnull + SoundSample getStartSound(); + + /** + * This sound will be played when the challenge is won and the plugin setting "enabled-win-sounds" is enabled. + * If this returns {@code null} no sound will be played. + * + * @return the sound to play + */ + @Nullable + SoundSample getWinSound(); + + /** + * This method will be called, when the challenges are being ended with a winnable cause ({@link ChallengeEndCause#isWinnable()}) and when there is no player supplier given in order to determine the winner of this challenge run. + * If no players are added to the winners list, the {@link ChallengeEndCause#getNoWinnerMessage()} will be shown instead of the {@link ChallengeEndCause#getWinnerMessage()}. + * + * @param winners the list to which the winners should be added + */ + void getWinnersOnEnd(@Nonnull List winners); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java index ee15e6ef5..8f1a6be8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java @@ -2,23 +2,19 @@ import javax.annotation.Nonnegative; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public interface IModifier { - @Nonnegative - int getValue(); + @Nonnegative + int getValue(); - void setValue(int value); + void setValue(int value); - @Nonnegative - int getMinValue(); + @Nonnegative + int getMinValue(); - @Nonnegative - int getMaxValue(); + @Nonnegative + int getMaxValue(); - void playValueChangeTitle(); + void playValueChangeTitle(); -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 3fcaeff27..35838577d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -2,9 +2,9 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.common.annotations.DeprecatedSince; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -28,195 +28,190 @@ import java.util.UUID; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class AbstractChallenge implements IChallenge, Listener { - protected static final Challenges plugin = Challenges.getInstance(); - protected static final IRandom globalRandom = IRandom.create(); + protected static final Challenges plugin = Challenges.getInstance(); + protected static final IRandom globalRandom = IRandom.create(); - private static final Map, AbstractChallenge> firstInstanceByClass = new HashMap<>(); - @Getter + private static final Map, AbstractChallenge> firstInstanceByClass = new HashMap<>(); + @Getter private static final boolean ignoreCreativePlayers, ignoreSpectatorPlayers; - static { - Document ignoreDocument = Challenges.getInstance().getConfigDocument().getDocument("ignore-players"); - ignoreCreativePlayers = ignoreDocument.getBoolean("creative"); - ignoreSpectatorPlayers = ignoreDocument.getBoolean("spectator"); - } + static { + Document ignoreDocument = Challenges.getInstance().getConfigDocument().getDocument("ignore-players"); + ignoreCreativePlayers = ignoreDocument.getBoolean("creative"); + ignoreSpectatorPlayers = ignoreDocument.getBoolean("spectator"); + } - protected final MenuType menu; - @Getter + protected final MenuType menu; + @Getter protected final ChallengeBossBar bossbar = new ChallengeBossBar(); - @Getter + @Getter protected final ChallengeScoreboard scoreboard = new ChallengeScoreboard(); - @Setter - protected SettingCategory category; - private String name; - private ItemStack cachedDisplayItem; - - public AbstractChallenge(@Nonnull MenuType menu) { - this.menu = menu; - firstInstanceByClass.put(this.getClass(), this); - } - - @Nonnull - public static C getFirstInstance(@Nonnull Class classOfChallenge) { - return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); - } - - public static void broadcast(@Nonnull Consumer action) { - Bukkit.getOnlinePlayers().forEach(action); - } - - public static void broadcastFiltered(@Nonnull Consumer action) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - action.accept(player); - } - } - - public static void broadcastIgnored(@Nonnull Consumer action) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (!ignorePlayer(player)) continue; - action.accept(player); - } - } - - @CheckReturnValue - public static boolean ignorePlayer(@Nonnull Player player) { - return ignoreGameMode(player.getGameMode()); - } - - @CheckReturnValue - public static boolean ignoreGameMode(@Nonnull GameMode gameMode) { - return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); - } + @Setter + protected SettingCategory category; + private String name; + private ItemStack cachedDisplayItem; + + public AbstractChallenge(@Nonnull MenuType menu) { + this.menu = menu; + firstInstanceByClass.put(this.getClass(), this); + } + + @Nonnull + public static C getFirstInstance(@Nonnull Class classOfChallenge) { + return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); + } + + public static void broadcast(@Nonnull Consumer action) { + Bukkit.getOnlinePlayers().forEach(action); + } + + public static void broadcastFiltered(@Nonnull Consumer action) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + action.accept(player); + } + } + + public static void broadcastIgnored(@Nonnull Consumer action) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (!ignorePlayer(player)) continue; + action.accept(player); + } + } + + @CheckReturnValue + public static boolean ignorePlayer(@Nonnull Player player) { + return ignoreGameMode(player.getGameMode()); + } + + @CheckReturnValue + public static boolean ignoreGameMode(@Nonnull GameMode gameMode) { + return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); + } + + @Nonnull + @Override + public final MenuType getType() { + return menu; + } + + @Override + public SettingCategory getCategory() { + return category; + } + + protected final void updateItems() { + ChallengeHelper.updateItems(this); + } + + @Nonnull + @Override + public ItemStack getDisplayItem() { + if (cachedDisplayItem != null) return cachedDisplayItem.clone(); + cachedDisplayItem = createDisplayItem().build(); + return cachedDisplayItem.clone(); + } + + @Nonnull + @Override + public ItemStack getSettingsItem() { + ItemBuilder item = createSettingsItem(); + String[] description = getSettingsDescription(); + if (description != null && isEnabled()) { + item.appendLore(" "); + item.appendLore(description); + } + + return item.build(); + } + + @Nullable + protected String[] getSettingsDescription() { + return null; + } + + @Nonnull + public abstract ItemBuilder createDisplayItem(); + + @Nonnull + public abstract ItemBuilder createSettingsItem(); + + @Nonnull + @Override + public String getUniqueGamestateName() { + return getUniqueName(); + } + + @Nonnull + @Override + public String getUniqueName() { + return name != null ? name : (name = getClass().getSimpleName().toLowerCase() + .replace("setting", "") + .replace("challenge", "") + .replace("modifier", "") + .replace("goal", "") + ); + } + + @Override + public void handleShutdown() { + } + + @Override + public void writeGameState(@Nonnull Document document) { + } + + @Override + public void loadGameState(@Nonnull Document document) { + } + + @Override + public void writeSettings(@Nonnull Document document) { + } + + @Override + public void loadSettings(@Nonnull Document document) { + } + + @CheckReturnValue + protected boolean shouldExecuteEffect() { + return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); + } + + /** + * @deprecated Use {@link ChallengeHelper#kill(Player)} + */ + @Deprecated + @DeprecatedSince("2.1.0") + public void kill(@Nonnull Player player) { + ChallengeHelper.kill(player); + } + + /** + * @deprecated Use {@link ChallengeHelper#kill(Player, int)} + */ + @Deprecated + @DeprecatedSince("2.1.0") + public void kill(@Nonnull Player player, int delay) { + ChallengeHelper.kill(player, delay); + + } + + @Nonnull + protected final Document getGameStateData() { + return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); + } + + @Nonnull + protected final Document getPlayerData(@Nonnull UUID player) { + return getGameStateData().getDocument("player").getDocument(player.toString()); + } @Nonnull - @Override - public final MenuType getType() { - return menu; - } - - @Override - public SettingCategory getCategory() { - return category; - } - - protected final void updateItems() { - ChallengeHelper.updateItems(this); - } - - @Nonnull - @Override - public ItemStack getDisplayItem() { - if (cachedDisplayItem != null) return cachedDisplayItem.clone(); - cachedDisplayItem = createDisplayItem().build(); - return cachedDisplayItem.clone(); - } - - @Nonnull - @Override - public ItemStack getSettingsItem() { - ItemBuilder item = createSettingsItem(); - String[] description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); - } - - return item.build(); - } - - @Nullable - protected String[] getSettingsDescription() { - return null; - } - - @Nonnull - public abstract ItemBuilder createDisplayItem(); - - @Nonnull - public abstract ItemBuilder createSettingsItem(); - - @Nonnull - @Override - public String getUniqueGamestateName() { - return getUniqueName(); - } - - @Nonnull - @Override - public String getUniqueName() { - return name != null ? name : (name = getClass().getSimpleName().toLowerCase() - .replace("setting", "") - .replace("challenge", "") - .replace("modifier", "") - .replace("goal", "") - ); - } - - @Override - public void handleShutdown() { - } - - @Override - public void writeGameState(@Nonnull Document document) { - } - - @Override - public void loadGameState(@Nonnull Document document) { - } - - @Override - public void writeSettings(@Nonnull Document document) { - } - - @Override - public void loadSettings(@Nonnull Document document) { - } - - @CheckReturnValue - protected boolean shouldExecuteEffect() { - return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); - } - - /** - * @deprecated Use {@link ChallengeHelper#kill(Player)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player) { - ChallengeHelper.kill(player); - } - - /** - * @deprecated Use {@link ChallengeHelper#kill(Player, int)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player, int delay) { - ChallengeHelper.kill(player, delay); - - } - - @Nonnull - protected final Document getGameStateData() { - return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); - } - - @Nonnull - protected final Document getPlayerData(@Nonnull UUID player) { - return getGameStateData().getDocument("player").getDocument(player.toString()); - } - - @Nonnull - protected final Document getPlayerData(@Nonnull Player player) { - return getPlayerData(player.getUniqueId()); - } + protected final Document getPlayerData(@Nonnull Player player) { + return getPlayerData(player.getUniqueId()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index a1e9fbf67..102977b53 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import lombok.Setter; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import org.bukkit.entity.Player; @@ -10,97 +11,90 @@ import javax.annotation.Nonnull; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +@Setter public abstract class AbstractForceChallenge extends TimedChallenge { - public static final int WAITING = 0, - COUNTDOWN = 1; - - private int state = WAITING; - - public AbstractForceChallenge(@Nonnull MenuType menu) { - super(menu, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue, false); - } - - @Override - protected void onTimeActivation() { - switch (state) { - case WAITING: - state = COUNTDOWN; - chooseForcing(); - restartTimer(getForcingTime()); - SoundSample.BASS_ON.broadcast(); - bossbar.update(); - break; - case COUNTDOWN: - state = WAITING; - restartTimer(); - handleCountdownEnd(); - bossbar.update(); - break; - } - } - - protected final void endForcing() { - state = WAITING; - restartTimer(); - bossbar.update(); - } - - protected abstract void handleCountdownEnd(); - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onEnable() { - bossbar.setContent(setupBossbar()); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.isEmpty()) { - state = WAITING; - } - } - - protected abstract void chooseForcing(); - - protected abstract int getForcingTime(); - - @Nonnull - protected abstract BiConsumer setupBossbar(); - - public final int getState() { - return state; - } - - public void setState(int state) { - this.state = state; - } + public static final int WAITING = 0, + COUNTDOWN = 1; + + private int state = WAITING; + + public AbstractForceChallenge(@Nonnull MenuType menu) { + super(menu, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue, false); + } + + @Override + protected void onTimeActivation() { + switch (state) { + case WAITING: + state = COUNTDOWN; + chooseForcing(); + restartTimer(getForcingTime()); + SoundSample.BASS_ON.broadcast(); + bossbar.update(); + break; + case COUNTDOWN: + state = WAITING; + restartTimer(); + handleCountdownEnd(); + bossbar.update(); + break; + } + } + + protected final void endForcing() { + state = WAITING; + restartTimer(); + bossbar.update(); + } + + protected abstract void handleCountdownEnd(); + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onEnable() { + bossbar.setContent(setupBossbar()); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.isEmpty()) { + state = WAITING; + } + } + + protected abstract void chooseForcing(); + + protected abstract int getForcingTime(); + + @Nonnull + protected abstract BiConsumer setupBossbar(); + + public final int getState() { + return state; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 860fa45ec..2ad3bacf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -15,118 +15,114 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class CollectionGoal extends SettingGoal { - private final Map> collections = new HashMap<>(); - protected Object[] target; - - public CollectionGoal(@Nonnull Object[] target) { - super(); - this.target = target; - } - - public CollectionGoal(boolean enabledByDefault, @Nonnull Object[] target) { - super(enabledByDefault); - this.target = target; - } - - @Override - protected void onEnable() { - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); - scoreboard.show(); - } - - @Override - protected void onDisable() { - scoreboard.hide(); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - AtomicInteger mostPoints = new AtomicInteger(); - Map points = getPoints(mostPoints, false); - if (mostPoints.get() == 0) return; // Nobody won, nobody has anything - - for (Entry entry : points.entrySet()) { - if (entry.getValue() != mostPoints.get()) continue; - winners.add(entry.getKey()); - } - } - - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectionFiltered(uuid).size(), zeros); - } - - protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Runnable success) { - if (ignorePlayer(player)) return; - List collection = getCollectionRaw(player.getUniqueId()); - if (collection.contains(item.toString())) return; - if (!Arrays.asList(target).contains(item)) return; - collection.add(item.toString()); - success.run(); - checkCollects(); - } - - protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); - return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); - } - - protected List getCollectionRaw(@Nonnull UUID uuid) { - return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); - } - - protected void checkCollects() { - scoreboard.update(); - for (Player player : Bukkit.getOnlinePlayers()) { - checkCollects(getCollectionFiltered(player.getUniqueId())); - } - } - - protected void checkCollects(@Nonnull List collection) { - if (collection.size() >= target.length) - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - collections.clear(); - Document scores = document.getDocument("scores"); - for (String key : scores.keys()) { - try { - UUID uuid = UUID.fromString(key); - List collection = scores.getStringList(key); - collections.put(uuid, collection); - } catch (Exception ex) { - Logger.error("Could not load scores for {}", key); - } - } - - if (scoreboard.isShown()) { - scoreboard.update(); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - Document scores = document.getDocument("scores"); - collections.forEach((uuid, collection) -> { - scores.set(uuid.toString(), collection); - }); - } - - protected void setTarget(@Nonnull Object... target) { - this.target = target; - } + private final Map> collections = new HashMap<>(); + protected Object[] target; + + public CollectionGoal(@Nonnull Object[] target) { + super(); + this.target = target; + } + + public CollectionGoal(boolean enabledByDefault, @Nonnull Object[] target) { + super(enabledByDefault); + this.target = target; + } + + @Override + protected void onEnable() { + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); + scoreboard.show(); + } + + @Override + protected void onDisable() { + scoreboard.hide(); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + AtomicInteger mostPoints = new AtomicInteger(); + Map points = getPoints(mostPoints, false); + if (mostPoints.get() == 0) return; // Nobody won, nobody has anything + + for (Entry entry : points.entrySet()) { + if (entry.getValue() != mostPoints.get()) continue; + winners.add(entry.getKey()); + } + } + + @Nonnull + @CheckReturnValue + protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectionFiltered(uuid).size(), zeros); + } + + protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Runnable success) { + if (ignorePlayer(player)) return; + List collection = getCollectionRaw(player.getUniqueId()); + if (collection.contains(item.toString())) return; + if (!Arrays.asList(target).contains(item)) return; + collection.add(item.toString()); + success.run(); + checkCollects(); + } + + protected List getCollectionFiltered(@Nonnull UUID uuid) { + List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); + return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); + } + + protected List getCollectionRaw(@Nonnull UUID uuid) { + return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); + } + + protected void checkCollects() { + scoreboard.update(); + for (Player player : Bukkit.getOnlinePlayers()) { + checkCollects(getCollectionFiltered(player.getUniqueId())); + } + } + + protected void checkCollects(@Nonnull List collection) { + if (collection.size() >= target.length) + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + collections.clear(); + Document scores = document.getDocument("scores"); + for (String key : scores.keys()) { + try { + UUID uuid = UUID.fromString(key); + List collection = scores.getStringList(key); + collections.put(uuid, collection); + } catch (Exception ex) { + Logger.error("Could not load scores for {}", key); + } + } + + if (scoreboard.isShown()) { + scoreboard.update(); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + Document scores = document.getDocument("scores"); + collections.forEach((uuid, collection) -> { + scores.set(uuid.toString(), collection); + }); + } + + protected void setTarget(@Nonnull Object... target) { + this.target = target; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 8e9f186e6..0c2ef8b48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -8,44 +8,40 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class CompletableForceChallenge extends AbstractForceChallenge { - public CompletableForceChallenge(@Nonnull MenuType menu) { - super(menu); - } + public CompletableForceChallenge(@Nonnull MenuType menu) { + super(menu); + } - public CompletableForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } + public CompletableForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } + public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } + public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } - @Override - protected final void handleCountdownEnd() { - broadcastFailedMessage(); - endForcing(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } + @Override + protected final void handleCountdownEnd() { + broadcastFailedMessage(); + endForcing(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } - protected final void completeForcing(@Nonnull Player player) { - if (getState() != COUNTDOWN) return; - broadcastSuccessMessage(player); - endForcing(); - SoundSample.LEVEL_UP.broadcast(); - } + protected final void completeForcing(@Nonnull Player player) { + if (getState() != COUNTDOWN) return; + broadcastSuccessMessage(player); + endForcing(); + SoundSample.LEVEL_UP.broadcast(); + } - protected abstract void broadcastFailedMessage(); + protected abstract void broadcastFailedMessage(); - protected abstract void broadcastSuccessMessage(@Nonnull Player player); + protected abstract void broadcastSuccessMessage(@Nonnull Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index b9ba6efe5..4c29f8444 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,64 +11,55 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class EndingForceChallenge extends AbstractForceChallenge { - public EndingForceChallenge(@Nonnull MenuType menu) { - super(menu); - } - - public EndingForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - protected final void handleCountdownEnd() { - checkAllPlayers(); - } - - private void checkAllPlayers() { - List failed = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (!ignorePlayer(player) && isFailing(player)) { - broadcastFailedMessage(player); - failed.add(player); - } - } - if (!failed.isEmpty()) { - killFailedPlayers(failed); - return; - } - - broadcastSuccessMessage(); - SoundSample.LEVEL_UP.broadcast(); - } - - private void killFailedPlayers(@Nonnull Iterable failed) { - if (!ChallengeAPI.isStarted()) return; - failed.forEach(ChallengeHelper::kill); - } - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - protected abstract boolean isFailing(@Nonnull Player player); - - protected abstract void broadcastFailedMessage(@Nonnull Player player); - - protected abstract void broadcastSuccessMessage(); + public EndingForceChallenge(@Nonnull MenuType menu) { + super(menu); + } + + public EndingForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public EndingForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public EndingForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + protected final void handleCountdownEnd() { + checkAllPlayers(); + } + + private void checkAllPlayers() { + List failed = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (!ignorePlayer(player) && isFailing(player)) { + broadcastFailedMessage(player); + failed.add(player); + } + } + if (!failed.isEmpty()) { + killFailedPlayers(failed); + return; + } + + broadcastSuccessMessage(); + SoundSample.LEVEL_UP.broadcast(); + } + + private void killFailedPlayers(@Nonnull Iterable failed) { + if (!ChallengeAPI.isStarted()) return; + failed.forEach(ChallengeHelper::kill); + } + + protected abstract boolean isFailing(@Nonnull Player player); + + protected abstract void broadcastFailedMessage(@Nonnull Player player); + + protected abstract void broadcastSuccessMessage(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index 33be66503..da5e8ffba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -15,43 +15,39 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class FindItemGoal extends SettingGoal { - private final Material searchedItem; - - public FindItemGoal(Material searchedItem) { - this.searchedItem = searchedItem; - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - private void checkItem(ItemStack itemStack, @Nonnull Player player) { - if (itemStack == null) return; - if (itemStack.getType() != searchedItem) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkItem(event.getItem().getItemStack(), event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - checkItem(event.getCurrentItem(), event.getPlayer()); - } + private final Material searchedItem; + + public FindItemGoal(Material searchedItem) { + this.searchedItem = searchedItem; + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + private void checkItem(ItemStack itemStack, @Nonnull Player player) { + if (itemStack == null) return; + if (itemStack.getType() != searchedItem) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkItem(event.getItem().getItemStack(), event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInventoryClick(PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + checkItem(event.getCurrentItem(), event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 035c06449..3db44282e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -14,49 +15,42 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ +@Getter public abstract class FirstPlayerAtHeightGoal extends SettingGoal { - private int heightToGetTo; - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-first-at-height-goal").asString(getHeightToGetTo())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; - if (event.getTo().getBlockY() == heightToGetTo) { - Message.forName("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - } - } - - public int getHeightToGetTo() { - return heightToGetTo; - } - - protected void setHeightToGetTo(int heightToGetTo) { - this.heightToGetTo = heightToGetTo; - } + private int heightToGetTo; + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + bar.setTitle(Message.forName("bossbar-first-at-height-goal").asString(getHeightToGetTo())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; + if (event.getTo().getBlockY() == heightToGetTo) { + Message.forName("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + } + } + + protected void setHeightToGetTo(int heightToGetTo) { + this.heightToGetTo = heightToGetTo; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index deb6b7486..b92624eed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; @@ -17,110 +17,107 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public abstract class ForceBattleDisplayGoal> extends ForceBattleGoal { - private Map displayStands; - - public ForceBattleDisplayGoal(@NotNull Message title) { - super(title); - } - - @Override - protected void onEnable() { - displayStands = new HashMap<>(); - broadcastFiltered(this::updateDisplayStand); - super.onEnable(); - } - - @Override - protected void onDisable() { - super.onDisable(); - displayStands.values().forEach(Entity::remove); - displayStands = null; - } - - public void updateDisplayStand(Player player) { - ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { - World world = player1.getWorld(); - ArmorStand entity = (ArmorStand) world - .spawnEntity(player1.getLocation().clone().add(0, 2, 0), EntityType.ARMOR_STAND); - entity.setVisible(false); - entity.setInvulnerable(true); - entity.setGravity(false); - entity.setMarker(true); - entity.setSilent(true); - entity.setSmall(true); - return entity; - }); - armorStand.setVelocity(player.getVelocity().clone().multiply(2)); - armorStand.teleport(player.getLocation().clone().add(0, 2, 0)); - - handleDisplayStandUpdate(player, armorStand); + private Map displayStands; + + public ForceBattleDisplayGoal(@NotNull Message title) { + super(title); + } + + @Override + protected void onEnable() { + displayStands = new HashMap<>(); + broadcastFiltered(this::updateDisplayStand); + super.onEnable(); + } + + @Override + protected void onDisable() { + super.onDisable(); + displayStands.values().forEach(Entity::remove); + displayStands = null; + } + + public void updateDisplayStand(Player player) { + ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { + World world = player1.getWorld(); + ArmorStand entity = (ArmorStand) world + .spawnEntity(player1.getLocation().clone().add(0, 2, 0), EntityType.ARMOR_STAND); + entity.setVisible(false); + entity.setInvulnerable(true); + entity.setGravity(false); + entity.setMarker(true); + entity.setSilent(true); + entity.setSmall(true); + return entity; + }); + armorStand.setVelocity(player.getVelocity().clone().multiply(2)); + armorStand.teleport(player.getLocation().clone().add(0, 2, 0)); + + handleDisplayStandUpdate(player, armorStand); + } + + public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { + if (currentTarget.containsKey(player.getUniqueId())) { + currentTarget.get(player.getUniqueId()).updateDisplayStand(armorStand); + } else if (Objects.requireNonNull(armorStand.getEquipment()).getHelmet() != null) { + armorStand.getEquipment().setHelmet(null); } + } - public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { - if (currentTarget.containsKey(player.getUniqueId())) { - currentTarget.get(player.getUniqueId()).updateDisplayStand(armorStand); - } else if (armorStand.getEquipment().getHelmet() != null) { - armorStand.getEquipment().setHelmet(null); - } + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (isEnabled()) { + broadcastFiltered(this::updateDisplayStand); } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (isEnabled()) { - broadcastFiltered(this::updateDisplayStand); - } + } + + @Override + public void setRandomTarget(Player player) { + super.setRandomTarget(player); + updateDisplayStand(player); + } + + @EventHandler(ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateDisplayStand(event.getPlayer()); + } + + @EventHandler + public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isNotIgnored()) { + setRandomTargetIfCurrentlyNone(event.getPlayer()); + updateDisplayStand(event.getPlayer()); + } else { + ArmorStand stand = displayStands.remove(event.getPlayer()); + if (stand != null) { + stand.remove(); + } } + } - @Override - public void setRandomTarget(Player player) { - super.setRandomTarget(player); - updateDisplayStand(player); + @Override + public void onTick() { + super.onTick(); + for (Player player : displayStands.keySet()) { + updateDisplayStand(player); } - - @EventHandler(ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateDisplayStand(event.getPlayer()); - } - - @EventHandler - public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isNotIgnored()) { - setRandomTargetIfCurrentlyNone(event.getPlayer()); - updateDisplayStand(event.getPlayer()); - } else { - ArmorStand stand = displayStands.remove(event.getPlayer()); - if (stand != null) { - stand.remove(); - } - } - } - - @Override - public void onTick() { - super.onTick(); - for (Player player : displayStands.keySet()) { - updateDisplayStand(player); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onQuit(PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - ArmorStand stand = displayStands.remove(event.getPlayer()); - if (stand != null) { - stand.remove(); - } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onQuit(PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + ArmorStand stand = displayStands.remove(event.getPlayer()); + if (stand != null) { + stand.remove(); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 8583464c3..0ff8f60b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; @@ -37,418 +37,414 @@ import java.util.*; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public abstract class ForceBattleGoal> extends MenuGoal { - protected final Map jokerUsed = new HashMap<>(); - protected final Map> foundTargets = new HashMap<>(); - protected final Map currentTarget = new HashMap<>(); - protected T[] targetsPossibleToFind; - private ItemStack jokerItem; - - public ForceBattleGoal(@NotNull Message title) { - super(MenuType.GOAL, title); - setCategory(SettingCategory.FORCE_BATTLE); - - registerSetting("jokers", new NumberSubSetting( - () -> new ItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), - value -> null, - value -> "§e" + value, - 1, - 32, - 5 - )); - registerSetting("showScoreboard", new BooleanSubSetting( - () -> new ItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), - true - )); - if (shouldRegisterDupedTargetsSetting()) { - registerSetting("dupedTargets", new BooleanSubSetting( - () -> new ItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), - true - )); - } - } - - @Override - protected void onEnable() { - jokerItem = new ItemBuilder(Material.BARRIER, "§cJoker").build(); - - targetsPossibleToFind = getTargetsPossibleToFind(); - - broadcastFiltered(this::updateJokersInInventory); - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - - setScoreboardContent(); - if (showScoreboard()) { - scoreboard.show(); - } - } - - @Override - protected void onDisable() { - if (jokerItem == null) return; // Disable through plugin disable - broadcastFiltered(this::updateJokersInInventory); - jokerItem = null; - scoreboard.hide(); - targetsPossibleToFind = null; - } - - protected abstract T[] getTargetsPossibleToFind(); - - private void updateJokersInInventory(Player player) { - PlayerInventory inventory = player.getInventory(); - boolean enabled = isEnabled() && ChallengeAPI.isStarted(); - int usableJokers = getUsableJokers(player.getUniqueId()); - - int jokersInInventory = 0; - - LinkedList itemStacks = new LinkedList<>(Arrays.asList(inventory.getContents())); - itemStacks.add(player.getItemOnCursor()); - for (ItemStack itemStack : itemStacks) { - if (jokerItem.isSimilar(itemStack)) { - if (enabled) { - jokersInInventory += itemStack.getAmount(); - if (jokersInInventory >= usableJokers) { - int jokersToSubtract = jokersInInventory - usableJokers; - jokersInInventory -= jokersToSubtract; - itemStack.setAmount(itemStack.getAmount() - jokersToSubtract); - } - } else { - inventory.removeItem(itemStack); - } - } - - } - - if (enabled) { - if (jokersInInventory < usableJokers) { - ItemStack clone = jokerItem.clone(); - clone.setAmount(usableJokers - jokersInInventory); - InventoryUtils.dropOrGiveItem(inventory, player.getLocation(), clone); - } - } - - } - - @Override - public void loadGameState(@NotNull Document document) { - this.jokerUsed.clear(); - this.currentTarget.clear(); - this.foundTargets.clear(); - - List players = document.getDocumentList("players"); - for (Document player : players) { - UUID uuid = player.getUUID("uuid"); - - T currentTarget = getTargetFromDocument(player, "currentTarget"); - - if (currentTarget != null) { - this.currentTarget.put(uuid, currentTarget); - } - List foundItems = getListFromDocument(player, "foundTargets"); - this.foundTargets.put(uuid, foundItems); - - int jokerUsed = player.getInt("jokerUsed"); - this.jokerUsed.put(uuid, jokerUsed); - } - - if (isEnabled()) { - if (ChallengeAPI.isStarted()) { - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - } - scoreboard.update(); - broadcastFiltered(this::updateJokersInInventory); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - List playersDocuments = new LinkedList<>(); - for (Map.Entry entry : currentTarget.entrySet()) { - List foundItems = this.foundTargets.get(entry.getKey()); - int jokerUsed = this.jokerUsed.getOrDefault(entry.getKey(), 0); - GsonDocument playerDocument = new GsonDocument(); - playerDocument.set("uuid", entry.getKey()); - setTargetInDocument(playerDocument, "currentTarget", entry.getValue()); - if (foundItems != null) { - setFoundListInDocument(playerDocument, "foundTargets", foundItems); - } - playerDocument.set("jokerUsed", jokerUsed); - playersDocuments.add(playerDocument); - } - - document.set("players", playersDocuments); - } - - public void setTargetInDocument(Document document, String path, T target) { - document.set(path, target.getTargetSaveObject()); - } - - public void setFoundListInDocument(Document document, String path, List targets) { - document.set(path, targets.stream().map(ForceTarget::getTargetSaveObject).collect(Collectors.toList())); - } - - public abstract T getTargetFromDocument(Document document, String path); - - public abstract List getListFromDocument(Document document, String path); - - public void setRandomTargetIfCurrentlyNone(Player player) { - if (currentTarget.containsKey(player.getUniqueId())) { - return; - } - setRandomTarget(player); - } - - public void setRandomTarget(Player player) { - T target = getRandomTarget(player); - - if (target != null) { - currentTarget.put(player.getUniqueId(), target); - getNewTargetMessage(target) - .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(target)); - SoundSample.PLING.play(player); - } else { - currentTarget.remove(player.getUniqueId()); - SoundSample.BASS_OFF.play(player); - } - scoreboard.update(); - - } - - protected T getRandomTarget(Player player) { - LinkedList list = new LinkedList<>(Arrays.asList(targetsPossibleToFind)); - if (!getSetting("dupedTargets").getAsBoolean()) { - list.removeAll(foundTargets.getOrDefault(player.getUniqueId(), new LinkedList<>())); - } - if (!list.isEmpty()) { - return globalRandom.choose(list); - } - return null; - } - - protected Message getNewTargetMessage(T newTarget) { - return newTarget.getNewTargetMessage(); - } - - protected Message getTargetCompletedMessage(T target) { - return target.getCompletedMessage(); - } - - public void handleTargetFound(Player player) { - T foundTarget = currentTarget.get(player.getUniqueId()); - if (foundTarget != null) { - List list = foundTargets - .computeIfAbsent(player.getUniqueId(), uuid -> new LinkedList<>()); - list.add(foundTarget); - getTargetCompletedMessage(foundTarget).send(player, Prefix.CHALLENGES, getTargetMessageReplacement(foundTarget)); - } - setRandomTarget(player); - } - - public Object getTargetMessageReplacement(T target) { - return target.toMessage(); - } - - public String getTargetName(T target) { - return target.getName(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - Bukkit.getScheduler().runTask(plugin, () -> { - int place = 0; - int placeValue = -1; - - List>> list = foundTargets.entrySet().stream() - .sorted(Comparator.comparingInt(value -> value.getValue().size())) - .collect(Collectors.toList()); - Collections.reverse(list); - - getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); - - for (Map.Entry> entry : list) { - if (entry.getValue().size() != placeValue) { - place++; - placeValue = entry.getValue().size(); - } - UUID uuid = entry.getKey(); - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); - ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") - .broadcast(Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); - } - - }); - - } - - public void sendResult(@NotNull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> { - int place = 0; - int placeValue = -1; - - List>> list = foundTargets.entrySet().stream() - .sorted(Comparator.comparingInt(value -> value.getValue().size())) - .collect(Collectors.toList()); - Collections.reverse(list); - - getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); - - for (Map.Entry> entry : list) { - if (entry.getValue().size() != placeValue) { - place++; - placeValue = entry.getValue().size(); - } - UUID uuid = entry.getKey(); - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); - ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") - .send(player, Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); - } - - }); - } - - protected abstract Message getLeaderboardTitleMessage(); - - protected ChatColor getPlaceColor(int place) { - switch (place) { - case 1: - return ChatColor.GOLD; - case 2: - return ChatColor.YELLOW; - case 3: - return ChatColor.RED; - default: - return ChatColor.GRAY; - } - } - - private int getUsableJokers(UUID uuid) { - return Math.max(0, getJokers() - jokerUsed.getOrDefault(uuid, 0)); - } - - public void handleJokerUse(Player player) { - if (currentTarget.get(player.getUniqueId()) == null) { - setRandomTargetIfCurrentlyNone(player); - return; - } - int jokerUsed = this.jokerUsed.getOrDefault(player.getUniqueId(), 0); - jokerUsed++; - this.jokerUsed.put(player.getUniqueId(), jokerUsed); - handleTargetFound(player); - updateJokersInInventory(player); - } - - protected void setScoreboardContent() { - scoreboard.setContent((board, player) -> { - List ingamePlayers = ChallengeAPI.getIngamePlayers(); - int emptyLinesAvailable = 15 - ingamePlayers.size(); - - if (emptyLinesAvailable > 0) { - board.addLine(""); - emptyLinesAvailable--; - } - - for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { - Player ingamePlayer = ingamePlayers.get(i); - T target = currentTarget.get(ingamePlayer.getUniqueId()); - String display = target == null ? Message.forName("none").asString() : getTargetName(target); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); - } - - if (emptyLinesAvailable > 0) { - board.addLine(""); - } - }); - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onStart() { - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - broadcastFiltered(this::updateJokersInInventory); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - setRandomTargetIfCurrentlyNone(event.getPlayer()); - updateJokersInInventory(event.getPlayer()); - } - - @ScheduledTask(ticks = 1, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void onTick() { - if (!isEnabled()) return; - - if (!scoreboard.isShown() && showScoreboard()) { - scoreboard.show(); - } else if (scoreboard.isShown() && !showScoreboard()) { - scoreboard.hide(); - } - broadcastFiltered(this::updateJokersInInventory); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAction() != Action.RIGHT_CLICK_AIR - && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (jokerItem.isSimilar(event.getItem())) { - handleJokerUse(event.getPlayer()); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDropItem(PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (jokerItem.isSimilar(event.getItemDrop().getItemStack())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getEntity())) return; - event.getDrops().removeIf(itemStack -> jokerItem.isSimilar(itemStack)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onRespawn(PlayerRespawnEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTask(plugin, () -> { - updateJokersInInventory(event.getPlayer()); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (jokerItem.isSimilar(event.getItemInHand())) { - event.setCancelled(true); - } - } - - private int getJokers() { - return getSetting("jokers").getAsInt(); - } - - private boolean showScoreboard() { - return getSetting("showScoreboard").getAsBoolean(); - } - - protected boolean shouldRegisterDupedTargetsSetting() { - return true; - } + protected final Map jokerUsed = new HashMap<>(); + protected final Map> foundTargets = new HashMap<>(); + protected final Map currentTarget = new HashMap<>(); + protected T[] targetsPossibleToFind; + private ItemStack jokerItem; + + public ForceBattleGoal(@NotNull Message title) { + super(MenuType.GOAL, title); + setCategory(SettingCategory.FORCE_BATTLE); + + registerSetting("jokers", new NumberSubSetting( + () -> new ItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), + value -> null, + value -> "§e" + value, + 1, + 32, + 5 + )); + registerSetting("showScoreboard", new BooleanSubSetting( + () -> new ItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), + true + )); + if (shouldRegisterDupedTargetsSetting()) { + registerSetting("dupedTargets", new BooleanSubSetting( + () -> new ItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), + true + )); + } + } + + @Override + protected void onEnable() { + jokerItem = new ItemBuilder(Material.BARRIER, "§cJoker").build(); + + targetsPossibleToFind = getTargetsPossibleToFind(); + + broadcastFiltered(this::updateJokersInInventory); + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + + setScoreboardContent(); + if (showScoreboard()) { + scoreboard.show(); + } + } + + @Override + protected void onDisable() { + if (jokerItem == null) return; // Disable through plugin disable + broadcastFiltered(this::updateJokersInInventory); + jokerItem = null; + scoreboard.hide(); + targetsPossibleToFind = null; + } + + protected abstract T[] getTargetsPossibleToFind(); + + private void updateJokersInInventory(Player player) { + PlayerInventory inventory = player.getInventory(); + boolean enabled = isEnabled() && ChallengeAPI.isStarted(); + int usableJokers = getUsableJokers(player.getUniqueId()); + + int jokersInInventory = 0; + + LinkedList itemStacks = new LinkedList<>(Arrays.asList(inventory.getContents())); + itemStacks.add(player.getItemOnCursor()); + for (ItemStack itemStack : itemStacks) { + if (jokerItem.isSimilar(itemStack)) { + if (enabled) { + jokersInInventory += itemStack.getAmount(); + if (jokersInInventory >= usableJokers) { + int jokersToSubtract = jokersInInventory - usableJokers; + jokersInInventory -= jokersToSubtract; + itemStack.setAmount(itemStack.getAmount() - jokersToSubtract); + } + } else { + inventory.removeItem(itemStack); + } + } + + } + + if (enabled) { + if (jokersInInventory < usableJokers) { + ItemStack clone = jokerItem.clone(); + clone.setAmount(usableJokers - jokersInInventory); + InventoryUtils.dropOrGiveItem(inventory, player.getLocation(), clone); + } + } + + } + + @Override + public void loadGameState(@NotNull Document document) { + this.jokerUsed.clear(); + this.currentTarget.clear(); + this.foundTargets.clear(); + + List players = document.getDocumentList("players"); + for (Document player : players) { + UUID uuid = player.getUUID("uuid"); + + T currentTarget = getTargetFromDocument(player, "currentTarget"); + + if (currentTarget != null) { + this.currentTarget.put(uuid, currentTarget); + } + List foundItems = getListFromDocument(player, "foundTargets"); + this.foundTargets.put(uuid, foundItems); + + int jokerUsed = player.getInt("jokerUsed"); + this.jokerUsed.put(uuid, jokerUsed); + } + + if (isEnabled()) { + if (ChallengeAPI.isStarted()) { + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + } + scoreboard.update(); + broadcastFiltered(this::updateJokersInInventory); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + List playersDocuments = new LinkedList<>(); + for (Map.Entry entry : currentTarget.entrySet()) { + List foundItems = this.foundTargets.get(entry.getKey()); + int jokerUsed = this.jokerUsed.getOrDefault(entry.getKey(), 0); + GsonDocument playerDocument = new GsonDocument(); + playerDocument.set("uuid", entry.getKey()); + setTargetInDocument(playerDocument, "currentTarget", entry.getValue()); + if (foundItems != null) { + setFoundListInDocument(playerDocument, "foundTargets", foundItems); + } + playerDocument.set("jokerUsed", jokerUsed); + playersDocuments.add(playerDocument); + } + + document.set("players", playersDocuments); + } + + public void setTargetInDocument(Document document, String path, T target) { + document.set(path, target.getTargetSaveObject()); + } + + public void setFoundListInDocument(Document document, String path, List targets) { + document.set(path, targets.stream().map(ForceTarget::getTargetSaveObject).collect(Collectors.toList())); + } + + public abstract T getTargetFromDocument(Document document, String path); + + public abstract List getListFromDocument(Document document, String path); + + public void setRandomTargetIfCurrentlyNone(Player player) { + if (currentTarget.containsKey(player.getUniqueId())) { + return; + } + setRandomTarget(player); + } + + public void setRandomTarget(Player player) { + T target = getRandomTarget(player); + + if (target != null) { + currentTarget.put(player.getUniqueId(), target); + getNewTargetMessage(target) + .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(target)); + SoundSample.PLING.play(player); + } else { + currentTarget.remove(player.getUniqueId()); + SoundSample.BASS_OFF.play(player); + } + scoreboard.update(); + + } + + protected T getRandomTarget(Player player) { + LinkedList list = new LinkedList<>(Arrays.asList(targetsPossibleToFind)); + if (!getSetting("dupedTargets").getAsBoolean()) { + list.removeAll(foundTargets.getOrDefault(player.getUniqueId(), new LinkedList<>())); + } + if (!list.isEmpty()) { + return globalRandom.choose(list); + } + return null; + } + + protected Message getNewTargetMessage(T newTarget) { + return newTarget.getNewTargetMessage(); + } + + protected Message getTargetCompletedMessage(T target) { + return target.getCompletedMessage(); + } + + public void handleTargetFound(Player player) { + T foundTarget = currentTarget.get(player.getUniqueId()); + if (foundTarget != null) { + List list = foundTargets + .computeIfAbsent(player.getUniqueId(), uuid -> new LinkedList<>()); + list.add(foundTarget); + getTargetCompletedMessage(foundTarget).send(player, Prefix.CHALLENGES, getTargetMessageReplacement(foundTarget)); + } + setRandomTarget(player); + } + + public Object getTargetMessageReplacement(T target) { + return target.toMessage(); + } + + public String getTargetName(T target) { + return target.getName(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + Bukkit.getScheduler().runTask(plugin, () -> { + int place = 0; + int placeValue = -1; + + List>> list = foundTargets.entrySet().stream() + .sorted(Comparator.comparingInt(value -> value.getValue().size())) + .collect(Collectors.toList()); + Collections.reverse(list); + + getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); + + for (Map.Entry> entry : list) { + if (entry.getValue().size() != placeValue) { + place++; + placeValue = entry.getValue().size(); + } + UUID uuid = entry.getKey(); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + ChatColor color = getPlaceColor(place); + Message.forName("force-battle-leaderboard-entry") + .broadcast(Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); + } + + }); + + } + + public void sendResult(@NotNull Player player) { + Bukkit.getScheduler().runTask(plugin, () -> { + int place = 0; + int placeValue = -1; + + List>> list = foundTargets.entrySet().stream() + .sorted(Comparator.comparingInt(value -> value.getValue().size())) + .collect(Collectors.toList()); + Collections.reverse(list); + + getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); + + for (Map.Entry> entry : list) { + if (entry.getValue().size() != placeValue) { + place++; + placeValue = entry.getValue().size(); + } + UUID uuid = entry.getKey(); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + ChatColor color = getPlaceColor(place); + Message.forName("force-battle-leaderboard-entry") + .send(player, Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); + } + + }); + } + + protected abstract Message getLeaderboardTitleMessage(); + + protected ChatColor getPlaceColor(int place) { + switch (place) { + case 1: + return ChatColor.GOLD; + case 2: + return ChatColor.YELLOW; + case 3: + return ChatColor.RED; + default: + return ChatColor.GRAY; + } + } + + private int getUsableJokers(UUID uuid) { + return Math.max(0, getJokers() - jokerUsed.getOrDefault(uuid, 0)); + } + + public void handleJokerUse(Player player) { + if (currentTarget.get(player.getUniqueId()) == null) { + setRandomTargetIfCurrentlyNone(player); + return; + } + int jokerUsed = this.jokerUsed.getOrDefault(player.getUniqueId(), 0); + jokerUsed++; + this.jokerUsed.put(player.getUniqueId(), jokerUsed); + handleTargetFound(player); + updateJokersInInventory(player); + } + + protected void setScoreboardContent() { + scoreboard.setContent((board, player) -> { + List ingamePlayers = ChallengeAPI.getIngamePlayers(); + int emptyLinesAvailable = 15 - ingamePlayers.size(); + + if (emptyLinesAvailable > 0) { + board.addLine(""); + emptyLinesAvailable--; + } + + for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { + Player ingamePlayer = ingamePlayers.get(i); + T target = currentTarget.get(ingamePlayer.getUniqueId()); + String display = target == null ? Message.forName("none").asString() : getTargetName(target); + board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); + } + + if (emptyLinesAvailable > 0) { + board.addLine(""); + } + }); + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onStart() { + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + broadcastFiltered(this::updateJokersInInventory); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + setRandomTargetIfCurrentlyNone(event.getPlayer()); + updateJokersInInventory(event.getPlayer()); + } + + @ScheduledTask(ticks = 1, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void onTick() { + if (!isEnabled()) return; + + if (!scoreboard.isShown() && showScoreboard()) { + scoreboard.show(); + } else if (scoreboard.isShown() && !showScoreboard()) { + scoreboard.hide(); + } + broadcastFiltered(this::updateJokersInInventory); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAction() != Action.RIGHT_CLICK_AIR + && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (jokerItem.isSimilar(event.getItem())) { + handleJokerUse(event.getPlayer()); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDropItem(PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (jokerItem.isSimilar(event.getItemDrop().getItemStack())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getEntity())) return; + event.getDrops().removeIf(itemStack -> jokerItem.isSimilar(itemStack)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onRespawn(PlayerRespawnEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTask(plugin, () -> { + updateJokersInInventory(event.getPlayer()); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (jokerItem.isSimilar(event.getItemInHand())) { + event.setCancelled(true); + } + } + + private int getJokers() { + return getSetting("jokers").getAsInt(); + } + + private boolean showScoreboard() { + return getSetting("showScoreboard").getAsBoolean(); + } + + protected boolean shouldRegisterDupedTargetsSetting() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index 80884d628..163829a2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import javax.annotation.Nonnull; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -13,35 +12,33 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ +import javax.annotation.Nonnull; + public abstract class HydraChallenge extends Setting { - public HydraChallenge(@Nonnull MenuType menu) { - super(menu); - } + public HydraChallenge(@Nonnull MenuType menu) { + super(menu); + } - public HydraChallenge(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); - } + public HydraChallenge(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu, enabledByDefault); + } - public abstract int getNewMobsCount(@Nonnull EntityType entityType); + public abstract int getNewMobsCount(@Nonnull EntityType entityType); - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; - if (ChallengeHelper.ignoreDamager(event.getKiller())) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; + if (ChallengeHelper.ignoreDamager(event.getKiller())) return; - int mobsCount = getNewMobsCount(event.getEntityType()); + int mobsCount = getNewMobsCount(event.getEntityType()); - for (int i = 0; i < mobsCount; i++) { - event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); - } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), event.getEntity().getLocation(), - MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); - } + for (int i = 0; i < mobsCount; i++) { + event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); + } + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), event.getEntity().getLocation(), + MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index f2a2a8348..aeec44b76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,52 +16,48 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public abstract class ItemCollectionGoal extends CollectionGoal { - public ItemCollectionGoal(@NotNull Material... target) { - super(target); - } - - public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) { - super(enabledByDefault, target); - } - - protected void handleCollect(@Nonnull Player player, @Nonnull Material material) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } - - @Override - protected void onEnable() { - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true), - player -> Collections.singletonList(Message.forName("items-to-collect").asString(target.length)))); - scoreboard.show(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - Material material = event.getItem().getItemStack().getType(); - Player player = event.getPlayer(); - handleCollect(player, material); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - Player player = event.getPlayer(); - Material material = event.getCurrentItem().getType(); - handleCollect(player, material); - } + public ItemCollectionGoal(@NotNull Material... target) { + super(target); + } + + public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) { + super(enabledByDefault, target); + } + + protected void handleCollect(@Nonnull Player player, @Nonnull Material material) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } + + @Override + protected void onEnable() { + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true), + player -> Collections.singletonList(Message.forName("items-to-collect").asString(target.length)))); + scoreboard.show(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + Material material = event.getItem().getItemStack().getType(); + Player player = event.getPlayer(); + handleCollect(player, material); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isCancelled()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + Player player = event.getPlayer(); + Material material = event.getCurrentItem().getType(); + handleCollect(player, material); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java index 8c1135858..3a70470bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java @@ -14,56 +14,52 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class KillEntityGoal extends SettingGoal { - protected final EntityType entity; - protected final Environment environment; - @Setter + protected final EntityType entity; + protected final Environment environment; + @Setter protected boolean oneWinner = true; - protected boolean killerNeeded = false; - protected Player winner; + protected boolean killerNeeded = false; + protected Player winner; - public KillEntityGoal(@Nonnull EntityType entity) { - this(entity, false); - } + public KillEntityGoal(@Nonnull EntityType entity) { + this(entity, false); + } - public KillEntityGoal(@Nonnull EntityType entity, boolean enabledByDefault) { - this(entity, null, enabledByDefault); - } + public KillEntityGoal(@Nonnull EntityType entity, boolean enabledByDefault) { + this(entity, null, enabledByDefault); + } - public KillEntityGoal(EntityType entity, Environment world) { - this(entity, world, false); - } + public KillEntityGoal(EntityType entity, Environment world) { + this(entity, world, false); + } - public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDefault) { - super(enabledByDefault); - this.entity = entity; - this.environment = world; - } + public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDefault) { + super(enabledByDefault); + this.entity = entity; + this.environment = world; + } - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - if (oneWinner && winner != null) winners.add(winner); - } + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + if (oneWinner && winner != null) winners.add(winner); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!isEnabled() || !ChallengeAPI.isStarted()) return; - LivingEntity entity = event.getEntity(); - if (entity.getType() != this.entity) return; - if (environment != null && event.getEntity().getWorld().getEnvironment() != environment) - return; - if (oneWinner) { - winner = event.getEntity().getKiller(); - if (killerNeeded && winner == null) { - return; - } - } - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!isEnabled() || !ChallengeAPI.isStarted()) return; + LivingEntity entity = event.getEntity(); + if (entity.getType() != this.entity) return; + if (environment != null && event.getEntity().getWorld().getEnvironment() != environment) + return; + if (oneWinner) { + winner = event.getEntity().getKiller(); + if (killerNeeded && winner == null) { + return; + } + } + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 1d58fd1bb..5b10af2c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -17,89 +17,85 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public abstract class KillMobsGoal extends SettingGoal { - protected static List entitiesKilled; - - protected final List entitiesToKill; - - public KillMobsGoal(List entitiesKilled) { - this.entitiesToKill = entitiesKilled; - resetEntitiesToKill(); - } - - public abstract Message getBossbarMessage(); - - private void resetEntitiesToKill() { - entitiesKilled = new LinkedList<>(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); - bar.setProgress(i); - bar.setColor(BarColor.GREEN); - bar.setTitle(getBossbarMessage().asString(getEntitiesKilled().size(), entitiesToKill.size())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { - if (event.getEntity().getKiller() == null) return; - } - if (entitiesKilled.contains(event.getEntityType())) return; - entitiesKilled.add(event.getEntityType()); - if (entitiesToKill.contains(event.getEntityType())) { - Message.forName("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); - bossbar.update(); - if (!getEntitiesLeftToKill().isEmpty()) return; - resetEntitiesToKill(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - document.set("entities", entitiesKilled); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - entitiesKilled = document.getEnumList("entities", EntityType.class); - } - - public List getEntitiesKilled() { - LinkedList entityTypes = new LinkedList<>(entitiesKilled); - entityTypes.removeIf(type -> !entitiesToKill.contains(type)); - return entityTypes; - } - - public List getEntitiesLeftToKill() { - LinkedList entityTypes = new LinkedList<>(entitiesToKill); - entityTypes.removeAll(entitiesKilled); - return entityTypes; - } + protected static List entitiesKilled; + + protected final List entitiesToKill; + + public KillMobsGoal(List entitiesKilled) { + this.entitiesToKill = entitiesKilled; + resetEntitiesToKill(); + } + + public abstract Message getBossbarMessage(); + + private void resetEntitiesToKill() { + entitiesKilled = new LinkedList<>(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); + bar.setProgress(i); + bar.setColor(BarColor.GREEN); + bar.setTitle(getBossbarMessage().asString(getEntitiesKilled().size(), entitiesToKill.size())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { + if (event.getEntity().getKiller() == null) return; + } + if (entitiesKilled.contains(event.getEntityType())) return; + entitiesKilled.add(event.getEntityType()); + if (entitiesToKill.contains(event.getEntityType())) { + Message.forName("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); + bossbar.update(); + if (!getEntitiesLeftToKill().isEmpty()) return; + resetEntitiesToKill(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + document.set("entities", entitiesKilled); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + entitiesKilled = document.getEnumList("entities", EntityType.class); + } + + public List getEntitiesKilled() { + LinkedList entityTypes = new LinkedList<>(entitiesKilled); + entityTypes.removeIf(type -> !entitiesToKill.contains(type)); + return entityTypes; + } + + public List getEntitiesLeftToKill() { + LinkedList entityTypes = new LinkedList<>(entitiesToKill); + entityTypes.removeAll(entitiesKilled); + return entityTypes; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index 2a4d0e6ed..11da3d1d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; @@ -10,31 +10,27 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.4 - */ public abstract class MenuGoal extends MenuSetting implements IGoal { - public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { - super(menu, title); - } + public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { + super(menu, title); + } - @Override - public final void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } + @Override + public final void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } + @Nonnull + @Override + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index 97b1684fe..b2d8270ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.EmptyMenuPosition; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; @@ -29,604 +29,600 @@ import java.util.function.Function; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class MenuSetting extends Setting { - private final Map settings = new LinkedHashMap<>(); - private final List inventories = new ArrayList<>(); - private final Message title; - - public MenuSetting(@Nonnull MenuType menu, @Nonnull Message title) { - super(menu); - this.title = title; - } - - @Nonnull - public static int[] getSlots(int amount) { - switch (amount) { - default: - return new int[0]; - case 1: - return new int[]{13}; - case 2: - return new int[]{12, 14}; - case 3: - return new int[]{11, 13, 15}; - case 4: - return new int[]{10, 12, 14, 16}; - } - } - - protected final void generateInventories() { - - inventories.clear(); - - int maxRowLength = 4; - int page = 0; - int index = 0; - - Collection settings = this.settings.values(); - - int pagesTotal = settings.size() / maxRowLength; - if (settings.size() % maxRowLength != 0) pagesTotal++; - - for (SubSetting setting : settings) { - - if (index >= maxRowLength) { - index = 0; - createNewInventory(++page, pagesTotal); - } else if (inventories.isEmpty()) { - createNewInventory(page, pagesTotal); - } - - int added = page * maxRowLength + index; - int left = settings.size() - added; - int fitOnThisPage = index + left; - if (fitOnThisPage > 4) fitOnThisPage = 4; - - int[] slots = getSlots(fitOnThisPage); - - int displaySlot = slots[index]; - - setting.setPage(page); - setting.setSlot(displaySlot); - setting.updateItems(); - - index++; - - } - - InventoryUtils.setNavigationItemsToInventory(inventories, SettingsMenuGenerator.NAVIGATION_SLOTS, true); - - } - - @Nonnull - private Inventory createNewInventory(int page, int pagesAmount) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } - - protected final void registerSetting(@Nonnull String name, @Nonnull SubSetting setting) { - if (name.equals("enabled")) throw new IllegalArgumentException(); - settings.put(name, setting); - Challenges.getInstance().registerListener(setting); - } - - public final SubSetting getSetting(@Nonnull String name) { - return settings.get(name); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick()) { - super.handleClick(info); - } else if (isEnabled() && !info.isRightClick()) { - openMenu(info); - } else { - super.handleClick(info); - } - } - - private void openMenu(@Nonnull ChallengeMenuClickInfo event) { - MenuPosition position = MenuPosition.get(event.getPlayer()); - if (position == null) position = new EmptyMenuPosition(); - Inventory inventory = event.getInventory(); - SoundSample.CLICK.play(event.getPlayer()); - open(event.getPlayer(), inventory, position, 0); - } - - private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull MenuPosition position, int page) { - if (inventories.isEmpty()) generateInventories(); - if (inventories.isEmpty()) { - SoundSample.BASS_OFF.play(player); - return; - } - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory menu = inventories.get(page); - MenuPosition.set(player, new SettingMenuPosition(position, inventory, page)); - player.openInventory(menu); - } - - @Nonnull - @Override - public final ItemBuilder createSettingsItem() { - return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", isEnabled()); - for (Entry entry : settings.entrySet()) { - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().writeSettings(subDocument); - } - } - - @Override - public void loadSettings(@Nonnull Document document) { - setEnabled(document.getBoolean("enabled")); - for (Entry entry : settings.entrySet()) { - if (!document.contains(entry.getKey())) continue; - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().loadSettings(subDocument); - } - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - settings.values().forEach(SubSetting::restoreDefaults); - } - - public abstract class SubSetting implements Listener { - - private int page = -1, slot = -1; - - private void setPage(int page) { - this.page = page; - } - - private void setSlot(int slot) { - this.slot = slot; - } - - public final void updateItems() { - if (inventories.isEmpty()) return; // Menu not generated yet, nothing to update here - if (page == -1 || slot == -1) return; // Invalid slots, menu not generated yet - - Inventory inventory = inventories.get(page); - - inventory.setItem(slot, getDisplayItem().hideAttributes().build()); - inventory.setItem(slot + 9, buildSettingsItem()); - } - - @Nonnull - private ItemStack buildSettingsItem() { - ItemBuilder item = getSettingsItem(); - String[] description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); - } - - return item.build(); - } - - @Nonnull - public abstract ItemBuilder getDisplayItem(); - - @Nonnull - public abstract ItemBuilder getSettingsItem(); - - @Nullable - protected abstract String[] getSettingsDescription(); - - public boolean isEnabled() { - return MenuSetting.this.isEnabled() && getAsBoolean(); - } - - public abstract int getAsInt(); - - public abstract boolean getAsBoolean(); - - public abstract void restoreDefaults(); - - public abstract void loadSettings(@Nonnull Document document); - - public abstract void writeSettings(@Nonnull Document document); - - public abstract void handleClick(@Nonnull ChallengeMenuClickInfo info); - - } - - public class BooleanSubSetting extends SubSetting { - - private final Supplier item; - private final Supplier description; - private final boolean enabledByDefault; - private boolean enabled; - - public BooleanSubSetting(@Nonnull Supplier item) { - this(item, () -> null); - } - - public BooleanSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { - this(item, () -> null, enabledByDefault); - } - - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description) { - this(item, description, false); - } - - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description, boolean enabledByDefault) { - this.item = item; - this.description = description; - this.enabledByDefault = enabledByDefault; - this.setEnabled(enabledByDefault); - } + private final Map settings = new LinkedHashMap<>(); + private final List inventories = new ArrayList<>(); + private final Message title; + + public MenuSetting(@Nonnull MenuType menu, @Nonnull Message title) { + super(menu); + this.title = title; + } + + @Nonnull + public static int[] getSlots(int amount) { + switch (amount) { + default: + return new int[0]; + case 1: + return new int[]{13}; + case 2: + return new int[]{12, 14}; + case 3: + return new int[]{11, 13, 15}; + case 4: + return new int[]{10, 12, 14, 16}; + } + } + + protected final void generateInventories() { + + inventories.clear(); + + int maxRowLength = 4; + int page = 0; + int index = 0; + + Collection settings = this.settings.values(); + + int pagesTotal = settings.size() / maxRowLength; + if (settings.size() % maxRowLength != 0) pagesTotal++; + + for (SubSetting setting : settings) { + + if (index >= maxRowLength) { + index = 0; + createNewInventory(++page, pagesTotal); + } else if (inventories.isEmpty()) { + createNewInventory(page, pagesTotal); + } + + int added = page * maxRowLength + index; + int left = settings.size() - added; + int fitOnThisPage = index + left; + if (fitOnThisPage > 4) fitOnThisPage = 4; + + int[] slots = getSlots(fitOnThisPage); + + int displaySlot = slots[index]; + + setting.setPage(page); + setting.setSlot(displaySlot); + setting.updateItems(); + + index++; + + } + + InventoryUtils.setNavigationItemsToInventory(inventories, SettingsMenuGenerator.NAVIGATION_SLOTS, true); + + } + + @Nonnull + private Inventory createNewInventory(int page, int pagesAmount) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + inventories.add(inventory); + return inventory; + } + + protected final void registerSetting(@Nonnull String name, @Nonnull SubSetting setting) { + if (name.equals("enabled")) throw new IllegalArgumentException(); + settings.put(name, setting); + Challenges.getInstance().registerListener(setting); + } + + public final SubSetting getSetting(@Nonnull String name) { + return settings.get(name); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick()) { + super.handleClick(info); + } else if (isEnabled() && !info.isRightClick()) { + openMenu(info); + } else { + super.handleClick(info); + } + } + + private void openMenu(@Nonnull ChallengeMenuClickInfo event) { + MenuPosition position = MenuPosition.get(event.getPlayer()); + if (position == null) position = new EmptyMenuPosition(); + Inventory inventory = event.getInventory(); + SoundSample.CLICK.play(event.getPlayer()); + open(event.getPlayer(), inventory, position, 0); + } + + private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull MenuPosition position, int page) { + if (inventories.isEmpty()) generateInventories(); + if (inventories.isEmpty()) { + SoundSample.BASS_OFF.play(player); + return; + } + if (page >= inventories.size()) page = inventories.size() - 1; + Inventory menu = inventories.get(page); + MenuPosition.set(player, new SettingMenuPosition(position, inventory, page)); + player.openInventory(menu); + } + + @Nonnull + @Override + public final ItemBuilder createSettingsItem() { + return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", isEnabled()); + for (Entry entry : settings.entrySet()) { + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().writeSettings(subDocument); + } + } + + @Override + public void loadSettings(@Nonnull Document document) { + setEnabled(document.getBoolean("enabled")); + for (Entry entry : settings.entrySet()) { + if (!document.contains(entry.getKey())) continue; + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().loadSettings(subDocument); + } + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + settings.values().forEach(SubSetting::restoreDefaults); + } + + public abstract class SubSetting implements Listener { + + private int page = -1, slot = -1; + + private void setPage(int page) { + this.page = page; + } + + private void setSlot(int slot) { + this.slot = slot; + } + + public final void updateItems() { + if (inventories.isEmpty()) return; // Menu not generated yet, nothing to update here + if (page == -1 || slot == -1) return; // Invalid slots, menu not generated yet + + Inventory inventory = inventories.get(page); + + inventory.setItem(slot, getDisplayItem().hideAttributes().build()); + inventory.setItem(slot + 9, buildSettingsItem()); + } + + @Nonnull + private ItemStack buildSettingsItem() { + ItemBuilder item = getSettingsItem(); + String[] description = getSettingsDescription(); + if (description != null && isEnabled()) { + item.appendLore(" "); + item.appendLore(description); + } + + return item.build(); + } + + @Nonnull + public abstract ItemBuilder getDisplayItem(); + + @Nonnull + public abstract ItemBuilder getSettingsItem(); + + @Nullable + protected abstract String[] getSettingsDescription(); + + public boolean isEnabled() { + return MenuSetting.this.isEnabled() && getAsBoolean(); + } + + public abstract int getAsInt(); + + public abstract boolean getAsBoolean(); + + public abstract void restoreDefaults(); + + public abstract void loadSettings(@Nonnull Document document); + + public abstract void writeSettings(@Nonnull Document document); + + public abstract void handleClick(@Nonnull ChallengeMenuClickInfo info); + + } + + public class BooleanSubSetting extends SubSetting { + + private final Supplier item; + private final Supplier description; + private final boolean enabledByDefault; + private boolean enabled; + + public BooleanSubSetting(@Nonnull Supplier item) { + this(item, () -> null); + } + + public BooleanSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + this(item, () -> null, enabledByDefault); + } + + public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description) { + this(item, description, false); + } + + public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description, boolean enabledByDefault) { + this.item = item; + this.description = description; + this.enabledByDefault = enabledByDefault; + this.setEnabled(enabledByDefault); + } - @Nonnull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } + @Nonnull + @Override + public ItemBuilder getDisplayItem() { + return item.get(); + } - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - return DefaultItem.status(enabled); - } + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + return DefaultItem.status(enabled); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.get(); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return description.get(); + } - @Override - public int getAsInt() { - return enabled ? 1 : 0; - } + @Override + public int getAsInt() { + return enabled ? 1 : 0; + } - @Override - public boolean getAsBoolean() { - return enabled; - } + @Override + public boolean getAsBoolean() { + return enabled; + } - @Override - public void restoreDefaults() { - this.setEnabled(enabledByDefault); - } + @Override + public void restoreDefaults() { + this.setEnabled(enabledByDefault); + } - @Nonnull - public BooleanSubSetting setEnabled(boolean enabled) { - if (this.enabled == enabled) return this; - this.enabled = enabled; + @Nonnull + public BooleanSubSetting setEnabled(boolean enabled) { + if (this.enabled == enabled) return this; + this.enabled = enabled; - if (enabled) this.onEnable(); - else this.onDisable(); + if (enabled) this.onEnable(); + else this.onDisable(); - this.updateItems(); - return this; - } + this.updateItems(); + return this; + } - @Override - public final void handleClick(@Nonnull ChallengeMenuClickInfo info) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } + @Override + public final void handleClick(@Nonnull ChallengeMenuClickInfo info) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } - @Override - public void loadSettings(@Nonnull Document document) { - this.setEnabled(document.getBoolean("enabled")); - } + @Override + public void loadSettings(@Nonnull Document document) { + this.setEnabled(document.getBoolean("enabled")); + } - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", enabled); - } + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", enabled); + } - protected void onEnable() { - } + protected void onEnable() { + } - protected void onDisable() { - } - - } - - public class NumberSubSetting extends SubSetting { - - private final Supplier item; - private final Function description; - private final Function name; - private final int max, min; - private final int defaultValue; - @Getter + protected void onDisable() { + } + + } + + public class NumberSubSetting extends SubSetting { + + private final Supplier item; + private final Function description; + private final Function name; + private final int max, min; + private final int defaultValue; + @Getter private int value; - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { - this(item, description, name, 64); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { - this(item, description, name, max, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { - this(item, description, name, min, max, min); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { - if (max <= min) throw new IllegalArgumentException("max <= min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.value = defaultValue; - this.defaultValue = defaultValue; - this.max = max; - this.min = min; - this.item = item; - this.description = description; - this.name = name; - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description) { - this(item, description, null, 64, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { - this(item, description, null, max, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { - this(item, description, null, min, max, min); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { - this(item, description, null, min, max, defaultValue); - } - - public NumberSubSetting(@Nonnull Supplier item) { - this(item, value -> null); - } - - public NumberSubSetting(@Nonnull Supplier item, int max) { - this(item, value -> null, max); - } - - public NumberSubSetting(@Nonnull Supplier item, int min, int max) { - this(item, value -> null, min, max); - } - - public NumberSubSetting(@Nonnull Supplier item, int min, int max, int defaultValue) { - this(item, value -> null, min, max, defaultValue); - } - - @Nonnull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } - - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - if (name != null) - return DefaultItem.create(Material.STONE_BUTTON, name.apply(getValue())).amount(getValue()); - - return DefaultItem.value(value); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.apply(getValue()); - } - - @Override - public void restoreDefaults() { - this.setValue(defaultValue); - } + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + this(item, description, name, 64); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + this(item, description, name, max, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + this(item, description, name, min, max, min); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + if (max <= min) throw new IllegalArgumentException("max <= min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.value = defaultValue; + this.defaultValue = defaultValue; + this.max = max; + this.min = min; + this.item = item; + this.description = description; + this.name = name; + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description) { + this(item, description, null, 64, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + this(item, description, null, max, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + this(item, description, null, min, max, min); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + this(item, description, null, min, max, defaultValue); + } + + public NumberSubSetting(@Nonnull Supplier item) { + this(item, value -> null); + } + + public NumberSubSetting(@Nonnull Supplier item, int max) { + this(item, value -> null, max); + } + + public NumberSubSetting(@Nonnull Supplier item, int min, int max) { + this(item, value -> null, min, max); + } + + public NumberSubSetting(@Nonnull Supplier item, int min, int max, int defaultValue) { + this(item, value -> null, min, max, defaultValue); + } + + @Nonnull + @Override + public ItemBuilder getDisplayItem() { + return item.get(); + } + + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + if (name != null) + return DefaultItem.create(Material.STONE_BUTTON, name.apply(getValue())).amount(getValue()); + + return DefaultItem.value(value); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return description.apply(getValue()); + } + + @Override + public void restoreDefaults() { + this.setValue(defaultValue); + } public void setValue(int value) { - if (this.value == value) return; - this.value = value; - - updateItems(); - onValueChange(); - } - - @Override - public int getAsInt() { - return value; - } - - @Override - public boolean getAsBoolean() { - return value > 0; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - int amount = info.isShiftClick() ? 10 : 1; - int newValue = value; - if (info.isRightClick()) { - newValue -= amount; - } else { - newValue += amount; - } - - if (newValue > max) - newValue = min; - if (newValue < min) - newValue = max; - - this.setValue(newValue); - SoundSample.CLICK.play(info.getPlayer()); - } - - @Override - public void loadSettings(@Nonnull Document document) { - this.setValue(document.getInt("value")); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } - - protected void onValueChange() { - } - - } - - public class NumberAndBooleanSubSetting extends NumberSubSetting { - - private final boolean enabledByDefault = false; // Implement in future - private boolean enabled; - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { - super(item, description, name); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { - super(item, description, name, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { - super(item, description, name, min, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { - super(item, description, name, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description) { - super(item, description); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { - super(item, description, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { - super(item, description, min, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { - super(item, description, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item) { - super(item); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int max) { - super(item, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int min, int max) { - super(item, min, max); - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - this.setEnabled(enabledByDefault); - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - if (enabled) this.onEnable(); - else this.onDisable(); - - this.updateItems(); - } - - @Override - public boolean getAsBoolean() { - return enabled; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } else { - super.handleClick(info); - } - } - - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - this.setEnabled(document.getBoolean("enabled")); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - } - - private final class SettingMenuPosition implements MenuPosition { - - private final MenuPosition before; - private final Inventory inventoryBefore; - private final int page; - - public SettingMenuPosition(@Nonnull MenuPosition before, @Nonnull Inventory inventoryBefore, int page) { - this.before = before; - this.inventoryBefore = inventoryBefore; - this.page = page; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { - if (page == 0) { - MenuPosition.set(info.getPlayer(), before); - info.getPlayer().openInventory(inventoryBefore); - } else { - open(info.getPlayer(), inventoryBefore, before, page - 1); - } - SoundSample.CLICK.play(info.getPlayer()); - return; - } else if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[1]) { - open(info.getPlayer(), inventoryBefore, before, page + 1); - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - for (SubSetting setting : settings.values()) { - if (setting.page != page) continue; - if (info.getSlot() != setting.slot && info.getSlot() != setting.slot + 9) continue; - - setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == setting.slot)); - return; - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - } + if (this.value == value) return; + this.value = value; + + updateItems(); + onValueChange(); + } + + @Override + public int getAsInt() { + return value; + } + + @Override + public boolean getAsBoolean() { + return value > 0; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + int amount = info.isShiftClick() ? 10 : 1; + int newValue = value; + if (info.isRightClick()) { + newValue -= amount; + } else { + newValue += amount; + } + + if (newValue > max) + newValue = min; + if (newValue < min) + newValue = max; + + this.setValue(newValue); + SoundSample.CLICK.play(info.getPlayer()); + } + + @Override + public void loadSettings(@Nonnull Document document) { + this.setValue(document.getInt("value")); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } + + protected void onValueChange() { + } + + } + + public class NumberAndBooleanSubSetting extends NumberSubSetting { + + private final boolean enabledByDefault = false; // Implement in future + private boolean enabled; + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + super(item, description, name); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + super(item, description, name, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + super(item, description, name, min, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + super(item, description, name, min, max, defaultValue); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description) { + super(item, description); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + super(item, description, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + super(item, description, min, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + super(item, description, min, max, defaultValue); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item) { + super(item); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, int max) { + super(item, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, int min, int max) { + super(item, min, max); + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + this.setEnabled(enabledByDefault); + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + if (enabled) this.onEnable(); + else this.onDisable(); + + this.updateItems(); + } + + @Override + public boolean getAsBoolean() { + return enabled; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } else { + super.handleClick(info); + } + } + + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + this.setEnabled(document.getBoolean("enabled")); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + } + + private final class SettingMenuPosition implements MenuPosition { + + private final MenuPosition before; + private final Inventory inventoryBefore; + private final int page; + + public SettingMenuPosition(@Nonnull MenuPosition before, @Nonnull Inventory inventoryBefore, int page) { + this.before = before; + this.inventoryBefore = inventoryBefore; + this.page = page; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { + if (page == 0) { + MenuPosition.set(info.getPlayer(), before); + info.getPlayer().openInventory(inventoryBefore); + } else { + open(info.getPlayer(), inventoryBefore, before, page - 1); + } + SoundSample.CLICK.play(info.getPlayer()); + return; + } else if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[1]) { + open(info.getPlayer(), inventoryBefore, before, page + 1); + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + for (SubSetting setting : settings.values()) { + if (setting.page != page) continue; + if (info.getSlot() != setting.slot && info.getSlot() != setting.slot + 9) continue; + + setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == setting.slot)); + return; + } + + SoundSample.CLICK.play(info.getPlayer()); + + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index ccb223b00..e6676859a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -12,110 +12,106 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public abstract class Modifier extends AbstractChallenge implements IModifier { - private final int max, min; - private final int defaultValue; - private int value; - - public Modifier(@Nonnull MenuType menu) { - this(menu, 64); - } - - public Modifier(@Nonnull MenuType menu, int max) { - this(menu, 1, max); - } - - public Modifier(@Nonnull MenuType menu, int min, int max) { - this(menu, min, max, min); - } - - public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu); - if (max < min) throw new IllegalArgumentException("max < min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.max = max; - this.min = min; - this.value = defaultValue; - this.defaultValue = defaultValue; - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(value); - } - - @Override - public void restoreDefaults() { - setValue(defaultValue); - } - - @Override - @Nonnegative - public final int getValue() { - return value; - } - - @Override - public void setValue(int value) { - if (value > max) throw new IllegalArgumentException("value > max"); - if (value < min) throw new IllegalArgumentException("value < min"); - this.value = value; - - try { - if (isEnabled()) onValueChange(); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); - } - - updateItems(); - } - - @Override - @Nonnegative - public final int getMaxValue() { - return max; - } - - @Override - @Nonnegative - public final int getMinValue() { - return min; - } - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - ChallengeHelper.handleModifierClick(info, this); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this); - } - - protected void onValueChange() { - } - - @Override - public void loadSettings(@Nonnull Document document) { - setValue(document.getInt("value", value)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } + private final int max, min; + private final int defaultValue; + private int value; + + public Modifier(@Nonnull MenuType menu) { + this(menu, 64); + } + + public Modifier(@Nonnull MenuType menu, int max) { + this(menu, 1, max); + } + + public Modifier(@Nonnull MenuType menu, int min, int max) { + this(menu, min, max, min); + } + + public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu); + if (max < min) throw new IllegalArgumentException("max < min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.max = max; + this.min = min; + this.value = defaultValue; + this.defaultValue = defaultValue; + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(value); + } + + @Override + public void restoreDefaults() { + setValue(defaultValue); + } + + @Override + @Nonnegative + public final int getValue() { + return value; + } + + @Override + public void setValue(int value) { + if (value > max) throw new IllegalArgumentException("value > max"); + if (value < min) throw new IllegalArgumentException("value < min"); + this.value = value; + + try { + if (isEnabled()) onValueChange(); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); + } + + updateItems(); + } + + @Override + @Nonnegative + public final int getMaxValue() { + return max; + } + + @Override + @Nonnegative + public final int getMinValue() { + return min; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + ChallengeHelper.handleModifierClick(info, this); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this); + } + + protected void onValueChange() { + } + + @Override + public void loadSettings(@Nonnull Document document) { + setValue(document.getInt("value", value)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 6d5bd4ffd..c656d0ff7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; @@ -9,113 +8,96 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class ModifierCollectionGoal extends CollectionGoal implements IModifier { - private final int max, min; - private final int defaultValue; - private int value; - - public ModifierCollectionGoal(int min, int max, @Nonnull Object[] target) { - this(min, max, min, target); - } - - public ModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object[] target) { - super(target); - if (max < min) throw new IllegalArgumentException("max < min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.max = max; - this.min = min; - this.value = defaultValue; - this.defaultValue = defaultValue; - } - - @Override - public void restoreDefaults() { - setValue(defaultValue); - } - - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - ChallengeHelper.handleModifierClick(info, this); - } - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } - - @Override - @Nonnegative - public final int getValue() { - return value; - } - - @Override - public void setValue(int value) { - if (value > max) throw new IllegalArgumentException("value > max"); - if (value < min) throw new IllegalArgumentException("value < min"); - this.value = value; - - if (isEnabled()) onValueChange(); - - updateItems(); - } - - @Override - @Nonnegative - public final int getMaxValue() { - return max; - } - - @Override - @Nonnegative - public final int getMinValue() { - return min; - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, this); - } - - protected void onValueChange() { - } - - @Override - public void loadSettings(@Nonnull Document document) { - setValue(document.getInt("value", value)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } - -} \ No newline at end of file + private final int max, min; + private final int defaultValue; + private int value; + + public ModifierCollectionGoal(int min, int max, @Nonnull Object[] target) { + this(min, max, min, target); + } + + public ModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object[] target) { + super(target); + if (max < min) throw new IllegalArgumentException("max < min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.max = max; + this.min = min; + this.value = defaultValue; + this.defaultValue = defaultValue; + } + + @Override + public void restoreDefaults() { + setValue(defaultValue); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + ChallengeHelper.handleModifierClick(info, this); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } + + @Override + @Nonnegative + public final int getValue() { + return value; + } + + @Override + public void setValue(int value) { + if (value > max) throw new IllegalArgumentException("value > max"); + if (value < min) throw new IllegalArgumentException("value < min"); + this.value = value; + + if (isEnabled()) onValueChange(); + + updateItems(); + } + + @Override + @Nonnegative + public final int getMaxValue() { + return max; + } + + @Override + @Nonnegative + public final int getMinValue() { + return min; + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, this); + } + + protected void onValueChange() { + } + + @Override + public void loadSettings(@Nonnull Document document) { + setValue(document.getInt("value", value)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 79303c354..5fc09751b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -18,186 +18,181 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { - private static final String id = "netherportal_handle"; - - private final Map netherPortalsByOverworldPortals = new HashMap<>(); - private final StructureType structureType; - private final Collection groundMaterial; - private final String unableToFindMessage; - - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { - super(menu, id); - this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; - this.groundMaterial = Arrays.asList(groundMaterial); - } - - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection groundMaterial) { - super(menu, id); - this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; - this.groundMaterial = groundMaterial; - } - - @EventHandler - public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { - if (!isEnabled()) return; - if (event.getCause() != TeleportCause.NETHER_PORTAL) return; - if (event.getTo() == null) return; - if (event.getTo().getWorld() == null) return; - - if (event.getTo().getWorld().getEnvironment() == Environment.NETHER) { - - World world = event.getTo().getWorld(); - Location location = getNetherPortal(event.getFrom(), world); - if (location == null) { - Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); - return; - } - - buildPortal(location); - event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal - - } else if (event.getTo().getWorld().getEnvironment() == Environment.NORMAL) { - Location location = getOverworldPortal(event.getFrom()); - if (location == null) return; - event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal - } - } - - @Nullable - private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { - - // Look if the current portal was used before - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (overworldPortal.distance(entry.getKey()) < 10) - return entry.getValue(); - } - - // Find next structure - Location structure = nether.locateNearestStructure(new Location(nether, 0, 100, 0), structureType, 10000, false); - if (structure == null) return null; - - // Look if there's already a portal to this structure - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (structure.distance(entry.getValue()) < 100) - return entry.getValue(); - } - - Location target = findNearestStructurePart(structure.clone()); - netherPortalsByOverworldPortals.put(overworldPortal, target); - return target; - - } - - @Nullable - private Location getOverworldPortal(@Nonnull Location netherPortal) { - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (netherPortal.distance(entry.getValue()) < 100) - return entry.getKey(); - } - return null; - } - - - @Nullable - private Location findNearestStructurePart(@Nonnull Location structure) { - - Chunk chunk = structure.getChunk(); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - - Location location = chunk.getBlock(x, 100, z).getLocation(); // Structures wont be above y=100 - while (location.getBlockY() > 30) { // Structures wont be below y=30 - location.subtract(0, 1, 0); - if (groundMaterial.contains(location.getBlock().getType())) - return location.add(0, 1, 0); - } - - } - } - - return null; - - } - - private void buildPortal(@Nonnull Location origin) { - - // Floor - origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(0, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(1, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, -1, 0).getBlock().setType(Material.OBSIDIAN); - - // Above - origin.clone().add(-1, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(0, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(1, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 3, 0).getBlock().setType(Material.OBSIDIAN); - - // Wall left - origin.clone().add(-1, 0, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(-1, 1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(-1, 2, 0).getBlock().setType(Material.OBSIDIAN); - - // Wall right - origin.clone().add(2, 0, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 2, 0).getBlock().setType(Material.OBSIDIAN); - - // Fill portal - origin.clone().add(0, 0, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 0, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(0, 1, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 1, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(0, 2, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 2, 0).getBlock().setType(Material.NETHER_PORTAL); - - // Free some place around - for (int x = -1; x <= 2; x++) { - for (int y = 0; y <= 3; y++) { - origin.clone().add(x, y, 1).getBlock().setType(Material.AIR); - origin.clone().add(x, y, 2).getBlock().setType(Material.AIR); - origin.clone().add(x, y, -1).getBlock().setType(Material.AIR); - origin.clone().add(x, y, -2).getBlock().setType(Material.AIR); - } - } - - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - Document portals = document.getDocument("portals"); - for (String key : portals.keys()) { - Document portal = portals.getDocument(key); - Location from = portal.getSerializable("portal", Location.class); - Location to = portal.getSerializable("target", Location.class); - - if (from == null || to == null) continue; - netherPortalsByOverworldPortals.put(from, to); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - int index = 0; - Document portals = document.getDocument("portals"); - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - Document portal = portals.getDocument(String.valueOf(index)); - portal.set("portal", entry.getKey()); - portal.set("target", entry.getValue()); - } - } - -} \ No newline at end of file + private static final String id = "netherportal_handle"; + + private final Map netherPortalsByOverworldPortals = new HashMap<>(); + private final StructureType structureType; + private final Collection groundMaterial; + private final String unableToFindMessage; + + public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { + super(menu, id); + this.structureType = structureType; + this.unableToFindMessage = unableToFindMessage; + this.groundMaterial = Arrays.asList(groundMaterial); + } + + public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection groundMaterial) { + super(menu, id); + this.structureType = structureType; + this.unableToFindMessage = unableToFindMessage; + this.groundMaterial = groundMaterial; + } + + @EventHandler + public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { + if (!isEnabled()) return; + if (event.getCause() != TeleportCause.NETHER_PORTAL) return; + if (event.getTo() == null) return; + if (event.getTo().getWorld() == null) return; + + if (event.getTo().getWorld().getEnvironment() == Environment.NETHER) { + + World world = event.getTo().getWorld(); + Location location = getNetherPortal(event.getFrom(), world); + if (location == null) { + Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); + return; + } + + buildPortal(location); + event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal + + } else if (event.getTo().getWorld().getEnvironment() == Environment.NORMAL) { + Location location = getOverworldPortal(event.getFrom()); + if (location == null) return; + event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal + } + } + + @Nullable + private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { + + // Look if the current portal was used before + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (overworldPortal.distance(entry.getKey()) < 10) + return entry.getValue(); + } + + // Find next structure + Location structure = nether.locateNearestStructure(new Location(nether, 0, 100, 0), structureType, 10000, false); + if (structure == null) return null; + + // Look if there's already a portal to this structure + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (structure.distance(entry.getValue()) < 100) + return entry.getValue(); + } + + Location target = findNearestStructurePart(structure.clone()); + netherPortalsByOverworldPortals.put(overworldPortal, target); + return target; + + } + + @Nullable + private Location getOverworldPortal(@Nonnull Location netherPortal) { + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (netherPortal.distance(entry.getValue()) < 100) + return entry.getKey(); + } + return null; + } + + + @Nullable + private Location findNearestStructurePart(@Nonnull Location structure) { + + Chunk chunk = structure.getChunk(); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + + Location location = chunk.getBlock(x, 100, z).getLocation(); // Structures wont be above y=100 + while (location.getBlockY() > 30) { // Structures wont be below y=30 + location.subtract(0, 1, 0); + if (groundMaterial.contains(location.getBlock().getType())) + return location.add(0, 1, 0); + } + + } + } + + return null; + + } + + private void buildPortal(@Nonnull Location origin) { + + // Floor + origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(0, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(1, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, -1, 0).getBlock().setType(Material.OBSIDIAN); + + // Above + origin.clone().add(-1, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(0, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(1, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 3, 0).getBlock().setType(Material.OBSIDIAN); + + // Wall left + origin.clone().add(-1, 0, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(-1, 1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(-1, 2, 0).getBlock().setType(Material.OBSIDIAN); + + // Wall right + origin.clone().add(2, 0, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 2, 0).getBlock().setType(Material.OBSIDIAN); + + // Fill portal + origin.clone().add(0, 0, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 0, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(0, 1, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 1, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(0, 2, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 2, 0).getBlock().setType(Material.NETHER_PORTAL); + + // Free some place around + for (int x = -1; x <= 2; x++) { + for (int y = 0; y <= 3; y++) { + origin.clone().add(x, y, 1).getBlock().setType(Material.AIR); + origin.clone().add(x, y, 2).getBlock().setType(Material.AIR); + origin.clone().add(x, y, -1).getBlock().setType(Material.AIR); + origin.clone().add(x, y, -2).getBlock().setType(Material.AIR); + } + } + + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + Document portals = document.getDocument("portals"); + for (String key : portals.keys()) { + Document portal = portals.getDocument(key); + Location from = portal.getSerializable("portal", Location.class); + Location to = portal.getSerializable("target", Location.class); + + if (from == null || to == null) continue; + netherPortalsByOverworldPortals.put(from, to); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + int index = 0; + Document portals = document.getDocument("portals"); + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + Document portal = portals.getDocument(String.valueOf(index)); + portal.set("portal", entry.getKey()); + portal.set("target", entry.getValue()); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index f8a0e3117..9bf18459d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -5,38 +5,34 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class OneEnabledSetting extends Setting { - private final String typeId; - - public OneEnabledSetting(@Nonnull MenuType menu, @Nonnull String typeId) { - super(menu); - this.typeId = typeId; - } - - public OneEnabledSetting(@Nonnull MenuType menu, boolean enabledByDefault, @Nonnull String typeId) { - super(menu, enabledByDefault); - this.typeId = typeId; - } - - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - if (isEnabled()) disableOthers(); - } - - protected final void disableOthers() { - Challenges.getInstance().getChallengeManager().getChallenges().stream() - .filter(challenge -> challenge != this) - .filter(challenge -> challenge instanceof OneEnabledSetting) - .map(challenge -> (OneEnabledSetting) challenge) - .filter(setting -> setting.typeId.equals(typeId)) - .forEach(setting -> setting.setEnabled(false)); - } + private final String typeId; + + public OneEnabledSetting(@Nonnull MenuType menu, @Nonnull String typeId) { + super(menu); + this.typeId = typeId; + } + + public OneEnabledSetting(@Nonnull MenuType menu, boolean enabledByDefault, @Nonnull String typeId) { + super(menu, enabledByDefault); + this.typeId = typeId; + } + + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (isEnabled()) disableOthers(); + } + + protected final void disableOthers() { + Challenges.getInstance().getChallengeManager().getChallenges().stream() + .filter(challenge -> challenge != this) + .filter(challenge -> challenge instanceof OneEnabledSetting) + .map(challenge -> (OneEnabledSetting) challenge) + .filter(setting -> setting.typeId.equals(typeId)) + .forEach(setting -> setting.setEnabled(false)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index b9b21cf94..58a57c890 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import org.bukkit.entity.Player; @@ -13,98 +13,94 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class PointsGoal extends SettingGoal { - private final Map points = new HashMap<>(); - - public PointsGoal() { - super(); - } - - public PointsGoal(boolean enabledByDefault) { - super(enabledByDefault); - } - - @Override - protected void onEnable() { - super.onEnable(); - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); - scoreboard.show(); - } - - @Override - protected void onDisable() { - super.onDisable(); - scoreboard.hide(); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - Document scores = document.getDocument("scores"); - for (String key : scores.keys()) { - try { - UUID uuid = UUID.fromString(key); - int value = scores.getInt(key); - points.put(uuid, value); - } catch (Exception ex) { - Logger.error("Could not load scores for {}", key); - } - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - Document scores = document.getDocument("scores"); - points.forEach((uuid, points) -> scores.set(uuid.toString(), points)); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); - } - - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); - } - - protected void collect(@Nonnull Player player) { - collect(player, 1); - } - - protected void collect(@Nonnull Player player, int amount) { - points.compute(player.getUniqueId(), (uuid, points) -> points == null ? amount : points + amount); - scoreboard.update(); - } - - protected void setPoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, amount); - scoreboard.update(); - } - - protected void addPoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, getPoints(uuid) + amount); - scoreboard.update(); - } - - protected void removePoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, getPoints(uuid) - amount); - scoreboard.update(); - } - - @CheckReturnValue - protected int getPoints(@Nonnull UUID uuid) { - Integer points = this.points.get(uuid); - return points == null ? 0 : points; - } + private final Map points = new HashMap<>(); + + public PointsGoal() { + super(); + } + + public PointsGoal(boolean enabledByDefault) { + super(enabledByDefault); + } + + @Override + protected void onEnable() { + super.onEnable(); + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); + scoreboard.show(); + } + + @Override + protected void onDisable() { + super.onDisable(); + scoreboard.hide(); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + Document scores = document.getDocument("scores"); + for (String key : scores.keys()) { + try { + UUID uuid = UUID.fromString(key); + int value = scores.getInt(key); + points.put(uuid, value); + } catch (Exception ex) { + Logger.error("Could not load scores for {}", key); + } + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + Document scores = document.getDocument("scores"); + points.forEach((uuid, points) -> scores.set(uuid.toString(), points)); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); + } + + @Nonnull + @CheckReturnValue + protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); + } + + protected void collect(@Nonnull Player player) { + collect(player, 1); + } + + protected void collect(@Nonnull Player player, int amount) { + points.compute(player.getUniqueId(), (uuid, points) -> points == null ? amount : points + amount); + scoreboard.update(); + } + + protected void setPoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, amount); + scoreboard.update(); + } + + protected void addPoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, getPoints(uuid) + amount); + scoreboard.update(); + } + + protected void removePoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, getPoints(uuid) - amount); + scoreboard.update(); + } + + @CheckReturnValue + protected int getPoints(@Nonnull UUID uuid) { + Integer points = this.points.get(uuid); + return points == null ? 0 : points; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index 332a9eb59..29a6f6e87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -1,65 +1,61 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class RandomizerSetting extends Setting { - protected IRandom random = IRandom.create(); - - public RandomizerSetting(@Nonnull MenuType menu) { - super(menu); - setCategory(SettingCategory.RANDOMIZER); - } - - public RandomizerSetting(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); - setCategory(SettingCategory.RANDOMIZER); - } - - protected abstract void reloadRandomization(); - - protected int getMatches(int pairs, int matchesRemaining) { - if ((pairs * 3) <= matchesRemaining - 3) return 3; - if ((pairs * 2) <= matchesRemaining - 2) return 2; - return 1; - } - - @Override - protected void onEnable() { - reloadRandomization(); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - if (!document.contains("seed")) { - random = new SeededRandomWrapper(); - return; - } - - long seed = document.getLong("seed"); - if (seed == random.getSeed()) return; - - random = IRandom.create(seed); - - if (!isEnabled()) return; - reloadRandomization(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("seed", random.getSeed()); - } + protected IRandom random = IRandom.create(); + + public RandomizerSetting(@Nonnull MenuType menu) { + super(menu); + setCategory(SettingCategory.RANDOMIZER); + } + + public RandomizerSetting(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu, enabledByDefault); + setCategory(SettingCategory.RANDOMIZER); + } + + protected abstract void reloadRandomization(); + + protected int getMatches(int pairs, int matchesRemaining) { + if ((pairs * 3) <= matchesRemaining - 3) return 3; + if ((pairs * 2) <= matchesRemaining - 2) return 2; + return 1; + } + + @Override + protected void onEnable() { + reloadRandomization(); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + if (!document.contains("seed")) { + random = new SeededRandomWrapper(); + return; + } + + long seed = document.getLong("seed"); + if (seed == random.getSeed()) return; + + random = IRandom.create(seed); + + if (!isEnabled()) return; + reloadRandomization(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("seed", random.getSeed()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 0662c6c36..3539e476a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,89 +11,85 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public abstract class Setting extends AbstractChallenge { - private final boolean enabledByDefault; - protected boolean enabled; - - public Setting(@Nonnull MenuType menu) { - this(menu, false); - } - - public Setting(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu); - this.enabledByDefault = enabledByDefault; - setEnabled(enabledByDefault); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } - - @Override - public void restoreDefaults() { - setEnabled(enabledByDefault); - } - - public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.status(enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - @Override - public void handleShutdown() { - super.handleShutdown(); - - if (isEnabled()) - onDisable(); - } - - @Override - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - try { - if (enabled) onEnable(); - else onDisable(); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); - } - - updateItems(); - } - - @Override - public void loadSettings(@Nonnull Document document) { - setEnabled(document.getBoolean("enabled", enabled)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", enabled); - } + private final boolean enabledByDefault; + protected boolean enabled; + + public Setting(@Nonnull MenuType menu) { + this(menu, false); + } + + public Setting(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu); + this.enabledByDefault = enabledByDefault; + setEnabled(enabledByDefault); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } + + @Override + public void restoreDefaults() { + setEnabled(enabledByDefault); + } + + public void playStatusUpdateTitle() { + ChallengeHelper.playToggleChallengeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.status(enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + @Override + public void handleShutdown() { + super.handleShutdown(); + + if (isEnabled()) + onDisable(); + } + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + try { + if (enabled) onEnable(); + else onDisable(); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); + } + + updateItems(); + } + + @Override + public void loadSettings(@Nonnull Document document) { + setEnabled(document.getBoolean("enabled", enabled)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", enabled); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 1893f2868..92721607a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -8,36 +8,32 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingGoal extends Setting implements IGoal { - public SettingGoal() { - super(MenuType.GOAL); - } - - public SettingGoal(boolean enabledByDefault) { - super(MenuType.GOAL, enabledByDefault); - } - - @Nonnull - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override - public void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } + public SettingGoal() { + super(MenuType.GOAL); + } + + public SettingGoal(boolean enabledByDefault) { + super(MenuType.GOAL, enabledByDefault); + } + + @Nonnull + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } + + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } + + @Override + public void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 3e9195f2a..7d407578f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; @@ -11,100 +11,96 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingModifier extends Modifier { - private boolean enabled; - - public SettingModifier(@Nonnull MenuType menu) { - super(menu); - } - - public SettingModifier(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public SettingModifier(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public SettingModifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - setEnabled(false); - } - - @Nonnull - @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); - } - - @Override - public final boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - if (enabled) onEnable(); - else onDisable(); - - updateItems(); - } - - public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - @Override - public void handleShutdown() { - super.handleShutdown(); - onDisable(); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } - - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - setEnabled(document.getBoolean("enabled")); - } + private boolean enabled; + + public SettingModifier(@Nonnull MenuType menu) { + super(menu); + } + + public SettingModifier(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public SettingModifier(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public SettingModifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + setEnabled(false); + } + + @Nonnull + @Override + public ItemStack getSettingsItem() { + return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.enabled().amount(getValue()); + } + + @Override + public final boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + if (enabled) onEnable(); + else onDisable(); + + updateItems(); + } + + public void playStatusUpdateTitle() { + ChallengeHelper.playToggleChallengeTitle(this); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + @Override + public void handleShutdown() { + super.handleShutdown(); + onDisable(); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } + + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + setEnabled(document.getBoolean("enabled")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index ae202aa1e..75f07e057 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; @@ -9,71 +9,67 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public abstract class SettingModifierCollectionGoal extends ModifierCollectionGoal { - public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { - super(min, max, target); - } + public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { + super(min, max, target); + } - public SettingModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object... target) { - super(min, max, defaultValue, target); - } + public SettingModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object... target) { + super(min, max, defaultValue, target); + } - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } - @Override - public void restoreDefaults() { - super.restoreDefaults(); - setEnabled(false); - } + @Override + public void restoreDefaults() { + super.restoreDefaults(); + setEnabled(false); + } - @Nonnull - @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } + @Nonnull + @Override + public ItemStack getSettingsItem() { + return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.enabled().amount(getValue()); + } - @Override - public void handleShutdown() { - super.handleShutdown(); - onDisable(); - } + @Override + public void handleShutdown() { + super.handleShutdown(); + onDisable(); + } - @Override - public boolean isEnabled() { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - setEnabled(document.getBoolean("enabled")); - } + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + setEnabled(document.getBoolean("enabled")); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 15e6aa98e..aab2ddca6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; @@ -10,56 +10,52 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingModifierGoal extends SettingModifier implements IGoal { - public SettingModifierGoal(@Nonnull MenuType menu) { - super(menu); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - public final void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } - - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isLowerItemClick() && isEnabled()) { - ChallengeHelper.handleModifierClick(info, this); - } else { - setEnabled(!isEnabled()); - SoundSample.playStatusSound(info.getPlayer(), isEnabled()); - playStatusUpdateTitle(); - } - } + public SettingModifierGoal(@Nonnull MenuType menu) { + super(menu); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + public final void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } + + @Nonnull + @Override + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } + + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isLowerItemClick() && isEnabled()) { + ChallengeHelper.handleModifierClick(info, this); + } else { + setEnabled(!isEnabled()); + SoundSample.playStatusSound(info.getPlayer(), isEnabled()); + playStatusUpdateTitle(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 7ad17ae2b..a4255303a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import org.bukkit.Bukkit; @@ -11,162 +11,158 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class TimedChallenge extends SettingModifier { - private final boolean runAsync; - @Setter + private final boolean runAsync; + @Setter protected int secondsUntilActivation; - private int originalSecondsUntilActivation; - private boolean timerStatus = false; - private boolean startedBefore = false; - - public TimedChallenge(@Nonnull MenuType menu) { - this(menu, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int max) { - this(menu, max, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max) { - this(menu, min, max, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - this(menu, min, max, defaultValue, true); - } - - public TimedChallenge(@Nonnull MenuType menu, boolean runAsync) { - super(menu); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { - super(menu, max); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue); - this.runAsync = runAsync; - } - - @Override - public void setValue(int value) { - super.setValue(value); - if (!timerStatus) { - restartTimer(); - } - } - - // Don't execute async to prevent sync issues with timer - @ScheduledTask(ticks = 20, async = false) - public final void handleTimedChallengeSecond() { - - if (!startedBefore) - restartTimer(); - - if (timerStatus) { - - if (getTimerTrigger()) { - secondsUntilActivation--; - if (secondsUntilActivation <= 0) { - secondsUntilActivation = 0; - timerStatus = false; - executeTimeActivation(); - } else { - handleCountdown(); - } - } else { - Logger.debug("getTimerTrigger returned false for {}", this.getClass().getSimpleName()); - } - } - - } - - public final void executeTimeActivation() { - if (runAsync) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, this::onTimeActivation); - } else { - Bukkit.getScheduler().runTask(plugin, this::onTimeActivation); - } - } - - public final void shortCountDownTo(@Nonnegative int seconds) { - if (!timerStatus) throw new IllegalArgumentException("Countdown is not started"); - if (seconds > originalSecondsUntilActivation) - throw new IllegalArgumentException("Cannot short countdown to a higher length than originally set"); - this.secondsUntilActivation = seconds; - } - - public final boolean isTimerRunning() { - return timerStatus; - } - - public final int getSecondsLeftUntilNextActivation() { - return secondsUntilActivation; - } - - public final int getOriginalSecondsUntilActivation() { - return originalSecondsUntilActivation; - } - - protected float getProgress() { - return getOriginalSecondsUntilActivation() == 0 ? 1 : (float) (getSecondsLeftUntilNextActivation()) / getOriginalSecondsUntilActivation(); - } - - protected void handleCountdown() { - } - - protected boolean getTimerTrigger() { - return true; - } - - protected abstract int getSecondsUntilNextActivation(); + private int originalSecondsUntilActivation; + private boolean timerStatus = false; + private boolean startedBefore = false; + + public TimedChallenge(@Nonnull MenuType menu) { + this(menu, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int max) { + this(menu, max, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max) { + this(menu, min, max, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + this(menu, min, max, defaultValue, true); + } + + public TimedChallenge(@Nonnull MenuType menu, boolean runAsync) { + super(menu); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + super(menu, max); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + super(menu, min, max); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + super(menu, min, max, defaultValue); + this.runAsync = runAsync; + } + + @Override + public void setValue(int value) { + super.setValue(value); + if (!timerStatus) { + restartTimer(); + } + } + + // Don't execute async to prevent sync issues with timer + @ScheduledTask(ticks = 20, async = false) + public final void handleTimedChallengeSecond() { + + if (!startedBefore) + restartTimer(); + + if (timerStatus) { + + if (getTimerTrigger()) { + secondsUntilActivation--; + if (secondsUntilActivation <= 0) { + secondsUntilActivation = 0; + timerStatus = false; + executeTimeActivation(); + } else { + handleCountdown(); + } + } else { + Logger.debug("getTimerTrigger returned false for {}", this.getClass().getSimpleName()); + } + } + + } + + public final void executeTimeActivation() { + if (runAsync) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, this::onTimeActivation); + } else { + Bukkit.getScheduler().runTask(plugin, this::onTimeActivation); + } + } + + public final void shortCountDownTo(@Nonnegative int seconds) { + if (!timerStatus) throw new IllegalArgumentException("Countdown is not started"); + if (seconds > originalSecondsUntilActivation) + throw new IllegalArgumentException("Cannot short countdown to a higher length than originally set"); + this.secondsUntilActivation = seconds; + } + + public final boolean isTimerRunning() { + return timerStatus; + } + + public final int getSecondsLeftUntilNextActivation() { + return secondsUntilActivation; + } + + public final int getOriginalSecondsUntilActivation() { + return originalSecondsUntilActivation; + } + + protected float getProgress() { + return getOriginalSecondsUntilActivation() == 0 ? 1 : (float) (getSecondsLeftUntilNextActivation()) / getOriginalSecondsUntilActivation(); + } + + protected void handleCountdown() { + } + + protected boolean getTimerTrigger() { + return true; + } + + protected abstract int getSecondsUntilNextActivation(); protected void restartTimer(int seconds) { - Logger.debug("Restarting timer of {} with {} second(s)", this.getClass().getSimpleName(), seconds); - - startedBefore = true; - secondsUntilActivation = seconds; - originalSecondsUntilActivation = seconds; - timerStatus = true; - } - - protected void restartTimer() { - restartTimer(getSecondsUntilNextActivation()); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (document.isEmpty()) { - startedBefore = true; - timerStatus = true; - restartTimer(); - } else if (document.contains("time")) { - startedBefore = true; - timerStatus = true; - secondsUntilActivation = document.getInt("time"); - Logger.debug("Starting timer of {} from gamestate value with {} second(s)", this.getClass().getSimpleName(), secondsUntilActivation); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - if (secondsUntilActivation != originalSecondsUntilActivation) { - document.set("time", secondsUntilActivation); - } - } - - protected abstract void onTimeActivation(); + Logger.debug("Restarting timer of {} with {} second(s)", this.getClass().getSimpleName(), seconds); + + startedBefore = true; + secondsUntilActivation = seconds; + originalSecondsUntilActivation = seconds; + timerStatus = true; + } + + protected void restartTimer() { + restartTimer(getSecondsUntilNextActivation()); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (document.isEmpty()) { + startedBefore = true; + timerStatus = true; + restartTimer(); + } else if (document.contains("time")) { + startedBefore = true; + timerStatus = true; + secondsUntilActivation = document.getInt("time"); + Logger.debug("Starting timer of {} from gamestate value with {} second(s)", this.getClass().getSimpleName(), secondsUntilActivation); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + if (secondsUntilActivation != originalSecondsUntilActivation) { + document.set("time", secondsUntilActivation); + } + } + + protected abstract void onTimeActivation(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 2321efc47..6e57cc5c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -20,140 +20,136 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class WorldDependentChallenge extends TimedChallenge { - private boolean inExtraWorld; - private BiConsumer lastTeleport; - private int teleportIndex; - - public WorldDependentChallenge(@Nonnull MenuType menu) { - super(menu); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, boolean runAsync) { - super(menu, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { - super(menu, max, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue, runAsync); - } - - /** - * Prevents the activation of two world challenges at the same time - */ - @Override - protected final void onTimeActivation() { - if (ChallengeAPI.isWorldInUse()) { - restartTimer(1); - } else { - startWorldChallenge(); - } - } - - public abstract void startWorldChallenge(); - - @Override - protected boolean getTimerTrigger() { - return inExtraWorld || !Challenges.getInstance().getWorldManager().isWorldInUse(); - } - - protected void teleportToWorld(boolean allowJoinCatchUp, @Nonnull BiConsumer action) { - if (Challenges.getInstance().getWorldManager().isWorldInUse()) return; - Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = true); - lastTeleport = allowJoinCatchUp ? action : null; - - teleportIndex = 0; - broadcastFiltered(player -> teleport(player, action)); - broadcastIgnored(player -> { - teleport(player, null); - teleportSpectator(player); - }); - } - - protected void teleportBack() { - if (!Challenges.getInstance().getWorldManager().isWorldInUse()) return; - Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = false); - lastTeleport = null; - teleportIndex = 0; - } - - protected void teleportBack(@Nonnull Player player) { - Challenges.getInstance().getWorldManager().restorePlayerData(player); - } - - private void teleport(@Nonnull Player player, @Nullable BiConsumer teleport) { - player.getInventory().clear(); - player.setFoodLevel(20); - player.setSaturation(20); - player.setNoDamageTicks(10); - player.setFallDistance(0); - player.setHealth(player.getMaxHealth()); - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - if (teleport != null) { - player.setVelocity(new Vector()); - teleport.accept(player, teleportIndex++); - SoundSample.TELEPORT.play(player); - } - } - - protected void teleportSpectator(@Nonnull Player player) { - player.setGameMode(GameMode.SPECTATOR); - List ingamePlayers = ChallengeHelper.getIngamePlayers(); - if (ingamePlayers.isEmpty()) return; - Player target = ingamePlayers.get(0); - player.teleport(target); - player.setSpectatorTarget(target); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (isInExtraWorld()) { - if (lastTeleport == null) return; - if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; - teleport(event.getPlayer(), lastTeleport); - } else { - Challenges.getInstance().getWorldManager().restorePlayerData(event.getPlayer()); - } - } - - @Nonnull - protected final World getExtraWorld() { - return Challenges.getInstance().getWorldManager().getExtraWorld(); - } - - @Nonnull - protected final WorldSettings getExtraWorldSettings() { - return Challenges.getInstance().getWorldManager().getSettings(); - } - - public final boolean isInExtraWorld() { - return inExtraWorld; - } + private boolean inExtraWorld; + private BiConsumer lastTeleport; + private int teleportIndex; + + public WorldDependentChallenge(@Nonnull MenuType menu) { + super(menu); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, boolean runAsync) { + super(menu, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + super(menu, max, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + super(menu, min, max, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + super(menu, min, max, defaultValue, runAsync); + } + + /** + * Prevents the activation of two world challenges at the same time + */ + @Override + protected final void onTimeActivation() { + if (ChallengeAPI.isWorldInUse()) { + restartTimer(1); + } else { + startWorldChallenge(); + } + } + + public abstract void startWorldChallenge(); + + @Override + protected boolean getTimerTrigger() { + return inExtraWorld || !Challenges.getInstance().getWorldManager().isWorldInUse(); + } + + protected void teleportToWorld(boolean allowJoinCatchUp, @Nonnull BiConsumer action) { + if (Challenges.getInstance().getWorldManager().isWorldInUse()) return; + Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = true); + lastTeleport = allowJoinCatchUp ? action : null; + + teleportIndex = 0; + broadcastFiltered(player -> teleport(player, action)); + broadcastIgnored(player -> { + teleport(player, null); + teleportSpectator(player); + }); + } + + protected void teleportBack() { + if (!Challenges.getInstance().getWorldManager().isWorldInUse()) return; + Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = false); + lastTeleport = null; + teleportIndex = 0; + } + + protected void teleportBack(@Nonnull Player player) { + Challenges.getInstance().getWorldManager().restorePlayerData(player); + } + + private void teleport(@Nonnull Player player, @Nullable BiConsumer teleport) { + player.getInventory().clear(); + player.setFoodLevel(20); + player.setSaturation(20); + player.setNoDamageTicks(10); + player.setFallDistance(0); + player.setHealth(player.getMaxHealth()); + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + if (teleport != null) { + player.setVelocity(new Vector()); + teleport.accept(player, teleportIndex++); + SoundSample.TELEPORT.play(player); + } + } + + protected void teleportSpectator(@Nonnull Player player) { + player.setGameMode(GameMode.SPECTATOR); + List ingamePlayers = ChallengeHelper.getIngamePlayers(); + if (ingamePlayers.isEmpty()) return; + Player target = ingamePlayers.get(0); + player.teleport(target); + player.setSpectatorTarget(target); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (isInExtraWorld()) { + if (lastTeleport == null) return; + if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; + teleport(event.getPlayer(), lastTeleport); + } else { + Challenges.getInstance().getWorldManager().restorePlayerData(event.getPlayer()); + } + } + + @Nonnull + protected final World getExtraWorld() { + return Challenges.getInstance().getWorldManager().getExtraWorld(); + } + + @Nonnull + protected final WorldSettings getExtraWorldSettings() { + return Challenges.getInstance().getWorldManager().getSettings(); + } + + public final boolean isInExtraWorld() { + return inExtraWorld; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index 0aa14399a..cc59d1b49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -1,30 +1,26 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ChallengeConfigHelper { - private static final Document settingsDocument; + private static final Document settingsDocument; - static { - settingsDocument = Challenges.getInstance().getConfigDocument().getDocument("challenge-settings"); - } + static { + settingsDocument = Challenges.getInstance().getConfigDocument().getDocument("challenge-settings"); + } - private ChallengeConfigHelper() { - } + private ChallengeConfigHelper() { + } - @Nonnull - @CheckReturnValue - public static Document getSettingsDocument() { - return settingsDocument; - } + @Nonnull + @CheckReturnValue + public static Document getSettingsDocument() { + return settingsDocument; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index f25548b8e..7cfd70ce4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -34,189 +34,184 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ChallengeHelper { - @Getter + @Getter private static boolean inInstantKill = false; - private ChallengeHelper() { - } + private ChallengeHelper() { + } - public static void kill(@Nonnull Player player) { + public static void kill(@Nonnull Player player) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); - return; - } + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); + return; + } - inInstantKill = true; - player.damage(Integer.MAX_VALUE); - inInstantKill = false; - } + inInstantKill = true; + player.damage(Integer.MAX_VALUE); + inInstantKill = false; + } - public static void kill(@Nonnull Player player, int delay) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); - } + public static void kill(@Nonnull Player player, int delay) { + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); + } public static void updateItems(@Nonnull IChallenge challenge) { - challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); - } - - public static boolean canInstaKillOnEnable(@Nonnull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); - } - - public static boolean isExcludedFromRandomChallenges(@Nonnull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); - } - - public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IModifier modifier) { - int newValue = modifier.getValue(); - int amount = info.isShiftClick() - ? (modifier.getValue() == modifier.getMinValue() || info.isRightClick() && modifier.getValue() == (10 - (modifier.getMinValue() - 1)) ? 9 : 10) - : 1; - newValue += info.isRightClick() ? -amount : amount; - - if (newValue > modifier.getMaxValue()) - newValue = modifier.getMinValue(); - if (newValue < modifier.getMinValue()) - newValue = modifier.getMaxValue(); - - modifier.setValue(newValue); - modifier.playValueChangeTitle(); - SoundSample.CLICK.play(info.getPlayer()); - } - - @Nonnull - public static String getColoredChallengeName(@Nonnull AbstractChallenge challenge) { - ItemBuilder item = challenge.createDisplayItem(); - ItemDescription description = item.getBuiltByItemDescription(); - if (description == null) return Message.NULL; - return description.getOriginalName(); - } - - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool) { - breakBlock(block, tool, null); - } - - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { - - if (!ChallengeAPI.getDropChance(block.getType())) return; - boolean putIntoInventory = ChallengeAPI.getItemsDirectIntoInventory() && targetInventory != null; - - List customDrops = ChallengeAPI.getCustomDrops(block.getType()); - Location location = block.getLocation().clone().add(0.5, 0, 0.5); - if (!customDrops.isEmpty()) { - if (putIntoInventory) { - customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); - } else { - customDrops.forEach(drop -> block.getWorld().dropItem(location, new ItemStack(drop))); - } - block.setType(Material.AIR); - return; - } - - if (putIntoInventory) { - block.getDrops(tool).forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); - block.setType(Material.AIR); - return; - } - - block.breakNaturally(tool); - - } - - public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location dropLocation, @Nonnull Inventory inventory) { - boolean directIntoInventory = Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); - - if (directIntoInventory) { - InventoryUtils.dropOrGiveItem(inventory, dropLocation, itemStack); - return; - } - - if (dropLocation.getWorld() == null) return; - dropLocation.getWorld().dropItemNaturally(dropLocation, itemStack); - - } - - public static boolean ignoreDamager(@Nonnull Entity damager) { - Player damagerPlayer = getDamagerPlayer(damager); - if (damagerPlayer == null) return false; - return AbstractChallenge.ignorePlayer(damagerPlayer); - } - - public static Player getDamagerPlayer(@Nonnull Entity damager) { - if (damager instanceof Player) return ((Player) damager); - if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) - return ((Player) ((Projectile) damager).getShooter()); - return null; - } - - public static List getIngamePlayers() { - return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); - } - - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge) { - playToggleChallengeTitle(challenge, challenge.isEnabled()); - } - - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge, boolean enabled) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); - } - - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge challenge, @Nonnull IModifier modifier) { - playChangeChallengeValueTitle(challenge, modifier.getValue()); - } - - public static void playChangeChallengeValueTitle(@Nonnull Modifier modifier) { - playChangeChallengeValueTitle(modifier, modifier.getValue()); - } - - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge modifier, @Nullable Object value) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); - } - - public static void playChallengeHeartsValueChangeTitle(@Nonnull AbstractChallenge challenge, int health) { - playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); - } - - public static void playChallengeHeartsValueChangeTitle(@Nonnull Modifier modifier) { - playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); - } - - public static void playChallengeSecondsValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); - } - - public static void playChallengeSecondsRangeValueChangeTitle(@Nonnull AbstractChallenge challenge, int min, int max) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); - } - - public static void playChallengeMinutesValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); - } - - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int multiplier, @Nonnegative int range) { - return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); - } - - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int range) { - return getTimeRangeSettingsDescription(modifier, 1, range); - } - - public static boolean finalDamageIsNull(@Nonnull EntityDamageEvent event) { - return getFinalDamage(event) == 0; - } - - public static double getFinalDamage(@Nonnull EntityDamageEvent event) { - return event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); - } + challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); + } + + public static boolean canInstaKillOnEnable(@Nonnull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); + } + + public static boolean isExcludedFromRandomChallenges(@Nonnull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); + } + + public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IModifier modifier) { + int newValue = modifier.getValue(); + int amount = info.isShiftClick() + ? (modifier.getValue() == modifier.getMinValue() || info.isRightClick() && modifier.getValue() == (10 - (modifier.getMinValue() - 1)) ? 9 : 10) + : 1; + newValue += info.isRightClick() ? -amount : amount; + + if (newValue > modifier.getMaxValue()) + newValue = modifier.getMinValue(); + if (newValue < modifier.getMinValue()) + newValue = modifier.getMaxValue(); + + modifier.setValue(newValue); + modifier.playValueChangeTitle(); + SoundSample.CLICK.play(info.getPlayer()); + } + + @Nonnull + public static String getColoredChallengeName(@Nonnull AbstractChallenge challenge) { + ItemBuilder item = challenge.createDisplayItem(); + ItemDescription description = item.getBuiltByItemDescription(); + if (description == null) return Message.NULL; + return description.getOriginalName(); + } + + public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool) { + breakBlock(block, tool, null); + } + + public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { + + if (!ChallengeAPI.getDropChance(block.getType())) return; + boolean putIntoInventory = ChallengeAPI.getItemsDirectIntoInventory() && targetInventory != null; + + List customDrops = ChallengeAPI.getCustomDrops(block.getType()); + Location location = block.getLocation().clone().add(0.5, 0, 0.5); + if (!customDrops.isEmpty()) { + if (putIntoInventory) { + customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); + } else { + customDrops.forEach(drop -> block.getWorld().dropItem(location, new ItemStack(drop))); + } + block.setType(Material.AIR); + return; + } + + if (putIntoInventory) { + block.getDrops(tool).forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); + block.setType(Material.AIR); + return; + } + + block.breakNaturally(tool); + + } + + public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location dropLocation, @Nonnull Inventory inventory) { + boolean directIntoInventory = Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); + + if (directIntoInventory) { + InventoryUtils.dropOrGiveItem(inventory, dropLocation, itemStack); + return; + } + + if (dropLocation.getWorld() == null) return; + dropLocation.getWorld().dropItemNaturally(dropLocation, itemStack); + + } + + public static boolean ignoreDamager(@Nonnull Entity damager) { + Player damagerPlayer = getDamagerPlayer(damager); + if (damagerPlayer == null) return false; + return AbstractChallenge.ignorePlayer(damagerPlayer); + } + + public static Player getDamagerPlayer(@Nonnull Entity damager) { + if (damager instanceof Player) return ((Player) damager); + if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) + return ((Player) ((Projectile) damager).getShooter()); + return null; + } + + public static List getIngamePlayers() { + return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); + } + + public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge) { + playToggleChallengeTitle(challenge, challenge.isEnabled()); + } + + public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge, boolean enabled) { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); + } + + public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge challenge, @Nonnull IModifier modifier) { + playChangeChallengeValueTitle(challenge, modifier.getValue()); + } + + public static void playChangeChallengeValueTitle(@Nonnull Modifier modifier) { + playChangeChallengeValueTitle(modifier, modifier.getValue()); + } + + public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge modifier, @Nullable Object value) { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); + } + + public static void playChallengeHeartsValueChangeTitle(@Nonnull AbstractChallenge challenge, int health) { + playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); + } + + public static void playChallengeHeartsValueChangeTitle(@Nonnull Modifier modifier) { + playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); + } + + public static void playChallengeSecondsValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); + } + + public static void playChallengeSecondsRangeValueChangeTitle(@Nonnull AbstractChallenge challenge, int min, int max) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); + } + + public static void playChallengeMinutesValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); + } + + @Nonnull + public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int multiplier, @Nonnegative int range) { + return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); + } + + @Nonnull + public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int range) { + return getTimeRangeSettingsDescription(modifier, 1, range); + } + + public static boolean finalDamageIsNull(@Nonnull EntityDamageEvent event) { + return getFinalDamage(event) == 0; + } + + public static double getFinalDamage(@Nonnull EntityDamageEvent event) { + return event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index b2d7105e2..1051d797c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -21,127 +21,123 @@ import java.util.function.Supplier; import java.util.function.ToIntBiFunction; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class GoalHelper { - public static final int LEADERBOARD_SIZE = 9; - - private GoalHelper() { - } - - public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { - if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { - Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); - } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { - Challenges.getInstance().getChallengeManager().setCurrentGoal(null); - } - } - - @Nonnull - public static SortedMap> createLeaderboardFromPoints(@Nonnull Map points) { - SortedMap> leaderboard = new TreeMap<>(Collections.reverseOrder()); - for (Entry entry : points.entrySet()) { - List players = leaderboard.computeIfAbsent(entry.getValue(), key -> new ArrayList<>()); - players.add(entry.getKey()); - } - return leaderboard; - } - - @Nonnull - public static Map createPointsFromValues(@Nonnull AtomicInteger mostPoints, @Nonnull Map map, @Nonnull ToIntBiFunction mapper, boolean zeros) { - Map result = new HashMap<>(); - if (zeros) ChallengeAPI.getIngamePlayers().forEach(player -> result.put(player, 0)); - for (Entry entry : map.entrySet()) { - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) - continue; - // Ignore spectators when playing but show spectators after challenge end - if (!AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && player.getGameMode() == GameMode.SPECTATOR)) { - int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); - if (points == 0) - continue; - - result.put(player, points); - - if (points >= mostPoints.get()) - mostPoints.set(points); - } - } - return result; - } - - public static int determinePosition(@Nonnull SortedMap> map, @Nonnull E target) { - int position = 1; - for (Entry> entry : map.entrySet()) { - if (entry.getValue().contains(target)) break; - position++; - } - return position; - } - - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points) { - return createScoreboard(points, player -> new LinkedList<>()); - } - - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points, Function> additionalLines) { - return (scoreboard, player) -> { - SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); - int playerPlace = GoalHelper.determinePosition(leaderboard, player); - - scoreboard.addLine(""); - scoreboard.addLine(Message.forName("your-place").asString(playerPlace)); - scoreboard.addLine(""); - { - int place = 1; - int displayed = 0; - for (Entry> entry : leaderboard.entrySet()) { - List players = entry.getValue(); - for (Player current : players) { - displayed++; - if (displayed >= LEADERBOARD_SIZE) break; - scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); - } - if (displayed >= LEADERBOARD_SIZE) break; - place++; - } - } - scoreboard.addLine(""); - - List lines = additionalLines.apply(player); - if (!lines.isEmpty()) { - int linesThatCanBeAdded = 15 - scoreboard.getLines().size() - 1; - for (int i = 0; i < lines.size() && linesThatCanBeAdded > 0; i++) { - linesThatCanBeAdded--; - String line = lines.get(i); - scoreboard.addLine(line); - } - } - }; - } - - public static void getWinnersOnEnd(@Nonnull List winners, @Nonnull Map points) { - AtomicInteger mostPoints = new AtomicInteger(); - List currentWinners = new LinkedList<>(); - - for (Entry entry : points.entrySet()) { - if (entry.getValue() <= 0) continue; - if (entry.getValue() == mostPoints.get()) { - currentWinners.add(entry.getKey()); - continue; - } - if (entry.getValue() > mostPoints.get()) { - mostPoints.set(entry.getValue()); - currentWinners.clear(); - currentWinners.add(entry.getKey()); - } - } - - winners.addAll(currentWinners); - } + public static final int LEADERBOARD_SIZE = 9; + + private GoalHelper() { + } + + public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { + if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { + Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); + } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { + Challenges.getInstance().getChallengeManager().setCurrentGoal(null); + } + } + + @Nonnull + public static SortedMap> createLeaderboardFromPoints(@Nonnull Map points) { + SortedMap> leaderboard = new TreeMap<>(Collections.reverseOrder()); + for (Entry entry : points.entrySet()) { + List players = leaderboard.computeIfAbsent(entry.getValue(), key -> new ArrayList<>()); + players.add(entry.getKey()); + } + return leaderboard; + } + + @Nonnull + public static Map createPointsFromValues(@Nonnull AtomicInteger mostPoints, @Nonnull Map map, @Nonnull ToIntBiFunction mapper, boolean zeros) { + Map result = new HashMap<>(); + if (zeros) ChallengeAPI.getIngamePlayers().forEach(player -> result.put(player, 0)); + for (Entry entry : map.entrySet()) { + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) + continue; + // Ignore spectators when playing but show spectators after challenge end + if (!AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && player.getGameMode() == GameMode.SPECTATOR)) { + int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); + if (points == 0) + continue; + + result.put(player, points); + + if (points >= mostPoints.get()) + mostPoints.set(points); + } + } + return result; + } + + public static int determinePosition(@Nonnull SortedMap> map, @Nonnull E target) { + int position = 1; + for (Entry> entry : map.entrySet()) { + if (entry.getValue().contains(target)) break; + position++; + } + return position; + } + + @Nonnull + public static BiConsumer createScoreboard(@Nonnull Supplier> points) { + return createScoreboard(points, player -> new LinkedList<>()); + } + + @Nonnull + public static BiConsumer createScoreboard(@Nonnull Supplier> points, Function> additionalLines) { + return (scoreboard, player) -> { + SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); + int playerPlace = GoalHelper.determinePosition(leaderboard, player); + + scoreboard.addLine(""); + scoreboard.addLine(Message.forName("your-place").asString(playerPlace)); + scoreboard.addLine(""); + { + int place = 1; + int displayed = 0; + for (Entry> entry : leaderboard.entrySet()) { + List players = entry.getValue(); + for (Player current : players) { + displayed++; + if (displayed >= LEADERBOARD_SIZE) break; + scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); + } + if (displayed == LEADERBOARD_SIZE) break; + place++; + } + } + scoreboard.addLine(""); + + List lines = additionalLines.apply(player); + if (!lines.isEmpty()) { + int linesThatCanBeAdded = 15 - scoreboard.getLines().size() - 1; + for (int i = 0; i < lines.size() && linesThatCanBeAdded > 0; i++) { + linesThatCanBeAdded--; + String line = lines.get(i); + scoreboard.addLine(line); + } + } + }; + } + + public static void getWinnersOnEnd(@Nonnull List winners, @Nonnull Map points) { + AtomicInteger mostPoints = new AtomicInteger(); + List currentWinners = new LinkedList<>(); + + for (Entry entry : points.entrySet()) { + if (entry.getValue() <= 0) continue; + if (entry.getValue() == mostPoints.get()) { + currentWinners.add(entry.getKey()); + continue; + } + if (entry.getValue() > mostPoints.get()) { + mostPoints.set(entry.getValue()); + currentWinners.clear(); + currentWinners.add(entry.getKey()); + } + } + + winners.addAll(currentWinners); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index f8390f8db..f4dfa9226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; @@ -17,146 +17,142 @@ import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class SubSettingsHelper { - public static final String - ENTITY_TYPE = "entity_type", - BLOCK = "block", - ANY = "any", - ITEM = "item", - LIQUID = "liquid", - TARGET_ENTITY = "target_entity", - STRUCTURE = "structure"; - - public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilder(boolean any, boolean player) { - return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { - - if (any) { - builder.addSetting(ANY, new ItemBuilder( - Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); - } - if (player) { - builder.addSetting("PLAYER", new ItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); - } - for (EntityType type : EntityType.values()) { - if (!type.isSpawnable() || !type.isAlive()) continue; - try { - Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); - builder.addSetting(type.name(), new ItemBuilder(spawnEgg, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); - } catch (Exception ex) { - builder.addSetting(type.name(), new ItemBuilder(Material.STRUCTURE_VOID, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); - } - } - }); - } - - public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { - return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - }); - } - - public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { - return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - }); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob) { - return createEntityTargetSettingsBuilder(everyMob, false); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer) { - return createEntityTargetSettingsBuilder(everyMob, onlyPlayer, false); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer, boolean console) { - ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); - - if (console) { - builder.addSetting("console", new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); - } - - if (!onlyPlayer) { - builder.addSetting("current", new ItemBuilder(Material.DRAGON_HEAD, - Message.forName("item-custom-setting-target-current"))); - } - - builder.addSetting("current_player", new ItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-current_player"))); - builder.addSetting("random_player", new ItemBuilder(Material.ZOMBIE_HEAD, - Message.forName("item-custom-setting-target-random_player"))); - builder.addSetting("every_player", new ItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-every_player"))); - - if (everyMob && !onlyPlayer) { - builder.addSetting("every_mob", new ItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob"))); - builder.addSetting("every_mob_except_current", new ItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_current"))); - builder.addSetting("every_mob_except_players", new ItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_players"))); - } - return builder; - } - - public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, - boolean potionTime) { - - SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { - - if (potionTime) { - builder.addModifierSetting("length", new ItemBuilder(Material.CLOCK, - Message.forName("item-random-effect-length-challenge")), - 30, 1, 60, - value -> "", - value -> Message.forName(value == 1 ? "second" : "seconds").asString()); - } - builder.addModifierSetting("amplifier", new ItemBuilder(Material.STONE_SWORD, - Message.forName("item-random-effect-amplifier-challenge")), - 3, 1, 8, - value -> Message.forName("amplifier").asString(), - integer -> ""); - }); - - if (potionType) { - potionSettings = potionSettings.createChooseItemChild("potion_type").fill(builder -> { - for (PotionEffectType effectType : PotionEffectType.values()) { - builder.addSetting(effectType.getName(), new PotionBuilder(Material.POTION, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(effectType.getName())) - .addEffect(effectType.createEffect(1, 0)) - .color(effectType.getColor()).build()); - } - }); - } - - - return potionSettings; - } - - public static SubSettingsBuilder createStructureSettingsBuilder() { - return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { - builder.addSetting("random_structure", new ItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); - for (StructureType structure : StructureType.getStructureTypes().values()) { - builder.addSetting(structure.getName(), new ItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); - } - }); - } + public static final String + ENTITY_TYPE = "entity_type", + BLOCK = "block", + ANY = "any", + ITEM = "item", + LIQUID = "liquid", + TARGET_ENTITY = "target_entity", + STRUCTURE = "structure"; + + public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilder(boolean any, boolean player) { + return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { + + if (any) { + builder.addSetting(ANY, new ItemBuilder( + Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); + } + if (player) { + builder.addSetting("PLAYER", new ItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); + } + for (EntityType type : EntityType.values()) { + if (!type.isSpawnable() || !type.isAlive()) continue; + try { + Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); + builder.addSetting(type.name(), new ItemBuilder(spawnEgg, + DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); + } catch (Exception ex) { + builder.addSetting(type.name(), new ItemBuilder(Material.STRUCTURE_VOID, + DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); + } + } + }); + } + + public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { + return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { + builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + }); + } + + public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { + return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { + builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + }); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob) { + return createEntityTargetSettingsBuilder(everyMob, false); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer) { + return createEntityTargetSettingsBuilder(everyMob, onlyPlayer, false); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer, boolean console) { + ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); + + if (console) { + builder.addSetting("console", new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); + } + + if (!onlyPlayer) { + builder.addSetting("current", new ItemBuilder(Material.DRAGON_HEAD, + Message.forName("item-custom-setting-target-current"))); + } + + builder.addSetting("current_player", new ItemBuilder(Material.PLAYER_HEAD, + Message.forName("item-custom-setting-target-current_player"))); + builder.addSetting("random_player", new ItemBuilder(Material.ZOMBIE_HEAD, + Message.forName("item-custom-setting-target-random_player"))); + builder.addSetting("every_player", new ItemBuilder(Material.PLAYER_HEAD, + Message.forName("item-custom-setting-target-every_player"))); + + if (everyMob && !onlyPlayer) { + builder.addSetting("every_mob", new ItemBuilder(Material.WITHER_SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob"))); + builder.addSetting("every_mob_except_current", new ItemBuilder(Material.SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob_except_current"))); + builder.addSetting("every_mob_except_players", new ItemBuilder(Material.SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob_except_players"))); + } + return builder; + } + + public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, + boolean potionTime) { + + SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { + + if (potionTime) { + builder.addModifierSetting("length", new ItemBuilder(Material.CLOCK, + Message.forName("item-random-effect-length-challenge")), + 30, 1, 60, + value -> "", + value -> Message.forName(value == 1 ? "second" : "seconds").asString()); + } + builder.addModifierSetting("amplifier", new ItemBuilder(Material.STONE_SWORD, + Message.forName("item-random-effect-amplifier-challenge")), + 3, 1, 8, + value -> Message.forName("amplifier").asString(), + integer -> ""); + }); + + if (potionType) { + potionSettings = potionSettings.createChooseItemChild("potion_type").fill(builder -> { + for (PotionEffectType effectType : PotionEffectType.values()) { + builder.addSetting(effectType.getName(), new PotionBuilder(Material.POTION, + DefaultItem.getItemPrefix() + StringUtils.getEnumName(effectType.getName())) + .addEffect(effectType.createEffect(1, 0)) + .color(effectType.getColor()).build()); + } + }); + } + + + return potionSettings; + } + + public static SubSettingsBuilder createStructureSettingsBuilder() { + return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { + builder.addSetting("random_structure", new ItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); + for (StructureType structure : StructureType.getStructureTypes().values()) { + builder.addSetting(structure.getName(), new ItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 4e0b2018a..9ea299e7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.misc.ColorConversions; import org.bukkit.ChatColor; @@ -10,133 +10,129 @@ import java.util.LinkedList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ItemDescription { - private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); - - private final String[] colors; - private final String[] lore; - private final String name; - private final String originalName; - - public ItemDescription(@Nonnull String[] themeColors, @Nonnull String name, @Nonnull String[] formattedLore) { - this.colors = themeColors; - this.name = Message.forName("item-prefix") + name; - this.originalName = name; - this.lore = formattedLore; - } - - public ItemDescription(@Nonnull String[] description) { - if (description.length == 0) - throw new IllegalArgumentException("Invalid item description: Cannot be empty"); - - originalName = description[0]; - name = Message.forName("item-prefix") + originalName; - colors = determineColors(originalName); - - List loreOutput = new ArrayList<>(); - fillLore(description, loreOutput); - lore = loreOutput.toArray(new String[0]); - } - - public static ItemDescription empty() { - return new ItemDescription(new String[]{"§e"}, Message.NULL, new String[0]); - } - - @Nonnull - public String getName() { - return name; - } - - @Nonnull - public String getOriginalName() { - return originalName; - } - - @Nonnull - public String[] getTheme() { - return colors; - } - - @Nonnull - public String[] getLore() { - return lore; - } - - private void fillLore(@Nonnull String[] origin, @Nonnull List output) { - - String colorBefore = "§7"; - boolean inColor = false; - boolean nextIsColor = false; - int themeIndex = 0; - - // Start at 1, first entry is not content of lore - for (int i = 1; i < origin.length; i++) { - StringBuilder line = new StringBuilder(); - line.append(colorBefore); - for (char c : origin[i].toCharArray()) { - if (c == '*') { - if (inColor) { - line.append(colorBefore); - inColor = false; - } else { - line.append(colors[themeIndex]); - themeIndex++; - if (themeIndex >= colors.length) - themeIndex = 0; - inColor = true; - } - } else { - line.append(c); - if (c == '§') { - nextIsColor = true; - } else if (nextIsColor) { - nextIsColor = false; - if (ColorConversions.isValidColorCode(c)) - colorBefore = ""; - colorBefore += "§" + c; - } - } - } - output.add(line.toString()); - } - - if (output.isEmpty()) return; - if (config.getBoolean("empty-line-above")) output.add(0, " "); - if (config.getBoolean("empty-line-underneath")) output.add(" "); - - } - - private String[] determineColors(@Nonnull String input) { - List colors = new LinkedList<>(); - int colorIndex = 0; - - boolean nextIsCode = false; - for (char c : input.toCharArray()) { - if (c == ChatColor.COLOR_CHAR) { - nextIsCode = true; - continue; - } - if (!nextIsCode) continue; - nextIsCode = false; - - String latestColors = ""; - if (colors.size() > colorIndex) - latestColors = colors.remove(colorIndex); - - colors.add(latestColors + ChatColor.COLOR_CHAR + c); - - if (ColorConversions.isValidColorCode(c)) - colorIndex++; - } - - if (colors.isEmpty()) - colors.add("§e"); - return colors.toArray(new String[0]); - } + private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); + + private final String[] colors; + private final String[] lore; + private final String name; + private final String originalName; + + public ItemDescription(@Nonnull String[] themeColors, @Nonnull String name, @Nonnull String[] formattedLore) { + this.colors = themeColors; + this.name = Message.forName("item-prefix") + name; + this.originalName = name; + this.lore = formattedLore; + } + + public ItemDescription(@Nonnull String[] description) { + if (description.length == 0) + throw new IllegalArgumentException("Invalid item description: Cannot be empty"); + + originalName = description[0]; + name = Message.forName("item-prefix") + originalName; + colors = determineColors(originalName); + + List loreOutput = new ArrayList<>(); + fillLore(description, loreOutput); + lore = loreOutput.toArray(new String[0]); + } + + public static ItemDescription empty() { + return new ItemDescription(new String[]{"§e"}, Message.NULL, new String[0]); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getOriginalName() { + return originalName; + } + + @Nonnull + public String[] getTheme() { + return colors; + } + + @Nonnull + public String[] getLore() { + return lore; + } + + private void fillLore(@Nonnull String[] origin, @Nonnull List output) { + + String colorBefore = "§7"; + boolean inColor = false; + boolean nextIsColor = false; + int themeIndex = 0; + + // Start at 1, first entry is not content of lore + for (int i = 1; i < origin.length; i++) { + StringBuilder line = new StringBuilder(); + line.append(colorBefore); + for (char c : origin[i].toCharArray()) { + if (c == '*') { + if (inColor) { + line.append(colorBefore); + inColor = false; + } else { + line.append(colors[themeIndex]); + themeIndex++; + if (themeIndex >= colors.length) + themeIndex = 0; + inColor = true; + } + } else { + line.append(c); + if (c == '§') { + nextIsColor = true; + } else if (nextIsColor) { + nextIsColor = false; + if (ColorConversions.isValidColorCode(c)) + colorBefore = ""; + colorBefore += "§" + c; + } + } + } + output.add(line.toString()); + } + + if (output.isEmpty()) return; + if (config.getBoolean("empty-line-above")) output.add(0, " "); + if (config.getBoolean("empty-line-underneath")) output.add(" "); + + } + + private String[] determineColors(@Nonnull String input) { + List colors = new LinkedList<>(); + int colorIndex = 0; + + boolean nextIsCode = false; + for (char c : input.toCharArray()) { + if (c == ChatColor.COLOR_CHAR) { + nextIsCode = true; + continue; + } + if (!nextIsCode) continue; + nextIsCode = false; + + String latestColors = ""; + if (colors.size() > colorIndex) + latestColors = colors.remove(colorIndex); + + colors.add(latestColors + ChatColor.COLOR_CHAR + c); + + if (ColorConversions.isValidColorCode(c)) + colorIndex++; + } + + if (colors.isEmpty()) + colors.add("§e"); + return colors.toArray(new String[0]); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index 45de793ce..a7266d1a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.command.CommandSender; @@ -13,75 +13,71 @@ import java.util.ArrayList; import java.util.Collection; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface Message { - String NULL = "§r§fN/A"; - Collection UNKNOWN_MESSAGES = new ArrayList<>(); + String NULL = "§r§fN/A"; + Collection UNKNOWN_MESSAGES = new ArrayList<>(); - static String unknown(@Nonnull String name) { - if (!UNKNOWN_MESSAGES.contains(name)) { - UNKNOWN_MESSAGES.add(name); - Logger.warn("Tried accessing unknown messages '{}'", name); - } + static String unknown(@Nonnull String name) { + if (!UNKNOWN_MESSAGES.contains(name)) { + UNKNOWN_MESSAGES.add(name); + Logger.warn("Tried accessing unknown messages '{}'", name); + } - return name; - } + return name; + } - @Nonnull - @CheckReturnValue - static Message forName(@Nonnull String name) { - return MessageManager.getOrCreateMessage(name); - } + @Nonnull + @CheckReturnValue + static Message forName(@Nonnull String name) { + return MessageManager.getOrCreateMessage(name); + } - @Nonnull - String asString(@Nonnull Object... args); + @Nonnull + String asString(@Nonnull Object... args); - @Nonnull - BaseComponent asComponent(@Nonnull Object... args); + @Nonnull + BaseComponent asComponent(@Nonnull Object... args); - @Nonnull - String asRandomString(@Nonnull IRandom random, @Nonnull Object... args); + @Nonnull + String asRandomString(@Nonnull IRandom random, @Nonnull Object... args); - @Nonnull - BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + @Nonnull + BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); - @Nonnull - String asRandomString(@Nonnull Object... args); + @Nonnull + String asRandomString(@Nonnull Object... args); - @Nonnull - String[] asArray(@Nonnull Object... args); + @Nonnull + String[] asArray(@Nonnull Object... args); - @Nonnull - BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args); + @Nonnull + BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args); - @Nonnull - ItemDescription asItemDescription(@Nonnull Object... args); + @Nonnull + ItemDescription asItemDescription(@Nonnull Object... args); - void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastTitle(@Nonnull Object... args); + void broadcastTitle(@Nonnull Object... args); - void sendTitle(@Nonnull Player player, @Nonnull Object... args); + void sendTitle(@Nonnull Player player, @Nonnull Object... args); - void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args); + void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args); - void setValue(@Nonnull String[] value); + void setValue(@Nonnull String[] value); - @Nonnull - String getName(); + @Nonnull + String getName(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java index 0995acc77..710264bdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java @@ -8,67 +8,63 @@ import java.util.HashMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.2 - */ public class Prefix { - private static final Map values = new HashMap<>(); + private static final Map values = new HashMap<>(); - public static final Prefix - CHALLENGES = forName("challenges", "§6Challenges"), - CUSTOM = forName("custom", "§bCustom"), - DAMAGE = forName("damage", "§cDamage"), - POSITION = forName("position", "§9Position"), - BACKPACK = forName("backpack", "§aBackpack"), - TIMER = forName("timer", "§5Timer"); + public static final Prefix + CHALLENGES = forName("challenges", "§6Challenges"), + CUSTOM = forName("custom", "§bCustom"), + DAMAGE = forName("damage", "§cDamage"), + POSITION = forName("position", "§9Position"), + BACKPACK = forName("backpack", "§aBackpack"), + TIMER = forName("timer", "§5Timer"); - private final String name; - private final String defaultValue; - private String value; + private final String name; + private final String defaultValue; + private String value; - private Prefix(@Nonnull String name, @Nonnull String defaultValue) { - this.defaultValue = getDefaultValueFor(defaultValue); - this.name = name; - } + private Prefix(@Nonnull String name, @Nonnull String defaultValue) { + this.defaultValue = getDefaultValueFor(defaultValue); + this.name = name; + } - @Nonnull - @CheckReturnValue - public static Collection values() { - return Collections.unmodifiableCollection(values.values()); - } + @Nonnull + @CheckReturnValue + public static Collection values() { + return Collections.unmodifiableCollection(values.values()); + } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name, @Nonnull String defaultValue) { - return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); - } + @Nonnull + @CheckReturnValue + public static Prefix forName(@Nonnull String name, @Nonnull String defaultValue) { + return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); + } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name) { - return forName(name, name); - } + @Nonnull + @CheckReturnValue + public static Prefix forName(@Nonnull String name) { + return forName(name, name); + } - @Nonnull - public static String getDefaultValueFor(@Nonnull String value) { - return "§8§l┃ " + value + " §8┃ "; - } + @Nonnull + public static String getDefaultValueFor(@Nonnull String value) { + return "§8§l┃ " + value + " §8┃ "; + } - public void setValue(@Nullable String value) { - this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; - } + public void setValue(@Nullable String value) { + this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; + } - @Nonnull - @Override - public String toString() { - return (value == null ? defaultValue : value) + "§7"; - } + @Nonnull + @Override + public String toString() { + return (value == null ? defaultValue : value) + "§7"; + } - @Nonnull - public String getName() { - return name; - } + @Nonnull + public String getName() { + return name; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index 3056fb22e..bbef01e1d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content.impl; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; @@ -22,208 +22,204 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class MessageImpl implements Message { - protected final String name; - protected String[] value; - - public MessageImpl(@Nonnull String name) { - this.name = name; - } - - @Nonnull - protected static IRandom defaultRandom() { - return IRandom.threadLocal(); - } - - @Nonnull - @Override - public String asString(@Nonnull Object... args) { - if (value == null) return name; - return String.join("\n", asArray(args)); - } - - @Nonnull - @Override - public BaseComponent asComponent(@Nonnull Object... args) { - if (value == null) return new TextComponent(name); - BaseComponent[] components = asComponentArray(null, args); - BaseComponent first = null; - // TODO: This will bug with colors as they wont be added to the next line - for (BaseComponent component : components) { - if (first == null) first = component; - else first.addExtra(component); - } - return first == null ? new TextComponent() : first; - } - - @Nonnull - @Override - public String asRandomString(@Nonnull Object... args) { - return asRandomString(defaultRandom(), args); - } - - @Nonnull - @Override - public String asRandomString(@Nonnull IRandom random, @Nonnull Object... args) { - String[] array = asArray(args); - if (array.length == 0) return Message.unknown(name); - return random.choose(array); - } - - @Nonnull - @Override - public BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { - BaseComponent[] array = asComponentArray(prefix, args); - if (array.length == 0) return new TextComponent(Message.unknown(name)); - return random.choose(array); - } - - @Nonnull - @Override - public String[] asArray(@Nonnull Object... args) { - if (value == null) return new String[]{Message.unknown(name)}; - args = BukkitStringUtils.replaceArguments(args, true); - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); - return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); - } - - @Nonnull - @Override - public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args) { - if (value == null) return new TextComponent[] { new TextComponent(Message.unknown(name)) }; - return BukkitStringUtils.format(prefix, value, args); - } - - @Nonnull - @Override - public ItemDescription asItemDescription(@Nonnull Object... args) { - if (value == null) { - Message.unknown(name); - return ItemDescription.empty(); - } - return new ItemDescription(asArray(args)); - } - - @Override - public void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLines(component -> target.spigot().sendMessage(component), prefix, asComponentArray(prefix, args)); - } - - @Override - public void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - sendRandom(defaultRandom(), target, prefix, args); - } - - @Override - public void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLine(components -> target.spigot().sendMessage(components), prefix, asRandomComponent(random, prefix, args)); - } - - @Override - public void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLines(components -> Bukkit.spigot().broadcast(components), prefix, asComponentArray(prefix, args)); - } - - @Override - public void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args) { - broadcastRandom(defaultRandom(), prefix, args); - } - - @Override - public void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLine(component -> Bukkit.spigot().broadcast(component), prefix, asRandomComponent(random, prefix, args)); - } - - private void doSendLines(@Nonnull Consumer sender, @Nonnull Prefix prefix, @Nonnull BaseComponent[] components) { - for (BaseComponent line : components) { - doSendLine(sender, prefix, line); - } - } - - private void doSendLine(@Nonnull Consumer sender, @Nonnull Prefix prefix, BaseComponent component) { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); - - BaseComponent component1 = component; - if (capsFont) { - if (component1 instanceof TextComponent) { - component1 = new TextComponent(FontUtils.toSmallCaps(((TextComponent) component1).getText())); - } - if (component != null) { - List extra = component.getExtra(); - if (extra != null) { - component.setExtra(new LinkedList<>()); - for (BaseComponent baseComponent : extra) { - if (baseComponent instanceof TextComponent) { - String text = ((TextComponent) baseComponent).getText(); - component1.addExtra(new TextComponent(text)); - } else { - component1.addExtra(baseComponent); - } - } - } - } - } - - // Weird bugs can cause this to be null if the line is empty and kicks the player in 1.19+ - if (component1 != null) { - sender.accept(component1); - } - - } - - @Override - public void broadcastTitle(@Nonnull Object... args) { - String[] title = asArray(args); - Bukkit.getOnlinePlayers().forEach(player -> doSendTitle(player, title)); - } - - @Override - public void sendTitle(@Nonnull Player player, @Nonnull Object... args) { - doSendTitle(player, asArray(args)); - } - - @Override - public void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args) { - doSendTitleInstant(player, asArray(args)); - } - - protected void doSendTitle(@Nonnull Player player, @Nonnull String[] title) { - sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitle(player, line1, line2)); - } - - protected void doSendTitleInstant(@Nonnull Player player, @Nonnull String[] title) { - sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitleInstant(player, line1, line2)); - } - - protected void sendTitle(@Nonnull String[] title, @Nonnull BiConsumer send) { - if (title.length == 0) send.accept("", ""); - else if (title.length == 1) send.accept(title[0], ""); - else send.accept(title[0], title[1]); - } - - @Override - public void setValue(@Nonnull String[] value) { - this.value = value; - } - - @Nonnull - @Override - public String getName() { - return name; - } - - @Override - public String toString() { - return asString(); - } + protected final String name; + protected String[] value; + + public MessageImpl(@Nonnull String name) { + this.name = name; + } + + @Nonnull + protected static IRandom defaultRandom() { + return IRandom.threadLocal(); + } + + @Nonnull + @Override + public String asString(@Nonnull Object... args) { + if (value == null) return name; + return String.join("\n", asArray(args)); + } + + @Nonnull + @Override + public BaseComponent asComponent(@Nonnull Object... args) { + if (value == null) return new TextComponent(name); + BaseComponent[] components = asComponentArray(null, args); + BaseComponent first = null; + // TODO: This will bug with colors as they wont be added to the next line + for (BaseComponent component : components) { + if (first == null) first = component; + else first.addExtra(component); + } + return first == null ? new TextComponent() : first; + } + + @Nonnull + @Override + public String asRandomString(@Nonnull Object... args) { + return asRandomString(defaultRandom(), args); + } + + @Nonnull + @Override + public String asRandomString(@Nonnull IRandom random, @Nonnull Object... args) { + String[] array = asArray(args); + if (array.length == 0) return Message.unknown(name); + return random.choose(array); + } + + @Nonnull + @Override + public BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + BaseComponent[] array = asComponentArray(prefix, args); + if (array.length == 0) return new TextComponent(Message.unknown(name)); + return random.choose(array); + } + + @Nonnull + @Override + public String[] asArray(@Nonnull Object... args) { + if (value == null) return new String[]{Message.unknown(name)}; + args = BukkitStringUtils.replaceArguments(args, true); + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + boolean capsFont = false; + if (loader != null) capsFont = loader.isSmallCapsFont(); + return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); + } + + @Nonnull + @Override + public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args) { + if (value == null) return new TextComponent[]{new TextComponent(Message.unknown(name))}; + return BukkitStringUtils.format(prefix, value, args); + } + + @Nonnull + @Override + public ItemDescription asItemDescription(@Nonnull Object... args) { + if (value == null) { + Message.unknown(name); + return ItemDescription.empty(); + } + return new ItemDescription(asArray(args)); + } + + @Override + public void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLines(component -> target.spigot().sendMessage(component), prefix, asComponentArray(prefix, args)); + } + + @Override + public void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + sendRandom(defaultRandom(), target, prefix, args); + } + + @Override + public void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLine(components -> target.spigot().sendMessage(components), prefix, asRandomComponent(random, prefix, args)); + } + + @Override + public void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLines(components -> Bukkit.spigot().broadcast(components), prefix, asComponentArray(prefix, args)); + } + + @Override + public void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args) { + broadcastRandom(defaultRandom(), prefix, args); + } + + @Override + public void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLine(component -> Bukkit.spigot().broadcast(component), prefix, asRandomComponent(random, prefix, args)); + } + + private void doSendLines(@Nonnull Consumer sender, @Nonnull Prefix prefix, @Nonnull BaseComponent[] components) { + for (BaseComponent line : components) { + doSendLine(sender, prefix, line); + } + } + + private void doSendLine(@Nonnull Consumer sender, @Nonnull Prefix prefix, BaseComponent component) { + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + boolean capsFont = false; + if (loader != null) capsFont = loader.isSmallCapsFont(); + + BaseComponent component1 = component; + if (capsFont) { + if (component1 instanceof TextComponent) { + component1 = new TextComponent(FontUtils.toSmallCaps(((TextComponent) component1).getText())); + } + if (component != null) { + List extra = component.getExtra(); + if (extra != null) { + component.setExtra(new LinkedList<>()); + for (BaseComponent baseComponent : extra) { + if (baseComponent instanceof TextComponent) { + String text = ((TextComponent) baseComponent).getText(); + component1.addExtra(new TextComponent(text)); + } else { + component1.addExtra(baseComponent); + } + } + } + } + } + + // Weird bugs can cause this to be null if the line is empty and kicks the player in 1.19+ + if (component1 != null) { + sender.accept(component1); + } + + } + + @Override + public void broadcastTitle(@Nonnull Object... args) { + String[] title = asArray(args); + Bukkit.getOnlinePlayers().forEach(player -> doSendTitle(player, title)); + } + + @Override + public void sendTitle(@Nonnull Player player, @Nonnull Object... args) { + doSendTitle(player, asArray(args)); + } + + @Override + public void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args) { + doSendTitleInstant(player, asArray(args)); + } + + protected void doSendTitle(@Nonnull Player player, @Nonnull String[] title) { + sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitle(player, line1, line2)); + } + + protected void doSendTitleInstant(@Nonnull Player player, @Nonnull String[] title) { + sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitleInstant(player, line1, line2)); + } + + protected void sendTitle(@Nonnull String[] title, @Nonnull BiConsumer send) { + if (title.length == 0) send.accept("", ""); + else if (title.length == 1) send.accept(title[0], ""); + else send.accept(title[0], title[1]); + } + + @Override + public void setValue(@Nonnull String[] value) { + this.value = value; + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Override + public String toString() { + return asString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java index 95986bfbf..bf3b08a3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java @@ -7,30 +7,26 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class MessageManager { - private static final Map cache = new ConcurrentHashMap<>(); + private static final Map cache = new ConcurrentHashMap<>(); - private MessageManager() { - } + private MessageManager() { + } - @Nonnull - @CheckReturnValue - public static Message getOrCreateMessage(@Nonnull String name) { - return cache.computeIfAbsent(name, key -> new MessageImpl(key)); - } + @Nonnull + @CheckReturnValue + public static Message getOrCreateMessage(@Nonnull String name) { + return cache.computeIfAbsent(name, key -> new MessageImpl(key)); + } - @CheckReturnValue - public static boolean hasMessageInCache(@Nonnull String name) { - return cache.containsKey(name); - } + @CheckReturnValue + public static boolean hasMessageInCache(@Nonnull String name) { + return cache.containsKey(name); + } - public static int getMessageCountCached() { - return cache.size(); - } + public static int getMessageCountCached() { + return cache.size(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java index 2c7e3f422..7cc40dc00 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java @@ -5,27 +5,23 @@ import javax.annotation.Nonnull; import java.io.File; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class ContentLoader { - @Nonnull - protected final File getMessagesFolder() { - return Challenges.getInstance().getDataFile("messages"); - } + @Nonnull + protected final File getMessagesFolder() { + return Challenges.getInstance().getDataFile("messages"); + } - @Nonnull - protected final File getMessageFile(@Nonnull String name, @Nonnull String extension) { - return new File(getMessagesFolder(), name + "." + extension); - } + @Nonnull + protected final File getMessageFile(@Nonnull String name, @Nonnull String extension) { + return new File(getMessagesFolder(), name + "." + extension); + } - @Nonnull - protected final String getGitHubUrl(@Nonnull String path) { - return "https://raw.githubusercontent.com/anweisen/Challenges/" + (Challenges.getInstance().isDevMode() ? "development" : "master") + "/" + path; - } + @Nonnull + protected final String getGitHubUrl(@Nonnull String path) { + return "https://raw.githubusercontent.com/anweisen/Challenges/" + (Challenges.getInstance().isDevMode() ? "development" : "master") + "/" + path; + } - protected abstract void load(); + protected abstract void load(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 828d867d1..fc34aca48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -4,11 +4,13 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.FileUtils; -import net.anweisen.utilities.common.misc.GsonUtils; +import lombok.Getter; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; @@ -18,145 +20,189 @@ import java.io.IOException; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LanguageLoader extends ContentLoader { - public static final String DEFAULT_LANGUAGE = "en"; - public static final String DIRECT_FILE_PATH = "direct-language-file"; - - private static final JsonParser parser = new JsonParser(); - - private static volatile boolean loaded = false; - private String language; - private boolean smallCapsFont; - - public static boolean isLoaded() { - return loaded; - } - - @Override - protected void load() { - - Document config = Challenges.getInstance().getConfigDocument(); - - smallCapsFont = config.getBoolean("small-caps", false); - - if (config.contains(DIRECT_FILE_PATH)) { - language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); - String path = config.getString(DIRECT_FILE_PATH); - if (path == null) return; - Logger.info("Using direct language file '{}'", path); - readLanguage(new File(path)); - return; - } - - loadDefault(); - } - - private void loadDefault() { - download(); - init(); - read(); - } - - private void init() { - - language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); - File file = getMessageFile(language, "json"); - - if (!file.exists()) { - if (language.equalsIgnoreCase(DEFAULT_LANGUAGE)) return; - ConsolePrint.unknownLanguage(language); - language = DEFAULT_LANGUAGE; - } - - Logger.debug("Language '{}' is currently selected", language); - - } - - private void download() { - try { - - JsonArray languages = parser.parse(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); - Logger.debug("Fetched languages {}", languages); - for (JsonElement element : languages) { - try { - String name = element.getAsString(); - String url = getGitHubUrl("language/files/" + name + ".json"); - - Document language = Document.parseJson(IOUtils.toString(url)); - File file = getMessageFile(name, "json"); - - Logger.debug("Writing language {} to {}", name, file); - verifyLanguage(language, file, name); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); - } - } - - } catch (Exception ex) { - Logger.error("Could not download languages", ex); - } - } - - private void verifyLanguage(@Nonnull Document download, @Nonnull File file, @Nonnull String name) throws IOException { - Document existing = Document.readJsonFile(file); - FileUtils.createFilesIfNecessary(file); - download.forEach((key, value) -> { - if (!existing.contains(key)) { - Logger.debug("Overwriting message {} in {} with {}", key, name, String.valueOf(value).replace("\"", "§r\"")); - existing.set(key, value); - } - }); - existing.saveToFile(file); - } - - private void read() { - readLanguage(getMessageFile(language, "json")); - } - - private void readLanguage(@Nonnull File file) { - try { - - if (!file.exists()) { - ConsolePrint.unableToGetLanguages(); - return; - } - - int messages = 0; - JsonObject read = parser.parse(FileUtils.newBufferedReader(file)).getAsJsonObject(); - for (Entry entry : read.entrySet()) { - Message message = Message.forName(entry.getKey()); - JsonElement element = entry.getValue(); - if (element.isJsonPrimitive()) { - message.setValue(new String[]{element.getAsString()}); - messages++; - } else if (element.isJsonArray()) { - message.setValue(GsonUtils.convertJsonArrayToStringArray(element.getAsJsonArray())); - messages++; - } else { - Logger.warn("Illegal type '{}' for {}", element.getClass().getName(), message.getName()); - } - } - - loaded = true; - Logger.info("Successfully loaded language '{}' from config file: {} message(s)", language, messages); - - } catch (Exception ex) { - Logger.error("Could not read languages", ex); - } - } - - public String getLanguage() { - return language; - } - - public boolean isSmallCapsFont() { - return smallCapsFont; - } + public static final String DEFAULT_LANGUAGE = "en"; + + public static final String KEY_LANGUAGE = "language", KEY_SMALL_CAPS = "smallcaps", KEY_DIRECT_LANGUAGE_FILE = "manualfile"; + + @Getter + private static volatile boolean loaded = false; + @Getter + private String language; + @Getter + private boolean smallCapsFont; + + public File getLanguagePropertiesFile() { + return getMessageFile("language", "properties"); + } + + public Document getLanguageProperties() { + try { + FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); + + FileDocument document = FileDocument.readPropertiesFile(getLanguagePropertiesFile()); + } catch (Exception e) { + Logger.error("Could not read language properties", e); + } + return Document.empty(); + } + + public void migrateLanguageConfig() { + Document configDocument = Challenges.getInstance().getConfigDocument(); + String oldLanguage = configDocument.getString("language"); + String oldDirectFilePath = configDocument.getString("direct-language-file"); + boolean oldSmallCapsFont = configDocument.getBoolean("small-caps"); + + Document languageProperties = getLanguageProperties(); + languageProperties.set(KEY_LANGUAGE, oldLanguage); + languageProperties.set(KEY_SMALL_CAPS, oldSmallCapsFont); + + if (configDocument.contains("direct-language-file")) { + languageProperties.set(KEY_DIRECT_LANGUAGE_FILE, oldDirectFilePath); + } + } + + @Override + protected void load() { + migrateLanguageConfig(); + + Document config = getLanguageProperties(); + + smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); + + if (config.contains(KEY_DIRECT_LANGUAGE_FILE)) { + language = config.getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); + String path = config.getString(KEY_DIRECT_LANGUAGE_FILE); + if (path == null) return; + Logger.info("Using direct language file '{}'", path); + readLanguage(new File(path)); + return; + } + + loadDefault(); + } + + public void changeLanguage(@Nonnull String language) { + if (language.equalsIgnoreCase(this.language)) { + Logger.info("Language '{}' is already selected", language); + return; + } + + this.language = language; + Document properties = getLanguageProperties(); + properties.set(KEY_LANGUAGE, language); + try { + properties.saveToFile(getLanguagePropertiesFile()); + } catch (IOException e) { + Logger.error("Could not save language properties", e); + } + reload(language); + Logger.info("Language changed to '{}'", language); + } + + public void reload(String language) { + this.language = language; + read(); + download(); + init(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); + } + + private void loadDefault() { + download(); + init(); + read(); + } + + private void init() { + + language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); + File file = getMessageFile(language, "json"); + + if (!file.exists()) { + if (language.equalsIgnoreCase(DEFAULT_LANGUAGE)) return; + ConsolePrint.unknownLanguage(language); + language = DEFAULT_LANGUAGE; + } + + Logger.debug("Language '{}' is currently selected", language); + + } + + private void download() { + try { + + JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); + Logger.debug("Fetched languages {}", languages); + for (JsonElement element : languages) { + try { + String name = element.getAsString(); + String url = getGitHubUrl("language/files/" + name + ".json"); + + Document language = Document.parseJson(IOUtils.toString(url)); + File file = getMessageFile(name, "json"); + + Logger.debug("Writing language {} to {}", name, file); + verifyLanguage(language, file, name); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); + Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); + } + } + + } catch (Exception ex) { + Logger.error("Could not download languages", ex); + } + } + + private void verifyLanguage(@Nonnull Document download, @Nonnull File file, @Nonnull String name) throws IOException { + Document existing = Document.readJsonFile(file); + FileUtils.createFilesIfNecessary(file); + download.forEach((key, value) -> { + if (!existing.contains(key)) { + Logger.debug("Overwriting message {} in {} with {}", key, name, String.valueOf(value).replace("\"", "§r\"")); + existing.set(key, value); + } + }); + existing.saveToFile(file); + } + + private void read() { + readLanguage(getMessageFile(language, "json")); + } + + private void readLanguage(@Nonnull File file) { + try { + + if (!file.exists()) { + ConsolePrint.unableToGetLanguages(); + return; + } + + int messages = 0; + JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); + for (Entry entry : read.entrySet()) { + Message message = Message.forName(entry.getKey()); + JsonElement element = entry.getValue(); + if (element.isJsonPrimitive()) { + message.setValue(new String[]{element.getAsString()}); + messages++; + } else if (element.isJsonArray()) { + message.setValue(GsonUtils.convertJsonArrayToStringArray(element.getAsJsonArray())); + messages++; + } else { + Logger.warn("Illegal type '{}' for {}", element.getClass().getName(), message.getName()); + } + } + + loaded = true; + Logger.info("Successfully loaded language '{}' from config file: {} message(s)", language, messages); + + } catch (Exception ex) { + Logger.error("Could not read languages", ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 4cf96e944..05a44760a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; @@ -8,106 +8,103 @@ import java.util.*; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LoaderRegistry { - private static final AtomicInteger loading = new AtomicInteger(); // Keeps track of how many loaders are still loading - private final Map, Subscribers> subscribers = new HashMap<>(); - private final Collection loaders; - public LoaderRegistry(@Nonnull ContentLoader... loaders) { - this.loaders = Arrays.asList(loaders); - } - - private static void execute(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - try { - action.run(); - } catch (Exception ex) { - Logger.error("Could not execute subscriber for {}", classOfLoader.getSimpleName(), ex); - } - } - - public void load() { - if (isLoading()) { - ConsolePrint.alreadyExecutingContentLoader(); - return; - } - - loaders.forEach(this::executeLoader); - } - - private void executeLoader(@Nonnull ContentLoader loader) { - loading.incrementAndGet(); - loader.load(); - loading.decrementAndGet(); - handleCompleteLoading(loader.getClass()); - } - - private void handleCompleteLoading(@Nonnull Class classOfLoader) { - Logger.debug("{} finished loading. {} loader(s) left", classOfLoader.getSimpleName(), loading); - - if (loading.get() == 0) - Logger.info("All loaders finished loading"); - - if (Challenges.getInstance().isEnabled()) { - Subscribers subscribers = this.subscribers.get(classOfLoader); - if (subscribers == null) return; - subscribers.execute(); - } - } - - public void enable() { - for (Subscribers subscribers : subscribers.values()) { - if (subscribers.executed) continue; - subscribers.execute(); - } - } - - public void disable() { - subscribers.clear(); - } - - public boolean isLoading() { - return loading.get() > 0; - } - - public void subscribe(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - Subscribers subscribers = this.subscribers.computeIfAbsent(classOfLoader, key -> new Subscribers(classOfLoader)); - subscribers.actions.add(action); - - if (subscribers.executed) - execute(classOfLoader, action); - } - - @SuppressWarnings("unchecked") - public T getFirstLoaderByClass(@Nonnull Class clazz) { - for (ContentLoader loader : loaders) { - if (loader.getClass().equals(clazz)) { - return (T) loader; - } - } - return null; - } - - private static class Subscribers { - - private final Class loader; - private final Collection actions = new ArrayList<>(1); - private boolean executed = false; - - public Subscribers(Class loader) { - this.loader = loader; - } - - public void execute() { - Logger.debug("Executing subscribers for {}", loader.getSimpleName()); - executed = true; - for (Runnable subscriber : actions) { - LoaderRegistry.execute(loader, subscriber); - } - } - - } + private static final AtomicInteger loading = new AtomicInteger(); // Keeps track of how many loaders are still loading + private final Map, Subscribers> subscribers = new HashMap<>(); + private final Collection loaders; + + public LoaderRegistry(@Nonnull ContentLoader... loaders) { + this.loaders = Arrays.asList(loaders); + } + + private static void execute(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + try { + action.run(); + } catch (Exception ex) { + Logger.error("Could not execute subscriber for {}", classOfLoader.getSimpleName(), ex); + } + } + + public void load() { + if (isLoading()) { + ConsolePrint.alreadyExecutingContentLoader(); + return; + } + + loaders.forEach(this::executeLoader); + } + + private void executeLoader(@Nonnull ContentLoader loader) { + loading.incrementAndGet(); + loader.load(); + loading.decrementAndGet(); + handleCompleteLoading(loader.getClass()); + } + + private void handleCompleteLoading(@Nonnull Class classOfLoader) { + Logger.debug("{} finished loading. {} loader(s) left", classOfLoader.getSimpleName(), loading); + + if (loading.get() == 0) + Logger.info("All loaders finished loading"); + + if (Challenges.getInstance().isEnabled()) { + Subscribers subscribers = this.subscribers.get(classOfLoader); + if (subscribers == null) return; + subscribers.execute(); + } + } + + public void enable() { + for (Subscribers subscribers : subscribers.values()) { + if (subscribers.executed) continue; + subscribers.execute(); + } + } + + public void disable() { + subscribers.clear(); + } + + public boolean isLoading() { + return loading.get() > 0; + } + + public void subscribe(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + Subscribers subscribers = this.subscribers.computeIfAbsent(classOfLoader, key -> new Subscribers(classOfLoader)); + subscribers.actions.add(action); + + if (subscribers.executed) + execute(classOfLoader, action); + } + + @SuppressWarnings("unchecked") + public T getFirstLoaderByClass(@Nonnull Class clazz) { + for (ContentLoader loader : loaders) { + if (loader.getClass().equals(clazz)) { + return (T) loader; + } + } + return null; + } + + private static class Subscribers { + + private final Class loader; + private final Collection actions = new ArrayList<>(1); + private boolean executed = false; + + public Subscribers(Class loader) { + this.loader = loader; + } + + public void execute() { + Logger.debug("Executing subscribers for {}", loader.getSimpleName()); + executed = true; + for (Runnable subscriber : actions) { + LoaderRegistry.execute(loader, subscriber); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index bdd9124f9..0cf9321b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -1,44 +1,40 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.content.Prefix; import java.io.File; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class PrefixLoader extends ContentLoader { - @Override - protected void load() { - try { + @Override + protected void load() { + try { - File file = getMessageFile("prefix", "properties"); - FileUtils.createFilesIfNecessary(file); + File file = getMessageFile("prefix", "properties"); + FileUtils.createFilesIfNecessary(file); - FileDocument document = FileDocument.readPropertiesFile(file); - boolean changed = false; + FileDocument document = FileDocument.readPropertiesFile(file); + boolean changed = false; - for (Prefix prefix : Prefix.values()) { - if (!document.contains(prefix.getName())) { - document.set(prefix.getName(), prefix.toString()); - changed = true; - continue; - } + for (Prefix prefix : Prefix.values()) { + if (!document.contains(prefix.getName())) { + document.set(prefix.getName(), prefix.toString()); + changed = true; + continue; + } - prefix.setValue(document.getString(prefix.getName())); - } + prefix.setValue(document.getString(prefix.getName())); + } - if (changed) document.save(); - Logger.info("Successfully loaded {} prefixes from config file", Prefix.values().size()); + if (changed) document.save(); + Logger.info("Successfully loaded {} prefixes from config file", Prefix.values().size()); - } catch (Exception ex) { - Logger.error("Could not load prefixes", ex); - } - } + } catch (Exception ex) { + Logger.error("Could not load prefixes", ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index 01b08a662..129814eb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -1,65 +1,50 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.version.Version; +import lombok.Getter; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.file.YamlConfiguration; import java.net.URL; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class UpdateLoader extends ContentLoader { - public static final int RESOURCE_ID = 80548; - - private static boolean newestPluginVersion = true; - private static boolean newestConfigVersion = true; - private static Version defaultConfigVersion; - private static Version currentConfigVersion; - - public static Version getDefaultConfigVersion() { - return defaultConfigVersion; - } - - public static Version getCurrentConfigVersion() { - return currentConfigVersion; - } - - public static boolean isNewestConfigVersion() { - return newestConfigVersion; - } - - public static boolean isNewestPluginVersion() { - return newestPluginVersion; - } - - @Override - protected void load() { - try { - URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); - String response = IOUtils.toString(url); - Version plugin = Challenges.getInstance().getVersion(); - YamlConfiguration defaultConfig = Challenges.getInstance().getConfigManager().getDefaultConfig(); - defaultConfigVersion = defaultConfig == null ? plugin : Version.parse(defaultConfig.getString("config-version")); - currentConfigVersion = Version.parse(Challenges.getInstance().getConfigDocument().getString("config-version")); - Version latestVersion = Version.parse(response); - - if (latestVersion.isNewerThan(plugin)) { - Logger.info("A new version of Challenges is available: {}, you have {}", latestVersion, plugin); - newestPluginVersion = false; - } - if (defaultConfigVersion.isNewerThan(currentConfigVersion)) { - Logger.info("A new version of the config (plugins/Challenges/config.yml) is available"); - newestConfigVersion = false; - } - - } catch (Exception ex) { - Logger.error("Could not check for update: {}", ex.getMessage()); - } - } + public static final int RESOURCE_ID = 80548; + + @Getter + private static boolean newestPluginVersion = true; + @Getter + private static boolean newestConfigVersion = true; + @Getter + private static Version defaultConfigVersion; + @Getter + private static Version currentConfigVersion; + + @Override + protected void load() { + try { + URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); + String response = IOUtils.toString(url); + Version plugin = Challenges.getInstance().getVersion(); + YamlConfiguration defaultConfig = Challenges.getInstance().getConfigManager().getDefaultConfig(); + defaultConfigVersion = defaultConfig == null ? plugin : Version.parse(defaultConfig.getString("config-version")); + currentConfigVersion = Version.parse(Challenges.getInstance().getConfigDocument().getString("config-version")); + Version latestVersion = Version.parse(response); + + if (latestVersion.isNewerThan(plugin)) { + Logger.info("A new version of Challenges is available: {}, you have {}", latestVersion, plugin); + newestPluginVersion = false; + } + if (defaultConfigVersion.isNewerThan(currentConfigVersion)) { + Logger.info("A new version of the config (plugins/Challenges/config.yml) is available"); + newestConfigVersion = false; + } + + } catch (Exception ex) { + Logger.error("Could not check for update: {}", ex.getMessage()); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 26baedf27..6d9734968 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.blocks; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.implementation.setting.CutCleanSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting.SubSetting; @@ -15,157 +15,153 @@ import java.util.function.BooleanSupplier; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class BlockDropManager { - private final Map drops = new HashMap<>(); - private final Map chance = new HashMap<>(); - private SubSetting directInventorySetting; - - @Nonnull - public Collection getDrops(@Nonnull Block block) { - if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); - List customDrops = getCustomDrops(block.getType()); - if (!customDrops.isEmpty()) - return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); - return block.getDrops(); - } - - @Nonnull - public Collection getDrops(@Nonnull Block block, @Nullable ItemStack tool) { - if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); - List customDrops = getCustomDrops(block.getType()); - if (!customDrops.isEmpty()) - return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); - return block.getDrops(tool); - } + private final Map drops = new HashMap<>(); + private final Map chance = new HashMap<>(); + private SubSetting directInventorySetting; + + @Nonnull + public Collection getDrops(@Nonnull Block block) { + if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); + List customDrops = getCustomDrops(block.getType()); + if (!customDrops.isEmpty()) + return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); + return block.getDrops(); + } + + @Nonnull + public Collection getDrops(@Nonnull Block block, @Nullable ItemStack tool) { + if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); + List customDrops = getCustomDrops(block.getType()); + if (!customDrops.isEmpty()) + return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); + return block.getDrops(tool); + } - @Nonnull - public List getCustomDrops(@Nonnull Material block) { - RegisteredDrops option = drops.get(block); - if (option == null) return new ArrayList<>(); - return option.getFirst().orElse(new ArrayList<>()); - } - - public void setCustomDrops(@Nonnull Material block, @Nonnull Material item, byte priority) { - setCustomDrops(block, Collections.singletonList(item), priority); - } - - public void setCustomDrops(@Nonnull Material block, @Nonnull List items, byte priority) { - Logger.debug("Setting block drop for {} to {} at priority {}", block, items, priority); - - RegisteredDrops option = this.drops.computeIfAbsent(block, key -> new RegisteredDrops()); - option.setOption(priority, items); - } - - public void resetCustomDrop(@Nonnull Material block, byte priority) { - Logger.debug("Resetting block drop for {} at priority {}", block, priority); - - RegisteredDrops option = drops.get(block); - if (option == null) return; - - option.resetOption(priority); - if (option.isEmpty()) drops.remove(block); - } - - public void resetCustomDrops(byte priority) { - Logger.debug("Resetting block drops at priority {}", priority); - - List remove = new ArrayList<>(); - for (Entry entry : drops.entrySet()) { - - RegisteredDrops option = entry.getValue(); - option.resetOption(priority); - if (option.isEmpty()) remove.add(entry.getKey()); - } - - remove.forEach(drops::remove); - } - - @Nonnull - public BooleanSupplier getDropChance(@Nonnull Material block) { - RegisteredChance option = chance.get(block); - if (option == null) return () -> true; - return option.getFirst().orElse(() -> true); - } - - public void setDropChance(@Nonnull Material block, byte priority, @Nonnull BooleanSupplier chance) { - Logger.debug("Setting block drop chance for {} at priority {}", block, priority); - - RegisteredChance option = this.chance.computeIfAbsent(block, key -> new RegisteredChance()); - option.setOption(priority, chance); - } - - public void resetDropChance(byte priority) { - Logger.debug("Resetting block drop chance at priority " + priority); - - List remove = new ArrayList<>(); - for (Entry entry : chance.entrySet()) { - - RegisteredChance option = entry.getValue(); - option.resetOption(priority); - if (option.isEmpty()) remove.add(entry.getKey()); - } - - remove.forEach(drops::remove); - } - - @Nonnull - public Map getRegisteredDrops() { - return Collections.unmodifiableMap(drops); - } - - public boolean isItemsDirectIntoInventory() { - if (directInventorySetting == null) - directInventorySetting = AbstractChallenge.getFirstInstance(CutCleanSetting.class).getSetting("items->inventory"); - return directInventorySetting.isEnabled(); - } - - public static final class DropPriority { - - public static final byte - CUT_CLEAN = 10, - RANDOMIZER = 5, - CHANCE = -128; - - private DropPriority() { - } - } - - private static abstract class RegisteredOptions { + @Nonnull + public List getCustomDrops(@Nonnull Material block) { + RegisteredDrops option = drops.get(block); + if (option == null) return new ArrayList<>(); + return option.getFirst().orElse(new ArrayList<>()); + } + + public void setCustomDrops(@Nonnull Material block, @Nonnull Material item, byte priority) { + setCustomDrops(block, Collections.singletonList(item), priority); + } + + public void setCustomDrops(@Nonnull Material block, @Nonnull List items, byte priority) { + Logger.debug("Setting block drop for {} to {} at priority {}", block, items, priority); + + RegisteredDrops option = this.drops.computeIfAbsent(block, key -> new RegisteredDrops()); + option.setOption(priority, items); + } + + public void resetCustomDrop(@Nonnull Material block, byte priority) { + Logger.debug("Resetting block drop for {} at priority {}", block, priority); + + RegisteredDrops option = drops.get(block); + if (option == null) return; + + option.resetOption(priority); + if (option.isEmpty()) drops.remove(block); + } + + public void resetCustomDrops(byte priority) { + Logger.debug("Resetting block drops at priority {}", priority); + + List remove = new ArrayList<>(); + for (Entry entry : drops.entrySet()) { + + RegisteredDrops option = entry.getValue(); + option.resetOption(priority); + if (option.isEmpty()) remove.add(entry.getKey()); + } + + remove.forEach(drops::remove); + } + + @Nonnull + public BooleanSupplier getDropChance(@Nonnull Material block) { + RegisteredChance option = chance.get(block); + if (option == null) return () -> true; + return option.getFirst().orElse(() -> true); + } + + public void setDropChance(@Nonnull Material block, byte priority, @Nonnull BooleanSupplier chance) { + Logger.debug("Setting block drop chance for {} at priority {}", block, priority); + + RegisteredChance option = this.chance.computeIfAbsent(block, key -> new RegisteredChance()); + option.setOption(priority, chance); + } + + public void resetDropChance(byte priority) { + Logger.debug("Resetting block drop chance at priority " + priority); + + List remove = new ArrayList<>(); + for (Entry entry : chance.entrySet()) { + + RegisteredChance option = entry.getValue(); + option.resetOption(priority); + if (option.isEmpty()) remove.add(entry.getKey()); + } + + remove.forEach(drops::remove); + } + + @Nonnull + public Map getRegisteredDrops() { + return Collections.unmodifiableMap(drops); + } + + public boolean isItemsDirectIntoInventory() { + if (directInventorySetting == null) + directInventorySetting = AbstractChallenge.getFirstInstance(CutCleanSetting.class).getSetting("items->inventory"); + return directInventorySetting.isEnabled(); + } + + public static final class DropPriority { + + public static final byte + CUT_CLEAN = 10, + RANDOMIZER = 5, + CHANCE = -128; + + private DropPriority() { + } + } + + private static abstract class RegisteredOptions { - private final SortedMap optionByPriority = new TreeMap<>(Collections.reverseOrder()); + private final SortedMap optionByPriority = new TreeMap<>(Collections.reverseOrder()); - public void setOption(byte priority, @Nonnull T option) { - optionByPriority.put(priority, option); - } + public void setOption(byte priority, @Nonnull T option) { + optionByPriority.put(priority, option); + } - public void resetOption(byte priority) { - optionByPriority.remove(priority); - } + public void resetOption(byte priority) { + optionByPriority.remove(priority); + } - @Nonnull - public Optional getFirst() { - return optionByPriority.values().stream().findFirst(); - } + @Nonnull + public Optional getFirst() { + return optionByPriority.values().stream().findFirst(); + } - public boolean isEmpty() { - return optionByPriority.isEmpty(); - } + public boolean isEmpty() { + return optionByPriority.isEmpty(); + } - } + } - public static class RegisteredDrops extends RegisteredOptions> { - private RegisteredDrops() { - } - } + public static class RegisteredDrops extends RegisteredOptions> { + private RegisteredDrops() { + } + } - public static class RegisteredChance extends RegisteredOptions { - private RegisteredChance() { - } - } + public static class RegisteredChance extends RegisteredOptions { + private RegisteredChance() { + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 4c7223d50..92bd18d14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -1,47 +1,43 @@ package net.codingarea.challenges.plugin.management.bstats; -import net.anweisen.utilities.bukkit.utils.bstats.Metrics; -import net.anweisen.utilities.bukkit.utils.bstats.chart.AdvancedPie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SimplePie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SingleLineChart; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.bstats.Metrics; +import net.codingarea.commons.bukkit.utils.bstats.chart.AdvancedPie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SimplePie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SingleLineChart; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.misc.MemoryConverter; import java.util.HashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class MetricsLoader { - public void start() { - Challenges plugin = Challenges.getInstance(); - - Metrics metrics = new Metrics(plugin, 11494); - metrics.addCustomChart(new SimplePie("language", () -> { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry() - .getFirstLoaderByClass(LanguageLoader.class); - if (loader == null) return "NULL"; - return loader.getLanguage(); - })); - metrics.addCustomChart(new SimplePie("cloudType", () -> StringUtils.getEnumName(plugin.getCloudSupportManager().getType()))); - metrics.addCustomChart(new SimplePie("databaseType", () -> StringUtils.getEnumName(plugin.getDatabaseManager().getType()))); - metrics.addCustomChart(new SingleLineChart("totalMemory", this::getMemory)); - metrics.addCustomChart(new SingleLineChart("totalCores", () -> Runtime.getRuntime().availableProcessors())); - metrics.addCustomChart(new AdvancedPie("maxMemory", () -> { - HashMap map = new HashMap<>(); - if (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE) return map; - map.put(String.valueOf(getMemory()), 1); - return map; - })); - - } - - private int getMemory() { - return MemoryConverter.getGB(Runtime.getRuntime().maxMemory()); - } - -} \ No newline at end of file + public void start() { + Challenges plugin = Challenges.getInstance(); + + Metrics metrics = new Metrics(plugin, 11494); + metrics.addCustomChart(new SimplePie("language", () -> { + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry() + .getFirstLoaderByClass(LanguageLoader.class); + if (loader == null) return "NULL"; + return loader.getLanguage(); + })); + metrics.addCustomChart(new SimplePie("cloudType", () -> StringUtils.getEnumName(plugin.getCloudSupportManager().getType()))); + metrics.addCustomChart(new SimplePie("databaseType", () -> StringUtils.getEnumName(plugin.getDatabaseManager().getType()))); + metrics.addCustomChart(new SingleLineChart("totalMemory", this::getMemory)); + metrics.addCustomChart(new SingleLineChart("totalCores", () -> Runtime.getRuntime().availableProcessors())); + metrics.addCustomChart(new AdvancedPie("maxMemory", () -> { + HashMap map = new HashMap<>(); + if (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE) return map; + map.put(String.valueOf(getMemory()), 1); + return map; + })); + + } + + private int getMemory() { + return MemoryConverter.getGB(Runtime.getRuntime().maxMemory()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 94cf138a9..cf5b7a59a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -1,98 +1,20 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.AdvancementDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.BlockBreakDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.BlockPlaceDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DamagePerBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DamagePerItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DeathOnFallChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.FreezeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.JumpDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.ReversedDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.SneakDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.WaterAllergyChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.BlockEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.ChunkRandomEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.EntityRandomEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.InfectionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.PermanentEffectOnDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.RandomPotionEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.AllMobsToDeathPoint; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.BlockMobsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.DupedSpawningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.HydraNormalChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.HydraPlusChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.InvisibleMobsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobSightDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobTransformationChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobsRespawnInEndChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.NewEntityOnJumpChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.StoneSightChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.JumpAndRunChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.WaterMLGChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceBiomeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceHeightChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceMobChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.DamageInventoryClearChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.MissingItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.MovementItemRemovingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.NoDupedItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.PermanentItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.PickupItemLaunchChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.UncraftItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.EnderGamesChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.FoodLaunchChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.FoodOnceChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.InvertHealthChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.LowDropRateChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoExpChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoSharedAdvancementsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoTradingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.OneDurabilityChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.AlwaysRunningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.DontStopRunningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.FiveHundredBlocksChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.HigherJumpsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.HungerPerBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.MoveMouseDamage; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.OnlyDirtChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.OnlyDownChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.TrafficLightChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.BlockRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.CraftingRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.EntityLootRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.HotBarRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.MobRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomChallengeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomEventChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemDroppingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemRemovingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemSwappingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomTeleportOnHitChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomizedHPChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxBiomeTimeChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxHeightTimeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.AllBlocksDisappearChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.AnvilRainChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BedrockPathChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BedrockWallChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BlockFlyInAirChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BlocksDisappearAfterTimeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.ChunkDeconstructionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.ChunkDeletionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.FloorIsLavaChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.IceFloorChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.LevelBorderChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.LoopChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.RepeatInChunkChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.SnakeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.SurfaceHoleChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.TsunamiChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; @@ -103,260 +25,257 @@ /** * This class loads all challenges of this plugin. - * In pre2 versions, this class was known as PluginChallengeLoader. - * - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 */ public final class ChallengeLoader extends ModuleChallengeLoader { - public ChallengeLoader() { - super(Challenges.getInstance()); - } - - public void enable() { - - // Settings - registerWithCommand(DifficultySetting.class, "difficulty"); - register(RegenerationSetting.class); - register(OneTeamLifeSetting.class); - register(RespawnSetting.class); - register(SplitHealthSetting.class); - register(DamageDisplaySetting.class); - register(PregameMovementSetting.class); - - register(DeathMessageSetting.class); - register(HealthDisplaySetting.class); - registerWithCommand(PositionSetting.class, "position"); - register(DeathPositionSetting.class); - register(PlayerGlowSetting.class); - register(SoupSetting.class); - register(NoHungerSetting.class); - - register(NoItemDamageSetting.class); - register(MobGriefingSetting.class); - register(KeepInventorySetting.class); - registerWithCommand(BackpackSetting.class, "backpack"); - registerWithCommand(EnderChestCommandSetting.class, "enderchest"); - register(TimberSetting.class); - register(PvPSetting.class); - - register(NoHitDelaySetting.class); - registerWithCommand(TopCommandSetting.class, "top"); - register(MaxHealthSetting.class); - register(DamageMultiplierModifier.class); - register(CutCleanSetting.class); - register(FortressSpawnSetting.class); - register(BastionSpawnSetting.class); - - register(NoOffhandSetting.class); - register(ImmediateRespawnSetting.class); - - register(SlotLimitSetting.class); - register(OldPvPSetting.class); - register(TotemSaveDeathSetting.class); - - - // Challenges - - // Randomizer - register(RandomChallengeChallenge.class); - register(RandomizedHPChallenge.class); - register(BlockRandomizerChallenge.class); - register(CraftingRandomizerChallenge.class); - register(HotBarRandomizerChallenge.class); - registerWithCommand(EntityLootRandomizerChallenge.class, "searchloot"); - register(MobRandomizerChallenge.class); - register(RandomItemDroppingChallenge.class); - register(RandomItemRemovingChallenge.class); - register(RandomItemSwappingChallenge.class); - register(RandomItemChallenge.class); - register(RandomEventChallenge.class); - register(RandomTeleportOnHitChallenge.class); - - // Force - register(ForceHeightChallenge.class); - register(ForceBlockChallenge.class); - register(ForceMobChallenge.class); - register(ForceItemChallenge.class); - register(ForceBiomeChallenge.class); - - // Entities - register(HydraNormalChallenge.class); - register(HydraPlusChallenge.class); - register(DupedSpawningChallenge.class); - register(NewEntityOnJumpChallenge.class); - register(InvisibleMobsChallenge.class); - register(StoneSightChallenge.class); - register(MobSightDamageChallenge.class); - register(AllMobsToDeathPoint.class); - register(MobsRespawnInEndChallenge.class); - register(MobTransformationChallenge.class); - register(BlockMobsChallenge.class); - - // Damage - register(DamagePerBlockChallenge.class); - register(SneakDamageChallenge.class); - register(JumpDamageChallenge.class); - register(BlockBreakDamageChallenge.class); - register(BlockPlaceDamageChallenge.class); - register(AdvancementDamageChallenge.class); - register(DamagePerItemChallenge.class); - register(WaterAllergyChallenge.class); - register(DeathOnFallChallenge.class); - register(ReversedDamageChallenge.class); - register(FreezeChallenge.class); - - // Effect - register(ChunkRandomEffectChallenge.class); - register(BlockEffectChallenge.class); - register(EntityRandomEffectChallenge.class); - register(RandomPotionEffectChallenge.class); - register(PermanentEffectOnDamageChallenge.class); - register(InfectionChallenge.class); - - // World - register(SurfaceHoleChallenge.class); - register(BedrockWallChallenge.class); - register(BedrockPathChallenge.class); - register(FloorIsLavaChallenge.class); - register(ChunkDeconstructionChallenge.class); - register(AllBlocksDisappearChallenge.class); - register(AnvilRainChallenge.class); - register(TsunamiChallenge.class); - register(RepeatInChunkChallenge.class); - register(SnakeChallenge.class); - register(BlockFlyInAirChallenge.class); - register(BlocksDisappearAfterTimeChallenge.class); - register(LoopChallenge.class); - register(IceFloorChallenge.class); - register(LevelBorderChallenge.class); - register(ChunkDeletionChallenge.class); - - // Inventory - register(PermanentItemChallenge.class); - register(NoDupedItemsChallenge.class); - register(DamageInventoryClearChallenge.class); - register(UncraftItemsChallenge.class); - registerWithCommand(MissingItemsChallenge.class, "openmissingitems"); - register(PickupItemLaunchChallenge.class); - register(MovementItemRemovingChallenge.class); - - // Movement - register(TrafficLightChallenge.class); - register(HungerPerBlockChallenge.class); - register(OnlyDownChallenge.class); - register(OnlyDirtChallenge.class); - register(HigherJumpsChallenge.class); - register(AlwaysRunningChallenge.class); - register(DontStopRunningChallenge.class); - register(MoveMouseDamage.class); - register(FiveHundredBlocksChallenge.class); - - // Limited Time - register(MaxBiomeTimeChallenge.class); - register(MaxHeightTimeChallenge.class); - - // Custom World - register(WaterMLGChallenge.class); - register(JumpAndRunChallenge.class); - - // Misc - register(OneDurabilityChallenge.class); - register(NoTradingChallenge.class); - register(NoExpChallenge.class); - register(FoodOnceChallenge.class); - register(FoodLaunchChallenge.class); - register(LowDropRateChallenge.class); - register(EnderGamesChallenge.class); - register(InvertHealthChallenge.class); - register(NoSharedAdvancementsChallenge.class); - - - // Goal - - // Kill - register(KillEnderDragonGoal.class); - register(KillWitherGoal.class); - register(KillElderGuardianGoal.class); - register(KillWardenGoal.class); - register(KillAllBossesGoal.class); - register(KillAllBossesNewGoal.class); - register(KillIronGolemGoal.class); - register(KillSnowGolemGoal.class); - register(KillAllMobsGoal.class); - register(KillAllMonsterGoal.class); - - // Score Points - register(CollectMostDeathsGoal.class); - register(CollectMostItemsGoal.class); - register(MineMostBlocksGoal.class); - register(CollectMostExpGoal.class); - register(MostEmeraldsGoal.class); - register(MostOresGoal.class); - register(EatMostGoal.class); - - // Fastest Time - register(FirstOneToDieGoal.class); - register(CollectWoodGoal.class); - register(FinishRaidGoal.class); - register(AllAdvancementGoal.class); - register(MaxHeightGoal.class); - register(MinHeightGoal.class); - register(RaceGoal.class); - register(FindElytraGoal.class); - register(EatCakeGoal.class); - register(CollectHorseAmorGoal.class); - register(CollectIceBlocksGoal.class); - register(CollectSwordsGoal.class); - register(CollectWorkstationsGoal.class); - register(GetFullHealthGoal.class); - - // Force battle - register(ForceItemBattleGoal.class); - register(ForceMobBattleGoal.class); - register(ForceAdvancementBattleGoal.class); - register(ForceBlockBattleGoal.class); - register(ForceBiomeBattleGoal.class); - register(ForceDamageBattleGoal.class); - register(ForceHeightBattleGoal.class); - register(ForcePositionBattleGoal.class); - register(ExtremeForceBattleGoal.class); - - // Misc - register(LastManStandingGoal.class); - registerWithCommand(CollectAllItemsGoal.class, "skipitem"); - - - // Damage Rules - registerDamageRule("none", Material.TOTEM_OF_UNDYING, DamageCause.values()); - registerDamageRule("fire", Material.LAVA_BUCKET, DamageCause.FIRE, DamageCause.FIRE_TICK, DamageCause.LAVA, DamageCause.HOT_FLOOR); - registerDamageRule("attack", Material.DIAMOND_SWORD, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_SWEEP_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.THORNS); - registerDamageRule("projectile", Material.ARROW, DamageCause.PROJECTILE); - registerDamageRule("fall", Material.FEATHER, DamageCause.FALL); - registerDamageRule("explosion", Material.TNT, DamageCause.ENTITY_EXPLOSION, DamageCause.BLOCK_EXPLOSION); - registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); - registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); - registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_17)) { - registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); - } - - // Material Rules - registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); - registerMaterialRule("§6Golden Apple", "Golden Apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); - registerMaterialRule("§6Crafting Table", "Crafting Table", Material.CRAFTING_TABLE); - registerMaterialRule("§6Chest", "Chest", Material.CHEST); - registerMaterialRule("§cFurnace", "Furnace", Material.FURNACE, Material.FURNACE_MINECART); - registerMaterialRule("§5Enchanting Table", "Enchanting Table", Material.ENCHANTING_TABLE); - registerMaterialRule("§cAnvil", "Anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); - registerMaterialRule("§dBrewing Stand", "Brewing Stand", Material.BREWING_STAND); - registerMaterialRule("§cBow", "Bow", Material.BOW); - registerMaterialRule("§fSnowball", "Snowball", Material.SNOWBALL); - registerMaterialRule("§cFlint and Steel", "Flint and Steel", Material.FLINT_AND_STEEL); - registerMaterialRule("§cBucket", "Bucket", Material.BUCKET); - } + public ChallengeLoader() { + super(Challenges.getInstance()); + } + + public void enable() { + + // Settings + registerWithCommand(DifficultySetting.class, "difficulty"); + register(RegenerationSetting.class); + register(OneTeamLifeSetting.class); + register(RespawnSetting.class); + register(SplitHealthSetting.class); + register(DamageDisplaySetting.class); + register(LanguageSetting.class); + + register(PregameMovementSetting.class); + register(DeathMessageSetting.class); + register(HealthDisplaySetting.class); + registerWithCommand(PositionSetting.class, "position"); + register(DeathPositionSetting.class); + register(PlayerGlowSetting.class); + register(NoHungerSetting.class); + + register(NoItemDamageSetting.class); + register(MobGriefingSetting.class); + register(KeepInventorySetting.class); + registerWithCommand(BackpackSetting.class, "backpack"); + registerWithCommand(EnderChestCommandSetting.class, "enderchest"); + register(TimberSetting.class); + register(PvPSetting.class); + + register(NoHitDelaySetting.class); + registerWithCommand(TopCommandSetting.class, "top"); + register(MaxHealthSetting.class); + register(DamageMultiplierModifier.class); + register(CutCleanSetting.class); + register(FortressSpawnSetting.class); + register(BastionSpawnSetting.class); + + register(NoOffhandSetting.class); + register(ImmediateRespawnSetting.class); + + register(SlotLimitSetting.class); + register(OldPvPSetting.class); + register(TotemSaveDeathSetting.class); + register(SoupSetting.class); + + + // Challenges + + // Randomizer + register(RandomChallengeChallenge.class); + register(RandomizedHPChallenge.class); + register(BlockRandomizerChallenge.class); + register(CraftingRandomizerChallenge.class); + register(HotBarRandomizerChallenge.class); + registerWithCommand(EntityLootRandomizerChallenge.class, "searchloot"); + register(MobRandomizerChallenge.class); + register(RandomItemDroppingChallenge.class); + register(RandomItemRemovingChallenge.class); + register(RandomItemSwappingChallenge.class); + register(RandomItemChallenge.class); + register(RandomEventChallenge.class); + register(RandomTeleportOnHitChallenge.class); + + // Force + register(ForceHeightChallenge.class); + register(ForceBlockChallenge.class); + register(ForceMobChallenge.class); + register(ForceItemChallenge.class); + register(ForceBiomeChallenge.class); + + // Entities + register(HydraNormalChallenge.class); + register(HydraPlusChallenge.class); + register(DupedSpawningChallenge.class); + register(NewEntityOnJumpChallenge.class); + register(InvisibleMobsChallenge.class); + register(StoneSightChallenge.class); + register(MobSightDamageChallenge.class); + register(AllMobsToDeathPoint.class); + register(MobsRespawnInEndChallenge.class); + register(MobTransformationChallenge.class); + register(BlockMobsChallenge.class); + + // Damage + register(DamagePerBlockChallenge.class); + register(SneakDamageChallenge.class); + register(JumpDamageChallenge.class); + register(BlockBreakDamageChallenge.class); + register(BlockPlaceDamageChallenge.class); + register(AdvancementDamageChallenge.class); + register(DamagePerItemChallenge.class); + register(WaterAllergyChallenge.class); + register(DeathOnFallChallenge.class); + register(ReversedDamageChallenge.class); + register(FreezeChallenge.class); + register(DelayDamageChallenge.class); + + // Effect + register(ChunkRandomEffectChallenge.class); + register(BlockEffectChallenge.class); + register(EntityRandomEffectChallenge.class); + register(RandomPotionEffectChallenge.class); + register(PermanentEffectOnDamageChallenge.class); + register(InfectionChallenge.class); + + // World + register(SurfaceHoleChallenge.class); + register(BedrockWallChallenge.class); + register(BedrockPathChallenge.class); + register(FloorIsLavaChallenge.class); + register(ChunkDeconstructionChallenge.class); + register(AllBlocksDisappearChallenge.class); + register(AnvilRainChallenge.class); + register(TsunamiChallenge.class); + register(RepeatInChunkChallenge.class); + register(SnakeChallenge.class); + register(BlockFlyInAirChallenge.class); + register(BlocksDisappearAfterTimeChallenge.class); + register(LoopChallenge.class); + register(IceFloorChallenge.class); + register(LevelBorderChallenge.class); + register(ChunkDeletionChallenge.class); + + // Inventory + register(PermanentItemChallenge.class); + register(NoDupedItemsChallenge.class); + register(DamageInventoryClearChallenge.class); + register(UncraftItemsChallenge.class); + registerWithCommand(MissingItemsChallenge.class, "openmissingitems"); + register(PickupItemLaunchChallenge.class); + register(MovementItemRemovingChallenge.class); + + // Movement + register(TrafficLightChallenge.class); + register(HungerPerBlockChallenge.class); + register(OnlyDownChallenge.class); + register(OnlyDirtChallenge.class); + register(HigherJumpsChallenge.class); + register(AlwaysRunningChallenge.class); + register(DontStopRunningChallenge.class); + register(MoveMouseDamage.class); + register(FiveHundredBlocksChallenge.class); + + // Limited Time + register(MaxBiomeTimeChallenge.class); + register(MaxHeightTimeChallenge.class); + + // Custom World + register(WaterMLGChallenge.class); + register(JumpAndRunChallenge.class); + + // Misc + register(OneDurabilityChallenge.class); + register(NoTradingChallenge.class); + register(NoExpChallenge.class); + register(FoodOnceChallenge.class); + register(FoodLaunchChallenge.class); + register(LowDropRateChallenge.class); + register(EnderGamesChallenge.class); + register(InvertHealthChallenge.class); + register(NoSharedAdvancementsChallenge.class); + + + // Goal + + // Kill + register(KillEnderDragonGoal.class); + register(KillWitherGoal.class); + register(KillElderGuardianGoal.class); + register(KillWardenGoal.class); + register(KillAllBossesGoal.class); + register(KillAllBossesNewGoal.class); + register(KillIronGolemGoal.class); + register(KillSnowGolemGoal.class); + register(KillAllMobsGoal.class); + register(KillAllMonsterGoal.class); + + // Score Points + register(CollectMostDeathsGoal.class); + register(CollectMostItemsGoal.class); + register(MineMostBlocksGoal.class); + register(CollectMostExpGoal.class); + register(MostEmeraldsGoal.class); + register(MostOresGoal.class); + register(EatMostGoal.class); + + // Fastest Time + register(FirstOneToDieGoal.class); + register(CollectWoodGoal.class); + register(FinishRaidGoal.class); + register(AllAdvancementGoal.class); + register(MaxHeightGoal.class); + register(MinHeightGoal.class); + register(RaceGoal.class); + register(FindElytraGoal.class); + register(EatCakeGoal.class); + register(CollectHorseAmorGoal.class); + register(CollectIceBlocksGoal.class); + register(CollectSwordsGoal.class); + register(CollectWorkstationsGoal.class); + register(GetFullHealthGoal.class); + + // Force battle + register(ForceItemBattleGoal.class); + register(ForceMobBattleGoal.class); + register(ForceAdvancementBattleGoal.class); + register(ForceBlockBattleGoal.class); + register(ForceBiomeBattleGoal.class); + register(ForceDamageBattleGoal.class); + register(ForceHeightBattleGoal.class); + register(ForcePositionBattleGoal.class); + register(ExtremeForceBattleGoal.class); + + // Misc + register(LastManStandingGoal.class); + registerWithCommand(CollectAllItemsGoal.class, "skipitem"); + + + // Damage Rules + registerDamageRule("none", Material.TOTEM_OF_UNDYING, DamageCause.values()); + registerDamageRule("fire", Material.LAVA_BUCKET, DamageCause.FIRE, DamageCause.FIRE_TICK, DamageCause.LAVA, DamageCause.HOT_FLOOR); + registerDamageRule("attack", Material.DIAMOND_SWORD, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_SWEEP_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.THORNS); + registerDamageRule("projectile", Material.ARROW, DamageCause.PROJECTILE); + registerDamageRule("fall", Material.FEATHER, DamageCause.FALL); + registerDamageRule("explosion", Material.TNT, DamageCause.ENTITY_EXPLOSION, DamageCause.BLOCK_EXPLOSION); + registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); + registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); + registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_17)) { + registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); + } + + // Material Rules + registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); + registerMaterialRule("§6Golden Apple", "Golden Apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); + registerMaterialRule("§6Crafting Table", "Crafting Table", Material.CRAFTING_TABLE); + registerMaterialRule("§6Chest", "Chest", Material.CHEST); + registerMaterialRule("§cFurnace", "Furnace", Material.FURNACE, Material.FURNACE_MINECART); + registerMaterialRule("§5Enchanting Table", "Enchanting Table", Material.ENCHANTING_TABLE); + registerMaterialRule("§cAnvil", "Anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); + registerMaterialRule("§dBrewing Stand", "Brewing Stand", Material.BREWING_STAND); + registerMaterialRule("§cBow", "Bow", Material.BOW); + registerMaterialRule("§fSnowball", "Snowball", Material.SNOWBALL); + registerMaterialRule("§cFlint and Steel", "Flint and Steel", Material.FLINT_AND_STEEL); + registerMaterialRule("§cBucket", "Bucket", Material.BUCKET); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index f9a972891..da5245eac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.wrapper.FileDocumentWrapper; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -22,235 +22,231 @@ import java.util.List; import java.util.function.Predicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeManager { - private final List challenges = new LinkedList<>(); - private final List additionalSaver = new LinkedList<>(); - - private IGoal currentGoal; - - @Nonnull - public List getChallenges() { - return Collections.unmodifiableList(challenges); - } - - public void registerGameStateSaver(@Nonnull GamestateSaveable savable) { - additionalSaver.add(savable); - } - - public void register(@Nonnull IChallenge challenge) { - if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); - challenges.add(challenge); - } - - public void unregister(@Nonnull IChallenge challenge) { - challenges.remove(challenge); - } - - public void unregisterIf(@Nonnull Predicate predicate) { - challenges.removeIf(predicate); - } - - public void shutdownChallenges() { - for (IChallenge challenge : challenges) { - try { - challenge.handleShutdown(); - } catch (Exception ex) { - Logger.error("Could not handle shutdown for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void clearChallengeCache() { - challenges.clear(); - currentGoal = null; - } - - public void restoreDefaults() { - Logger.debug("Restoring default settings.."); - Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); - for (IChallenge challenge : challenges) { - try { - challenge.restoreDefaults(); - } catch (Exception ex) { - Logger.error("Could not restore defaults for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void saveSettings(@Nonnull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveSettingsInto(document); - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", player.getUniqueId()) - .set("config", document) - .execute(); - } - - public void saveCustomChallenges(@Nonnull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveCustomChallengesInto(document); - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", player.getUniqueId()) - .set("custom_challenges", document) - .execute(); - } - - public void enable() { - loadGamestate(Challenges.getInstance().getConfigManager().getGamestateConfig().readonly()); - loadSettings(Challenges.getInstance().getConfigManager().getSettingsConfig().readonly()); - loadCustomChallenges(Challenges.getInstance().getConfigManager().getCustomChallengesConfig().readonly()); - } - - public synchronized void loadSettings(@Nonnull Document config) { - - for (IChallenge challenge : challenges) { - if (challenge instanceof CustomChallenge) continue; - - String name = challenge.getUniqueName(); - if (!config.contains(name)) continue; - try { - Document document = config.getDocument(name); - challenge.loadSettings(document); - } catch (Exception ex) { - Logger.error("Could not load setting for challenge {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void loadGamestate(@Nonnull Document config) { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - String name = challenge.getUniqueGamestateName(); - if (!config.contains(name)) continue; - try { - Document document = config.getDocument(name); - challenge.loadGameState(document); - - if (challenge instanceof AbstractChallenge) { - AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; - if (abstractChallenge.getBossbar().isShown()) { - abstractChallenge.getBossbar().update(); - } - if (abstractChallenge.getScoreboard().isShown()) { - abstractChallenge.getScoreboard().update(); - } - } - - } catch (Exception ex) { - Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void loadCustomChallenges(@Nonnull Document config) { - Challenges.getInstance().getCustomChallengesLoader().loadCustomChallengesFrom(config); - } - - public void resetGamestate() { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - try { - challenge.loadGameState(Document.empty()); - - if (challenge instanceof AbstractChallenge) { - AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; - if (abstractChallenge.getBossbar().isShown()) { - abstractChallenge.getBossbar().update(); - } - if (abstractChallenge.getScoreboard().isShown()) { - abstractChallenge.getScoreboard().update(); - } - } - } catch (Exception ex) { - Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void saveGameStateInto(@Nonnull Document config) { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - try { - Document document = config.getDocument(challenge.getUniqueGamestateName()); - challenge.writeGameState(document); - } catch (Exception ex) { - Logger.error("Could not write gamestate of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveGamestate(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getGamestateConfig(); - saveGameStateInto(config); - config.save(async); - } - - public void saveSettingsInto(@Nonnull Document config) { - for (IChallenge challenge : challenges) { - if (challenge instanceof CustomChallenge) continue; - try { - Document document = config.getDocument(challenge.getUniqueGamestateName()); - challenge.writeSettings(document); - } catch (Exception ex) { - Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveLocalSettings(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getSettingsConfig(); - saveSettingsInto(config); - config.save(async); - } - - public void saveCustomChallengesInto(@Nonnull Document config) { - Collection customChallenges = Challenges.getInstance().getCustomChallengesLoader() - .getCustomChallenges().values(); - - for (IChallenge challenge : customChallenges) { - try { - Document document = config.getDocument(challenge.getUniqueName()); - challenge.writeSettings(document); - challenge.writeGameState(document); - } catch (Exception ex) { - Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveLocalCustomChallenges(boolean async) { - FileDocument config = new FileDocumentWrapper(Challenges.getInstance().getDataFile("internal/custom_challenges.json"), new GsonDocument()); - saveCustomChallengesInto(config); - config.save(async); - } - - - @Nullable - public IGoal getCurrentGoal() { - return currentGoal; - } - - public void setCurrentGoal(@Nullable IGoal goal) { - - IGoal oldGoal = currentGoal; - currentGoal = goal; - - if (oldGoal != null) - oldGoal.setEnabled(false); - - if (goal != null) - goal.setEnabled(true); - - } + private final List challenges = new LinkedList<>(); + private final List additionalSaver = new LinkedList<>(); + + private IGoal currentGoal; + + @Nonnull + public List getChallenges() { + return Collections.unmodifiableList(challenges); + } + + public void registerGameStateSaver(@Nonnull GamestateSaveable savable) { + additionalSaver.add(savable); + } + + public void register(@Nonnull IChallenge challenge) { + if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); + challenges.add(challenge); + } + + public void unregister(@Nonnull IChallenge challenge) { + challenges.remove(challenge); + } + + public void unregisterIf(@Nonnull Predicate predicate) { + challenges.removeIf(predicate); + } + + public void shutdownChallenges() { + for (IChallenge challenge : challenges) { + try { + challenge.handleShutdown(); + } catch (Exception ex) { + Logger.error("Could not handle shutdown for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void clearChallengeCache() { + challenges.clear(); + currentGoal = null; + } + + public void restoreDefaults() { + Logger.debug("Restoring default settings.."); + Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); + for (IChallenge challenge : challenges) { + try { + challenge.restoreDefaults(); + } catch (Exception ex) { + Logger.error("Could not restore defaults for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void saveSettings(@Nonnull Player player) throws DatabaseException { + Document document = new GsonDocument(); + saveSettingsInto(document); + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", player.getUniqueId()) + .set("config", document) + .execute(); + } + + public void saveCustomChallenges(@Nonnull Player player) throws DatabaseException { + Document document = new GsonDocument(); + saveCustomChallengesInto(document); + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", player.getUniqueId()) + .set("custom_challenges", document) + .execute(); + } + + public void enable() { + loadGamestate(Challenges.getInstance().getConfigManager().getGamestateConfig().readonly()); + loadSettings(Challenges.getInstance().getConfigManager().getSettingsConfig().readonly()); + loadCustomChallenges(Challenges.getInstance().getConfigManager().getCustomChallengesConfig().readonly()); + } + + public synchronized void loadSettings(@Nonnull Document config) { + + for (IChallenge challenge : challenges) { + if (challenge instanceof CustomChallenge) continue; + + String name = challenge.getUniqueName(); + if (!config.contains(name)) continue; + try { + Document document = config.getDocument(name); + challenge.loadSettings(document); + } catch (Exception ex) { + Logger.error("Could not load setting for challenge {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void loadGamestate(@Nonnull Document config) { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + String name = challenge.getUniqueGamestateName(); + if (!config.contains(name)) continue; + try { + Document document = config.getDocument(name); + challenge.loadGameState(document); + + if (challenge instanceof AbstractChallenge) { + AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; + if (abstractChallenge.getBossbar().isShown()) { + abstractChallenge.getBossbar().update(); + } + if (abstractChallenge.getScoreboard().isShown()) { + abstractChallenge.getScoreboard().update(); + } + } + + } catch (Exception ex) { + Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void loadCustomChallenges(@Nonnull Document config) { + Challenges.getInstance().getCustomChallengesLoader().loadCustomChallengesFrom(config); + } + + public void resetGamestate() { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + try { + challenge.loadGameState(Document.empty()); + + if (challenge instanceof AbstractChallenge) { + AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; + if (abstractChallenge.getBossbar().isShown()) { + abstractChallenge.getBossbar().update(); + } + if (abstractChallenge.getScoreboard().isShown()) { + abstractChallenge.getScoreboard().update(); + } + } + } catch (Exception ex) { + Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void saveGameStateInto(@Nonnull Document config) { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + try { + Document document = config.getDocument(challenge.getUniqueGamestateName()); + challenge.writeGameState(document); + } catch (Exception ex) { + Logger.error("Could not write gamestate of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveGamestate(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getGamestateConfig(); + saveGameStateInto(config); + config.save(async); + } + + public void saveSettingsInto(@Nonnull Document config) { + for (IChallenge challenge : challenges) { + if (challenge instanceof CustomChallenge) continue; + try { + Document document = config.getDocument(challenge.getUniqueGamestateName()); + challenge.writeSettings(document); + } catch (Exception ex) { + Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveLocalSettings(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getSettingsConfig(); + saveSettingsInto(config); + config.save(async); + } + + public void saveCustomChallengesInto(@Nonnull Document config) { + Collection customChallenges = Challenges.getInstance().getCustomChallengesLoader() + .getCustomChallenges().values(); + + for (IChallenge challenge : customChallenges) { + try { + Document document = config.getDocument(challenge.getUniqueName()); + challenge.writeSettings(document); + challenge.writeGameState(document); + } catch (Exception ex) { + Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveLocalCustomChallenges(boolean async) { + FileDocument config = new FileDocumentWrapper(Challenges.getInstance().getDataFile("internal/custom_challenges.json"), new GsonDocument()); + saveCustomChallengesInto(config); + config.save(async); + } + + + @Nullable + public IGoal getCurrentGoal() { + return currentGoal; + } + + public void setCurrentGoal(@Nullable IGoal goal) { + + IGoal oldGoal = currentGoal; + currentGoal = goal; + + if (oldGoal != null) + oldGoal.setEnabled(false); + + if (goal != null) + goal.setEnabled(true); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 976d2f181..4696a756d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.common.config.Document; +import lombok.Getter; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; @@ -16,120 +17,109 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ +@Getter public class CustomChallengesLoader extends ModuleChallengeLoader { - private final Map customChallenges = new LinkedHashMap<>(); - - private final int maxNameLength; - - public CustomChallengesLoader() { - super(Challenges.getInstance()); - maxNameLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-name-length"); - } - - public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material material, String name, ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions, boolean generate) { - CustomChallenge challenge = customChallenges.getOrDefault(uuid, new CustomChallenge(MenuType.CUSTOM, uuid, material, name, trigger, subTriggers, action, subActions)); - if (!customChallenges.containsKey(uuid)) { - customChallenges.put(uuid, challenge); - register(challenge); - } else { - challenge.applySettings(material, name, trigger, subTriggers, action, subActions); - } - generateCustomChallenge(challenge, false, generate); - return challenge; - } - - public void unregisterCustomChallenge(@Nonnull UUID uuid) { - CustomChallenge challenge = customChallenges.remove(uuid); - if (challenge == null) return; - Challenges.getInstance().getChallengeLoader().unregister(challenge); - generateCustomChallenge(challenge, true, true); - } - - public void loadCustomChallengesFrom(@Nonnull Document document) { - customChallenges.clear(); - Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); - - for (String key : document.keys()) { - try { - Document doc = document.getDocument(key); - - UUID uuid = UUID.fromString(key); - String name = doc.getString("name"); - Material material = doc.getEnum("material", Material.class); - ChallengeTrigger trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(doc.getString("trigger")); - Map subTriggers = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subTrigger")); - ChallengeAction action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(doc.getString("action")); - Map subActions = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subActions")); - - CustomChallenge challenge = registerCustomChallenge(uuid, material, name, trigger, subTriggers, action, subActions, false); - challenge.setEnabled(doc.getBoolean("enabled")); - - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); - Challenges.getInstance().getLogger().error("", exception); - } - - } - - MenuType.CUSTOM.getMenuGenerator().generateInventories(); - } - - public void resetChallenges() { - customChallenges.clear(); - Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); - } - - private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { - MenuGenerator generator = challenge.getType().getMenuGenerator(); - if (generator instanceof ChallengeMenuGenerator) { - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; - if (deleted) { - menuGenerator.removeChallengeFromCache(challenge); - if (generate) generator.generateInventories(); - } else { - if (!menuGenerator.isInChallengeCache(challenge)) { - menuGenerator.addChallengeToCache(challenge); - if (generate) generator.generateInventories(); - } else { - menuGenerator.updateItem(challenge); - } - - } - } - } - - public List getCustomChallengesByTrigger(@Nonnull IChallengeTrigger trigger) { - List challenges = new LinkedList<>(); - - for (CustomChallenge challenge : customChallenges.values()) { - if (challenge.getTrigger() != null && challenge.getTrigger() == trigger) { - challenges.add(challenge); - } - } - - return challenges; - } - - public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionData) { - getCustomChallengesByTrigger(challengeExecutionData.getTrigger()) - .forEach(customChallenge -> customChallenge - .onTriggerFulfilled(challengeExecutionData)); - } - - public int getMaxNameLength() { - return maxNameLength; - } - - public Map getCustomChallenges() { - return customChallenges; - } + private final Map customChallenges = new LinkedHashMap<>(); + + private final int maxNameLength; + + public CustomChallengesLoader() { + super(Challenges.getInstance()); + maxNameLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-name-length"); + } + + public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material material, String name, ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions, boolean generate) { + CustomChallenge challenge = customChallenges.getOrDefault(uuid, new CustomChallenge(MenuType.CUSTOM, uuid, material, name, trigger, subTriggers, action, subActions)); + if (!customChallenges.containsKey(uuid)) { + customChallenges.put(uuid, challenge); + register(challenge); + } else { + challenge.applySettings(material, name, trigger, subTriggers, action, subActions); + } + generateCustomChallenge(challenge, false, generate); + return challenge; + } + + public void unregisterCustomChallenge(@Nonnull UUID uuid) { + CustomChallenge challenge = customChallenges.remove(uuid); + if (challenge == null) return; + Challenges.getInstance().getChallengeLoader().unregister(challenge); + generateCustomChallenge(challenge, true, true); + } + + public void loadCustomChallengesFrom(@Nonnull Document document) { + customChallenges.clear(); + Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); + ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + + for (String key : document.keys()) { + try { + Document doc = document.getDocument(key); + + UUID uuid = UUID.fromString(key); + String name = doc.getString("name"); + Material material = doc.getEnum("material", Material.class); + ChallengeTrigger trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(doc.getString("trigger")); + Map subTriggers = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subTrigger")); + ChallengeAction action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(doc.getString("action")); + Map subActions = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subActions")); + + CustomChallenge challenge = registerCustomChallenge(uuid, material, name, trigger, subTriggers, action, subActions, false); + challenge.setEnabled(doc.getBoolean("enabled")); + + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); + Challenges.getInstance().getILogger().error("", exception); + } + + } + + MenuType.CUSTOM.getMenuGenerator().generateInventories(); + } + + public void resetChallenges() { + customChallenges.clear(); + Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); + ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + } + + private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { + MenuGenerator generator = challenge.getType().getMenuGenerator(); + if (generator instanceof ChallengeMenuGenerator) { + ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; + if (deleted) { + menuGenerator.removeChallengeFromCache(challenge); + if (generate) generator.generateInventories(); + } else { + if (!menuGenerator.isInChallengeCache(challenge)) { + menuGenerator.addChallengeToCache(challenge); + if (generate) generator.generateInventories(); + } else { + menuGenerator.updateItem(challenge); + } + + } + } + } + + public List getCustomChallengesByTrigger(@Nonnull IChallengeTrigger trigger) { + List challenges = new LinkedList<>(); + + for (CustomChallenge challenge : customChallenges.values()) { + if (challenge.getTrigger() != null && challenge.getTrigger() == trigger) { + challenges.add(challenge); + } + } + + return challenges; + } + + public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionData) { + getCustomChallengesByTrigger(challengeExecutionData.getTrigger()) + .forEach(customChallenge -> customChallenge + .onTriggerFulfilled(challengeExecutionData)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index d43232af7..28950d530 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; @@ -19,116 +19,112 @@ import java.lang.reflect.Constructor; import java.util.Optional; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class ModuleChallengeLoader { - protected final BukkitModule plugin; + protected final BukkitModule plugin; - public ModuleChallengeLoader(@Nonnull BukkitModule plugin) { - this.plugin = plugin; - } + public ModuleChallengeLoader(@Nonnull BukkitModule plugin) { + this.plugin = plugin; + } - public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull String... commandNames) { - try { + public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull String... commandNames) { + try { - Challenges.getInstance().getChallengeManager().register(challenge); - Challenges.getInstance().getScheduler().register(challenge); + Challenges.getInstance().getChallengeManager().register(challenge); + Challenges.getInstance().getScheduler().register(challenge); - if (challenge instanceof CommandExecutor) { - plugin.registerCommand((CommandExecutor) challenge, commandNames); - } - if (challenge instanceof Listener) { - plugin.registerListener((Listener) challenge); - } + if (challenge instanceof CommandExecutor) { + plugin.registerCommand((CommandExecutor) challenge, commandNames); + } + if (challenge instanceof Listener) { + plugin.registerListener((Listener) challenge); + } - } catch (Throwable ex) { - Logger.error("Could not register challenge {}", challenge.getClass().getSimpleName(), ex); - } - } + } catch (Throwable ex) { + Logger.error("Could not register challenge {}", challenge.getClass().getSimpleName(), ex); + } + } - public final void register(@Nonnull IChallenge challenge) { - registerWithCommand(challenge); - } + public final void register(@Nonnull IChallenge challenge) { + registerWithCommand(challenge); + } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String[] commandNames, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { - try { + public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String[] commandNames, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + try { - if (classOfChallenge.isAnnotationPresent(RequireVersion.class)) { - RequireVersion annotation = classOfChallenge.getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = annotation.value(); + if (classOfChallenge.isAnnotationPresent(RequireVersion.class)) { + RequireVersion annotation = classOfChallenge.getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = annotation.value(); - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register challenge {}, requires version {}, server running on {}", classOfChallenge.getSimpleName(), minVersion, MinecraftVersion.current()); - return; - } - } + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register challenge {}, requires version {}, server running on {}", classOfChallenge.getSimpleName(), minVersion, MinecraftVersion.current()); + return; + } + } - Constructor constructor = classOfChallenge.getDeclaredConstructor(parameterClasses); - IChallenge challenge = constructor.newInstance(parameters); + Constructor constructor = classOfChallenge.getDeclaredConstructor(parameterClasses); + IChallenge challenge = constructor.newInstance(parameters); - registerWithCommand(challenge, commandNames); + registerWithCommand(challenge, commandNames); - } catch (Throwable ex) { - Logger.error("Could not create challenge {}", classOfChallenge.getSimpleName(), ex); - } - } + } catch (Throwable ex) { + Logger.error("Could not create challenge {}", classOfChallenge.getSimpleName(), ex); + } + } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { - registerWithCommand(classOfChallenge, new String[0], parameterClasses, parameters); - } + public final void register(@Nonnull Class classOfChallenge, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + registerWithCommand(classOfChallenge, new String[0], parameterClasses, parameters); + } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Object... parameters) { + public final void register(@Nonnull Class classOfChallenge, @Nonnull Object... parameters) { - Class[] parameterClasses = new Class[parameters.length]; - for (int i = 0; i < parameters.length; i++) { - parameterClasses[i] = Optional.ofNullable(parameters[i]).>map(Object::getClass).orElse(Object.class); - } + Class[] parameterClasses = new Class[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + parameterClasses[i] = Optional.ofNullable(parameters[i]).>map(Object::getClass).orElse(Object.class); + } - register(classOfChallenge, parameterClasses, parameters); + register(classOfChallenge, parameterClasses, parameters); - } + } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String... commandNames) { - registerWithCommand(classOfChallenge, commandNames, new Class[0]); - } + public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String... commandNames) { + registerWithCommand(classOfChallenge, commandNames, new Class[0]); + } - public final void registerDamageRule(@Nonnull String name, @Nonnull Material material, @Nonnull DamageCause... causes) { - registerDamageRule(name, new ItemBuilder(material), causes); - } + public final void registerDamageRule(@Nonnull String name, @Nonnull Material material, @Nonnull DamageCause... causes) { + registerDamageRule(name, new ItemBuilder(material), causes); + } - public final void registerDamageRule(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull DamageCause... causes) { - register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); - } + public final void registerDamageRule(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull DamageCause... causes) { + register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); + } - public final void registerMaterialRule(@Nonnull String title, @Nonnull String replacement, @Nonnull Material... materials) { - registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); - } + public final void registerMaterialRule(@Nonnull String title, @Nonnull String replacement, @Nonnull Material... materials) { + registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); + } - public final void registerMaterialRule(@Nonnull String name, Object[] replacements, @Nonnull Material... materials) { - registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); - } + public final void registerMaterialRule(@Nonnull String name, Object[] replacements, @Nonnull Material... materials) { + registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); + } - public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilder preset, Object[] replacements, @Nonnull Material... materials) { - register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); - } + public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilder preset, Object[] replacements, @Nonnull Material... materials) { + register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); + } - /** - * Unregisters an existing challenge and deletes its settings. - * It does not unregister commands! - */ - public final void unregister(@Nonnull IChallenge challenge) { - Challenges.getInstance().getChallengeManager().unregister(challenge); - Challenges.getInstance().getScheduler().unregister(challenge); - Challenges.getInstance().getConfigManager().getSettingsConfig().remove(challenge.getUniqueName()); - Challenges.getInstance().getConfigManager().getGamestateConfig().remove(challenge.getUniqueGamestateName()); + /** + * Unregisters an existing challenge and deletes its settings. + * It does not unregister commands! + */ + public final void unregister(@Nonnull IChallenge challenge) { + Challenges.getInstance().getChallengeManager().unregister(challenge); + Challenges.getInstance().getScheduler().unregister(challenge); + Challenges.getInstance().getConfigManager().getSettingsConfig().remove(challenge.getUniqueName()); + Challenges.getInstance().getConfigManager().getGamestateConfig().remove(challenge.getUniqueGamestateName()); - if (challenge instanceof Listener) { - HandlerList.unregisterAll((Listener) challenge); - } - } + if (challenge instanceof Listener) { + HandlerList.unregisterAll((Listener) challenge); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java index c3a747521..b6c11153c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java @@ -5,10 +5,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CanInstaKillOnEnable { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java index 23aae2577..3db378b57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java @@ -5,10 +5,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ExcludeFromRandomChallenges { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 4d8666d86..3f76cf0df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges.annotations; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import javax.annotation.Nonnull; import java.lang.annotation.ElementType; @@ -8,15 +8,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface RequireVersion { - @Nonnull - MinecraftVersion value(); + @Nonnull + MinecraftVersion value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 4b8744b74..58f269cee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -1,19 +1,15 @@ package net.codingarea.challenges.plugin.management.challenges.entities; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface GamestateSaveable { - String getUniqueGamestateName(); + String getUniqueGamestateName(); - void writeGameState(@Nonnull Document document); + void writeGameState(@Nonnull Document document); - void loadGameState(@Nonnull Document document); + void loadGameState(@Nonnull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java index cf2806cfc..d916ae229 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java @@ -5,24 +5,20 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface CloudSupport { - @Nonnull - String getColoredName(@Nonnull Player player); + @Nonnull + String getColoredName(@Nonnull Player player); - @Nonnull - String getColoredName(@Nonnull UUID uuid); + @Nonnull + String getColoredName(@Nonnull UUID uuid); - boolean hasNameFor(@Nonnull UUID uuid); + boolean hasNameFor(@Nonnull UUID uuid); - void setIngame(); + void setIngame(); - void setLobby(); + void setLobby(); - void startNewService(); + void startNewService(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index 3066c6324..ff36638d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.cloud; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.cloud.support.CloudNet2Support; @@ -21,145 +21,141 @@ import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudSupportManager implements Listener { - private final Map cachedColoredNames = new HashMap<>(); - private final boolean nameSupport; - private final boolean resetToLobby; - private final boolean setIngame; - @Getter + private final Map cachedColoredNames = new HashMap<>(); + private final boolean nameSupport; + private final boolean resetToLobby; + private final boolean setIngame; + @Getter private final String type; - private final boolean startNewService; - private boolean startedNewService = false; - private CloudSupport support; - - public CloudSupportManager() { - Document config = Challenges.getInstance().getConfigDocument().getDocument("cloud-support"); - - startNewService = config.getBoolean("start-new-service"); - nameSupport = config.getBoolean("name-rank-colors"); - resetToLobby = config.getBoolean("reset-to-lobby"); - setIngame = config.getBoolean("set-ingame"); - type = config.getString("type", "none"); - Logger.debug("Detected cloud support type '{}'", type); - - if (type.equals("none")) return; - - support = loadSupport(type); - ChallengeAPI.registerScheduler(this); - Challenges.getInstance().registerListener(this); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { - cachedColoredNames.remove(event.getPlayer().getUniqueId()); - } - - private CloudSupport loadSupport(@Nonnull String name) { - switch (name) { - default: - return null; - case "cloudnet": - case "cloudnet3": - return new CloudNet3Support(); - case "cloudnet2": - return new CloudNet2Support(); - } - } - - @Nonnull - public String getColoredName(@Nonnull Player player) { - if (support == null) - throw new IllegalStateException("No support loaded! Check compatibility before use"); - if (cachedColoredNames.containsKey(player.getUniqueId())) - return cachedColoredNames.get(player.getUniqueId()); - - try { - return cacheColoredName(player.getUniqueId(), support.getColoredName(player)); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); - throw new WrappedException(ex); - } - } - - @Nonnull - public String getColoredName(@Nonnull UUID uuid) { - if (support == null) - throw new IllegalStateException("No support loaded! Check compatibility before use"); - if (cachedColoredNames.containsKey(uuid)) return cachedColoredNames.get(uuid); - - try { - return cacheColoredName(uuid, support.getColoredName(uuid)); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); - throw new WrappedException(ex); - } - } - - @Nonnull - private String cacheColoredName(@Nonnull UUID uuid, @Nonnull String name) { - cachedColoredNames.put(uuid, name); - return name; - } - - public boolean hasNameFor(@Nonnull UUID uuid) { - if (support == null) return false; - - try { - return support.hasNameFor(uuid); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to check name with cloud support '{}', missing dependencies", type); - return false; - } - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void setIngameAndStartService() { - if (!setIngame) return; - if (support == null) return; - - try { - support.setIngame(); - - if (startNewService && !startedNewService) - support.startNewService(); - startedNewService = true; - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to set to ingame with cloud support '{}', missing dependencies", type); - } - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void setLobby() { - if (!resetToLobby || !startNewService) return; - if (support == null) return; - - try { - support.setLobby(); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to set to lobby with cloud support '{}', missing dependencies", type); - } - } + private final boolean startNewService; + private boolean startedNewService = false; + private CloudSupport support; + + public CloudSupportManager() { + Document config = Challenges.getInstance().getConfigDocument().getDocument("cloud-support"); + + startNewService = config.getBoolean("start-new-service"); + nameSupport = config.getBoolean("name-rank-colors"); + resetToLobby = config.getBoolean("reset-to-lobby"); + setIngame = config.getBoolean("set-ingame"); + type = config.getString("type", "none"); + Logger.debug("Detected cloud support type '{}'", type); + + if (type.equals("none")) return; + + support = loadSupport(type); + ChallengeAPI.registerScheduler(this); + Challenges.getInstance().registerListener(this); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + cachedColoredNames.remove(event.getPlayer().getUniqueId()); + } + + private CloudSupport loadSupport(@Nonnull String name) { + switch (name) { + default: + return null; + case "cloudnet": + case "cloudnet3": + return new CloudNet3Support(); + case "cloudnet2": + return new CloudNet2Support(); + } + } + + @Nonnull + public String getColoredName(@Nonnull Player player) { + if (support == null) + throw new IllegalStateException("No support loaded! Check compatibility before use"); + if (cachedColoredNames.containsKey(player.getUniqueId())) + return cachedColoredNames.get(player.getUniqueId()); + + try { + return cacheColoredName(player.getUniqueId(), support.getColoredName(player)); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); + throw new WrappedException(ex); + } + } + + @Nonnull + public String getColoredName(@Nonnull UUID uuid) { + if (support == null) + throw new IllegalStateException("No support loaded! Check compatibility before use"); + if (cachedColoredNames.containsKey(uuid)) return cachedColoredNames.get(uuid); + + try { + return cacheColoredName(uuid, support.getColoredName(uuid)); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); + throw new WrappedException(ex); + } + } + + @Nonnull + private String cacheColoredName(@Nonnull UUID uuid, @Nonnull String name) { + cachedColoredNames.put(uuid, name); + return name; + } + + public boolean hasNameFor(@Nonnull UUID uuid) { + if (support == null) return false; + + try { + return support.hasNameFor(uuid); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to check name with cloud support '{}', missing dependencies", type); + return false; + } + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void setIngameAndStartService() { + if (!setIngame) return; + if (support == null) return; + + try { + support.setIngame(); + + if (startNewService && !startedNewService) + support.startNewService(); + startedNewService = true; + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to set to ingame with cloud support '{}', missing dependencies", type); + } + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void setLobby() { + if (!resetToLobby || !startNewService) return; + if (support == null) return; + + try { + support.setLobby(); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to set to lobby with cloud support '{}', missing dependencies", type); + } + } private boolean isEnabled() { - return support != null; - } + return support != null; + } - public boolean isNameSupport() { - return isEnabled() && nameSupport; - } + public boolean isNameSupport() { + return isEnabled() && nameSupport; + } - public boolean isResetToLobby() { - return isEnabled() && resetToLobby; - } + public boolean isResetToLobby() { + return isEnabled() && resetToLobby; + } - public boolean isStartNewService() { - return isEnabled() && startNewService; - } + public boolean isStartNewService() { + return isEnabled() && startNewService; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java index 6c1cfa1a0..8fcd02f28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java @@ -11,45 +11,41 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudNet2Support implements CloudSupport { - @Nonnull - @Override - public String getColoredName(@Nonnull Player player) { - return getColoredName(player.getUniqueId()); - } - - @Nonnull - @Override - public String getColoredName(@Nonnull UUID uuid) { - OfflinePlayer offlinePlayer = CloudAPI.getInstance().getOfflinePlayer(uuid); - PermissionGroup permissionGroup = offlinePlayer.getPermissionEntity().getHighestPermissionGroup(CloudAPI.getInstance().getPermissionPool()); - String color = permissionGroup.getColor(); - return color.replace('&', '§') + offlinePlayer.getName(); - } - - @Override - public boolean hasNameFor(@Nonnull UUID uuid) { - return CloudAPI.getInstance().getOfflinePlayer(uuid) != null; - } - - @Override - public void startNewService() { - CloudServer.getInstance().changeToIngame(); - } - - @Override - public void setIngame() { - CloudServer.getInstance().setServerState(ServerState.INGAME); - } - - @Override - public void setLobby() { - CloudServer.getInstance().setServerStateAndUpdate(ServerState.LOBBY); - } + @Nonnull + @Override + public String getColoredName(@Nonnull Player player) { + return getColoredName(player.getUniqueId()); + } + + @Nonnull + @Override + public String getColoredName(@Nonnull UUID uuid) { + OfflinePlayer offlinePlayer = CloudAPI.getInstance().getOfflinePlayer(uuid); + PermissionGroup permissionGroup = offlinePlayer.getPermissionEntity().getHighestPermissionGroup(CloudAPI.getInstance().getPermissionPool()); + String color = permissionGroup.getColor(); + return color.replace('&', '§') + offlinePlayer.getName(); + } + + @Override + public boolean hasNameFor(@Nonnull UUID uuid) { + return CloudAPI.getInstance().getOfflinePlayer(uuid) != null; + } + + @Override + public void startNewService() { + CloudServer.getInstance().changeToIngame(); + } + + @Override + public void setIngame() { + CloudServer.getInstance().setServerState(ServerState.INGAME); + } + + @Override + public void setLobby() { + CloudServer.getInstance().setServerStateAndUpdate(ServerState.LOBBY); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java index 1b96086b8..7c2e60f52 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java @@ -12,49 +12,45 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudNet3Support implements CloudSupport { - @Nonnull - @Override - public String getColoredName(@Nonnull Player player) { - return getColoredName(player.getUniqueId()); - } - - @Nonnull - @Override - public String getColoredName(@Nonnull UUID uuid) { - IPermissionManagement management = CloudNetDriver.getInstance().getPermissionManagement(); - IPermissionUser user = management.getUser(uuid); - if (user == null) return "Unknown CloudPlayer"; - IPermissionGroup group = management.getHighestPermissionGroup(user); - String color = group.getColor(); - return color.replace('&', '§') + user.getName(); - } - - @Override - public boolean hasNameFor(@Nonnull UUID uuid) { - return CloudNetDriver.getInstance().getPermissionManagement().getUser(uuid) != null; - } - - @Override - public void startNewService() { - BukkitCloudNetHelper.changeToIngame(); - } - - @Override - public void setIngame() { - BukkitCloudNetHelper.setState("INGAME"); - BridgeHelper.updateServiceInfo(); - } - - @Override - public void setLobby() { - BukkitCloudNetHelper.setState("LOBBY"); - BridgeHelper.updateServiceInfo(); - } + @Nonnull + @Override + public String getColoredName(@Nonnull Player player) { + return getColoredName(player.getUniqueId()); + } + + @Nonnull + @Override + public String getColoredName(@Nonnull UUID uuid) { + IPermissionManagement management = CloudNetDriver.getInstance().getPermissionManagement(); + IPermissionUser user = management.getUser(uuid); + if (user == null) return "Unknown CloudPlayer"; + IPermissionGroup group = management.getHighestPermissionGroup(user); + String color = group.getColor(); + return color.replace('&', '§') + user.getName(); + } + + @Override + public boolean hasNameFor(@Nonnull UUID uuid) { + return CloudNetDriver.getInstance().getPermissionManagement().getUser(uuid) != null; + } + + @Override + public void startNewService() { + BukkitCloudNetHelper.changeToIngame(); + } + + @Override + public void setIngame() { + BukkitCloudNetHelper.setState("INGAME"); + BridgeHelper.updateServiceInfo(); + } + + @Override + public void setLobby() { + BukkitCloudNetHelper.setState("LOBBY"); + BridgeHelper.updateServiceInfo(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index d061a9da7..1ff4612f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -1,19 +1,19 @@ package net.codingarea.challenges.plugin.management.database; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.database.Database; -import net.anweisen.utilities.database.DatabaseConfig; -import net.anweisen.utilities.database.SQLColumn; -import net.anweisen.utilities.database.action.ExecutedQuery; -import net.anweisen.utilities.database.exceptions.DatabaseException; -import net.anweisen.utilities.database.internal.sql.abstraction.AbstractSQLDatabase; -import net.anweisen.utilities.database.internal.sql.mysql.MySQLDatabase; -import net.anweisen.utilities.database.internal.sql.sqlite.SQLiteDatabase; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.MySQLDatabase; +import net.codingarea.commons.database.sql.sqlite.SQLiteDatabase; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -24,136 +24,132 @@ import java.util.HashMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DatabaseManager { - private final Map> registry = new HashMap<>(); - @Getter + private final Map> registry = new HashMap<>(); + @Getter private String type; - @Getter + @Getter private Database database; - { - // Database types supported by default - registerDatabase("sqlite", SQLiteDatabase.class, Challenges.getInstance()); - registerDatabase("mysql", MySQLDatabase.class, Challenges.getInstance()); - } - - public void enable() { - Document document = Challenges.getInstance().getConfigDocument().getDocument("database"); - - type = document.getString("type", "none").toLowerCase(); - if ("none".equals(type)) return; - - // Check dependencies - if ("mongodb".equals(type) && !checkDependencies("com.mongodb.client.MongoClient")) { - ConsolePrint.noMongoDependencies(); - return; - } - - try { - Tuple pair = getDatabaseForName(type); - if (pair == null) { - Logger.error("Selected illegal database type '{}'", type); - return; - } - - JavaPlugin provider = pair.getSecond(); - PluginManager manager = Bukkit.getPluginManager(); - if (!manager.isPluginEnabled(provider) && provider != Challenges.getInstance()) { - manager.enablePlugin(provider); - } - - ClassLoader loader = provider.getClass().getClassLoader(); - - String className = pair.getFirst(); - @SuppressWarnings("unchecked") - Class classOfDatabase = (Class) loader.loadClass(className); - - DatabaseConfig config = new DatabaseConfig(document.getDocument(type)); - Constructor constructor = classOfDatabase.getDeclaredConstructor(DatabaseConfig.class); - database = constructor.newInstance(config); - - connect(); - } catch (ClassNotFoundException ex) { - Logger.error("Could not find class for database '{}'", type, ex); - } catch (Throwable ex) { - Logger.error("Could not create database", ex); - } - } - - private void connect() { - Challenges.getInstance().runAsync(() -> { - database.connectSafely(); - database.createTableSafely("challenges", - new SQLColumn("uuid", "varchar", 36), - new SQLColumn("name", "varchar", 16), - new SQLColumn("textures", "varchar", 500), - new SQLColumn("stats", "varchar", 1500), - new SQLColumn("config", "varchar", 15000), - new SQLColumn("custom_challenges", "text", 30000) - ); - loadMigration(); - }); - } - - private void loadMigration() { - - if (database instanceof AbstractSQLDatabase) { - AbstractSQLDatabase sqlDatabase = (AbstractSQLDatabase) this.database; - - // Create custom_challenges column - try { - ExecutedQuery execute = sqlDatabase.query("challenges").select("custom_challenges").execute(); - } catch (DatabaseException databaseException) { - try { - sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); - Challenges.getInstance().getLogger().info("Creating not existing column 'custom_challenges' in SQL Database"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); - Challenges.getInstance().getLogger().error("", exception); - } - } - - } - - } - - public void disconnectIfConnected() { - if (database != null) { - database.disconnectSafely(); - } - } - - @Nullable - private Tuple getDatabaseForName(@Nonnull String type) throws ClassNotFoundException { - return registry.get(type); - } - - public void registerDatabase(@Nonnull String name, @Nonnull Class classOfDatabase, @Nonnull JavaPlugin provider) { - registry.put(name, new Tuple<>(classOfDatabase.getName(), provider)); - } - - public boolean isConnected() { - return database != null && database.isConnected(); - } - - public boolean isEnabled() { - return database != null; - } + { + // Database types supported by default + registerDatabase("sqlite", SQLiteDatabase.class, Challenges.getInstance()); + registerDatabase("mysql", MySQLDatabase.class, Challenges.getInstance()); + } + + public void enable() { + Document document = Challenges.getInstance().getConfigDocument().getDocument("database"); + + type = document.getString("type", "none").toLowerCase(); + if ("none".equals(type)) return; + + // Check dependencies + if ("mongodb".equals(type) && !checkDependencies("com.mongodb.client.MongoClient")) { + ConsolePrint.noMongoDependencies(); + return; + } + + try { + Tuple pair = getDatabaseForName(type); + if (pair == null) { + Logger.error("Selected illegal database type '{}'", type); + return; + } + + JavaPlugin provider = pair.getSecond(); + PluginManager manager = Bukkit.getPluginManager(); + if (!manager.isPluginEnabled(provider) && provider != Challenges.getInstance()) { + manager.enablePlugin(provider); + } + + ClassLoader loader = provider.getClass().getClassLoader(); + + String className = pair.getFirst(); + @SuppressWarnings("unchecked") + Class classOfDatabase = (Class) loader.loadClass(className); + + DatabaseConfig config = new DatabaseConfig(document.getDocument(type)); + Constructor constructor = classOfDatabase.getDeclaredConstructor(DatabaseConfig.class); + database = constructor.newInstance(config); + + connect(); + } catch (ClassNotFoundException ex) { + Logger.error("Could not find class for database '{}'", type, ex); + } catch (Throwable ex) { + Logger.error("Could not create database", ex); + } + } + + private void connect() { + Challenges.getInstance().runAsync(() -> { + database.connectSafely(); + database.createTableSafely("challenges", + new SQLColumn("uuid", "varchar", 36), + new SQLColumn("name", "varchar", 16), + new SQLColumn("textures", "varchar", 500), + new SQLColumn("stats", "varchar", 1500), + new SQLColumn("config", "varchar", 15000), + new SQLColumn("custom_challenges", "text", 30000) + ); + loadMigration(); + }); + } + + private void loadMigration() { + + if (database instanceof AbstractSQLDatabase) { + AbstractSQLDatabase sqlDatabase = (AbstractSQLDatabase) this.database; + + // Create custom_challenges column + try { + ExecutedQuery execute = sqlDatabase.query("challenges").select("custom_challenges").execute(); + } catch (DatabaseException databaseException) { + try { + sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); + Challenges.getInstance().getILogger().info("Creating not existing column 'custom_challenges' in SQL Database"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getILogger().error("", exception); + } + } + + } + + } + + public void disconnectIfConnected() { + if (database != null) { + database.disconnectSafely(); + } + } + + @Nullable + private Tuple getDatabaseForName(@Nonnull String type) throws ClassNotFoundException { + return registry.get(type); + } + + public void registerDatabase(@Nonnull String name, @Nonnull Class classOfDatabase, @Nonnull JavaPlugin provider) { + registry.put(name, new Tuple<>(classOfDatabase.getName(), provider)); + } + + public boolean isConnected() { + return database != null && database.isConnected(); + } + + public boolean isEnabled() { + return database != null; + } private boolean checkDependencies(@Nonnull String... classes) { - try { - for (String name : classes) { - Class.forName(name); - } - } catch (Throwable ex) { - return false; - } - return true; - } + try { + for (String name : classes) { + Class.forName(name); + } + } catch (Throwable ex) { + return false; + } + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 09b2cccd5..73ad01456 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.management.files; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.YamlDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -17,97 +17,93 @@ import java.util.LinkedList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ConfigManager { - private final List missingConfigSettings; - @Getter + private final List missingConfigSettings; + @Getter private FileDocument sessionConfig, gamestateConfig, settingsConfig, customChallengesConfig; - public ConfigManager() { - missingConfigSettings = new LinkedList<>(); - GsonDocument.setCleanupEmptyObjects(true); - GsonDocument.setCleanupEmptyObjects(true); - } - - public void loadConfigs() { - sessionConfig = load("internal/session.json"); - gamestateConfig = load("internal/gamestate.json"); - settingsConfig = load("internal/settings.json"); - customChallengesConfig = load("internal/custom_challenges.json"); - - Challenges plugin = Challenges.getInstance(); - Document config = plugin.getConfigDocument(); - YamlConfiguration defaultConfig = getDefaultConfig(); - - if (defaultConfig != null) { - for (String key : defaultConfig.getKeys(true)) { - if (!config.contains(key)) { - missingConfigSettings.add(key); - } - } - } - - } - - public Document getDefaultConfigDocument() { - YamlConfiguration defaultConfig = getDefaultConfig(); - return defaultConfig == null ? null : new YamlDocument(defaultConfig); - } - - public YamlConfiguration getDefaultConfig() { - Challenges plugin = Challenges.getInstance(); - try { - // Create Temp File for loading the yaml configuration - File defaultConfigTempFile = new File("defaultConfig.yml"); - // Create an output stream from that file to write into it - FileOutputStream stream = new FileOutputStream(defaultConfigTempFile); - // Copy the default config inside the temp file - InputStream resource = plugin.getResource("config.yml"); - if (resource == null) return null; - copyLarge(resource, stream, new byte[1024 * 4]); - // Load the File as a yaml config - // Spigot Config Implementation because the Document Library does not contain deep-keys. - YamlConfiguration defaultConfig = new YamlConfiguration(); - defaultConfig.load(defaultConfigTempFile); - - return defaultConfig; - } catch (IOException | NullPointerException | InvalidConfigurationException exception) { - plugin.getLogger().severe("Error while checking missing keys in the current config"); - Challenges.getInstance().getLogger().error("", exception); - } - - return null; - } - - /** - * Copied method from or {@link org.apache.commons.io.IOUtils} because it is not implemented in older versions - */ - private void copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { - int n; - while (-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - } - } - - @Nullable - private FileDocument load(@Nonnull String filename) { - try { - File file = Challenges.getInstance().getDataFile(filename); - FileUtils.createFilesIfNecessary(file); - return FileDocument.readJsonFile(file); - } catch (Exception ex) { - Logger.error("Could not load config '{}': {}", filename, ex); - return null; - } - } - - @Nonnull - public List getMissingConfigSettings() { - return new LinkedList<>(missingConfigSettings); - } + public ConfigManager() { + missingConfigSettings = new LinkedList<>(); + GsonDocument.setCleanupEmptyObjects(true); + GsonDocument.setCleanupEmptyObjects(true); + } + + public void loadConfigs() { + sessionConfig = load("internal/session.json"); + gamestateConfig = load("internal/gamestate.json"); + settingsConfig = load("internal/settings.json"); + customChallengesConfig = load("internal/custom_challenges.json"); + + Challenges plugin = Challenges.getInstance(); + Document config = plugin.getConfigDocument(); + YamlConfiguration defaultConfig = getDefaultConfig(); + + if (defaultConfig != null) { + for (String key : defaultConfig.getKeys(true)) { + if (!config.contains(key)) { + missingConfigSettings.add(key); + } + } + } + + } + + public Document getDefaultConfigDocument() { + YamlConfiguration defaultConfig = getDefaultConfig(); + return defaultConfig == null ? null : new YamlDocument(defaultConfig); + } + + public YamlConfiguration getDefaultConfig() { + Challenges plugin = Challenges.getInstance(); + try { + // Create Temp File for loading the yaml configuration + File defaultConfigTempFile = new File("defaultConfig.yml"); + // Create an output stream from that file to write into it + FileOutputStream stream = new FileOutputStream(defaultConfigTempFile); + // Copy the default config inside the temp file + InputStream resource = plugin.getResource("config.yml"); + if (resource == null) return null; + copyLarge(resource, stream, new byte[1024 * 4]); + // Load the File as a yaml config + // Spigot Config Implementation because the Document Library does not contain deep-keys. + YamlConfiguration defaultConfig = new YamlConfiguration(); + defaultConfig.load(defaultConfigTempFile); + + return defaultConfig; + } catch (IOException | NullPointerException | InvalidConfigurationException exception) { + plugin.getLogger().severe("Error while checking missing keys in the current config"); + Challenges.getInstance().getILogger().error("", exception); + } + + return null; + } + + /** + * Copied method from or {@link org.apache.commons.io.IOUtils} because it is not implemented in older versions + */ + private void copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { + int n; + while (-1 != (n = input.read(buffer))) { + output.write(buffer, 0, n); + } + } + + @Nullable + private FileDocument load(@Nonnull String filename) { + try { + File file = Challenges.getInstance().getDataFile(filename); + FileUtils.createFilesIfNecessary(file); + return FileDocument.readJsonFile(file); + } catch (Exception ex) { + Logger.error("Could not load config '{}': {}", filename, ex); + return null; + } + } + + @Nonnull + public List getMissingConfigSettings() { + return new LinkedList<>(missingConfigSettings); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 86dbe5052..e2c86f35f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.inventory; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -29,255 +29,252 @@ import java.util.List; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class PlayerInventoryManager implements Listener { - private final List hotbarItems; - - public PlayerInventoryManager() { - Challenges.getInstance().registerListener(this); - ChallengeAPI.registerScheduler(this); - ChallengeAPI.subscribeLoader(LanguageLoader.class, () -> Bukkit.getOnlinePlayers().forEach(Challenges.getInstance().getPlayerInventoryManager()::updateInventoryAuto)); - - hotbarItems = new LinkedList<>(); - loadItems(); - } - - public void loadItems() { - FileDocument config = Challenges.getInstance().getConfig("hotbar-items.yml"); - loadItem(config.getDocument("timer"), "item-menu-timer", "challenges.timer", p -> p.performCommand("timer")); - loadItem(config.getDocument("challenges"), "item-menu-challenges", "challenges.gui", p -> p.performCommand("challenges")); - loadItem(config.getDocument("start"), "item-menu-start", "challenges.timer", p -> p.performCommand("start")); - loadItem(config.getDocument("leaderboard"), "item-menu-leaderboard", null, p -> p.performCommand("leaderboard")); - loadItem(config.getDocument("stats"), "item-menu-stats", null, p -> p.performCommand("stats")); - } - - public void loadItem(Document config, String message, String permission, Consumer action) { - if (!config.getBoolean("enabled", false)) return; - int slot = config.getInt("slot", 0); - Material material = config.getEnum("material", Material.BARRIER); - HotbarItem item = new HotbarItem(slot, message, material, action, permission); - hotbarItems.add(item); - } - - public void handleDisable() { - Bukkit.getOnlinePlayers().forEach(this::removeItems); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { - updateInventoryAuto(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - updateInventoryJoin(event.getPlayer(), true); - } - - @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { - removeItems(event.getPlayer()); - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - updateInventoryGamemode(event.getPlayer(), event.getNewGameMode()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!hasItems(event.getPlayer())) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - updateInventoryAlive(event.getPlayer(), true); - } - - @EventHandler - public void onInteract(@Nonnull PlayerInteractEvent event) { - switch (event.getAction()) { - case LEFT_CLICK_AIR: - case LEFT_CLICK_BLOCK: - case PHYSICAL: - return; - } - - if (ChallengeAPI.isStarted()) return; - if (!hasItems(event.getPlayer())) return; - Triple, String>[] pairs = createItemPairs(event.getPlayer()); - - int slot = event.getPlayer().getInventory().getHeldItemSlot(); - if (slot >= pairs.length) return; - Triple, String> pair = pairs[slot]; - if (pair == null) return; - if (pair.getThird() != null && !event.getPlayer().hasPermission(pair.getThird())) return; - - Consumer action = pair.getSecond(); - if (action == null) return; - - action.accept(event.getPlayer()); - SoundSample.PLOP.play(event.getPlayer()); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) - public void updateInventories() { - Bukkit.getOnlinePlayers().forEach(this::updateInventoryAuto); - } - - public void updateInventoryAuto(@Nonnull Player player) { - updateInventory(player, player.getGameMode(), false, !player.isDead()); - } - - public void updateInventoryAlive(@Nonnull Player player, boolean alive) { - updateInventory(player, player.getGameMode(), false, alive); - } - - public void updateInventoryGamemode(@Nonnull Player player, @Nonnull GameMode gamemode) { - updateInventory(player, gamemode, false, !player.isDead()); - } - - public void updateInventoryJoin(@Nonnull Player player, boolean join) { - updateInventory(player, player.getGameMode(), join, !player.isDead()); - } - - public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - if (Bukkit.isPrimaryThread()) { - Challenges.getInstance().runAsync(() -> updateInventory(player, gamemode, join, alive)); - return; - } - - try { - if (!LanguageLoader.isLoaded()) return; - if (ChallengeAPI.isPaused()) { - updateInventoryPaused(player, gamemode, join, alive); - } else { - updateInventoryStarted(player, gamemode, join, alive); - } - } catch (Exception ex) { - Logger.error("Failed to update inventory", ex); - } - } - - private void updateInventoryStarted(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - removeItems(player); - } - - private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - if (gamemode == GameMode.CREATIVE || gamemode == GameMode.SPECTATOR) { - removeItems(player); - return; - } - if (canGiveItems(player)) { - if (!alive) return; - giveItems(player); - if (join) player.getInventory().setHeldItemSlot(4); - } - } - - private boolean hasItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - ItemStack expected = pair == null ? null : pair.getFirst(); - ItemStack found = player.getInventory().getItem(i); - if (pair != null && pair.getThird() != null && !player.hasPermission(pair.getThird())) - continue; - if (expected != null && found == null) return false; - if (expected == null) continue; - if (expected.getType() != found.getType()) return false; - } - return true; - } - - private boolean canGiveItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - ItemStack expected = pair == null ? null : pair.getFirst(); - ItemStack found = player.getInventory().getItem(i); - if (expected == null && found != null) return false; - if (expected == null) continue; - if (found == null) continue; - if (expected.getType() != found.getType()) return false; - } - return true; - } - - private void removeItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (Triple, String> pair : pairs) { - if (pair == null) continue; - ItemStack item = pair.getFirst(); - if (item == null) continue; - if (item.getItemMeta() == null) continue; - ItemStack[] content = player.getInventory().getContents(); - for (int i = 0; i < content.length; i++) { - ItemStack current = content[i]; - if (current == null) continue; - if (current.getType() != item.getType()) continue; - if (current.getItemMeta() == null) continue; - if (!current.getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) - continue; - player.getInventory().setItem(i, null); - } - } - } - - private void giveItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - if (pair == null) continue; - if (pair.getThird() != null && !player.hasPermission(pair.getThird())) continue; - player.getInventory().setItem(i, pair.getFirst()); - } - } - - @Nonnull - private Triple, String>[] createItemPairs(@Nonnull Player player) { - Triple, String>[] pairs = new Triple[9]; - - for (HotbarItem item : hotbarItems) { - - ItemStack stack; - if (item.getMaterial() == Material.PLAYER_HEAD) { - stack = new SkullBuilder(player.getUniqueId(), player.getName(), Message.forName(item.getMessage()).asString()).build(); - } else { - stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); - } - - pairs[item.getSlot()] = new Triple<>( - stack, - item.getAction(), - item.getPermission() - ); - } - - return pairs; - } - - @Getter + private final List hotbarItems; + + public PlayerInventoryManager() { + Challenges.getInstance().registerListener(this); + ChallengeAPI.registerScheduler(this); + ChallengeAPI.subscribeLoader(LanguageLoader.class, () -> Bukkit.getOnlinePlayers().forEach(Challenges.getInstance().getPlayerInventoryManager()::updateInventoryAuto)); + + hotbarItems = new LinkedList<>(); + loadItems(); + } + + public void loadItems() { + FileDocument config = Challenges.getInstance().getConfig("hotbar-items.yml"); + loadItem(config.getDocument("timer"), "item-menu-timer", "challenges.timer", p -> p.performCommand("timer")); + loadItem(config.getDocument("challenges"), "item-menu-challenges", "challenges.gui", p -> p.performCommand("challenges")); + loadItem(config.getDocument("start"), "item-menu-start", "challenges.timer", p -> p.performCommand("start")); + loadItem(config.getDocument("leaderboard"), "item-menu-leaderboard", null, p -> p.performCommand("leaderboard")); + loadItem(config.getDocument("stats"), "item-menu-stats", null, p -> p.performCommand("stats")); + } + + public void loadItem(Document config, String message, String permission, Consumer action) { + if (!config.getBoolean("enabled", false)) return; + int slot = config.getInt("slot", 0); + Material material = config.getEnum("material", Material.BARRIER); + HotbarItem item = new HotbarItem(slot, message, material, action, permission); + hotbarItems.add(item); + } + + public void handleDisable() { + Bukkit.getOnlinePlayers().forEach(this::removeItems); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + updateInventoryAuto(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + updateInventoryJoin(event.getPlayer(), true); + } + + @EventHandler + public void onQuit(@Nonnull PlayerQuitEvent event) { + removeItems(event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + updateInventoryGamemode(event.getPlayer(), event.getNewGameMode()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!hasItems(event.getPlayer())) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + updateInventoryAlive(event.getPlayer(), true); + } + + @EventHandler + public void onInteract(@Nonnull PlayerInteractEvent event) { + switch (event.getAction()) { + case LEFT_CLICK_AIR: + case LEFT_CLICK_BLOCK: + case PHYSICAL: + return; + } + + if (ChallengeAPI.isStarted()) return; + if (!hasItems(event.getPlayer())) return; + Triple, String>[] pairs = createItemPairs(event.getPlayer()); + + int slot = event.getPlayer().getInventory().getHeldItemSlot(); + if (slot >= pairs.length) return; + Triple, String> pair = pairs[slot]; + if (pair == null) return; + if (pair.getThird() != null && !event.getPlayer().hasPermission(pair.getThird())) return; + + Consumer action = pair.getSecond(); + if (action == null) return; + + action.accept(event.getPlayer()); + SoundSample.PLOP.play(event.getPlayer()); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) + public void updateInventories() { + Bukkit.getOnlinePlayers().forEach(this::updateInventoryAuto); + } + + public void updateInventoryAuto(@Nonnull Player player) { + updateInventory(player, player.getGameMode(), false, !player.isDead()); + } + + public void updateInventoryAlive(@Nonnull Player player, boolean alive) { + updateInventory(player, player.getGameMode(), false, alive); + } + + public void updateInventoryGamemode(@Nonnull Player player, @Nonnull GameMode gamemode) { + updateInventory(player, gamemode, false, !player.isDead()); + } + + public void updateInventoryJoin(@Nonnull Player player, boolean join) { + updateInventory(player, player.getGameMode(), join, !player.isDead()); + } + + public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + if (Bukkit.isPrimaryThread()) { + Challenges.getInstance().runAsync(() -> updateInventory(player, gamemode, join, alive)); + return; + } + + try { + if (!LanguageLoader.isLoaded()) return; + if (ChallengeAPI.isPaused()) { + updateInventoryPaused(player, gamemode, join, alive); + } else { + updateInventoryStarted(player, gamemode, join, alive); + } + } catch (Exception ex) { + Logger.error("Failed to update inventory", ex); + } + } + + private void updateInventoryStarted(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + removeItems(player); + } + + private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + if (gamemode == GameMode.CREATIVE || gamemode == GameMode.SPECTATOR) { + removeItems(player); + return; + } + if (canGiveItems(player)) { + if (!alive) return; + giveItems(player); + if (join) player.getInventory().setHeldItemSlot(4); + } + } + + private boolean hasItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + ItemStack expected = pair == null ? null : pair.getFirst(); + ItemStack found = player.getInventory().getItem(i); + if (pair != null && pair.getThird() != null && !player.hasPermission(pair.getThird())) + continue; + if (expected != null && found == null) return false; + if (expected == null) continue; + if (expected.getType() != found.getType()) return false; + } + return true; + } + + private boolean canGiveItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + ItemStack expected = pair == null ? null : pair.getFirst(); + ItemStack found = player.getInventory().getItem(i); + if (expected == null && found != null) return false; + if (expected == null) continue; + if (found == null) continue; + if (expected.getType() != found.getType()) return false; + } + return true; + } + + private void removeItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (Triple, String> pair : pairs) { + if (pair == null) continue; + ItemStack item = pair.getFirst(); + if (item == null) continue; + if (item.getItemMeta() == null) continue; + ItemStack[] content = player.getInventory().getContents(); + for (int i = 0; i < content.length; i++) { + ItemStack current = content[i]; + if (current == null) continue; + if (current.getType() != item.getType()) continue; + if (current.getItemMeta() == null) continue; + if (!current.getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) + continue; + player.getInventory().setItem(i, null); + } + } + } + + private void giveItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + if (pair == null) continue; + if (pair.getThird() != null && !player.hasPermission(pair.getThird())) continue; + player.getInventory().setItem(i, pair.getFirst()); + } + } + + @Nonnull + private Triple, String>[] createItemPairs(@Nonnull Player player) { + Triple, String>[] pairs = new Triple[9]; + + for (HotbarItem item : hotbarItems) { + + ItemStack stack; + if (item.getMaterial() == Material.PLAYER_HEAD) { + stack = new SkullBuilder(Message.forName(item.getMessage()).asString()) + .setOwner(player.getUniqueId(), player.getName()).build(); + } else { + stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); + } + + pairs[item.getSlot()] = new Triple<>( + stack, + item.getAction(), + item.getPermission() + ); + } + + return pairs; + } + + @Getter public static class HotbarItem { - private final int slot; - private final String message; - private final Material material; - private final Consumer action; - private final String permission; - - public HotbarItem(int slot, String message, Material material, Consumer action, String permission) { - this.slot = slot; - this.message = message; - this.material = material; - this.action = action; - this.permission = permission; - } + private final int slot; + private final String message; + private final Material material; + private final Consumer action; + private final String permission; + + public HotbarItem(int slot, String message, Material material, Consumer action, String permission) { + this.slot = slot; + this.message = message; + this.material = material; + this.action = action; + this.permission = permission; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 2a5128579..3a82767da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -4,67 +4,63 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class InventoryTitleManager { - private InventoryTitleManager() { - } + private InventoryTitleManager() { + } - @Nonnull - public static String getTitle(@Nonnull String name) { - return "§8» " + Message.forName("inventory-color").asString() + name; - } + @Nonnull + public static String getTitle(@Nonnull String name) { + return "§8» " + Message.forName("inventory-color").asString() + name; + } - @Nonnull - public static String getMainMenuTitle() { - return getTitle(Message.forName("menu-title").asString()); - } + @Nonnull + public static String getMainMenuTitle() { + return getTitle(Message.forName("menu-title").asString()); + } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, int page) { - return getTitle(menu.getName(), String.valueOf(page + 1)); - } + @Nonnull + public static String getTitle(@Nonnull MenuType menu, int page) { + return getTitle(menu.getName(), String.valueOf(page + 1)); + } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, String... sub) { - return getTitle(menu.getName(), sub); - } + @Nonnull + public static String getTitle(@Nonnull MenuType menu, String... sub) { + return getTitle(menu.getName(), sub); + } - @Nonnull - public static String getTitle(@Nonnull String menu, String... sub) { - String name = menu; - for (String s : sub) { - name += getTitleSplitter() + s; - } - return getTitle(name); - } + @Nonnull + public static String getTitle(@Nonnull String menu, String... sub) { + StringBuilder name = new StringBuilder(menu); + for (String s : sub) { + name.append(getTitleSplitter()).append(s); + } + return getTitle(name.toString()); + } - @Nonnull - public static String getTitleSplitter() { - return " §8┃ " + Message.forName("inventory-color").asString(); - } + @Nonnull + public static String getTitleSplitter() { + return " §8┃ " + Message.forName("inventory-color").asString(); + } - @Nonnull - public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { - return getTitle(menu.getName() + getTitleSplitter() + name + (showPages && false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); - } + @Nonnull + public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { + return getTitle(menu.getName() + getTitleSplitter() + name + (showPages ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); + } - @Nonnull - public static String getStatsTitle(@Nonnull String playerName) { - return getTitle("§2Stats §8┃ §2" + playerName); - } + @Nonnull + public static String getStatsTitle(@Nonnull String playerName) { + return getTitle("§2Stats §8┃ §2" + playerName); + } - @Nonnull - public static String getLeaderboardTitle() { - return getTitle("§2Leaderboard"); - } + @Nonnull + public static String getLeaderboardTitle() { + return getTitle("§2Leaderboard"); + } - @Nonnull - public static String getLeaderboardTitle(@Nonnull String name, int page) { - return getTitle("§2" + name + " §8┃ §2" + page); - } + @Nonnull + public static String getLeaderboardTitle(@Nonnull String name, int page) { + return getTitle("§2" + name + " §8┃ §2" + page); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 8ba82108f..f4f63b65e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -19,137 +19,133 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class MenuManager { - public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; - public static final int[] GUI_SLOTS = {30, 32, 19, 25, 11, 15, 4}; - @Getter + public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; + public static final int[] GUI_SLOTS = {30, 32, 19, 25, 11, 15, 4}; + @Getter private final boolean displayNewInFront; - private final boolean permissionToManageGUI; - private AnimatedInventory gui; - private boolean generated = false; - - public MenuManager() { - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); - displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("display-new-in-front"); - permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); - generateMainMenu(); - } - - public void generateMainMenu() { - - gui = new AnimatedInventory(InventoryTitleManager.getMainMenuTitle(), 5 * 9, MenuPosition.HOLDER); - gui.addFrame(new AnimationFrame(5 * 9).fill(ItemBuilder.FILL_ITEM)); - gui.cloneLastAndAdd().setAccent(39, 41); - gui.cloneLastAndAdd().setAccent(38, 42); - gui.cloneLastAndAdd().setAccent(37, 43); - gui.cloneLastAndAdd().setAccent(28, 34); - gui.cloneLastAndAdd().setAccent(27, 35); - gui.cloneLastAndAdd().setAccent(18, 26); - gui.cloneLastAndAdd().setAccent(9, 17); - gui.cloneLastAndAdd().setAccent(10, 16); - gui.cloneLastAndAdd().setAccent(1, 7); - gui.cloneLastAndAdd().setAccent(2, 6); - - MenuType[] values = MenuType.values(); - for (int i = 0; i < values.length; i += 2) { - - AnimationFrame frame = gui.getLastFrame().clone(); - - MenuType first = values[i]; - frame.setItem(GUI_SLOTS[i], new ItemBuilder(first.getDisplayItem()).name( - DefaultItem.getItemPrefix() + first.getDisplayName()).hideAttributes()); - - if (values.length > i + 1) { - MenuType second = values[i + 1]; - frame.setItem(GUI_SLOTS[i + 1], new ItemBuilder(second.getDisplayItem()).name( - DefaultItem.getItemPrefix() + second.getDisplayName()).hideAttributes()); - } - - gui.addFrame(frame); - } - - } - - public void generateMenus() { - - for (MenuType value : MenuType.values()) { - value.executeWithGenerator(ChallengeMenuGenerator.class, ChallengeMenuGenerator::resetChallengeCache); - } - - for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { - MenuType type = challenge.getType(); - type.executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.addChallengeToCache(challenge)); - } - - for (MenuType value : MenuType.values()) { - value.getMenuGenerator().generateInventories(); - } - - generated = true; - } - - public void openGUI(@Nonnull Player player) { - SoundSample.PLOP.play(player); - MenuPosition.set(player, new MainMenuPosition()); - gui.open(player, Challenges.getInstance()); - } - - public void openGUIInstantly(@Nonnull Player player) { - MenuPosition.set(player, new MainMenuPosition()); - gui.openNotAnimated(player, true, Challenges.getInstance()); - } - - /** - * @return If the specified menu page could be opened. - * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded - */ - public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page) { - if (!generated) { - SoundSample.BASS_OFF.play(player); - player.sendMessage(Prefix.CHALLENGES + "§cCould not open gui, languages are not loaded"); - player.sendMessage(Prefix.CHALLENGES + "§cIs the plugin set up correctly?"); - return false; - } - - type.getMenuGenerator().open(player, page); - - return true; - } + private final boolean permissionToManageGUI; + private AnimatedInventory gui; + private boolean generated = false; + + public MenuManager() { + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); + displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("display-new-in-front"); + permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); + generateMainMenu(); + } + + public void generateMainMenu() { + + gui = new AnimatedInventory(InventoryTitleManager.getMainMenuTitle(), 5 * 9, MenuPosition.HOLDER); + gui.addFrame(new AnimationFrame(5 * 9).fill(ItemBuilder.FILL_ITEM)); + gui.cloneLastAndAdd().setAccent(39, 41); + gui.cloneLastAndAdd().setAccent(38, 42); + gui.cloneLastAndAdd().setAccent(37, 43); + gui.cloneLastAndAdd().setAccent(28, 34); + gui.cloneLastAndAdd().setAccent(27, 35); + gui.cloneLastAndAdd().setAccent(18, 26); + gui.cloneLastAndAdd().setAccent(9, 17); + gui.cloneLastAndAdd().setAccent(10, 16); + gui.cloneLastAndAdd().setAccent(1, 7); + gui.cloneLastAndAdd().setAccent(2, 6); + + MenuType[] values = MenuType.values(); + for (int i = 0; i < values.length; i += 2) { + + AnimationFrame frame = gui.getLastFrame().clone(); + + MenuType first = values[i]; + frame.setItem(GUI_SLOTS[i], new ItemBuilder(first.getDisplayItem()).name( + DefaultItem.getItemPrefix() + first.getDisplayName()).hideAttributes()); + + if (values.length > i + 1) { + MenuType second = values[i + 1]; + frame.setItem(GUI_SLOTS[i + 1], new ItemBuilder(second.getDisplayItem()).name( + DefaultItem.getItemPrefix() + second.getDisplayName()).hideAttributes()); + } + + gui.addFrame(frame); + } + + } + + public void generateMenus() { + + for (MenuType value : MenuType.values()) { + value.executeWithGenerator(ChallengeMenuGenerator.class, ChallengeMenuGenerator::resetChallengeCache); + } + + for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { + MenuType type = challenge.getType(); + type.executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.addChallengeToCache(challenge)); + } + + for (MenuType value : MenuType.values()) { + value.getMenuGenerator().generateInventories(); + } + + generated = true; + } + + public void openGUI(@Nonnull Player player) { + SoundSample.PLOP.play(player); + MenuPosition.set(player, new MainMenuPosition()); + gui.open(player, Challenges.getInstance()); + } + + public void openGUIInstantly(@Nonnull Player player) { + MenuPosition.set(player, new MainMenuPosition()); + gui.openNotAnimated(player, true, Challenges.getInstance()); + } + + /** + * @return If the specified menu page could be opened. + * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded + */ + public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page) { + if (!generated) { + SoundSample.BASS_OFF.play(player); + player.sendMessage(Prefix.CHALLENGES + "§cCould not open gui, languages are not loaded"); + player.sendMessage(Prefix.CHALLENGES + "§cIs the plugin set up correctly?"); + return false; + } + + type.getMenuGenerator().open(player, page); + + return true; + } public void playNoPermissionsEffect(@Nonnull Player player) { - SoundSample.BASS_OFF.play(player); - Message.forName("no-permission").send(player, Prefix.CHALLENGES); - } + SoundSample.BASS_OFF.play(player); + Message.forName("no-permission").send(player, Prefix.CHALLENGES); + } - public boolean permissionToManageGUI() { - return permissionToManageGUI; - } + public boolean permissionToManageGUI() { + return permissionToManageGUI; + } - private class MainMenuPosition implements MenuPosition { + private class MainMenuPosition implements MenuPosition { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - for (int i = 0; i < GUI_SLOTS.length; i++) { - int current = GUI_SLOTS[i]; - if (current == info.getSlot()) { - MenuType type = MenuType.values()[i]; - if (openMenu(info.getPlayer(), type, 0)) - SoundSample.CLICK.play(info.getPlayer()); - return; - } - } + for (int i = 0; i < GUI_SLOTS.length; i++) { + int current = GUI_SLOTS[i]; + if (current == info.getSlot()) { + MenuType type = MenuType.values()[i]; + if (openMenu(info.getPlayer(), type, 0)) + SoundSample.CLICK.play(info.getPlayer()); + return; + } + } - SoundSample.CLICK.play(info.getPlayer()); + SoundSample.CLICK.play(info.getPlayer()); - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index 704e544c5..8dc5528c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -14,56 +14,53 @@ import javax.annotation.Nonnull; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ + public enum MenuType { - TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), - GOAL("goal", Material.COMPASS, new SmallCategorisedMenuGenerator()), - DAMAGE("damage", Material.IRON_SWORD, new SettingsMenuGenerator()), - ITEMS("item_blocks", Material.STICK, new SettingsMenuGenerator()), - CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), - SETTINGS("settings", Material.COMPARATOR, new SettingsMenuGenerator()), - CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); + TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), + GOAL("goal", Material.COMPASS, new SmallCategorisedMenuGenerator()), + DAMAGE("damage", Material.IRON_SWORD, new SettingsMenuGenerator()), + ITEMS("item_blocks", Material.STICK, new SettingsMenuGenerator()), + CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), + SETTINGS("settings", Material.COMPARATOR, new SettingsMenuGenerator()), + CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); - private final String key; - @Getter + private final String key; + @Getter private final Material displayItem; - @Getter + @Getter private final MenuGenerator menuGenerator; - @Getter + @Getter private final boolean usable; - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator, boolean usable) { - this.key = key; - this.displayItem = displayItem; - this.menuGenerator = menuGenerator; - this.usable = usable; + MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator, boolean usable) { + this.key = key; + this.displayItem = displayItem; + this.menuGenerator = menuGenerator; + this.usable = usable; - menuGenerator.setMenuType(this); - } + menuGenerator.setMenuType(this); + } - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator) { - this(key, displayItem, menuGenerator, true); - } + MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator) { + this(key, displayItem, menuGenerator, true); + } - @Nonnull - public String getName() { - return ChatColor.stripColor(getDisplayName()); - } + @Nonnull + public String getName() { + return ChatColor.stripColor(getDisplayName()); + } - @Nonnull - public String getDisplayName() { - return Message.forName("menu-" + key).asString(); - } + @Nonnull + public String getDisplayName() { + return Message.forName("menu-" + key).asString(); + } @SuppressWarnings("unchecked") - public void executeWithGenerator(Class clazz, Consumer action) { - if (clazz.isAssignableFrom(menuGenerator.getClass())) { - action.accept((T) menuGenerator); - } - } + public void executeWithGenerator(Class clazz, Consumer action) { + if (clazz.isAssignableFrom(menuGenerator.getClass())) { + action.accept((T) menuGenerator); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 2faa5a257..6996e9588 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu.generator; import com.google.common.collect.ImmutableList; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; @@ -24,237 +24,233 @@ import java.util.List; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeMenuGenerator extends MultiPageMenuGenerator { - protected final List challenges = new LinkedList<>(); - protected final boolean newSuffix; + protected final List challenges = new LinkedList<>(); + protected final boolean newSuffix; - private final int startPage; - protected Consumer onLeaveClick; + private final int startPage; + protected Consumer onLeaveClick; - public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { - newSuffix = Challenges.getInstance().getConfigDocument().getBoolean("new-suffix"); - this.startPage = startPage; - this.onLeaveClick = onLeaveClick; - } + public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { + newSuffix = Challenges.getInstance().getConfigDocument().getBoolean("new-suffix"); + this.startPage = startPage; + this.onLeaveClick = onLeaveClick; + } - public ChallengeMenuGenerator(int startPage) { - this(startPage, player -> Challenges.getInstance().getMenuManager().openGUIInstantly(player)); - } + public ChallengeMenuGenerator(int startPage) { + this(startPage, player -> Challenges.getInstance().getMenuManager().openGUIInstantly(player)); + } - public ChallengeMenuGenerator() { - this(0); - } + public ChallengeMenuGenerator() { + this(0); + } - public static boolean playNoPermissionsEffect(@Nonnull Player player) { - MenuManager menuManager = Challenges.getInstance().getMenuManager(); - if (!menuManager.permissionToManageGUI()) return false; - if (mayManageSettings(player)) return false; - menuManager.playNoPermissionsEffect(player); - return true; - } - - private static boolean mayManageSettings(@Nonnull Player player) { - return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new ChallengeMenuPositionGenerator(this, page); - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) challenges.size() / getSlots().length) + startPage); - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - - } - - @Override - public void generateInventories() { - super.generateInventories(); - - for (IChallenge challenge : challenges) { - updateItem(challenge); - } - - } - - public void updateItem(IChallenge challenge) { - - int index = challenges.indexOf(challenge); - if (index == -1) return; // Challenge not registered or menus not loaded - - int page = (index / getSlots().length); - if (page >= getInventories().size()) return; // This should never happen - - int slot = index - getSlots().length * page; - - Inventory inventory = getInventories().get(page + startPage); - setSettingsItems(inventory, challenge, slot); + public static boolean playNoPermissionsEffect(@Nonnull Player player) { + MenuManager menuManager = Challenges.getInstance().getMenuManager(); + if (!menuManager.permissionToManageGUI()) return false; + if (mayManageSettings(player)) return false; + menuManager.playNoPermissionsEffect(player); + return true; + } + + private static boolean mayManageSettings(@Nonnull Player player) { + return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new ChallengeMenuPositionGenerator(this, page); + } + + @Override + public int getPagesCount() { + return (int) (Math.ceil((double) challenges.size() / getSlots().length) + startPage); + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + + } + + @Override + public void generateInventories() { + super.generateInventories(); + + for (IChallenge challenge : challenges) { + updateItem(challenge); + } + + } + + public void updateItem(IChallenge challenge) { + + int index = challenges.indexOf(challenge); + if (index == -1) return; // Challenge not registered or menus not loaded + + int page = (index / getSlots().length); + if (page >= getInventories().size()) return; // This should never happen + + int slot = index - getSlots().length * page; + + Inventory inventory = getInventories().get(page + startPage); + setSettingsItems(inventory, challenge, slot); - if (newSuffix && isNew(challenge)) { - inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - } - } + if (newSuffix && isNew(challenge)) { + inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + } + } - public int getPageOfChallenge(IChallenge challenge) { - int index = challenges.indexOf(challenge); - if (index == -1) return -1; // Challenge not registered or menus not loaded + public int getPageOfChallenge(IChallenge challenge) { + int index = challenges.indexOf(challenge); + if (index == -1) return -1; // Challenge not registered or menus not loaded - int page = (index / getSlots().length); - if (page >= getInventories().size()) return -1; // This should never happen - - return page; - } - - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); - inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); - } - - public void resetChallengeCache() { - this.challenges.clear(); - } - - public boolean isInChallengeCache(@Nonnull IChallenge challenge) { - return challenges.contains(challenge); - } - - public void addChallengeToCache(@Nonnull IChallenge challenge) { - if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { - challenges.add(countNewChallenges(), challenge); - } else { - challenges.add(challenge); - } - } - - public void removeChallengeFromCache(@Nonnull IChallenge challenge) { - challenges.remove(challenge); - } - - protected ItemStack getDisplayItem(@Nonnull IChallenge challenge) { - return getDisplayItemBuilder(challenge).build(); - } - - protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { - try { - ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); - if (newSuffix && isNew(challenge)) { - return item.appendName(" " + Message.forName("new-challenge")); - } else { - return item; - } - } catch (Exception ex) { - Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder(); - } - } - - protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { - try { - ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); - return item.build(); - } catch (Exception ex) { - Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder().build(); - } - } - - protected boolean isNew(@Nonnull IChallenge challenge) { - Version version = Challenges.getInstance().getVersion(); - Version since = Version.getAnnotatedSince(challenge); - return since.isNewerOrEqualThan(version); - } - - protected int countNewChallenges() { - return (int) challenges.stream().filter(this::isNew).count(); - } - - public abstract int[] getSlots(); - - public abstract void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex); - - public void onPreChallengePageClicking(@Nonnull MenuClickInfo clickInfo, @Nonnegative int page) { - - } - - public List getChallenges() { - return ImmutableList.copyOf(challenges); - } - - private class ChallengeMenuPositionGenerator extends GeneratorMenuPosition { - - public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { - super(generator, page); - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { - return; - } - - - if (page < startPage) { - onPreChallengePageClicking(info, page); - return; - } - - int itemIndex = 0; - int index = 0; - for (int i : getSlots()) { - if (i == info.getSlot()) break; - if ((i + 9) == info.getSlot()) { - itemIndex = 1; - break; - } else if ((i + 18) == info.getSlot()) { - itemIndex = 2; - break; - } - index++; - } - - if (itemIndex >= 2) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - if (index == getSlots().length) { // No possible bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - int offset = (page - startPage) * getSlots().length; - index += offset; - - if (index >= challenges.size()) { // No bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - IChallenge challenge = challenges.get(index); - - if (playNoPermissionsEffect(info.getPlayer())) return; - - try { - executeClickAction(challenge, info, itemIndex); - updateItem(challenge); - } catch (Exception ex) { - Logger.error("An exception occurred while handling click on {}", challenge.getClass().getName(), ex); - } - - } - - } + int page = (index / getSlots().length); + if (page >= getInventories().size()) return -1; // This should never happen + + return page; + } + + public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); + inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); + } + + public void resetChallengeCache() { + this.challenges.clear(); + } + + public boolean isInChallengeCache(@Nonnull IChallenge challenge) { + return challenges.contains(challenge); + } + + public void addChallengeToCache(@Nonnull IChallenge challenge) { + if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { + challenges.add(countNewChallenges(), challenge); + } else { + challenges.add(challenge); + } + } + + public void removeChallengeFromCache(@Nonnull IChallenge challenge) { + challenges.remove(challenge); + } + + protected ItemStack getDisplayItem(@Nonnull IChallenge challenge) { + return getDisplayItemBuilder(challenge).build(); + } + + protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { + try { + ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); + if (newSuffix && isNew(challenge)) { + return item.appendName(" " + Message.forName("new-challenge")); + } else { + return item; + } + } catch (Exception ex) { + Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); + return new ItemBuilder(); + } + } + + protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { + try { + ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); + return item.build(); + } catch (Exception ex) { + Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); + return new ItemBuilder().build(); + } + } + + protected boolean isNew(@Nonnull IChallenge challenge) { + Version version = Challenges.getInstance().getVersion(); + Version since = Version.getAnnotatedSince(challenge); + return since.isNewerOrEqualThan(version); + } + + protected int countNewChallenges() { + return (int) challenges.stream().filter(this::isNew).count(); + } + + public abstract int[] getSlots(); + + public abstract void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex); + + public void onPreChallengePageClicking(@Nonnull MenuClickInfo clickInfo, @Nonnegative int page) { + + } + + public List getChallenges() { + return ImmutableList.copyOf(challenges); + } + + private class ChallengeMenuPositionGenerator extends GeneratorMenuPosition { + + public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { + super(generator, page); + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { + return; + } + + + if (page < startPage) { + onPreChallengePageClicking(info, page); + return; + } + + int itemIndex = 0; + int index = 0; + for (int i : getSlots()) { + if (i == info.getSlot()) break; + if ((i + 9) == info.getSlot()) { + itemIndex = 1; + break; + } else if ((i + 18) == info.getSlot()) { + itemIndex = 2; + break; + } + index++; + } + + if (itemIndex == 2) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + if (index == getSlots().length) { // No possible bound slot was clicked + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + int offset = (page - startPage) * getSlots().length; + index += offset; + + if (index >= challenges.size()) { // No bound slot was clicked + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + IChallenge challenge = challenges.get(index); + + if (playNoPermissionsEffect(info.getPlayer())) return; + + try { + executeClickAction(challenge, info, itemIndex); + updateItem(challenge); + } catch (Exception ex) { + Logger.error("An exception occurred while handling click on {}", challenge.getClass().getName(), ex); + } + + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index 0f4ad6e67..b268c8558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; @@ -16,113 +16,109 @@ import javax.annotation.Nonnull; import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChooseItemGenerator extends MultiPageMenuGenerator { - private final LinkedHashMap items; + private final LinkedHashMap items; - public ChooseItemGenerator(LinkedHashMap items) { - this.items = items; - } + public ChooseItemGenerator(LinkedHashMap items) { + this.items = items; + } - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } + private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + if (currentSlot >= 53) return currentSlot; + if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); + return currentSlot; + } - private static boolean isSideSlot(@Nonnegative int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } + private static boolean isSideSlot(@Nonnegative int slot) { + return slot % 9 == 0 || slot % 9 == 8; + } - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { - return slot < 9 || slot > 35; - } + private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + return slot < 9 || slot > 35; + } - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; + int slot = info.getSlot(); + int index = getItemsPerPage() * page + slot - 10; - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; + if (slot > 18) index -= 2; + if (slot > 27) index -= 2; - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (index >= items.size()) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - String[] array = items.keySet().toArray(new String[0]); + String[] array = items.keySet().toArray(new String[0]); - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - String itemKey = array[index]; + String itemKey = array[index]; - onItemClick(info.getPlayer(), itemKey); - SoundSample.PLOP.play(info.getPlayer()); + onItemClick(info.getPlayer(), itemKey); + SoundSample.PLOP.play(info.getPlayer()); - } - }; - } + } + }; + } - @Override - public int getSize() { - return 5 * 9; - } + @Override + public int getSize() { + return 5 * 9; + } - @Override - public int getPagesCount() { - return (int) Math.ceil((float) items.size() / getItemsPerPage()); - } + @Override + public int getPagesCount() { + return (int) Math.ceil((float) items.size() / getItemsPerPage()); + } - public int getItemsPerPage() { - return 3 * 7; - } + public int getItemsPerPage() { + return 3 * 7; + } - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - ItemStack itemStack = items.get(key); - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemStack); - lastSlot++; - } + int lastSlot = 10; + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { + String key = items.keySet().toArray(new String[0])[i]; + ItemStack itemStack = items.get(key); + lastSlot = getNextMiddleSlot(lastSlot); + inventory.setItem(lastSlot, itemStack); + lastSlot++; + } - } + } - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } + @Override + public int[] getNavigationSlots(int page) { + return MainCustomMenuGenerator.NAVIGATION_SLOTS; + } - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } - public abstract String[] getSubTitles(int page); + public abstract String[] getSubTitles(int page); - public abstract void onItemClick(Player player, String itemKey); + public abstract void onItemClick(Player player, String itemKey); - public abstract void onBackToMenuItemClick(Player player); + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 99ef204a9..8efcc07f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -1,13 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -22,137 +17,139 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; + public abstract class ChooseMultipleItemGenerator extends MultiPageMenuGenerator { - public static final int FINISH_SLOT = 40; - - private final LinkedHashMap items; - private final List selectedKeys; - - public ChooseMultipleItemGenerator(LinkedHashMap items) { - this.items = items; - selectedKeys = new LinkedList<>(); - } - - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } - - private static boolean isSideSlot(@Nonnegative int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } - - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { - return slot < 9 || slot > 35; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == FINISH_SLOT) { - onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); - SoundSample.PLOP.play(info.getPlayer()); - return; - } - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } - - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; - - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; - - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String[] array = items.keySet().toArray(new String[0]); - - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String itemKey = array[index]; - - if (selectedKeys.contains(itemKey)) { - selectedKeys.remove(itemKey); - } else { - selectedKeys.add(itemKey); - } - generatePage(info.getInventory(), page); - SoundSample.LOW_PLOP.play(info.getPlayer()); - } - }; - } - - @Override - public int getSize() { - return 5 * 9; - } - - @Override - public int getPagesCount() { - return (items.size() / getItemsPerPage()) + 1; - } - - public int getItemsPerPage() { - return 3 * 7; - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - ItemBuilder itemBuilder = new ItemBuilder(items.get(key)).clone(); - itemBuilder.hideAttributes(); - - if (selectedKeys.contains(key)) { - itemBuilder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); - itemBuilder.appendName(" §8┃ §2§l✔"); - } else { - itemBuilder.appendName(" §8┃ §c✖"); - } - - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemBuilder.build()); - lastSlot++; - } - - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } - - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } - - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } - - public abstract String[] getSubTitles(int page); - - public abstract void onItemClick(Player player, String[] itemKeys); - - public abstract void onBackToMenuItemClick(Player player); + public static final int FINISH_SLOT = 40; + + private final LinkedHashMap items; + private final List selectedKeys; + + public ChooseMultipleItemGenerator(LinkedHashMap items) { + this.items = items; + selectedKeys = new LinkedList<>(); + } + + private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + if (currentSlot >= 53) return currentSlot; + if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); + return currentSlot; + } + + private static boolean isSideSlot(@Nonnegative int slot) { + return slot % 9 == 0 || slot % 9 == 8; + } + + private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + return slot < 9 || slot > 35; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == FINISH_SLOT) { + onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); + SoundSample.PLOP.play(info.getPlayer()); + return; + } + + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } + + int slot = info.getSlot(); + int index = getItemsPerPage() * page + slot - 10; + + if (slot > 18) index -= 2; + if (slot > 27) index -= 2; + + if (index >= items.size()) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + String[] array = items.keySet().toArray(new String[0]); + + if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + String itemKey = array[index]; + + if (selectedKeys.contains(itemKey)) { + selectedKeys.remove(itemKey); + } else { + selectedKeys.add(itemKey); + } + generatePage(info.getInventory(), page); + SoundSample.LOW_PLOP.play(info.getPlayer()); + } + }; + } + + @Override + public int getSize() { + return 5 * 9; + } + + @Override + public int getPagesCount() { + return (items.size() / getItemsPerPage()) + 1; + } + + public int getItemsPerPage() { + return 3 * 7; + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + + int lastSlot = 10; + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { + String key = items.keySet().toArray(new String[0])[i]; + ItemBuilder itemBuilder = new ItemBuilder(items.get(key)).clone(); + itemBuilder.hideAttributes(); + + if (selectedKeys.contains(key)) { + itemBuilder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); + itemBuilder.appendName(" §8┃ §2§l✔"); + } else { + itemBuilder.appendName(" §8┃ §c✖"); + } + + lastSlot = getNextMiddleSlot(lastSlot); + inventory.setItem(lastSlot, itemBuilder.build()); + lastSlot++; + } + + inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); + } + + @Override + public int[] getNavigationSlots(int page) { + return MainCustomMenuGenerator.NAVIGATION_SLOTS; + } + + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } + + public abstract String[] getSubTitles(int page); + + public abstract void onItemClick(Player player, String[] itemKeys); + + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index e112dea0f..5fadbe3f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -1,10 +1,9 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import java.util.List; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; +import lombok.Getter; +import lombok.Setter; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import org.bukkit.Bukkit; @@ -12,59 +11,53 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ -public abstract class MenuGenerator { - - private MenuType menuType; - - public abstract void generateInventories(); - - public abstract List getInventories(); - - public abstract MenuPosition getMenuPosition(@Nonnegative int page); - - public boolean hasInventoryOpen(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - return menuPosition instanceof GeneratorMenuPosition - && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING - && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; - } - - public int getPage(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - if (menuPosition instanceof GeneratorMenuPosition) - return ((GeneratorMenuPosition) menuPosition).getPage(); - return 0; - } - - public void reopenInventoryForPlayers() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (hasInventoryOpen(player)) { - open(player, getPage(player)); - } - } - } - - public void open(@Nonnull Player player, @Nonnegative int page) { - List inventories = getInventories(); - if (inventories == null || inventories.isEmpty()) generateInventories(); - if (inventories == null || inventories.isEmpty()) return; - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory inventory = inventories.get(page); - MenuPosition.set(player, getMenuPosition(page)); - player.openInventory(inventory); - } +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.List; - public MenuType getMenuType() { - return menuType; - } +@Getter +@Setter +public abstract class MenuGenerator { - // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING - public void setMenuType(MenuType menuType) { - this.menuType = menuType; - } + // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING + private MenuType menuType; + + public abstract void generateInventories(); + + public abstract List getInventories(); + + public abstract MenuPosition getMenuPosition(@Nonnegative int page); + + public boolean hasInventoryOpen(Player player) { + MenuPosition menuPosition = MenuPosition.get(player); + return menuPosition instanceof GeneratorMenuPosition + && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING + && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; + } + + public int getPage(Player player) { + MenuPosition menuPosition = MenuPosition.get(player); + if (menuPosition instanceof GeneratorMenuPosition) + return ((GeneratorMenuPosition) menuPosition).getPage(); + return 0; + } + + public void reopenInventoryForPlayers() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (hasInventoryOpen(player)) { + open(player, getPage(player)); + } + } + } + + public void open(@Nonnull Player player, @Nonnegative int page) { + List inventories = getInventories(); + if (inventories == null || inventories.isEmpty()) generateInventories(); + if (inventories == null || inventories.isEmpty()) return; + if (page >= inventories.size()) page = inventories.size() - 1; + Inventory inventory = inventories.get(page); + MenuPosition.set(player, getMenuPosition(page)); + player.openInventory(inventory); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 60898ed8d..e0a398b3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; @@ -14,62 +14,58 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class MultiPageMenuGenerator extends MenuGenerator { - protected final List inventories = new ArrayList<>(); + protected final List inventories = new ArrayList<>(); - @Nonnull - protected Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } + @Nonnull + protected Inventory createNewInventory(int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + inventories.add(inventory); + return inventory; + } - protected String getTitle(@Nonnegative int page) { - return InventoryTitleManager.getTitle(getMenuType(), page); - } + protected String getTitle(@Nonnegative int page) { + return InventoryTitleManager.getTitle(getMenuType(), page); + } - public abstract int getSize(); + public abstract int getSize(); - public abstract int getPagesCount(); + public abstract int getPagesCount(); - public abstract void generatePage(@Nonnull Inventory inventory, int page); + public abstract void generatePage(@Nonnull Inventory inventory, int page); - public abstract int[] getNavigationSlots(@Nonnegative int page); + public abstract int[] getNavigationSlots(@Nonnegative int page); - @Override - public void generateInventories() { - inventories.clear(); + @Override + public void generateInventories() { + inventories.clear(); - for (int page = 0; page < getPagesCount(); page++) { - Inventory inventory = createNewInventory(page); - generatePage(inventory, page); - } + for (int page = 0; page < getPagesCount(); page++) { + Inventory inventory = createNewInventory(page); + generatePage(inventory, page); + } - for (int i = 0; i < inventories.size(); i++) { - addNavigationItems(inventories.get(i), i); - } + for (int i = 0; i < inventories.size(); i++) { + addNavigationItems(inventories.get(i), i); + } - reopenInventoryForPlayers(); + reopenInventoryForPlayers(); - } + } - @Override - public List getInventories() { - return inventories; - } + @Override + public List getInventories() { + return inventories; + } - public void addNavigationItems(@Nonnull Inventory inventory, int page) { - InventoryUtils.setNavigationItems(inventory, - getNavigationSlots(page), true, - InventorySetter.INVENTORY, page, inventories.size(), - DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), - DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); - } + public void addNavigationItems(@Nonnull Inventory inventory, int page) { + InventoryUtils.setNavigationItems(inventory, + getNavigationSlots(page), true, + InventorySetter.INVENTORY, page, inventories.size(), + DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), + DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index 05ccc2f9d..42bcb88e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.menu.generator; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; @@ -18,107 +18,103 @@ import javax.annotation.Nonnull; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @Getter public abstract class ValueMenuGenerator extends MultiPageMenuGenerator { - public static final int FINISH_SLOT = 31; + public static final int FINISH_SLOT = 31; - private final Map settings; + private final Map settings; - public ValueMenuGenerator(Map settings) { - this.settings = settings; - } + public ValueMenuGenerator(Map settings) { + this.settings = settings; + } - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - if (info.getSlot() == FINISH_SLOT) { - onSaveItemClick(info.getPlayer()); - SoundSample.PLOP.play(info.getPlayer()); - return; - } + if (info.getSlot() == FINISH_SLOT) { + onSaveItemClick(info.getPlayer()); + SoundSample.PLOP.play(info.getPlayer()); + return; + } - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } - int slot = info.getSlot(); + int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; + int index = getItemsPerPage() * page + slot - 10; - if (slot > 18) index -= 9; + if (slot > 18) index -= 9; - if (index >= settings.size() || index < 0) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (index >= settings.size() || index < 0) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - ValueSetting[] array = settings.keySet().toArray(new ValueSetting[0]); + ValueSetting[] array = settings.keySet().toArray(new ValueSetting[0]); - ValueSetting key = array[index]; - String oldValue = settings.get(key); + ValueSetting key = array[index]; + String oldValue = settings.get(key); - int itemIndex = slot >= 18 ? 1 : 0; - String newValue = key.onClick(info, oldValue, itemIndex); - settings.put(key, newValue); - SoundSample.CLICK.play(info.getPlayer()); - generatePage(info.getInventory(), page); - open(info.getPlayer(), page); - } - }; - } + int itemIndex = slot >= 18 ? 1 : 0; + String newValue = key.onClick(info, oldValue, itemIndex); + settings.put(key, newValue); + SoundSample.CLICK.play(info.getPlayer()); + generatePage(info.getInventory(), page); + open(info.getPlayer(), page); + } + }; + } - @Override - public int getSize() { - return 4 * 9; - } + @Override + public int getSize() { + return 4 * 9; + } - @Override - public int getPagesCount() { - return (settings.size() / getItemsPerPage()) + 1; - } + @Override + public int getPagesCount() { + return (settings.size() / getItemsPerPage()) + 1; + } - public int getItemsPerPage() { - return 4; - } + public int getItemsPerPage() { + return 4; + } - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { - int slot = i - (getItemsPerPage() * page) + 10; - ValueSetting key = settings.keySet().toArray(new ValueSetting[0])[i]; - String value = settings.get(key); - inventory.setItem(slot, key.getDisplayItem(value).build()); - inventory.setItem(slot + 9, key.getSettingsItem(value).build()); - } + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { + int slot = i - (getItemsPerPage() * page) + 10; + ValueSetting key = settings.keySet().toArray(new ValueSetting[0])[i]; + String value = settings.get(key); + inventory.setItem(slot, key.getDisplayItem(value).build()); + inventory.setItem(slot + 9, key.getSettingsItem(value).build()); + } - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } + inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); + } - @Override - public int[] getNavigationSlots(int page) { - return new int[]{27, 35}; - } + @Override + public int[] getNavigationSlots(int page) { + return new int[]{27, 35}; + } - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } - public abstract String[] getSubTitles(int page); + public abstract String[] getSubTitles(int page); - public abstract void onSaveItemClick(Player player); + public abstract void onSaveItemClick(Player player); - public abstract void onBackToMenuItemClick(Player player); + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 1541f1070..865652da3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; @@ -20,178 +20,174 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class CategorisedMenuGenerator extends SettingsMenuGenerator { - private final Map categories = new LinkedHashMap<>(); - - @Override - public void addChallengeToCache(@NotNull IChallenge challenge) { - SettingCategory category = challenge.getCategory() != null ? challenge.getCategory() : getMiscCategory(); - if (!categories.containsKey(challenge.getCategory())) { - categories.computeIfAbsent(category, challengeCategory -> { - CategorisedSettingsMenuGenerator generator = new CategorisedSettingsMenuGenerator(this, category); - generator.setMenuType(getMenuType()); - return generator; - }); - } - categories.get(category).addChallengeToCache(challenge); - } - - @Override - public void resetChallengeCache() { - categories.clear(); - } - - private SettingCategory getMiscCategory() { - if (getMenuType() == MenuType.GOAL) { - return SettingCategory.MISC_GOAL; - } - return SettingCategory.MISC_CHALLENGE; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - SettingCategory category = entry.getKey(); - CategorisedSettingsMenuGenerator generator = entry.getValue(); - - ItemBuilder builder = category.getDisplayItem(); - String attachment = getLoreAttachment(generator); - if (!attachment.isEmpty()) { - builder.appendLore("", attachment); - } - - int slot = i + 10; - if (i >= 7) slot += 2; - - for (IChallenge challenge : generator.getChallenges()) { - if (newSuffix && isNew(challenge)) { - builder.appendName(" " + Message.forName("new-challenge")); - break; - } - } - - inventory.setItem(slot, builder.build()); - i++; - } - - } - - private String getLoreAttachment(CategorisedSettingsMenuGenerator generator) { - - if (getMenuType() == MenuType.GOAL) { - for (IChallenge challenge : generator.getChallenges()) { - if (challenge.isEnabled()) { - return Message.forName("lore-category-activated").asString(); - } - } - return Message.forName("lore-category-deactivated").asString(); - } - long activatedCount = generator.getChallenges().stream().filter(IChallenge::isEnabled).count(); - return Message.forName("lore-category-activated-count").asString(activatedCount, generator.getChallenges().size()); - } - - @Override - public void updateItem(IChallenge challenge) { - generateInventories(); - - for (Map.Entry entry : categories.entrySet()) { - if (entry.getValue().getChallenges().contains(challenge)) { - entry.getValue().updateGeneratorItem(challenge); - } - } - - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) categories.size() / getEntriesPerPage())); - } - - public int getEntriesPerPage() { - return 14; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return info -> { - if (InventoryUtils.handleNavigationClicking(this, - getNavigationSlots(page), - page, - info, - () -> Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()))) { - return; - } - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - int slot = i + 10; - if (i >= 7) slot += 2; - if (slot == info.getSlot()) { - SettingsMenuGenerator generator = entry.getValue(); - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), 0); - return; - } - i++; - } - - SoundSample.CLICK.play(info.getPlayer()); - }; - } - - private List> getCategoriesForPage(int page) { - - List> list = categories.entrySet() - .stream() - // Priority might be removed in a future version - .sorted(Comparator.comparingInt(value -> value.getKey().getPriority())) - .collect(Collectors.toList()); - - int entriesPerPage = getEntriesPerPage(); - int startIndex = page * entriesPerPage; - int endIndex = Math.min(page * entriesPerPage + entriesPerPage, categories.size()); - - return list.subList(startIndex, endIndex); - } - - public static class CategorisedSettingsMenuGenerator extends SettingsMenuGenerator { - - private final CategorisedMenuGenerator generator; - private final SettingCategory category; - - public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, SettingCategory category) { - this.generator = generator; - this.category = category; - this.onLeaveClick = player -> { - SoundSample.CLICK.play(player); - generator.open(player, 0); - }; - } - - @Override - protected String getTitle(int page) { - String[] strings = category.getMessageSupplier().get().asArray(); - String display = strings.length == 0 ? "" : ChatColor.stripColor(strings[0]); - return InventoryTitleManager.getTitle(getMenuType(), display, String.valueOf(page + 1)); - } - - @Override - public void updateItem(IChallenge challenge) { - generator.updateItem(challenge); - super.updateItem(challenge); - } - - public void updateGeneratorItem(IChallenge challenge) { - super.updateItem(challenge); - } - - } + private final Map categories = new LinkedHashMap<>(); + + @Override + public void addChallengeToCache(@NotNull IChallenge challenge) { + SettingCategory category = challenge.getCategory() != null ? challenge.getCategory() : getMiscCategory(); + if (!categories.containsKey(challenge.getCategory())) { + categories.computeIfAbsent(category, challengeCategory -> { + CategorisedSettingsMenuGenerator generator = new CategorisedSettingsMenuGenerator(this, category); + generator.setMenuType(getMenuType()); + return generator; + }); + } + categories.get(category).addChallengeToCache(challenge); + } + + @Override + public void resetChallengeCache() { + categories.clear(); + } + + private SettingCategory getMiscCategory() { + if (getMenuType() == MenuType.GOAL) { + return SettingCategory.MISC_GOAL; + } + return SettingCategory.MISC_CHALLENGE; + } + + @Override + public void generatePage(@NotNull Inventory inventory, int page) { + + int i = 0; + for (Map.Entry entry : getCategoriesForPage(page)) { + SettingCategory category = entry.getKey(); + CategorisedSettingsMenuGenerator generator = entry.getValue(); + + ItemBuilder builder = category.getDisplayItem(); + String attachment = getLoreAttachment(generator); + if (!attachment.isEmpty()) { + builder.appendLore("", attachment); + } + + int slot = i + 10; + if (i >= 7) slot += 2; + + for (IChallenge challenge : generator.getChallenges()) { + if (newSuffix && isNew(challenge)) { + builder.appendName(" " + Message.forName("new-challenge")); + break; + } + } + + inventory.setItem(slot, builder.build()); + i++; + } + + } + + private String getLoreAttachment(CategorisedSettingsMenuGenerator generator) { + + if (getMenuType() == MenuType.GOAL) { + for (IChallenge challenge : generator.getChallenges()) { + if (challenge.isEnabled()) { + return Message.forName("lore-category-activated").asString(); + } + } + return Message.forName("lore-category-deactivated").asString(); + } + long activatedCount = generator.getChallenges().stream().filter(IChallenge::isEnabled).count(); + return Message.forName("lore-category-activated-count").asString(activatedCount, generator.getChallenges().size()); + } + + @Override + public void updateItem(IChallenge challenge) { + generateInventories(); + + for (Map.Entry entry : categories.entrySet()) { + if (entry.getValue().getChallenges().contains(challenge)) { + entry.getValue().updateGeneratorItem(challenge); + } + } + + } + + @Override + public int getPagesCount() { + return (int) (Math.ceil((double) categories.size() / getEntriesPerPage())); + } + + public int getEntriesPerPage() { + return 14; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return info -> { + if (InventoryUtils.handleNavigationClicking(this, + getNavigationSlots(page), + page, + info, + () -> Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()))) { + return; + } + + int i = 0; + for (Map.Entry entry : getCategoriesForPage(page)) { + int slot = i + 10; + if (i >= 7) slot += 2; + if (slot == info.getSlot()) { + SettingsMenuGenerator generator = entry.getValue(); + SoundSample.CLICK.play(info.getPlayer()); + generator.open(info.getPlayer(), 0); + return; + } + i++; + } + + SoundSample.CLICK.play(info.getPlayer()); + }; + } + + private List> getCategoriesForPage(int page) { + + List> list = categories.entrySet() + .stream() + // Priority might be removed in a future version + .sorted(Comparator.comparingInt(value -> value.getKey().getPriority())) + .collect(Collectors.toList()); + + int entriesPerPage = getEntriesPerPage(); + int startIndex = page * entriesPerPage; + int endIndex = Math.min(page * entriesPerPage + entriesPerPage, categories.size()); + + return list.subList(startIndex, endIndex); + } + + public static class CategorisedSettingsMenuGenerator extends SettingsMenuGenerator { + + private final CategorisedMenuGenerator generator; + private final SettingCategory category; + + public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, SettingCategory category) { + this.generator = generator; + this.category = category; + this.onLeaveClick = player -> { + SoundSample.CLICK.play(player); + generator.open(player, 0); + }; + } + + @Override + protected String getTitle(int page) { + String[] strings = category.getMessageSupplier().get().asArray(); + String display = strings.length == 0 ? "" : ChatColor.stripColor(strings[0]); + return InventoryTitleManager.getTitle(getMenuType(), display, String.valueOf(page + 1)); + } + + @Override + public void updateItem(IChallenge challenge) { + generator.updateItem(challenge); + super.updateItem(challenge); + } + + public void updateGeneratorItem(IChallenge challenge) { + super.updateItem(challenge); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java index 87b064286..99a11186e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; +import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -7,57 +8,42 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ +@Getter public class SettingCategory { - //Challenges - public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_challenge")); - public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, () -> Message.forName("category-randomizer")); - public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, () -> Message.forName("category-force")); - public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, () -> Message.forName("category-entities")); - public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, () -> Message.forName("category-damage")); - public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, () -> Message.forName("category-effect")); - public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, () -> Message.forName("category-world")); - public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, () -> Message.forName("category-inventory")); - public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, () -> Message.forName("category-movement")); - public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, () -> Message.forName("category-limited_time")); - public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, () -> Message.forName("category-extra_world")); - - //Goals - public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_goal")); - public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, () -> Message.forName("category-kill_entity")); - public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, () -> Message.forName("category-score_points")); - public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, () -> Message.forName("category-fastest_time")); - public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, () -> Message.forName("category-force_battle")); - - // Lowest priority will be displayed first - private final int priority; - private final Material material; - private final Supplier messageSupplier; - - public SettingCategory(int priority, Material material, Supplier messageSupplier) { - this.priority = priority; - this.material = material; - this.messageSupplier = messageSupplier; - } - - public int getPriority() { - return priority; - } - - public ItemBuilder getDisplayItem() { - return new ItemBuilder(material, messageSupplier.get()); - } - - public Material getMaterial() { - return material; - } - - public Supplier getMessageSupplier() { - return messageSupplier; - } + //Challenges + public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_challenge")); + public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, () -> Message.forName("category-randomizer")); + public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, () -> Message.forName("category-force")); + public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, () -> Message.forName("category-entities")); + public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, () -> Message.forName("category-damage")); + public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, () -> Message.forName("category-effect")); + public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, () -> Message.forName("category-world")); + public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, () -> Message.forName("category-inventory")); + public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, () -> Message.forName("category-movement")); + public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, () -> Message.forName("category-limited_time")); + public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, () -> Message.forName("category-extra_world")); + + //Goals + public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_goal")); + public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, () -> Message.forName("category-kill_entity")); + public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, () -> Message.forName("category-score_points")); + public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, () -> Message.forName("category-fastest_time")); + public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, () -> Message.forName("category-force_battle")); + + // Lowest priority will be displayed first + private final int priority; + private final Material material; + private final Supplier messageSupplier; + + public SettingCategory(int priority, Material material, Supplier messageSupplier) { + this.priority = priority; + this.material = material; + this.messageSupplier = messageSupplier; + } + + public ItemBuilder getDisplayItem() { + return new ItemBuilder(material, messageSupplier.get()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java index b8b9b81bd..c84df1f4c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java @@ -1,23 +1,19 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class SmallCategorisedMenuGenerator extends CategorisedMenuGenerator { - @Override - public int getEntriesPerPage() { - return 7; - } + @Override + public int getEntriesPerPage() { + return 7; + } - @Override - public int getSize() { - return 9 * 3; - } + @Override + public int getSize() { + return 9 * 3; + } - @Override - public int[] getNavigationSlots(int page) { - return new int[]{18, 26}; - } + @Override + public int[] getNavigationSlots(int page) { + return new int[]{18, 26}; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 13404457a..02585fecf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -1,43 +1,39 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SettingsMenuGenerator extends ChallengeMenuGenerator { - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {27, 35}; - public static final int SIZE = 4 * 9; + public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; + public static final int[] NAVIGATION_SLOTS = {27, 35}; + public static final int SIZE = 4 * 9; - @Override - public int[] getSlots() { - return SLOTS; - } + @Override + public int[] getSlots() { + return SLOTS; + } - @Override - public int getSize() { - return SIZE; - } + @Override + public int getSize() { + return SIZE; + } - @Override - public int[] getNavigationSlots(int page) { - return NAVIGATION_SLOTS; - } + @Override + public int[] getNavigationSlots(int page) { + return NAVIGATION_SLOTS; + } - @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { - if (itemIndex <= 1) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } + @Override + public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + if (itemIndex <= 1) { + challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 3aeaaca2c..194f6e778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -15,8 +15,8 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; @@ -29,203 +29,199 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class TimerMenuGenerator extends MenuGenerator { - public static final int SIZE = 5 * 9; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int START_SLOT = 21; - public static final int MODE_SLOT = 23; - public static final int[] HOUR_SLOTS = {11, 20, 29}; - public static final int[] MINUTE_SLOTS = {13, 22, 31}; - public static final int[] SECOND_SLOTS = {15, 24, 33}; - - private final List inventories = new ArrayList<>(); - - public TimerMenuGenerator() { - ChallengeAPI.registerScheduler(this); - Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::generateInventories); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) - public void updateInventories() { - updateFirstPage(); - updateSecondPage(); - } - - public void updateFirstPage() { - Inventory inventory = inventories.get(0); - inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? - new ItemBuilder(Material.LIME_DYE).name(Message.forName("timer-is-running")).build() : - new ItemBuilder(MinecraftNameWrapper.RED_DYE).name(Message.forName("timer-is-paused")).build()); - inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.LIME).name(Message.forName("timer-counting-up")).hideAttributes().build() : - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).name(Message.forName("timer-counting-down")).hideAttributes().build()); - } - - @ScheduledTask(ticks = 20) - public void updateSecondPage() { - setTimeNavigation(HOUR_SLOTS, Message.forName("hour"), Message.forName("hours")); - setTimeNavigation(MINUTE_SLOTS, Message.forName("minute"), Message.forName("minutes")); - setTimeNavigation(SECOND_SLOTS, Message.forName("second"), Message.forName("seconds")); - - long seconds = Challenges.getInstance().getChallengeTimer().getTime(); - long minutes = seconds / 60; - long hours = minutes / 60; - seconds %= 60; - minutes %= 60; - - Inventory inventory = inventories.get(1); - inventory.setItem(HOUR_SLOTS[1], getTimeItem(hours, Message.forName("hour"), Message.forName("hours"))); - inventory.setItem(MINUTE_SLOTS[1], getTimeItem(minutes, Message.forName("minute"), Message.forName("minutes"))); - inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); - } - - private void setTimeNavigation(@Nonnull int[] slots, @Nonnull Message singular, @Nonnull Message plural) { - Inventory inventory = inventories.get(1); - inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); - inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); - } - - @Nonnull - private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonnull Message plural) { - return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( - " ", - "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, - "§7§o[Shift-Click] §8» §" + (up ? "a+" : "c-") + "10 " + plural, - " " - ).hideAttributes().build(); - } - - @Nonnull - private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Message plural) { - return new ItemBuilder(Material.CLOCK).name( - "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, - " ", - "§7§o[Click] §8» §cReset §7timer", - " " - ).hideAttributes().amount((int) Math.max(value, 1)).build(); - } - - @Nonnull - private Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { - inventory.setItem(i, ItemBuilder.FILL_ITEM_2); - } - inventories.add(inventory); - return inventory; - } - - private void setNavigation() { - InventoryUtils.setNavigationItemsToInventory(inventories, NAVIGATION_SLOTS); - } - - @Override - public void generateInventories() { - createNewInventory(0); - createNewInventory(1); - setNavigation(); - updateInventories(); - } - - @Override - public List getInventories() { - return inventories; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new TimerMenuPosition(page); - } - - private class TimerMenuPosition implements MenuPosition { - - private final int page; - - public TimerMenuPosition(@Nonnegative int page) { - this.page = page; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == NAVIGATION_SLOTS[0]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page == 0) { - Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()); - } else { - open(info.getPlayer(), page - 1); - } - return; - } else if (info.getSlot() == NAVIGATION_SLOTS[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (inventories.size() - 1)) - open(info.getPlayer(), page + 1); - return; - } - - if (page == 0) { - if (info.getSlot() == START_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - if (Challenges.getInstance().getChallengeTimer().isStarted()) { - Challenges.getInstance().getChallengeTimer().pause(true); - } else { - Challenges.getInstance().getChallengeTimer().resume(); - } - return; - } else if (info.getSlot() == MODE_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); - return; - } - } else if (page == 1) { - for (int[] slots : new int[][]{HOUR_SLOTS, MINUTE_SLOTS, SECOND_SLOTS}) { - for (int i = 0; i < 3; i++) { - - if (info.getSlot() != slots[i]) continue; - if (playNoPermissionsEffect(info.getPlayer())) return; - - if (i == 1) { - Challenges.getInstance().getChallengeTimer().reset(); - SoundSample.BASS_OFF.play(info.getPlayer()); - updateInventories(); - Challenges.getInstance().getChallengeTimer().updateActionbar(); - return; - } - - int amount = (slots == HOUR_SLOTS ? 60 * 60 : (slots == MINUTE_SLOTS ? 60 : 1)); - if (info.isShiftClick()) amount *= 10; - - boolean plus = i == 0; - - Challenges.getInstance().getChallengeTimer().addSeconds(plus ? +amount : -amount); - updateInventories(); - - SoundSample.PLOP.play(info.getPlayer()); - return; - } - } - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - private boolean playNoPermissionsEffect(@Nonnull Player player) { - if (mayManageTimer(player)) return false; - Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); - return true; - } - - private boolean mayManageTimer(@Nonnull Player player) { - return player.hasPermission("challenges.timer"); - } - - } + public static final int SIZE = 5 * 9; + public static final int[] NAVIGATION_SLOTS = {36, 44}; + public static final int START_SLOT = 21; + public static final int MODE_SLOT = 23; + public static final int[] HOUR_SLOTS = {11, 20, 29}; + public static final int[] MINUTE_SLOTS = {13, 22, 31}; + public static final int[] SECOND_SLOTS = {15, 24, 33}; + + private final List inventories = new ArrayList<>(); + + public TimerMenuGenerator() { + ChallengeAPI.registerScheduler(this); + Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::generateInventories); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) + public void updateInventories() { + updateFirstPage(); + updateSecondPage(); + } + + public void updateFirstPage() { + Inventory inventory = inventories.get(0); + inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? + new ItemBuilder(Material.LIME_DYE).name(Message.forName("timer-is-running")).build() : + new ItemBuilder(MinecraftNameWrapper.RED_DYE).name(Message.forName("timer-is-paused")).build()); + inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? + new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.LIME).name(Message.forName("timer-counting-up")).hideAttributes().build() : + new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).name(Message.forName("timer-counting-down")).hideAttributes().build()); + } + + @ScheduledTask(ticks = 20) + public void updateSecondPage() { + setTimeNavigation(HOUR_SLOTS, Message.forName("hour"), Message.forName("hours")); + setTimeNavigation(MINUTE_SLOTS, Message.forName("minute"), Message.forName("minutes")); + setTimeNavigation(SECOND_SLOTS, Message.forName("second"), Message.forName("seconds")); + + long seconds = Challenges.getInstance().getChallengeTimer().getTime(); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + Inventory inventory = inventories.get(1); + inventory.setItem(HOUR_SLOTS[1], getTimeItem(hours, Message.forName("hour"), Message.forName("hours"))); + inventory.setItem(MINUTE_SLOTS[1], getTimeItem(minutes, Message.forName("minute"), Message.forName("minutes"))); + inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); + } + + private void setTimeNavigation(@Nonnull int[] slots, @Nonnull Message singular, @Nonnull Message plural) { + Inventory inventory = inventories.get(1); + inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); + inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); + } + + @Nonnull + private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonnull Message plural) { + return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( + " ", + "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, + "§7§o[Shift-Click] §8» §" + (up ? "a+" : "c-") + "10 " + plural, + " " + ).hideAttributes().build(); + } + + @Nonnull + private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Message plural) { + return new ItemBuilder(Material.CLOCK).name( + "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, + " ", + "§7§o[Click] §8» §cReset §7timer", + " " + ).hideAttributes().amount((int) Math.max(value, 1)).build(); + } + + @Nonnull + private Inventory createNewInventory(int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { + inventory.setItem(i, ItemBuilder.FILL_ITEM_2); + } + inventories.add(inventory); + return inventory; + } + + private void setNavigation() { + InventoryUtils.setNavigationItemsToInventory(inventories, NAVIGATION_SLOTS); + } + + @Override + public void generateInventories() { + createNewInventory(0); + createNewInventory(1); + setNavigation(); + updateInventories(); + } + + @Override + public List getInventories() { + return inventories; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new TimerMenuPosition(page); + } + + private class TimerMenuPosition implements MenuPosition { + + private final int page; + + public TimerMenuPosition(@Nonnegative int page) { + this.page = page; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == NAVIGATION_SLOTS[0]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page == 0) { + Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()); + } else { + open(info.getPlayer(), page - 1); + } + return; + } else if (info.getSlot() == NAVIGATION_SLOTS[1]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page < (inventories.size() - 1)) + open(info.getPlayer(), page + 1); + return; + } + + if (page == 0) { + if (info.getSlot() == START_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return; + if (Challenges.getInstance().getChallengeTimer().isStarted()) { + Challenges.getInstance().getChallengeTimer().pause(true); + } else { + Challenges.getInstance().getChallengeTimer().resume(); + } + return; + } else if (info.getSlot() == MODE_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return; + Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); + return; + } + } else if (page == 1) { + for (int[] slots : new int[][]{HOUR_SLOTS, MINUTE_SLOTS, SECOND_SLOTS}) { + for (int i = 0; i < 3; i++) { + + if (info.getSlot() != slots[i]) continue; + if (playNoPermissionsEffect(info.getPlayer())) return; + + if (i == 1) { + Challenges.getInstance().getChallengeTimer().reset(); + SoundSample.BASS_OFF.play(info.getPlayer()); + updateInventories(); + Challenges.getInstance().getChallengeTimer().updateActionbar(); + return; + } + + int amount = (slots == HOUR_SLOTS ? 60 * 60 : (slots == MINUTE_SLOTS ? 60 : 1)); + if (info.isShiftClick()) amount *= 10; + + boolean plus = i == 0; + + Challenges.getInstance().getChallengeTimer().addSeconds(plus ? +amount : -amount); + updateInventories(); + + SoundSample.PLOP.play(info.getPlayer()); + return; + } + } + } + + SoundSample.CLICK.play(info.getPlayer()); + + } + + private boolean playNoPermissionsEffect(@Nonnull Player player) { + if (mayManageTimer(player)) return false; + Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); + return true; + } + + private boolean mayManageTimer(@Nonnull Player player) { + return player.hasPermission("challenges.timer"); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java index 1daee6263..3aad5dcf6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java @@ -14,87 +14,78 @@ import java.util.Map; import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class CustomMainSettingsMenuGenerator extends ChooseItemGenerator implements IParentCustomGenerator { - @Getter + @Getter private final IParentCustomGenerator parent; - private final SettingType type; - private final String title; - private final String key; - private final Function instanceGetter; - private IChallengeSetting setting; - private SubSettingsBuilder subSettingsBuilder; - private Map subSettings; - - public CustomMainSettingsMenuGenerator(IParentCustomGenerator parent, SettingType type, String key, String title, LinkedHashMap items, Function instanceGetter) { - super(items); - this.parent = parent; - this.type = type; - this.title = title; - this.key = key; - this.instanceGetter = instanceGetter; - this.subSettings = new HashMap<>(); - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } + private final SettingType type; + private final String title; + private final String key; + private final Function instanceGetter; + private IChallengeSetting setting; + private SubSettingsBuilder subSettingsBuilder; + private Map subSettings; + + public CustomMainSettingsMenuGenerator(IParentCustomGenerator parent, SettingType type, String key, String title, LinkedHashMap items, Function instanceGetter) { + super(items); + this.parent = parent; + this.type = type; + this.title = title; + this.key = key; + this.instanceGetter = instanceGetter; + this.subSettings = new HashMap<>(); + } @Override - public void accept(Player player, SettingType type, Map data) { + public String[] getSubTitles(int page) { + return new String[]{title}; + } - subSettings.putAll(data); + @Override + public void accept(Player player, SettingType type, Map data) { - if (!openSubSettingsMenu(player)) { - parent.accept(player, this.type, subSettings); - } + subSettings.putAll(data); - } + if (!openSubSettingsMenu(player)) { + parent.accept(player, this.type, subSettings); + } - @Override - public void onItemClick(Player player, String itemKey) { - this.setting = instanceGetter.apply(itemKey); - this.subSettingsBuilder = setting.getSubSettingsBuilder(); + } - subSettings.put(key, new String[]{setting.getName()}); + @Override + public void onItemClick(Player player, String itemKey) { + this.setting = instanceGetter.apply(itemKey); + this.subSettingsBuilder = setting.getSubSettingsBuilder(); - if (!openSubSettingsMenu(player)) { - parent.accept(player, type, subSettings); - } + subSettings.put(key, new String[]{setting.getName()}); - } + if (!openSubSettingsMenu(player)) { + parent.accept(player, type, subSettings); + } - private boolean openSubSettingsMenu(Player player) { + } - if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { - subSettingsBuilder.open(player, this, title); - subSettingsBuilder = subSettingsBuilder.getChild(); + private boolean openSubSettingsMenu(Player player) { - return true; - } - return false; - } + if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { + subSettingsBuilder.open(player, this, title); + subSettingsBuilder = subSettingsBuilder.getChild(); - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + return true; + } + return false; + } - @Override - public void decline(Player player) { - if (setting != null) - this.subSettings = MapUtils.createStringArrayMap(key, setting.getName()); - open(player, 0); - } + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } + + @Override + public void decline(Player player) { + if (setting != null) + this.subSettings = MapUtils.createStringArrayMap(key, setting.getName()); + open(player, 0); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java index 30b47968b..47b13b20d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java @@ -5,19 +5,15 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IParentCustomGenerator { - /** - * @param player the player that has the menu open - * @param type the type of the current setting. Only needed if parent is the first setting menu. - * @param data a map that contains all the data of the settings - */ - void accept(Player player, SettingType type, Map data); + /** + * @param player the player that has the menu open + * @param type the type of the current setting. Only needed if parent is the first setting menu. + * @param data a map that contains all the data of the settings + */ + void accept(Player player, SettingType type, Map data); - void decline(Player player); + void decline(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 44cff4691..0700ff5bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; @@ -34,279 +34,275 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @ToString public class InfoMenuGenerator extends MenuGenerator implements IParentCustomGenerator { - public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; - - private static final Material[] defaultMaterials; - private static final boolean savePlayerChallenges; - - static { - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); - ArrayList list = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - list.removeIf(material1 -> !material1.isItem()); - defaultMaterials = list.toArray(new Material[0]); - } - - private final UUID uuid; - private String name; - private Material material; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - private Inventory inventory; - - public InfoMenuGenerator(CustomChallenge customChallenge) { - this.uuid = customChallenge.getUniqueId(); - this.material = customChallenge.getMaterial(); - this.name = customChallenge.getDisplayName(); - this.trigger = customChallenge.getTrigger(); - this.subTriggers = customChallenge.getSubTriggers(); - this.action = customChallenge.getAction(); - this.subActions = customChallenge.getSubActions(); - } - - /** - * Default Settings for new Custom Challenges - */ - public InfoMenuGenerator() { - this.trigger = null; - this.action = null; - this.subTriggers = new HashMap<>(); - this.subActions = new HashMap<>(); - this.uuid = UUID.randomUUID(); - this.material = IRandom.threadLocal().choose(defaultMaterials); - this.name = "§7Custom §e#" + - (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); - } - - public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { - List display = new LinkedList<>(); - for (SubSettingsBuilder child : builder.getAllChildren()) { - display.addAll(child.getDisplay(activated)); - } - return display; - } - - @Override - public void generateInventories() { - inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - - updateItems(); - - InventoryUtils.setNavigationItems(inventory, new int[]{36 + 9}, true, InventorySetter.INVENTORY, 0, 1); - } - - public void updateItems() { - String currently = Message.forName("custom-info-currently").asString(); - String none = Message.forName("none").asString(); - - // Save / Delete Item - inventory.setItem(DELETE_SLOT, new ItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); - inventory.setItem(SAVE_SLOT, new ItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); - - // Trigger Item - ItemBuilder triggerItem = new ItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-info-trigger")) - .appendLore( - currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); - if (trigger != null) { - triggerItem.appendLore(getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers)); - } - inventory.setItem(CONDITION_SLOT, triggerItem.build()); - - // Action Item - ItemBuilder actionItem = new ItemBuilder(Material.NETHER_STAR, - Message.forName("item-custom-info-action")) - .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); - if (action != null) { - actionItem.appendLore(getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions)); - } - inventory.setItem(ACTION_SLOT, actionItem.build()); - - // Display Item - inventory.setItem(MATERIAL_SLOT, new ItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) - .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); - - // Name Item - inventory.setItem(NAME_SLOT, new ItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) - .appendLore(currently + "§7" + name).build()); - } - - @Override - public List getInventories() { - return Collections.singletonList(inventory); - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new InfoMenuPosition(page, this); - } - - @Override - public void open(@Nonnull Player player, int page) { - if (inventory == null) generateInventories(); - super.open(player, page); - } - - @Override - public void accept(Player player, SettingType type, Map data) { - open(player, 0); - - switch (type) { - case CONDITION: - trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); - this.subTriggers = data; - break; - - case ACTION: - action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); - this.subActions = data; - break; - - case MATERIAL: - material = Material.valueOf(data.remove("material")[0]); - updateItems(); - break; - } - - updateItems(); - } - - public void setName(String name) { - this.name = name; - updateItems(); - } - - @Override - public void decline(Player player) { - open(player, 0); - } - - public CustomChallenge save() { - return Challenges.getInstance().getCustomChallengesLoader().registerCustomChallenge(uuid, material, name, - trigger, subTriggers, action, subActions, true); - } - - public void openChallengeMenu(Player player) { - CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader() - .getCustomChallenges().get(uuid); - if (challenge == null) { - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); - } else { - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); - int page = menuGenerator.getPageOfChallenge(challenge) + 1; // +1 because the main and challenge menu are in the same generator - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, page); - } - } - - public class InfoMenuPosition implements MenuPosition { - - private final int page; - @Getter + public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; + + private static final Material[] defaultMaterials; + private static final boolean savePlayerChallenges; + + static { + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); + ArrayList list = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + list.removeIf(material1 -> !material1.isItem()); + defaultMaterials = list.toArray(new Material[0]); + } + + private final UUID uuid; + private String name; + private Material material; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + private Inventory inventory; + + public InfoMenuGenerator(CustomChallenge customChallenge) { + this.uuid = customChallenge.getUniqueId(); + this.material = customChallenge.getMaterial(); + this.name = customChallenge.getDisplayName(); + this.trigger = customChallenge.getTrigger(); + this.subTriggers = customChallenge.getSubTriggers(); + this.action = customChallenge.getAction(); + this.subActions = customChallenge.getSubActions(); + } + + /** + * Default Settings for new Custom Challenges + */ + public InfoMenuGenerator() { + this.trigger = null; + this.action = null; + this.subTriggers = new HashMap<>(); + this.subActions = new HashMap<>(); + this.uuid = UUID.randomUUID(); + this.material = IRandom.threadLocal().choose(defaultMaterials); + this.name = "§7Custom §e#" + + (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); + } + + public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { + List display = new LinkedList<>(); + for (SubSettingsBuilder child : builder.getAllChildren()) { + display.addAll(child.getDisplay(activated)); + } + return display; + } + + @Override + public void generateInventories() { + inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + + updateItems(); + + InventoryUtils.setNavigationItems(inventory, new int[]{36 + 9}, true, InventorySetter.INVENTORY, 0, 1); + } + + public void updateItems() { + String currently = Message.forName("custom-info-currently").asString(); + String none = Message.forName("none").asString(); + + // Save / Delete Item + inventory.setItem(DELETE_SLOT, new ItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); + inventory.setItem(SAVE_SLOT, new ItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); + + // Trigger Item + ItemBuilder triggerItem = new ItemBuilder(Material.WITHER_SKELETON_SKULL, + Message.forName("item-custom-info-trigger")) + .appendLore( + currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); + if (trigger != null) { + triggerItem.appendLore(getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers)); + } + inventory.setItem(CONDITION_SLOT, triggerItem.build()); + + // Action Item + ItemBuilder actionItem = new ItemBuilder(Material.NETHER_STAR, + Message.forName("item-custom-info-action")) + .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); + if (action != null) { + actionItem.appendLore(getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions)); + } + inventory.setItem(ACTION_SLOT, actionItem.build()); + + // Display Item + inventory.setItem(MATERIAL_SLOT, new ItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) + .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); + + // Name Item + inventory.setItem(NAME_SLOT, new ItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) + .appendLore(currently + "§7" + name).build()); + } + + @Override + public List getInventories() { + return Collections.singletonList(inventory); + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new InfoMenuPosition(page, this); + } + + @Override + public void open(@Nonnull Player player, int page) { + if (inventory == null) generateInventories(); + super.open(player, page); + } + + @Override + public void accept(Player player, SettingType type, Map data) { + open(player, 0); + + switch (type) { + case CONDITION: + trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); + this.subTriggers = data; + break; + + case ACTION: + action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); + this.subActions = data; + break; + + case MATERIAL: + material = Material.valueOf(data.remove("material")[0]); + updateItems(); + break; + } + + updateItems(); + } + + public void setName(String name) { + this.name = name; + updateItems(); + } + + @Override + public void decline(Player player) { + open(player, 0); + } + + public CustomChallenge save() { + return Challenges.getInstance().getCustomChallengesLoader().registerCustomChallenge(uuid, material, name, + trigger, subTriggers, action, subActions, true); + } + + public void openChallengeMenu(Player player) { + CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader() + .getCustomChallenges().get(uuid); + if (challenge == null) { + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); + } else { + ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); + int page = menuGenerator.getPageOfChallenge(challenge) + 1; // +1 because the main and challenge menu are in the same generator + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, page); + } + } + + public class InfoMenuPosition implements MenuPosition { + + private final int page; + @Getter private final InfoMenuGenerator generator; - public InfoMenuPosition(int page, InfoMenuGenerator generator) { - this.page = page; - this.generator = generator; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { - return; - } - - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - info.getPlayer().closeInventory(); - return; - } - - Player player = info.getPlayer(); - - switch (info.getSlot()) { - default: - SoundSample.CLICK.play(player); - break; - case DELETE_SLOT: - if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { - Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - break; - } - openChallengeMenu(player); - Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); - new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); - break; - case SAVE_SLOT: - - String defaults = new InfoMenuGenerator().toString(); - String current = InfoMenuGenerator.this.toString(); - if (defaults.equals(current)) { - Message.forName("custom-no-changes").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - return; - } - - save(); - openChallengeMenu(player); - Message.forName("custom-saved").send(player, Prefix.CUSTOM); - if (savePlayerChallenges) { - Message.forName("custom-saved-db").send(player, Prefix.CUSTOM); - } - SoundSample.LEVEL_UP.play(player); - break; - case CONDITION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.CONDITION, - "trigger", Message.forName("custom-title-trigger").asString(), - ChallengeTrigger.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case ACTION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.ACTION, - "action", Message.forName("custom-title-action").asString(), - ChallengeAction.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case NAME_SLOT: - - Message.forName("custom-name-info").send(player, Prefix.CUSTOM); - player.closeInventory(); - - ChatInputListener.setInputAction(player, event -> { - int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() - .getMaxNameLength(); - if (event.getMessage().length() > maxNameLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); - return; - } - - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); - open(event.getPlayer(), 0); - }); - - }); - - break; - case MATERIAL_SLOT: - MaterialMenuGenerator materialMenuGenerator = new MaterialMenuGenerator(generator); - materialMenuGenerator.open(player, 0); - SoundSample.CLICK.play(player); - break; - } - } + public InfoMenuPosition(int page, InfoMenuGenerator generator) { + this.page = page; + this.generator = generator; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { + return; + } + + if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { + info.getPlayer().closeInventory(); + return; + } + + Player player = info.getPlayer(); + + switch (info.getSlot()) { + case DELETE_SLOT: + if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { + Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + break; + } + openChallengeMenu(player); + Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); + new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); + break; + case SAVE_SLOT: + + String defaults = new InfoMenuGenerator().toString(); + String current = InfoMenuGenerator.this.toString(); + if (defaults.equals(current)) { + Message.forName("custom-no-changes").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + return; + } + + save(); + openChallengeMenu(player); + Message.forName("custom-saved").send(player, Prefix.CUSTOM); + if (savePlayerChallenges) { + Message.forName("custom-saved-db").send(player, Prefix.CUSTOM); + } + SoundSample.LEVEL_UP.play(player); + break; + case CONDITION_SLOT: + new CustomMainSettingsMenuGenerator(generator, SettingType.CONDITION, + "trigger", Message.forName("custom-title-trigger").asString(), + ChallengeTrigger.getMenuItems(), + s -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(s)) + .open(player, 0); + SoundSample.CLICK.play(player); + break; + case ACTION_SLOT: + new CustomMainSettingsMenuGenerator(generator, SettingType.ACTION, + "action", Message.forName("custom-title-action").asString(), + ChallengeAction.getMenuItems(), + s -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(s)) + .open(player, 0); + SoundSample.CLICK.play(player); + break; + case NAME_SLOT: + + Message.forName("custom-name-info").send(player, Prefix.CUSTOM); + player.closeInventory(); + + ChatInputListener.setInputAction(player, event -> { + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() + .getMaxNameLength(); + if (event.getMessage().length() > maxNameLength) { + Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); + return; + } + + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); + open(event.getPlayer(), 0); + }); + + }); + + break; + case MATERIAL_SLOT: + MaterialMenuGenerator materialMenuGenerator = new MaterialMenuGenerator(generator); + materialMenuGenerator.open(player, 0); + SoundSample.CLICK.play(player); + break; + default: + SoundSample.CLICK.play(player); + break; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 83da67ff0..2f5417ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -17,97 +17,93 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MainCustomMenuGenerator extends ChallengeMenuGenerator { - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int SIZE = 5 * 9; - private static final int VIEW_SLOT = 21; - private static final int CREATE_SLOT = 23; - - private static final int maxCustomChallenges; - - static { - maxCustomChallenges = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-challenges"); - } - - public MainCustomMenuGenerator() { - super(1); - } - - @Override - protected String getTitle(int page) { - return page != 0 ? InventoryTitleManager.getTitle(getMenuType(), - Message.forName("custom-title-view").asString(), String.valueOf(page)) : - InventoryTitleManager.getTitle(getMenuType(), "Menu"); - } - - @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { - if (itemIndex == 0 || itemIndex == 2) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } else if (challenge instanceof CustomChallenge) { - InfoMenuGenerator infoMenuGenerator = new InfoMenuGenerator((CustomChallenge) challenge); - infoMenuGenerator.open(info.getPlayer(), 0); - SoundSample.CLICK.play(info.getPlayer()); - } - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - if (page == 0) { - inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); - inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); - } - } - - @Override - public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { - if (info.getSlot() == VIEW_SLOT) { - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() == 0) { - Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); - return; - } - open(info.getPlayer(), 1); - SoundSample.PLOP.play(info.getPlayer()); - } else if (info.getSlot() == CREATE_SLOT) { - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - return; - } - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { - Message.forName("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); - SoundSample.BASS_OFF.play(info.getPlayer()); - return; - } - new InfoMenuGenerator().open(info.getPlayer(), 0); - SoundSample.PLING.play(info.getPlayer()); - } - } - - @Override - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); - inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); - inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); - } - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getSize() { - return SIZE; - } - - @Override - public int[] getNavigationSlots(int page) { - return page == 0 ? new int[]{NAVIGATION_SLOTS[0]} : NAVIGATION_SLOTS; - } + public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; + public static final int[] NAVIGATION_SLOTS = {36, 44}; + public static final int SIZE = 5 * 9; + private static final int VIEW_SLOT = 21; + private static final int CREATE_SLOT = 23; + + private static final int maxCustomChallenges; + + static { + maxCustomChallenges = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-challenges"); + } + + public MainCustomMenuGenerator() { + super(1); + } + + @Override + protected String getTitle(int page) { + return page != 0 ? InventoryTitleManager.getTitle(getMenuType(), + Message.forName("custom-title-view").asString(), String.valueOf(page)) : + InventoryTitleManager.getTitle(getMenuType(), "Menu"); + } + + @Override + public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + if (itemIndex == 0 || itemIndex == 2) { + challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); + } else if (challenge instanceof CustomChallenge) { + InfoMenuGenerator infoMenuGenerator = new InfoMenuGenerator((CustomChallenge) challenge); + infoMenuGenerator.open(info.getPlayer(), 0); + SoundSample.CLICK.play(info.getPlayer()); + } + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + if (page == 0) { + inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); + inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); + } + } + + @Override + public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { + if (info.getSlot() == VIEW_SLOT) { + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { + Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); + return; + } + open(info.getPlayer(), 1); + SoundSample.PLOP.play(info.getPlayer()); + } else if (info.getSlot() == CREATE_SLOT) { + if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { + return; + } + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { + Message.forName("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); + SoundSample.BASS_OFF.play(info.getPlayer()); + return; + } + new InfoMenuGenerator().open(info.getPlayer(), 0); + SoundSample.PLING.play(info.getPlayer()); + } + } + + @Override + public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); + inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); + inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getSize() { + return SIZE; + } + + @Override + public int[] getNavigationSlots(int page) { + return page == 0 ? new int[]{NAVIGATION_SLOTS[0]} : NAVIGATION_SLOTS; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index ed35c3120..ff40c7b97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; @@ -11,44 +11,40 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MaterialMenuGenerator extends ChooseItemGenerator { - private final IParentCustomGenerator parent; + private final IParentCustomGenerator parent; - public MaterialMenuGenerator(IParentCustomGenerator parent) { - super(createMaterialsMap()); - this.parent = parent; - } + public MaterialMenuGenerator(IParentCustomGenerator parent) { + super(createMaterialsMap()); + this.parent = parent; + } - public static LinkedHashMap createMaterialsMap() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap createMaterialsMap() { + LinkedHashMap map = new LinkedHashMap<>(); - for (Material material : ExperimentalUtils.getMaterials()) { - if (BukkitReflectionUtils.isAir(material)) continue; - if (!material.isItem()) continue; - map.put(material.name(), new ItemStack(material)); - } + for (Material material : ExperimentalUtils.getMaterials()) { + if (BukkitReflectionUtils.isAir(material)) continue; + if (!material.isItem()) continue; + map.put(material.name(), new ItemStack(material)); + } - return map; - } + return map; + } - @Override - public String[] getSubTitles(int page) { - return new String[]{"Material"}; - } + @Override + public String[] getSubTitles(int page) { + return new String[]{"Material"}; + } - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, SettingType.MATERIAL, MapUtils.createStringArrayMap("material", itemKey)); - } + @Override + public void onItemClick(Player player, String itemKey) { + parent.accept(player, SettingType.MATERIAL, MapUtils.createStringArrayMap("material", itemKey)); + } - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java index 90d9fa22e..e02dd6e66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java @@ -7,36 +7,32 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingChooseMenuGenerator extends ChooseItemGenerator { - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + private final String key; + private final String title; + + public SubSettingChooseMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { + super(map); + this.key = key; + this.title = title; + this.parent = parent; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void onItemClick(Player player, String itemKey) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java index 718804f12..aa84364ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java @@ -7,36 +7,32 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingChooseMultipleMenuGenerator extends ChooseMultipleItemGenerator { - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMultipleMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String[] itemKeys) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKeys)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + private final String key; + private final String title; + + public SubSettingChooseMultipleMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { + super(map); + this.key = key; + this.title = title; + this.parent = parent; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void onItemClick(Player player, String[] itemKeys) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKeys)); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java index 99620a15a..1e7c300c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java @@ -8,40 +8,36 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingValueMenuGenerator extends ValueMenuGenerator { - private final IParentCustomGenerator parent; - private final String title; + private final IParentCustomGenerator parent; + private final String title; - public SubSettingValueMenuGenerator(IParentCustomGenerator parent, Map settings, String title) { - super(settings); - this.title = title; - this.parent = parent; - } + public SubSettingValueMenuGenerator(IParentCustomGenerator parent, Map settings, String title) { + super(settings); + this.title = title; + this.parent = parent; + } - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } - @Override - public void onSaveItemClick(Player player) { + @Override + public void onSaveItemClick(Player player) { - Map map = new HashMap<>(); - for (Entry entry : getSettings().entrySet()) { - map.put(entry.getKey().getKey(), new String[]{entry.getValue()}); - } + Map map = new HashMap<>(); + for (Entry entry : getSettings().entrySet()) { + map.put(entry.getKey().getKey(), new String[]{entry.getValue()}); + } - parent.accept(player, null, map); - } + parent.accept(player, null, map); + } - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index b6ac0ff2d..53b285c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -1,47 +1,43 @@ package net.codingarea.challenges.plugin.management.menu.info; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ToString public class ChallengeMenuClickInfo extends MenuClickInfo { - protected final boolean upperItem; + protected final boolean upperItem; - public ChallengeMenuClickInfo(@Nonnull MenuClickInfo parent, boolean upperItem) { - this(parent.getPlayer(), parent.getInventory(), parent.isShiftClick(), parent.isRightClick(), parent.getSlot(), upperItem); - } + public ChallengeMenuClickInfo(@Nonnull MenuClickInfo parent, boolean upperItem) { + this(parent.getPlayer(), parent.getInventory(), parent.isShiftClick(), parent.isRightClick(), parent.getSlot(), upperItem); + } - public ChallengeMenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot, boolean upperItem) { - super(player, inventory, shiftClick, rightClick, slot); - this.upperItem = upperItem; - } + public ChallengeMenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot, boolean upperItem) { + super(player, inventory, shiftClick, rightClick, slot); + this.upperItem = upperItem; + } - public boolean isUpperItemClick() { - return upperItem; - } + public boolean isUpperItemClick() { + return upperItem; + } - public boolean isLowerItemClick() { - return !upperItem; - } + public boolean isLowerItemClick() { + return !upperItem; + } - @Nonnull - public Player getPlayer() { - return player; - } + @Nonnull + public Player getPlayer() { + return player; + } - @Nonnull - public Inventory getInventory() { - return inventory; - } + @Nonnull + public Inventory getInventory() { + return inventory; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 28142d975..694b9463f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -1,22 +1,18 @@ package net.codingarea.challenges.plugin.management.menu.position; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public abstract class GeneratorMenuPosition implements MenuPosition { - protected final MenuGenerator generator; - protected final int page; + protected final MenuGenerator generator; + protected final int page; - public GeneratorMenuPosition(MenuGenerator generator, int page) { - this.generator = generator; - this.page = page; - } + public GeneratorMenuPosition(MenuGenerator generator, int page) { + this.generator = generator; + this.page = page; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java index 04d86d139..793f86dc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java @@ -1,19 +1,14 @@ package net.codingarea.challenges.plugin.management.scheduler; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ -public abstract class AbstractTaskConfig { +import lombok.Getter; - protected final boolean async; +@Getter +public abstract class AbstractTaskConfig { - public AbstractTaskConfig(boolean async) { - this.async = async; - } + protected final boolean async; - public boolean isAsync() { - return async; - } + public AbstractTaskConfig(boolean async) { + this.async = async; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index 782750a1b..eecf8b281 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -1,40 +1,36 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class AbstractTaskExecutor implements Runnable { - protected final List functions = new ArrayList<>(1); - - @Override - public void run() { - for (ScheduledFunction function : functions) { - try { - function.invoke(); - } catch (InvocationTargetException | IllegalAccessException ex) { - Logger.error("An exception occurred while executing {}", function, ex); - } - } - } - - @Nonnull - public abstract AbstractTaskConfig getConfig(); - - public void register(@Nonnull ScheduledFunction function) { - functions.add(function); - } - - public void unregister(@Nonnull Object holder) { - functions.removeIf(function -> function.getHolder() == holder); - } + protected final List functions = new ArrayList<>(1); + + @Override + public void run() { + for (ScheduledFunction function : functions) { + try { + function.invoke(); + } catch (InvocationTargetException | IllegalAccessException ex) { + Logger.error("An exception occurred while executing {}", function, ex); + } + } + } + + @Nonnull + public abstract AbstractTaskConfig getConfig(); + + public void register(@Nonnull ScheduledFunction function) { + functions.add(function); + } + + public void unregister(@Nonnull Object holder) { + functions.removeIf(function -> function.getHolder() == holder); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java index ce7e033df..7288d4d96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java @@ -9,44 +9,40 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PoliciesContainer { - private final List policies = new ArrayList<>(); - - public PoliciesContainer(@Nonnull ScheduledTask annotation) { - addPolicies( - annotation.challengePolicy(), - annotation.timerPolicy(), - annotation.playerPolicy(), - annotation.worldPolicy(), - annotation.freshnessPolicy() - ); - } - - public PoliciesContainer(@Nonnull TimerTask annotation) { - addPolicies( - annotation.challengePolicy(), - annotation.playerPolicy(), - annotation.worldPolicy(), - annotation.freshnessPolicy() - ); - } - - private void addPolicies(@Nonnull IPolicy... policies) { - this.policies.addAll(Arrays.asList(policies)); - } - - public boolean allPoliciesAreTrue(@Nonnull Object holder) { - for (IPolicy policy : policies) { - if (!policy.isApplicable(holder)) continue; - if (!policy.check(holder)) - return false; - } - return true; - } + private final List policies = new ArrayList<>(); + + public PoliciesContainer(@Nonnull ScheduledTask annotation) { + addPolicies( + annotation.challengePolicy(), + annotation.timerPolicy(), + annotation.playerPolicy(), + annotation.worldPolicy(), + annotation.freshnessPolicy() + ); + } + + public PoliciesContainer(@Nonnull TimerTask annotation) { + addPolicies( + annotation.challengePolicy(), + annotation.playerPolicy(), + annotation.worldPolicy(), + annotation.freshnessPolicy() + ); + } + + private void addPolicies(@Nonnull IPolicy... policies) { + this.policies.addAll(Arrays.asList(policies)); + } + + public boolean allPoliciesAreTrue(@Nonnull Object holder) { + for (IPolicy policy : policies) { + if (!policy.isApplicable(holder)) continue; + if (!policy.check(holder)) + return false; + } + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index 4a2d455e2..9c3c5e88b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; @@ -11,115 +11,111 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ScheduleManager { - private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); - private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); - private boolean started = false; - - public void register(@Nonnull Object... schedulers) { - for (Object scheduler : schedulers) { - register(scheduler); - } - } - - public void register(@Nonnull Object scheduler) { - for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), ScheduledTask.class)) { - if (method.getParameterCount() != 0) { - Logger.warn("Could not register scheduler " + method); - continue; - } - - ScheduledTask annotation = method.getAnnotation(ScheduledTask.class); - ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); - - Logger.debug("Registered scheduled task {}", function); - register(function, new ScheduledTaskConfig(annotation)); - } - for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), TimerTask.class)) { - if (method.getParameterCount() != 0) { - Logger.warn("Could not register scheduler {}", method); - continue; - } - - TimerTask annotation = method.getAnnotation(TimerTask.class); - ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); - - Logger.debug("Registered timer task {}", function); - register(function, new TimerTaskConfig(annotation)); - } - } - - public void unregister(@Nonnull Object object) { - for (ScheduledTaskExecutor scheduler : scheduledTaskExecutorsByConfig.values()) { - scheduler.unregister(object); - } - } - - private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTaskConfig config) { - if (config instanceof ScheduledTaskConfig) { - ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; - if (taskConfig.getRate() < 1) { - Logger.warn("Schedule rate cannot be less than 1; Could not register {}", function); - return; - } - - ScheduledTaskExecutor executor = getOrCreateScheduledTaskExecutor(taskConfig); - executor.register(function); - } - if (config instanceof TimerTaskConfig) { - TimerTaskConfig taskConfig = (TimerTaskConfig) config; - - TimerTaskExecutor executor = getOrCreateTimerTaskExecutor(taskConfig); - executor.register(function); - } - } - - @Nonnull - private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { - ScheduledTaskExecutor executor = scheduledTaskExecutorsByConfig.get(config); - if (executor != null) return executor; - - // Create a new task - executor = new ScheduledTaskExecutor(config); - if (started) executor.start(); - scheduledTaskExecutorsByConfig.put(config, executor); - return executor; - } - - @Nonnull - private TimerTaskExecutor getOrCreateTimerTaskExecutor(@Nonnull TimerTaskConfig config) { - TimerTaskExecutor executor = timerTaskExecutorsByConfig.get(config); - if (executor != null) return executor; - - // Create a new task - executor = new TimerTaskExecutor(config); - timerTaskExecutorsByConfig.put(config, executor); - return executor; - } - - public void fireTimerStatusChange() { - if (!started) return; - for (TimerTaskExecutor executor : timerTaskExecutorsByConfig.values()) { - if (!executor.getConfig().acceptsStatus(ChallengeAPI.getTimerStatus())) continue; - executor.execute(); - } - } - - public void stop() { - started = false; - scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::stop); - scheduledTaskExecutorsByConfig.clear(); - timerTaskExecutorsByConfig.clear(); - } - - public void start() { - started = true; - scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::start); - } + private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); + private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); + private boolean started = false; + + public void register(@Nonnull Object... schedulers) { + for (Object scheduler : schedulers) { + register(scheduler); + } + } + + public void register(@Nonnull Object scheduler) { + for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), ScheduledTask.class)) { + if (method.getParameterCount() != 0) { + Logger.warn("Could not register scheduler " + method); + continue; + } + + ScheduledTask annotation = method.getAnnotation(ScheduledTask.class); + ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); + + Logger.debug("Registered scheduled task {}", function); + register(function, new ScheduledTaskConfig(annotation)); + } + for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), TimerTask.class)) { + if (method.getParameterCount() != 0) { + Logger.warn("Could not register scheduler {}", method); + continue; + } + + TimerTask annotation = method.getAnnotation(TimerTask.class); + ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); + + Logger.debug("Registered timer task {}", function); + register(function, new TimerTaskConfig(annotation)); + } + } + + public void unregister(@Nonnull Object object) { + for (ScheduledTaskExecutor scheduler : scheduledTaskExecutorsByConfig.values()) { + scheduler.unregister(object); + } + } + + private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTaskConfig config) { + if (config instanceof ScheduledTaskConfig) { + ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; + if (taskConfig.getRate() < 1) { + Logger.warn("Schedule rate cannot be less than 1; Could not register {}", function); + return; + } + + ScheduledTaskExecutor executor = getOrCreateScheduledTaskExecutor(taskConfig); + executor.register(function); + } + if (config instanceof TimerTaskConfig) { + TimerTaskConfig taskConfig = (TimerTaskConfig) config; + + TimerTaskExecutor executor = getOrCreateTimerTaskExecutor(taskConfig); + executor.register(function); + } + } + + @Nonnull + private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + ScheduledTaskExecutor executor = scheduledTaskExecutorsByConfig.get(config); + if (executor != null) return executor; + + // Create a new task + executor = new ScheduledTaskExecutor(config); + if (started) executor.start(); + scheduledTaskExecutorsByConfig.put(config, executor); + return executor; + } + + @Nonnull + private TimerTaskExecutor getOrCreateTimerTaskExecutor(@Nonnull TimerTaskConfig config) { + TimerTaskExecutor executor = timerTaskExecutorsByConfig.get(config); + if (executor != null) return executor; + + // Create a new task + executor = new TimerTaskExecutor(config); + timerTaskExecutorsByConfig.put(config, executor); + return executor; + } + + public void fireTimerStatusChange() { + if (!started) return; + for (TimerTaskExecutor executor : timerTaskExecutorsByConfig.values()) { + if (!executor.getConfig().acceptsStatus(ChallengeAPI.getTimerStatus())) continue; + executor.execute(); + } + } + + public void stop() { + started = false; + scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::stop); + scheduledTaskExecutorsByConfig.clear(); + timerTaskExecutorsByConfig.clear(); + } + + public void start() { + started = true; + scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::start); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java index c8d76f259..ac7d2f019 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java @@ -1,49 +1,46 @@ package net.codingarea.challenges.plugin.management.scheduler; +import lombok.EqualsAndHashCode; + +import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import javax.annotation.Nonnull; -import lombok.EqualsAndHashCode; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @EqualsAndHashCode public final class ScheduledFunction { - private final Method method; - private final Object holder; - private final PoliciesContainer policies; - - ScheduledFunction(@Nonnull Object holder, @Nonnull Method method, @Nonnull PoliciesContainer policies) { - this.method = method; - this.holder = holder; - this.policies = policies; - } - - public void invoke() throws InvocationTargetException, IllegalAccessException { - if (shouldInvoke()) - invokeAnyway(); - } - - public void invokeAnyway() throws InvocationTargetException, IllegalAccessException { - method.setAccessible(true); - method.invoke(holder); - } - - private boolean shouldInvoke() { - return policies.allPoliciesAreTrue(holder); - } - - @Nonnull - public Object getHolder() { - return holder; - } - - @Override - public String toString() { - return holder.getClass().getName() + "." + method.getName() + "()"; - } + private final Method method; + private final Object holder; + private final PoliciesContainer policies; + + ScheduledFunction(@Nonnull Object holder, @Nonnull Method method, @Nonnull PoliciesContainer policies) { + this.method = method; + this.holder = holder; + this.policies = policies; + } + + public void invoke() throws InvocationTargetException, IllegalAccessException { + if (shouldInvoke()) + invokeAnyway(); + } + + public void invokeAnyway() throws InvocationTargetException, IllegalAccessException { + method.setAccessible(true); + method.invoke(holder); + } + + private boolean shouldInvoke() { + return policies.allPoliciesAreTrue(holder); + } + + @Nonnull + public Object getHolder() { + return holder; + } + + @Override + public String toString() { + return holder.getClass().getName() + "." + method.getName() + "()"; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java index 1a2b8d454..e2bccf522 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java @@ -1,28 +1,25 @@ package net.codingarea.challenges.plugin.management.scheduler; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import lombok.EqualsAndHashCode; import lombok.Getter; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + @Getter @EqualsAndHashCode(callSuper = false) public final class ScheduledTaskConfig extends AbstractTaskConfig { - private final int rate; + private final int rate; - ScheduledTaskConfig(@Nonnull ScheduledTask annotation) { - this(annotation.ticks(), annotation.async()); - } + ScheduledTaskConfig(@Nonnull ScheduledTask annotation) { + this(annotation.ticks(), annotation.async()); + } - ScheduledTaskConfig(@Nonnegative int rate, boolean async) { - super(async); - this.rate = rate; - } + ScheduledTaskConfig(@Nonnegative int rate, boolean async) { + super(async); + this.rate = rate; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java index 296aca5e6..763b1e8b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java @@ -7,38 +7,33 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @see ScheduleManager - * @since 2.0 - */ final class ScheduledTaskExecutor extends AbstractTaskExecutor { - private final ScheduledTaskConfig config; - private BukkitTask task; - - ScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { - this.config = config; - } - - public void stop() { - if (task != null && !task.isCancelled()) { - task.cancel(); - task = null; - } - } - - public void start() { - BukkitScheduler scheduler = Bukkit.getScheduler(); - Challenges plugin = Challenges.getInstance(); - task = config.isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, config.getRate()) : - scheduler.runTaskTimer(plugin, this, 0, config.getRate()); - } - - @Nonnull - @Override - public ScheduledTaskConfig getConfig() { - return config; - } + private final ScheduledTaskConfig config; + private BukkitTask task; + + ScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + this.config = config; + } + + public void stop() { + if (task != null && !task.isCancelled()) { + task.cancel(); + task = null; + } + } + + public void start() { + BukkitScheduler scheduler = Bukkit.getScheduler(); + Challenges plugin = Challenges.getInstance(); + task = config.isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, config.getRate()) : + scheduler.runTaskTimer(plugin, this, 0, config.getRate()); + } + + @Nonnull + @Override + public ScheduledTaskConfig getConfig() { + return config; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java index c6b7a2af8..dd70940d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java @@ -6,30 +6,26 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class TimerTaskConfig extends AbstractTaskConfig { - private final TimerStatus[] status; + private final TimerStatus[] status; - TimerTaskConfig(@Nonnull TimerTask annotation) { - this(annotation.status(), annotation.async()); - } + TimerTaskConfig(@Nonnull TimerTask annotation) { + this(annotation.status(), annotation.async()); + } - TimerTaskConfig(@Nonnull TimerStatus[] status, boolean async) { - super(async); - this.status = status; - } + TimerTaskConfig(@Nonnull TimerStatus[] status, boolean async) { + super(async); + this.status = status; + } - @Nonnull - public TimerStatus[] getStatus() { - return status; - } + @Nonnull + public TimerStatus[] getStatus() { + return status; + } - public boolean acceptsStatus(@Nonnull TimerStatus status) { - return Arrays.asList(this.status).contains(status); - } + public boolean acceptsStatus(@Nonnull TimerStatus status) { + return Arrays.asList(this.status).contains(status); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java index c3e1ffde1..526198307 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java @@ -5,30 +5,26 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ final class TimerTaskExecutor extends AbstractTaskExecutor { - private final TimerTaskConfig config; - - TimerTaskExecutor(@Nonnull TimerTaskConfig config) { - this.config = config; - } - - public void execute() { - if (config.isAsync()) - Bukkit.getScheduler().runTaskAsynchronously(Challenges.getInstance(), this); - else if (!Bukkit.isPrimaryThread()) - Bukkit.getScheduler().runTask(Challenges.getInstance(), this); - else this.run(); - } - - @Nonnull - @Override - public TimerTaskConfig getConfig() { - return config; - } + private final TimerTaskConfig config; + + TimerTaskExecutor(@Nonnull TimerTaskConfig config) { + this.config = config; + } + + public void execute() { + if (config.isAsync()) + Bukkit.getScheduler().runTaskAsynchronously(Challenges.getInstance(), this); + else if (!Bukkit.isPrimaryThread()) + Bukkit.getScheduler().runTask(Challenges.getInstance(), this); + else this.run(); + } + + @Nonnull + @Override + public TimerTaskConfig getConfig() { + return config; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java index 44a127d36..6ea65ffc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java @@ -5,30 +5,26 @@ import javax.annotation.Nonnull; import java.util.function.Predicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum ChallengeStatusPolicy implements IPolicy { - ALWAYS(challenge -> true), - DISABLED(challenge -> !challenge.isEnabled()), - ENABLED(IChallenge::isEnabled); + ALWAYS(challenge -> true), + DISABLED(challenge -> !challenge.isEnabled()), + ENABLED(IChallenge::isEnabled); - private final Predicate check; + private final Predicate check; - ChallengeStatusPolicy(@Nonnull Predicate check) { - this.check = check; - } + ChallengeStatusPolicy(@Nonnull Predicate check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.test((IChallenge) holder); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.test((IChallenge) holder); + } - @Override - public boolean isApplicable(@Nonnull Object holder) { - return holder instanceof IChallenge; - } + @Override + public boolean isApplicable(@Nonnull Object holder) { + return holder instanceof IChallenge; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java index 164850658..50de73c31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java @@ -5,25 +5,21 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum ExtraWorldPolicy implements IPolicy { - ALWAYS(() -> true), - USED(ChallengeAPI::isWorldInUse), - NOT_USED(() -> !ChallengeAPI.isWorldInUse()); + ALWAYS(() -> true), + USED(ChallengeAPI::isWorldInUse), + NOT_USED(() -> !ChallengeAPI.isWorldInUse()); - private final BooleanSupplier check; + private final BooleanSupplier check; - ExtraWorldPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + ExtraWorldPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java index da57d60d3..af87bdbd8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java @@ -5,25 +5,21 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum FreshnessPolicy implements IPolicy { - ALWAYS(() -> true), - FRESH(ChallengeAPI::isFresh), - NOT_FRESH(() -> !ChallengeAPI.isFresh()); + ALWAYS(() -> true), + FRESH(ChallengeAPI::isFresh), + NOT_FRESH(() -> !ChallengeAPI.isFresh()); - private final BooleanSupplier check; + private final BooleanSupplier check; - FreshnessPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + FreshnessPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java index 6c39a8916..a2bed96cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java @@ -2,16 +2,12 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface IPolicy { - boolean check(@Nonnull Object holder); + boolean check(@Nonnull Object holder); - default boolean isApplicable(@Nonnull Object holder) { - return true; - } + default boolean isApplicable(@Nonnull Object holder) { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java index bcb29fd05..13b516467 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java @@ -5,26 +5,22 @@ import javax.annotation.Nonnull; import java.util.function.BiPredicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum PlayerCountPolicy implements IPolicy { - ALWAYS((online, max) -> true), - EMPTY((online, max) -> online == 0), - SOMEONE((online, max) -> online > 0), - FULL(Integer::equals); + ALWAYS((online, max) -> true), + EMPTY((online, max) -> online == 0), + SOMEONE((online, max) -> online > 0), + FULL(Integer::equals); - private final BiPredicate check; + private final BiPredicate check; - PlayerCountPolicy(@Nonnull BiPredicate check) { - this.check = check; - } + PlayerCountPolicy(@Nonnull BiPredicate check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.test(Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers()); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.test(Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java index b4b578e91..34cf541be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java @@ -5,25 +5,21 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum TimerPolicy implements IPolicy { - ALWAYS(() -> true), - PAUSED(ChallengeAPI::isPaused), - STARTED(ChallengeAPI::isStarted); + ALWAYS(() -> true), + PAUSED(ChallengeAPI::isPaused), + STARTED(ChallengeAPI::isStarted); - private final BooleanSupplier check; + private final BooleanSupplier check; - TimerPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + TimerPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java index eb72dc55e..9b0a6c3b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java @@ -9,32 +9,28 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ScheduledTask { - @Nonnegative - int ticks(); + @Nonnegative + int ticks(); - boolean async() default true; + boolean async() default true; - @Nonnull - TimerPolicy timerPolicy() default TimerPolicy.STARTED; + @Nonnull + TimerPolicy timerPolicy() default TimerPolicy.STARTED; - @Nonnull - ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; + @Nonnull + ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull - PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; + @Nonnull + PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull - ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; + @Nonnull + ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull - FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; + @Nonnull + FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java index bc63d36f3..68250f891 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java @@ -12,29 +12,25 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TimerTask { - @Nonnull - TimerStatus[] status(); + @Nonnull + TimerStatus[] status(); - boolean async() default true; + boolean async() default true; - @Nonnull - ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; + @Nonnull + ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull - PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; + @Nonnull + PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull - ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; + @Nonnull + ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull - FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; + @Nonnull + FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index fdfeb3470..44d2789c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -17,7 +17,6 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.misc.FontUtils; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; @@ -25,214 +24,209 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ChallengeTimer { - @Getter - private final TimerFormat format; - private final String stoppedMessage, upMessage, downMessage; - private final boolean specificStartSounds, defaultStartSound; - @Getter + @Getter + private final TimerFormat format; + private final Message stoppedMessage, upMessage, downMessage; + private final boolean specificStartSounds, defaultStartSound; + @Getter private long time = 0; - @Getter + @Getter private boolean countingUp = true; - @Getter + @Getter private boolean paused = true; - private boolean hidden = false; - private boolean sentEmpty; - - public ChallengeTimer() { - - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); - defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); - - // Load format + messages - Document timerConfig = pluginConfig.getDocument("timer"); - stoppedMessage = timerConfig.getString("stopped-message", ""); - upMessage = timerConfig.getString("count-up-message", ""); - downMessage = timerConfig.getString("count-down-message", ""); - - Document formatConfig = timerConfig.getDocument("format"); - format = new TimerFormat(formatConfig); - - Challenges.getInstance().getScheduler().register(this); - } - - public void enable() { - updateTimeRule(); - } - - private void updateTimeRule() { - for (World world : ChallengeAPI.getGameWorlds()) { - world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); - } - } - - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onTimerSecond() { - - if (!paused) { - if (countingUp) time++; - else time--; - - if (time <= 0) { - time = 0; - countingUp = true; - handleHitZero(); - } - } - - updateActionbar(); - - } - - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) - public void playPausedParticles() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (AbstractChallenge.ignorePlayer(player)) continue; - Location location = player.getLocation(); - if (location.getWorld() == null) continue; - location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 1); - } - } - - private void handleHitZero() { - ChallengeAPI.endChallenge(ChallengeEndCause.TIMER_HIT_ZERO); - } - - public void resume() { - if (!paused) return; - paused = false; - - updateActionbar(); - updateTimeRule(); - - Message.forName("timer-was-started").broadcast(Prefix.TIMER); - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-started")); - Challenges.getInstance().getServerManager().setNotFresh(); - - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() != GameMode.CREATIVE) - player.setGameMode(GameMode.SURVIVAL); - } - - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (currentGoal != null && specificStartSounds) { - currentGoal.getStartSound().broadcast(); - } else if (defaultStartSound) { - SoundSample.DRAGON_BREATH.broadcast(); - } - - } - - public void pause(boolean playInGameEffects) { - if (paused) return; - paused = true; - - updateActionbar(); - updateTimeRule(); - - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - if (playInGameEffects) { - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-paused")); - Message.forName("timer-was-paused").broadcast(Prefix.TIMER); - SoundSample.BASS_OFF.broadcast(); - } - } - - public void reset() { - if (!countingUp) pause(true); - time = 0; - countingUp = true; - updateActionbar(); - } - - public void updateActionbar() { - if (sentEmpty && hidden) return; - if (hidden) sentEmpty = true; - if (!hidden) { - for (Player player : Bukkit.getOnlinePlayers()) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(getActionbar())); - } - } - - } - - @Nonnull - private String getActionbar() { - String message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; - String time = getFormattedTime(); - message = message.replace("{time}", time); - return isSmallCaps() ? FontUtils.toSmallCaps(message) : message; - } - - private boolean isSmallCaps() { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader == null) return false; - return languageLoader.isSmallCapsFont(); - } - - public synchronized void loadSession() { - FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); - time = config.getInt("timer.seconds"); - countingUp = config.getBoolean("timer.countingUp", true); - hidden = config.getBoolean("timer.hidden", false); - } - - public synchronized void saveSession(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); - config.set("timer.seconds", time); - config.set("timer.countingUp", countingUp); - config.set("timer.hidden", hidden); - config.save(async); - } - - public void addSeconds(int amount) { - time += amount; - if (time < 0) - time = 0; - updateActionbar(); - } - - public void setSeconds(long seconds) { - this.time = seconds; - updateActionbar(); - } - - public void setHidden(boolean hide) { - this.sentEmpty = false; - this.hidden = hide; - updateActionbar(); - } - - @Nonnull - public String getFormattedTime() { - return format.format(time); - } + private boolean hidden = false; + private boolean sentEmpty; + + public ChallengeTimer() { + + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); + defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); + + // Load format + messages + Document timerConfig = pluginConfig.getDocument("timer"); + stoppedMessage = Message.forName("stopped-message"); + upMessage = Message.forName("count-up-message"); + downMessage = Message.forName("count-down-message"); + + Document formatConfig = timerConfig.getDocument("format"); + format = new TimerFormat(formatConfig); + + Challenges.getInstance().getScheduler().register(this); + } + + public void enable() { + updateTimeRule(); + } + + private void updateTimeRule() { + for (World world : ChallengeAPI.getGameWorlds()) { + world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); + } + } + + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onTimerSecond() { + + if (!paused) { + if (countingUp) time++; + else time--; + + if (time <= 0) { + time = 0; + countingUp = true; + handleHitZero(); + } + } + + updateActionbar(); + + } + + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) + public void playPausedParticles() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (AbstractChallenge.ignorePlayer(player)) continue; + Location location = player.getLocation(); + if (location.getWorld() == null) continue; + location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 1); + } + } + + private void handleHitZero() { + ChallengeAPI.endChallenge(ChallengeEndCause.TIMER_HIT_ZERO); + } + + public void resume() { + if (!paused) return; + paused = false; + + updateActionbar(); + updateTimeRule(); + + Message.forName("timer-was-started").broadcast(Prefix.TIMER); + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-started")); + Challenges.getInstance().getServerManager().setNotFresh(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() != GameMode.CREATIVE) + player.setGameMode(GameMode.SURVIVAL); + } + + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + if (currentGoal != null && specificStartSounds) { + currentGoal.getStartSound().broadcast(); + } else if (defaultStartSound) { + SoundSample.DRAGON_BREATH.broadcast(); + } + + } + + public void pause(boolean playInGameEffects) { + if (paused) return; + paused = true; + + updateActionbar(); + updateTimeRule(); + + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + if (playInGameEffects) { + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-paused")); + Message.forName("timer-was-paused").broadcast(Prefix.TIMER); + SoundSample.BASS_OFF.broadcast(); + } + } + + public void reset() { + if (!countingUp) pause(true); + time = 0; + countingUp = true; + updateActionbar(); + } + + public void updateActionbar() { + if (sentEmpty && hidden) return; + if (hidden) sentEmpty = true; + if (!hidden) { + for (Player player : Bukkit.getOnlinePlayers()) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(getActionbar())); + } + } + + } @Nonnull - public TimerStatus getStatus() { - return paused ? TimerStatus.PAUSED : TimerStatus.RUNNING; - } + private String getActionbar() { + Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; + String time = getFormattedTime(); + return message.asString(time); + } + + private boolean isSmallCaps() { + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + if (languageLoader == null) return false; + return languageLoader.isSmallCapsFont(); + } + + public synchronized void loadSession() { + FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); + time = config.getInt("timer.seconds"); + countingUp = config.getBoolean("timer.countingUp", true); + hidden = config.getBoolean("timer.hidden", false); + } + + public synchronized void saveSession(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); + config.set("timer.seconds", time); + config.set("timer.countingUp", countingUp); + config.set("timer.hidden", hidden); + config.save(async); + } + + public void addSeconds(int amount) { + time += amount; + if (time < 0) + time = 0; + updateActionbar(); + } + + public void setSeconds(long seconds) { + this.time = seconds; + updateActionbar(); + } + + public void setHidden(boolean hide) { + this.sentEmpty = false; + this.hidden = hide; + updateActionbar(); + } + + @Nonnull + public String getFormattedTime() { + return format.format(time); + } + + @Nonnull + public TimerStatus getStatus() { + return paused ? TimerStatus.PAUSED : TimerStatus.RUNNING; + } public boolean isStarted() { - return !paused; - } + return !paused; + } public void setCountingUp(boolean countingUp) { - if (this.countingUp == countingUp) return; - - this.countingUp = countingUp; - updateActionbar(); - TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); - menuGenerator.updateFirstPage(); - Message.forName("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); - SoundSample.BASS_ON.broadcast(); - } + if (this.countingUp == countingUp) return; + + this.countingUp = countingUp; + updateActionbar(); + TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); + menuGenerator.updateFirstPage(); + Message.forName("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); + SoundSample.BASS_ON.broadcast(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index f2e53215b..f96662dbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -1,75 +1,71 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class TimerFormat { - private final String seconds, minutes, hours, day, days; + private final String seconds, minutes, hours, day, days; - public TimerFormat(@Nonnull Document document) { - seconds = document.getString("seconds", ""); - minutes = document.getString("minutes", ""); - hours = document.getString("hours", ""); - day = document.getString("day", ""); - days = document.getString("days", ""); - } + public TimerFormat(@Nonnull Document document) { + seconds = document.getString("seconds", ""); + minutes = document.getString("minutes", ""); + hours = document.getString("hours", ""); + day = document.getString("day", ""); + days = document.getString("days", ""); + } - public TimerFormat() { - seconds = "{mm}:{ss}"; - minutes = "{mm}:{ss}"; - hours = "{hh}:{mm}:{ss}"; - day = "{d}:{hh}:{mm}:{ss}"; - days = "{d}:{hh}:{mm}:{ss}"; - } + public TimerFormat() { + seconds = "{mm}:{ss}"; + minutes = "{mm}:{ss}"; + hours = "{hh}:{mm}:{ss}"; + day = "{d}:{hh}:{mm}:{ss}"; + days = "{d}:{hh}:{mm}:{ss}"; + } - @Nonnull - public String format(@Nonnegative long time) { + @Nonnull + public String format(@Nonnegative long time) { - long seconds = time; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; + long seconds = time; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; - seconds %= 60; - minutes %= 60; - hours %= 24; + seconds %= 60; + minutes %= 60; + hours %= 24; - return getFormat(minutes, hours, days) - .replace("{d}", String.valueOf(days)) - .replace("{dd}", digit2(days)) - .replace("{h}", String.valueOf(hours)) - .replace("{hh}", digit2(hours)) - .replace("{m}", String.valueOf(minutes)) - .replace("{mm}", digit2(minutes)) - .replace("{s}", String.valueOf(seconds)) - .replace("{ss}", digit2(seconds)); - } + return getFormat(minutes, hours, days) + .replace("{d}", String.valueOf(days)) + .replace("{dd}", digit2(days)) + .replace("{h}", String.valueOf(hours)) + .replace("{hh}", digit2(hours)) + .replace("{m}", String.valueOf(minutes)) + .replace("{mm}", digit2(minutes)) + .replace("{s}", String.valueOf(seconds)) + .replace("{ss}", digit2(seconds)); + } - private String getFormat(long minutes, long hours, long days) { - String format; - if (days > 1) { - format = this.days; - } else if (days == 1) { - format = this.day; - } else if (hours >= 1) { - format = this.hours; - } else if (minutes >= 1) { - format = this.minutes; - } else { - format = this.seconds; - } - return format; - } + private String getFormat(long minutes, long hours, long days) { + String format; + if (days > 1) { + format = this.days; + } else if (days == 1) { + format = this.day; + } else if (hours >= 1) { + format = this.hours; + } else if (minutes >= 1) { + format = this.minutes; + } else { + format = this.seconds; + } + return format; + } - private String digit2(@Nonnegative long number) { - return number > 9 ? String.valueOf(number) : "0" + number; - } + private String digit2(@Nonnegative long number) { + return number > 9 ? String.valueOf(number) : "0" + number; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java index 25a62ddc7..242900031 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java @@ -1,12 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum TimerStatus { - RUNNING, - PAUSED + RUNNING, + PAUSED } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index 1202f3693..114d0bff3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -1,35 +1,32 @@ package net.codingarea.challenges.plugin.management.server; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + @Getter public enum ChallengeEndCause { - TIMER_HIT_ZERO(Message.forName("challenge-end-timer-hit-zero"), Message.forName("challenge-end-timer-hit-zero-winner")), - GOAL_REACHED(Message.forName("challenge-end-goal-reached"), Message.forName("challenge-end-goal-reached-winner")), - GOAL_FAILED(Message.forName("challenge-end-goal-failed"), null); + TIMER_HIT_ZERO(Message.forName("challenge-end-timer-hit-zero"), Message.forName("challenge-end-timer-hit-zero-winner")), + GOAL_REACHED(Message.forName("challenge-end-goal-reached"), Message.forName("challenge-end-goal-reached-winner")), + GOAL_FAILED(Message.forName("challenge-end-goal-failed"), null); - private final Message noWinnerMessage, winnerMessage; + private final Message noWinnerMessage, winnerMessage; - ChallengeEndCause(@Nonnull Message noWinnerMessage, @Nullable Message winnerMessage) { - this.noWinnerMessage = noWinnerMessage; - this.winnerMessage = winnerMessage; - } + ChallengeEndCause(@Nonnull Message noWinnerMessage, @Nullable Message winnerMessage) { + this.noWinnerMessage = noWinnerMessage; + this.winnerMessage = winnerMessage; + } - @Nonnull - public Message getMessage(boolean withWinner) { - return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; - } + @Nonnull + public Message getMessage(boolean withWinner) { + return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; + } - public boolean isWinnable() { - return winnerMessage != null; - } + public boolean isWinnable() { + return winnerMessage != null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index 398035789..fa4c045dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.spigot.generator.VoidMapGenerator; @@ -17,103 +17,99 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GameWorldStorage implements GamestateSaveable { - private final List worlds = new LinkedList<>(); - private World overworld; - private World nether; - private World end; - private World voidWorld; - - public void enable() { - Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); - - for (int i = 0; i < 3 && i < Bukkit.getWorlds().size(); i++) { - World world = Bukkit.getWorlds().get(i); - switch (i) { - case 0: { - overworld = world; - worlds.add(world); - } - break; - case 1: { - if (world.getEnvironment() == Environment.NETHER) { - nether = world; - worlds.add(world); - } else if (world.getEnvironment() == Environment.THE_END) { - end = world; - worlds.add(world); - } - } - break; - case 2: { - if (world.getEnvironment() == Environment.THE_END) { - end = world; - worlds.add(world); - } - } - break; - } - } - - } - - @Override - public String getUniqueGamestateName() { - return getClass().getSimpleName().toLowerCase(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("void-generated", voidWorld != null); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (document.getBoolean("void-generated")) { - getOrCreateVoidWorld(); - } - } - - @Nonnull - public World getOrCreateVoidWorld() { - if (voidWorld != null) { - return voidWorld; - } - - VoidMapGenerator generator = new VoidMapGenerator(); - voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator( - generator).createWorld(); - worlds.add(voidWorld); - - return voidWorld; - } - - public World getWorld(@Nullable Environment environment) { - if (environment == null) return null; - switch (environment) { - case NORMAL: - return overworld; - case NETHER: - return nether; - case THE_END: - return end; - case CUSTOM: - return Challenges.getInstance().getWorldManager().getExtraWorld(); - } - return null; - } - - public List getCustomGeneratedGameWorlds() { - return Collections.singletonList("void"); - } - - public List getGameWorlds() { - return Collections.unmodifiableList(worlds); - } + private final List worlds = new LinkedList<>(); + private World overworld; + private World nether; + private World end; + private World voidWorld; + + public void enable() { + Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); + + for (int i = 0; i < 3 && i < Bukkit.getWorlds().size(); i++) { + World world = Bukkit.getWorlds().get(i); + switch (i) { + case 0: { + overworld = world; + worlds.add(world); + } + break; + case 1: { + if (world.getEnvironment() == Environment.NETHER) { + nether = world; + worlds.add(world); + } else if (world.getEnvironment() == Environment.THE_END) { + end = world; + worlds.add(world); + } + } + break; + case 2: { + if (world.getEnvironment() == Environment.THE_END) { + end = world; + worlds.add(world); + } + } + break; + } + } + + } + + @Override + public String getUniqueGamestateName() { + return getClass().getSimpleName().toLowerCase(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("void-generated", voidWorld != null); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (document.getBoolean("void-generated")) { + getOrCreateVoidWorld(); + } + } + + @Nonnull + public World getOrCreateVoidWorld() { + if (voidWorld != null) { + return voidWorld; + } + + VoidMapGenerator generator = new VoidMapGenerator(); + voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator( + generator).createWorld(); + worlds.add(voidWorld); + + return voidWorld; + } + + public World getWorld(@Nullable Environment environment) { + if (environment == null) return null; + switch (environment) { + case NORMAL: + return overworld; + case NETHER: + return nether; + case THE_END: + return end; + case CUSTOM: + return Challenges.getInstance().getWorldManager().getExtraWorld(); + } + return null; + } + + public List getCustomGeneratedGameWorlds() { + return Collections.singletonList("void"); + } + + public List getGameWorlds() { + return Collections.unmodifiableList(worlds); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 08320b295..6d192f443 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import org.bukkit.Location; @@ -16,58 +16,55 @@ /** * Manages the portal locations of custom worlds - * - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 */ public class GeneratorWorldPortalManager implements GamestateSaveable { - public Map lastWorldLocations; + public Map lastWorldLocations; - public GeneratorWorldPortalManager() { - lastWorldLocations = new HashMap<>(); - Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); - } + public GeneratorWorldPortalManager() { + lastWorldLocations = new HashMap<>(); + Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); + } - @Nullable - public Location getAndRemoveLastWorld(@Nonnull Player player) { - return lastWorldLocations.remove(player.getUniqueId()); - } + @Nullable + public Location getAndRemoveLastWorld(@Nonnull Player player) { + return lastWorldLocations.remove(player.getUniqueId()); + } - public void setLastLocation(@Nonnull Player player, @Nonnull Location location) { - lastWorldLocations.put(player.getUniqueId(), location); - } + public void setLastLocation(@Nonnull Player player, @Nonnull Location location) { + lastWorldLocations.put(player.getUniqueId(), location); + } - public boolean isCustomWorld(@Nonnull String name) { - return Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds().contains(name); - } + public boolean isCustomWorld(@Nonnull String name) { + return Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds().contains(name); + } - @Override - public String getUniqueGamestateName() { - return getClass().getSimpleName().toLowerCase(); - } + @Override + public String getUniqueGamestateName() { + return getClass().getSimpleName().toLowerCase(); + } - @Override - public void writeGameState(@NotNull Document document) { - for (Entry entry : lastWorldLocations.entrySet()) { - UUID uuid = entry.getKey(); - Location location = entry.getValue(); - document.set(uuid.toString(), location); - } - } + @Override + public void writeGameState(@NotNull Document document) { + for (Entry entry : lastWorldLocations.entrySet()) { + UUID uuid = entry.getKey(); + Location location = entry.getValue(); + document.set(uuid.toString(), location); + } + } - @Override - public void loadGameState(@NotNull Document document) { - for (String key : document.keys()) { - try { - Location location = document.getInstance(key, Location.class); - UUID uuid = UUID.fromString(key); - lastWorldLocations.put(uuid, location); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Couldn't load last location of: " + key); - Challenges.getInstance().getLogger().error("", exception); - } - } - } + @Override + public void loadGameState(@NotNull Document document) { + for (String key : document.keys()) { + try { + Location location = document.getInstance(key, Location.class); + UUID uuid = UUID.fromString(key); + lastWorldLocations.put(uuid, location); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Couldn't load last location of: " + key); + Challenges.getInstance().getILogger().error("", exception); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java index 593438834..f054d28aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java @@ -15,88 +15,84 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ScoreboardManager { - private final List bossbars = new ArrayList<>(); - private ChallengeScoreboard currentScoreboard; - - public ScoreboardManager() { - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); - ChallengeAPI.registerScheduler(this); - } - - public void handleQuit(@Nonnull Player player) { - for (ChallengeBossBar bossbar : bossbars) { - bossbar.applyHide(player); - } - if (currentScoreboard != null) { - currentScoreboard.applyHide(player); - Bukkit.getScheduler().runTaskLaterAsynchronously(Challenges.getInstance(), () -> currentScoreboard.update(), 1); - } - } - - public void handleJoin(@Nonnull Player player) { - updateAll(); - } - - @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED}) - public void updateAll() { - for (ChallengeBossBar bossbar : bossbars) { - bossbar.update(); - } - if (currentScoreboard != null) { - currentScoreboard.update(); - } - } - - public void showBossBar(@Nonnull ChallengeBossBar bossbar) { - if (bossbars.contains(bossbar)) return; - bossbars.add(bossbar); - bossbar.update(); - } - - public void hideBossBar(@Nonnull ChallengeBossBar bossbar) { - if (!bossbars.remove(bossbar)) return; - Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); - } - - @Nullable - public ChallengeScoreboard getCurrentScoreboard() { - return currentScoreboard; - } - - public void setCurrentScoreboard(@Nullable ChallengeScoreboard scoreboard) { - if (currentScoreboard == scoreboard) return; - - // Remove old scoreboard - if (currentScoreboard != null) { - Bukkit.getOnlinePlayers().forEach(currentScoreboard::applyHide); - } - - currentScoreboard = scoreboard; - - // Add new scoreboard if available - if (scoreboard == null) return; - scoreboard.update(); - } - - public void disable() { - for (ChallengeBossBar bossbar : bossbars.toArray(new ChallengeBossBar[0])) { - hideBossBar(bossbar); - } - setCurrentScoreboard(null); - } - - public boolean isShown(@Nonnull ChallengeBossBar bossbar) { - return bossbars.contains(bossbar); - } - - public boolean isShown(@Nonnull ChallengeScoreboard scoreboard) { - return currentScoreboard == scoreboard; - } + private final List bossbars = new ArrayList<>(); + private ChallengeScoreboard currentScoreboard; + + public ScoreboardManager() { + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); + ChallengeAPI.registerScheduler(this); + } + + public void handleQuit(@Nonnull Player player) { + for (ChallengeBossBar bossbar : bossbars) { + bossbar.applyHide(player); + } + if (currentScoreboard != null) { + currentScoreboard.applyHide(player); + Bukkit.getScheduler().runTaskLaterAsynchronously(Challenges.getInstance(), () -> currentScoreboard.update(), 1); + } + } + + public void handleJoin(@Nonnull Player player) { + updateAll(); + } + + @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED}) + public void updateAll() { + for (ChallengeBossBar bossbar : bossbars) { + bossbar.update(); + } + if (currentScoreboard != null) { + currentScoreboard.update(); + } + } + + public void showBossBar(@Nonnull ChallengeBossBar bossbar) { + if (bossbars.contains(bossbar)) return; + bossbars.add(bossbar); + bossbar.update(); + } + + public void hideBossBar(@Nonnull ChallengeBossBar bossbar) { + if (!bossbars.remove(bossbar)) return; + Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); + } + + @Nullable + public ChallengeScoreboard getCurrentScoreboard() { + return currentScoreboard; + } + + public void setCurrentScoreboard(@Nullable ChallengeScoreboard scoreboard) { + if (currentScoreboard == scoreboard) return; + + // Remove old scoreboard + if (currentScoreboard != null) { + Bukkit.getOnlinePlayers().forEach(currentScoreboard::applyHide); + } + + currentScoreboard = scoreboard; + + // Add new scoreboard if available + if (scoreboard == null) return; + scoreboard.update(); + } + + public void disable() { + for (ChallengeBossBar bossbar : bossbars.toArray(new ChallengeBossBar[0])) { + hideBossBar(bossbar); + } + setCurrentScoreboard(null); + } + + public boolean isShown(@Nonnull ChallengeBossBar bossbar) { + return bossbars.contains(bossbar); + } + + public boolean isShown(@Nonnull ChallengeScoreboard scoreboard) { + return currentScoreboard == scoreboard; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 8fff31d40..a94da3f0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -23,110 +23,106 @@ import java.util.List; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ServerManager { - private final boolean setSpectatorOnWin; - private final boolean dropItemsOnEnd; - private final boolean winSounds; - - private boolean isFresh; // This indicated if the timer was never started before - private boolean hasCheated = false; - - public ServerManager() { - Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - hasCheated = sessionConfig.getBoolean("cheated"); - isFresh = sessionConfig.getBoolean("fresh", true); - - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - setSpectatorOnWin = pluginConfig.getBoolean("set-spectator-on-win"); - dropItemsOnEnd = pluginConfig.getBoolean("drop-items-on-end"); - winSounds = pluginConfig.getBoolean("enabled-win-sounds"); - } - - public void setNotFresh() { - isFresh = false; - Challenges.getInstance().getConfigManager().getSessionConfig().set("fresh", false); - } - - public void setHasCheated() { - hasCheated = true; - Challenges.getInstance().getConfigManager().getSessionConfig().set("cheated", true); - } - - public boolean isFresh() { - return isFresh; - } - - public boolean hasCheated() { - return hasCheated; - } - - public void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { - if (ChallengeAPI.isPaused()) { - Logger.warn("Tried to end challenge while timer was paused"); - return; - } - - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - List winners = new LinkedList<>(); - if (winnerGetter != null) { - winners = winnerGetter.get(); - } else if (currentGoal != null && endCause.isWinnable()) { - currentGoal.getWinnersOnEnd(winners); - } - - if (endCause != ChallengeEndCause.GOAL_REACHED || setSpectatorOnWin) { - setSpectator(); - } - if (endCause == ChallengeEndCause.GOAL_REACHED && winSounds && currentGoal != null && currentGoal.getWinSound() != null) { - currentGoal.getWinSound().broadcast(); - } - if (dropItemsOnEnd) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (winners.isEmpty() || winners.contains(player)) continue; - dropItems(player); - } - } - - Challenges.getInstance().getChallengeTimer().pause(false); - - String winnerString = StringUtils.getIterableAsString(winners, "§7, ", player -> "§e§l" + NameHelper.getName(player)); - String time = Challenges.getInstance().getChallengeTimer().getFormattedTime(); - String seed = Bukkit.getWorlds().isEmpty() ? "?" : - String.valueOf(ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); - endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, time, winnerString, seed); - - } - - private void setSpectator() { - for (Player player : Bukkit.getOnlinePlayers()) { - player.setGameMode(GameMode.SPECTATOR); - SoundSample.BLAST.play(player); - - try { - player.getWorld().spawnEntity(player.getLocation(), MinecraftNameWrapper.FIREWORK); - } catch (IllegalArgumentException ex) { - // We cant spawn fireworks like that in some versions of spigot - } - } - } - - private void dropItems(@Nonnull Player player) { - dropItems(player.getLocation(), player.getInventory().getContents()); - player.getInventory().clear(); - } - - private void dropItems(@Nonnull Location location, @Nonnull ItemStack[] items) { - for (ItemStack item : items) { - if (item == null) continue; - if (BukkitReflectionUtils.isAir(item.getType())) continue; - if (location.getWorld() == null) return; - location.getWorld().dropItem(location, item); - } - } + private final boolean setSpectatorOnWin; + private final boolean dropItemsOnEnd; + private final boolean winSounds; + + private boolean isFresh; // This indicated if the timer was never started before + private boolean hasCheated; + + public ServerManager() { + Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + hasCheated = sessionConfig.getBoolean("cheated"); + isFresh = sessionConfig.getBoolean("fresh", true); + + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + setSpectatorOnWin = pluginConfig.getBoolean("set-spectator-on-win"); + dropItemsOnEnd = pluginConfig.getBoolean("drop-items-on-end"); + winSounds = pluginConfig.getBoolean("enabled-win-sounds"); + } + + public void setNotFresh() { + isFresh = false; + Challenges.getInstance().getConfigManager().getSessionConfig().set("fresh", false); + } + + public void setHasCheated() { + hasCheated = true; + Challenges.getInstance().getConfigManager().getSessionConfig().set("cheated", true); + } + + public boolean isFresh() { + return isFresh; + } + + public boolean hasCheated() { + return hasCheated; + } + + public void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + if (ChallengeAPI.isPaused()) { + Logger.warn("Tried to end challenge while timer was paused"); + return; + } + + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + List winners = new LinkedList<>(); + if (winnerGetter != null) { + winners = winnerGetter.get(); + } else if (currentGoal != null && endCause.isWinnable()) { + currentGoal.getWinnersOnEnd(winners); + } + + if (endCause != ChallengeEndCause.GOAL_REACHED || setSpectatorOnWin) { + setSpectator(); + } + if (endCause == ChallengeEndCause.GOAL_REACHED && winSounds && currentGoal != null && currentGoal.getWinSound() != null) { + currentGoal.getWinSound().broadcast(); + } + if (dropItemsOnEnd) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (winners.isEmpty() || winners.contains(player)) continue; + dropItems(player); + } + } + + Challenges.getInstance().getChallengeTimer().pause(false); + + String winnerString = StringUtils.getIterableAsString(winners, "§7, ", player -> "§e§l" + NameHelper.getName(player)); + String time = Challenges.getInstance().getChallengeTimer().getFormattedTime(); + String seed = Bukkit.getWorlds().isEmpty() ? "?" : + String.valueOf(ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); + endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, time, winnerString, seed); + + } + + private void setSpectator() { + for (Player player : Bukkit.getOnlinePlayers()) { + player.setGameMode(GameMode.SPECTATOR); + SoundSample.BLAST.play(player); + + try { + player.getWorld().spawnEntity(player.getLocation(), MinecraftNameWrapper.FIREWORK); + } catch (IllegalArgumentException ex) { + // We cant spawn fireworks like that in some versions of spigot + } + } + } + + private void dropItems(@Nonnull Player player) { + dropItems(player.getLocation(), player.getInventory().getContents()); + player.getInventory().clear(); + } + + private void dropItems(@Nonnull Location location, @Nonnull ItemStack[] items) { + for (ItemStack item : items) { + if (item == null) continue; + if (BukkitReflectionUtils.isAir(item.getType())) continue; + if (location.getWorld() == null) return; + location.getWorld().dropItem(location, item); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 54e8bfc01..e27a364d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -1,53 +1,43 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import lombok.Getter; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +@Getter public final class TitleManager { - private static final int fadein = 5, duration = 20, fadeout = 10; + private static final int fadein = 5, duration = 20, fadeout = 10; - private final boolean timerStatusEnabled; - private final boolean challengeStatusEnabled; + private final boolean timerStatusEnabled; + private final boolean challengeStatusEnabled; - public TitleManager() { - Document config = Challenges.getInstance().getConfigDocument().getDocument("titles"); - timerStatusEnabled = config.getBoolean("timer-status"); - challengeStatusEnabled = config.getBoolean("challenge-status"); - } + public TitleManager() { + Document config = Challenges.getInstance().getConfigDocument().getDocument("titles"); + timerStatusEnabled = config.getBoolean("timer-status"); + challengeStatusEnabled = config.getBoolean("challenge-status"); + } - public void sendTimerStatusTitle(@Nonnull Message message) { - if (!timerStatusEnabled) return; - message.broadcastTitle(); - } + public void sendTimerStatusTitle(@Nonnull Message message) { + if (!timerStatusEnabled) return; + message.broadcastTitle(); + } - public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object... args) { - if (!challengeStatusEnabled) return; - message.broadcastTitle(args); - } + public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object... args) { + if (!challengeStatusEnabled) return; + message.broadcastTitle(args); + } - public boolean isChallengeStatusEnabled() { - return challengeStatusEnabled; - } + public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + player.sendTitle(title, subtitle, fadein, duration, fadeout); + } - public boolean isTimerStatusEnabled() { - return timerStatusEnabled; - } - - public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { - player.sendTitle(title, subtitle, fadein, duration, fadeout); - } - - public void sendTitleInstant(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { - player.sendTitle(title, subtitle, 0, duration, fadeout); - } + public void sendTitleInstant(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + player.sendTitle(title, subtitle, 0, duration, fadeout); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 449e8d750..2d7435838 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -1,12 +1,11 @@ package net.codingarea.challenges.plugin.management.server; -import java.nio.file.Files; import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -19,331 +18,332 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class WorldManager { - private static final String customSeedWorldPrefix = "pregenerated_"; - private final boolean restartOnReset; - @Getter - private final boolean enableFreshReset; - private final long customSeed; - private final String levelName; - private final String[] worlds; - private final Map playerData = new HashMap<>(); - @Getter + private static final String customSeedWorldPrefix = "pregenerated_"; + private final boolean restartOnReset; + @Getter + private final boolean enableFreshReset; + private final long customSeed; + private final String levelName; + private final String[] worlds; + private final Map playerData = new HashMap<>(); + @Getter private boolean shutdownBecauseOfReset = false; - private boolean useCustomSeed; - private WorldSettings settings = new WorldSettings(); - private World flatWorld; - @Getter - private boolean worldInUse; - public WorldManager() { - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - restartOnReset = pluginConfig.getBoolean("restart-on-reset"); - enableFreshReset = pluginConfig.getBoolean("enable-fresh-reset"); + private boolean useCustomSeed; + private WorldSettings settings = new WorldSettings(); + private World flatWorld; + @Getter + private boolean worldInUse; + + public WorldManager() { + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + restartOnReset = pluginConfig.getBoolean("restart-on-reset"); + enableFreshReset = pluginConfig.getBoolean("enable-fresh-reset"); + + Document seedConfig = pluginConfig.getDocument("custom-seed"); + useCustomSeed = seedConfig.getBoolean("config"); + customSeed = seedConfig.getLong("seed"); + + Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + levelName = sessionConfig.getString("level-name", "world"); + worlds = new String[]{ + levelName, + levelName + "_nether", + levelName + "_the_end" + }; + } + + public void load() { + executeWorldResetIfNecessary(); + } + + public void enable() { + loadExtraWorld(); + } + + public void prepareWorldReset(@Nullable CommandSender requestedBy) { + prepareWorldReset(requestedBy, customSeed); + } + + public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Long seed) { + if (seed == null && useCustomSeed) seed = customSeed; + if (seed != null) useCustomSeed = true; + + shutdownBecauseOfReset = true; + ChallengeAPI.pauseTimer(false); + + // Stop all tasks to prevent them from overwriting configs + Challenges.getInstance().getScheduler().stop(); + + resetConfigs(); + + String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; + String kickMessage = Message.forName("server-reset").asString(requester); + Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); + + if (seed != null) { + generateCustomSeedWorlds(seed); + } + + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); + + } + + private void generateCustomSeedWorlds(long seed) { + + Logger.debug("Generating custom seed worlds with seed " + seed); + for (String name : worlds) { + + World world = Bukkit.getWorld(name); + if (world == null) { + Logger.error("Could not find world {}", name); + continue; + } + + String newWorldName = customSeedWorldPrefix + name; + File folder = new File(Bukkit.getWorldContainer(), newWorldName); + if (folder.exists()) FileUtils.deleteWorldFolder(folder); + + WorldCreator creator = new WorldCreator(newWorldName).seed(seed).environment(world.getEnvironment()); + creator.createWorld(); + + Logger.debug("Created custom seed world {}", newWorldName); + + } + + } + + private void resetConfigs() { + + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + sessionConfig.clear(); + sessionConfig.set("reset", true); + sessionConfig.set("seed-reset", useCustomSeed); + if (!Bukkit.getWorlds().isEmpty()) { + sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); + } + sessionConfig.save(); + + FileDocument gamestateConfig = Challenges.getInstance().getConfigManager().getGamestateConfig(); + gamestateConfig.clear(); + gamestateConfig.save(); + + } + + private void loadExtraWorld() { + if (!Challenges.getInstance().isReloaded()) + deleteWorld("challenges-extra"); + + try { + flatWorld = new WorldCreator("challenges-extra").type(WorldType.FLAT).generateStructures(false).createWorld(); + if (flatWorld == null) return; + flatWorld.setSpawnFlags(false, false); + disableGameRuleInFlatWorld("doMobSpawning"); + disableGameRuleInFlatWorld("doTraderSpawning"); + disableGameRuleInFlatWorld("doWeatherCycle"); + disableGameRuleInFlatWorld("doDaylightCycle"); + disableGameRuleInFlatWorld("disableRaids"); + disableGameRuleInFlatWorld("mobGriefing"); + + } catch (Exception ex) { + Logger.error("Could not load extra world!", ex); + Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); + Logger.error("Please delete all worlds and try again!"); + return; + } + + teleportPlayersOutOfExtraWorld(); + } + + private void teleportPlayersOutOfExtraWorld() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getWorld() != flatWorld) continue; + + Location location = player.getRespawnLocation(); + if (location == null) { + World world = Bukkit.getWorld(levelName); + if (world == null) { + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + } + location = world.getSpawnLocation(); + } + + player.teleport(location); + } + } + + @SuppressWarnings("unchecked") + private void disableGameRuleInFlatWorld(@Nonnull String name) { + GameRule gamerule = (GameRule) GameRule.getByName(name); + if (gamerule == null) return; + flatWorld.setGameRule(gamerule, false); + } + + private void executeWorldResetIfNecessary() { + if (Challenges.getInstance().getConfigManager().getSessionConfig().getBoolean("reset")) + executeWorldReset(); + } + + public void executeWorldReset() { + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + boolean seedReset = sessionConfig.getBoolean("seed-reset"); + + Logger.info("Deleting worlds.."); + + for (String world : worlds) { + deleteWorld(world); + if (seedReset) { + copyPreGeneratedWorld(world); + } else { + deletePreGeneratedWorld(world); + } + } + + for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { + deleteWorld(world); + } + + sessionConfig.set("reset", false); + sessionConfig.set("seed-reset", false); + sessionConfig.save(); + + } + + private void deleteWorld(@Nonnull String name) { + File folder = new File(Bukkit.getWorldContainer(), name); + FileUtils.deleteWorldFolder(folder); + Logger.info("Deleted world {}", name); + } + + private void copyPreGeneratedWorld(@Nonnull String name) { + File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); + if (!source.exists() || !source.isDirectory()) { + Logger.warn("Custom seed world '{}' does not exist!", name); + return; + } + + File target = new File(Bukkit.getWorldContainer(), name); + try { + copy(source, target); + Logger.debug("Copied pre generated custom seed world {}", name); + } catch (IOException ex) { + Logger.error("Unable to copy pre generated custom seed world {}", name, ex); + } + } + + private void deletePreGeneratedWorld(@Nonnull String name) { + File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); + if (!source.exists() || !source.isDirectory()) return; + + FileUtils.deleteWorldFolder(source); + Logger.debug("Deleted pre generated custom seed world {}", name); + } + + public void copy(@Nonnull File source, @Nonnull File target) throws IOException { + if (source.isDirectory()) { + copyDirectory(source, target); + } else { + copyFile(source, target); + } + } + + private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IOException { + if (!target.exists()) { + if (!target.mkdir()) { + return; + } + } + + String[] list = source.list(); + if (list == null) return; + for (String child : list) { + if ("session.lock".equals(child)) continue; + copy(new File(source, child), new File(target, child)); + } + } + + private void copyFile(@Nonnull File source, @Nonnull File target) throws IOException { + try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { + byte[] buf = new byte[1024]; + int length; + while ((length = in.read(buf)) > 0) + out.write(buf, 0, length); + } + } + + private void stopServerNow() { + if (!restartOnReset) { + Bukkit.shutdown(); + return; + } + + try { + Bukkit.spigot().restart(); + } catch (NoSuchMethodError ex) { + Bukkit.shutdown(); + } + } + + public void setWorldInUse(boolean worldInUse) { + this.worldInUse = worldInUse; + if (worldInUse) { + cachePlayerData(); + } else { + settings = new WorldSettings(); + restorePlayerData(); + } + } + + private void cachePlayerData() { + Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); + } + + public void cachePlayerData(@Nonnull Player player) { + playerData.put(player.getUniqueId(), new PlayerData(player)); + } + + public void restorePlayerData() { + Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); + } + + public void restorePlayerData(@Nonnull Player player) { + PlayerData data = playerData.remove(player.getUniqueId()); + if (data == null) return; + data.apply(player); + } + + public boolean hasPlayerData(@Nonnull Player player) { + return playerData.containsKey(player.getUniqueId()); + } + + @Nonnull + public World getExtraWorld() { + return flatWorld; + } + + @Nonnull + public WorldSettings getSettings() { + return settings; + } - Document seedConfig = pluginConfig.getDocument("custom-seed"); - useCustomSeed = seedConfig.getBoolean("config"); - customSeed = seedConfig.getLong("seed"); - - Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - levelName = sessionConfig.getString("level-name", "world"); - worlds = new String[]{ - levelName, - levelName + "_nether", - levelName + "_the_end" - }; - } - - public void load() { - executeWorldResetIfNecessary(); - } - - public void enable() { - loadExtraWorld(); - } - - public void prepareWorldReset(@Nullable CommandSender requestedBy) { - prepareWorldReset(requestedBy, customSeed); - } - - public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Long seed) { - if (seed == null && useCustomSeed) seed = customSeed; - if (seed != null) useCustomSeed = true; - - shutdownBecauseOfReset = true; - ChallengeAPI.pauseTimer(false); - - // Stop all tasks to prevent them from overwriting configs - Challenges.getInstance().getScheduler().stop(); - - resetConfigs(); - - String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; - String kickMessage = Message.forName("server-reset").asString(requester); - Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); - - if (seed != null) { - generateCustomSeedWorlds(seed); - } - - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); - - } - - private void generateCustomSeedWorlds(long seed) { - - Logger.debug("Generating custom seed worlds with seed " + seed); - for (String name : worlds) { - - World world = Bukkit.getWorld(name); - if (world == null) { - Logger.error("Could not find world {}", name); - continue; - } - - String newWorldName = customSeedWorldPrefix + name; - File folder = new File(Bukkit.getWorldContainer(), newWorldName); - if (folder.exists()) FileUtils.deleteWorldFolder(folder); - - WorldCreator creator = new WorldCreator(newWorldName).seed(seed).environment(world.getEnvironment()); - creator.createWorld(); - - Logger.debug("Created custom seed world {}", newWorldName); - - } - - } - - private void resetConfigs() { - - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - sessionConfig.clear(); - sessionConfig.set("reset", true); - sessionConfig.set("seed-reset", useCustomSeed); - if (!Bukkit.getWorlds().isEmpty()) { - sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); - } - sessionConfig.save(); - - FileDocument gamestateConfig = Challenges.getInstance().getConfigManager().getGamestateConfig(); - gamestateConfig.clear(); - gamestateConfig.save(); - - } - - private void loadExtraWorld() { - if (!Challenges.getInstance().isReloaded()) - deleteWorld("challenges-extra"); - - try { - flatWorld = new WorldCreator("challenges-extra").type(WorldType.FLAT).generateStructures(false).createWorld(); - if (flatWorld == null) return; - flatWorld.setSpawnFlags(false, false); - disableGameRuleInFlatWorld("doMobSpawning"); - disableGameRuleInFlatWorld("doTraderSpawning"); - disableGameRuleInFlatWorld("doWeatherCycle"); - disableGameRuleInFlatWorld("doDaylightCycle"); - disableGameRuleInFlatWorld("disableRaids"); - disableGameRuleInFlatWorld("mobGriefing"); - - } catch (Exception ex) { - Logger.error("Could not load extra world!", ex); - Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); - Logger.error("Please delete all worlds and try again!"); - return; - } - - teleportPlayersOutOfExtraWorld(); - } - - private void teleportPlayersOutOfExtraWorld() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getWorld() != flatWorld) continue; - - Location location = player.getRespawnLocation(); - if (location == null) { - World world = Bukkit.getWorld(levelName); - if (world == null) { - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - } - location = world.getSpawnLocation(); - } - - player.teleport(location); - } - } - - @SuppressWarnings("unchecked") - private void disableGameRuleInFlatWorld(@Nonnull String name) { - GameRule gamerule = (GameRule) GameRule.getByName(name); - if (gamerule == null) return; - flatWorld.setGameRule(gamerule, false); - } - - private void executeWorldResetIfNecessary() { - if (Challenges.getInstance().getConfigManager().getSessionConfig().getBoolean("reset")) - executeWorldReset(); - } - - public void executeWorldReset() { - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - boolean seedReset = sessionConfig.getBoolean("seed-reset"); - - Logger.info("Deleting worlds.."); - - for (String world : worlds) { - deleteWorld(world); - if (seedReset) { - copyPreGeneratedWorld(world); - } else { - deletePreGeneratedWorld(world); - } - } - - for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { - deleteWorld(world); - } - - sessionConfig.set("reset", false); - sessionConfig.set("seed-reset", false); - sessionConfig.save(); - - } - - private void deleteWorld(@Nonnull String name) { - File folder = new File(Bukkit.getWorldContainer(), name); - FileUtils.deleteWorldFolder(folder); - Logger.info("Deleted world {}", name); - } - - private void copyPreGeneratedWorld(@Nonnull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) { - Logger.warn("Custom seed world '{}' does not exist!", name); - return; - } - - File target = new File(Bukkit.getWorldContainer(), name); - try { - copy(source, target); - Logger.debug("Copied pre generated custom seed world {}", name); - } catch (IOException ex) { - Logger.error("Unable to copy pre generated custom seed world {}", name, ex); - } - } - - private void deletePreGeneratedWorld(@Nonnull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) return; - - FileUtils.deleteWorldFolder(source); - Logger.debug("Deleted pre generated custom seed world {}", name); - } - - public void copy(@Nonnull File source, @Nonnull File target) throws IOException { - if (source.isDirectory()) { - copyDirectory(source, target); - } else { - copyFile(source, target); - } - } - - private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IOException { - if (!target.exists()) { - if (!target.mkdir()) { - return; - } - } - - String[] list = source.list(); - if (list == null) return; - for (String child : list) { - if ("session.lock".equals(child)) continue; - copy(new File(source, child), new File(target, child)); - } - } - - private void copyFile(@Nonnull File source, @Nonnull File target) throws IOException { - try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { - byte[] buf = new byte[1024]; - int length; - while ((length = in.read(buf)) > 0) - out.write(buf, 0, length); - } - } - - private void stopServerNow() { - if (!restartOnReset) { - Bukkit.shutdown(); - return; - } - - try { - Bukkit.spigot().restart(); - } catch (NoSuchMethodError ex) { - Bukkit.shutdown(); - } - } - - public void setWorldInUse(boolean worldInUse) { - this.worldInUse = worldInUse; - if (worldInUse) { - cachePlayerData(); - } else { - settings = new WorldSettings(); - restorePlayerData(); - } - } - - private void cachePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); - } - - public void cachePlayerData(@Nonnull Player player) { - playerData.put(player.getUniqueId(), new PlayerData(player)); - } - - public void restorePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); - } - - public void restorePlayerData(@Nonnull Player player) { - PlayerData data = playerData.remove(player.getUniqueId()); - if (data == null) return; - data.apply(player); - } - - public boolean hasPlayerData(@Nonnull Player player) { - return playerData.containsKey(player.getUniqueId()); - } - - @Nonnull - public World getExtraWorld() { - return flatWorld; - } - - @Nonnull - public WorldSettings getSettings() { - return settings; - } - - @Setter + @Setter @Getter public static class WorldSettings { - private boolean placeBlocks = false; - private boolean destroyBlocks = false; - private boolean dropItems = false; - private boolean pickupItems = false; + private boolean placeBlocks = false; + private boolean destroyBlocks = false; + private boolean dropItems = false; + private boolean pickupItems = false; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 701d7da05..a1f7d0ba8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server.scoreboard; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -19,138 +19,134 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeBossBar { - private final Map bossbars = new ConcurrentHashMap<>(); - private BiConsumer content = (bossbar, player) -> { - }; - - private BossBar createBossbar(@Nonnull BossBarInstance instance) { - BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); - bossbar.setProgress(instance.progress); - return bossbar; - } - - private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - bossbar.setTitle(instance.title.toPlainText()); - } else { - NMSUtils.setBossBarTitle(bossbar, instance.title); - } - bossbar.setColor(instance.color); - bossbar.setStyle(instance.style); - bossbar.setProgress(instance.progress); - bossbar.setVisible(instance.visible); - } - - public void setContent(@Nonnull BiConsumer content) { - this.content = content; - } - - public void applyHide(@Nonnull Player player) { - BossBar bossbar = bossbars.get(player); - if (bossbar == null) return; - bossbar.removePlayer(player); - } - - public void update() { - Bukkit.getOnlinePlayers().forEach(this::update); - } - - public void update(@Nonnull Player player) { - if (!isShown()) { - Logger.warn("Tried to update bossbar which is not shown"); - return; - } - - try { - - BossBarInstance instance = new BossBarInstance(); - - if (ChallengeAPI.isPaused()) { - instance.setTitle(Message.forName("bossbar-timer-paused").asString()); - instance.setColor(BarColor.RED); - } else { - content.accept(instance, player); - } - - - BossBar bossbar = bossbars.computeIfAbsent(player, key -> createBossbar(instance)); - apply(bossbar, instance); - - if (!bossbar.getPlayers().contains(player)) - bossbar.addPlayer(player); - - } catch (Exception ex) { - Logger.error("Unable to update bossbar for player '{}'", player.getName(), ex); - } - } - - public void show() { - Challenges.getInstance().getScoreboardManager().showBossBar(this); - } - - public void hide() { - Challenges.getInstance().getScoreboardManager().hideBossBar(this); - } - - public boolean isShown() { - return Challenges.getInstance().getScoreboardManager().isShown(this); - } - - public static final class BossBarInstance { - - private BaseComponent title = new TextComponent(); - private double progress = 1; - private BarColor color = BarColor.WHITE; - private BarStyle style = BarStyle.SOLID; - private boolean visible = true; - - private BossBarInstance() { - } - - @Nonnull - public BossBarInstance setTitle(@Nonnull String title) { - this.title = new TextComponent(title); - return this; - } - - @Nonnull - public BossBarInstance setTitle(@Nonnull BaseComponent title) { - this.title = title; - return this; - } - - @Nonnull - public BossBarInstance setProgress(double progress) { - if (progress < 0 || progress > 1) - throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); - this.progress = progress; - return this; - } - - @Nonnull - public BossBarInstance setColor(@Nonnull BarColor color) { - this.color = color; - return this; - } - - @Nonnull - public BossBarInstance setStyle(@Nonnull BarStyle style) { - this.style = style; - return this; - } - - @Nonnull - public BossBarInstance setVisible(boolean visible) { - this.visible = visible; - return this; - } - - } + private final Map bossbars = new ConcurrentHashMap<>(); + private BiConsumer content = (bossbar, player) -> { + }; + + private BossBar createBossbar(@Nonnull BossBarInstance instance) { + BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); + bossbar.setProgress(instance.progress); + return bossbar; + } + + private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) { + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { + bossbar.setTitle(instance.title.toPlainText()); + } else { + NMSUtils.setBossBarTitle(bossbar, instance.title); + } + bossbar.setColor(instance.color); + bossbar.setStyle(instance.style); + bossbar.setProgress(instance.progress); + bossbar.setVisible(instance.visible); + } + + public void setContent(@Nonnull BiConsumer content) { + this.content = content; + } + + public void applyHide(@Nonnull Player player) { + BossBar bossbar = bossbars.get(player); + if (bossbar == null) return; + bossbar.removePlayer(player); + } + + public void update() { + Bukkit.getOnlinePlayers().forEach(this::update); + } + + public void update(@Nonnull Player player) { + if (!isShown()) { + Logger.warn("Tried to update bossbar which is not shown"); + return; + } + + try { + + BossBarInstance instance = new BossBarInstance(); + + if (ChallengeAPI.isPaused()) { + instance.setTitle(Message.forName("bossbar-timer-paused").asString()); + instance.setColor(BarColor.RED); + } else { + content.accept(instance, player); + } + + + BossBar bossbar = bossbars.computeIfAbsent(player, key -> createBossbar(instance)); + apply(bossbar, instance); + + if (!bossbar.getPlayers().contains(player)) + bossbar.addPlayer(player); + + } catch (Exception ex) { + Logger.error("Unable to update bossbar for player '{}'", player.getName(), ex); + } + } + + public void show() { + Challenges.getInstance().getScoreboardManager().showBossBar(this); + } + + public void hide() { + Challenges.getInstance().getScoreboardManager().hideBossBar(this); + } + + public boolean isShown() { + return Challenges.getInstance().getScoreboardManager().isShown(this); + } + + public static final class BossBarInstance { + + private BaseComponent title = new TextComponent(); + private double progress = 1; + private BarColor color = BarColor.WHITE; + private BarStyle style = BarStyle.SOLID; + private boolean visible = true; + + private BossBarInstance() { + } + + @Nonnull + public BossBarInstance setTitle(@Nonnull String title) { + this.title = new TextComponent(title); + return this; + } + + @Nonnull + public BossBarInstance setTitle(@Nonnull BaseComponent title) { + this.title = title; + return this; + } + + @Nonnull + public BossBarInstance setProgress(double progress) { + if (progress < 0 || progress > 1) + throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); + this.progress = progress; + return this; + } + + @Nonnull + public BossBarInstance setColor(@Nonnull BarColor color) { + this.color = color; + return this; + } + + @Nonnull + public BossBarInstance setStyle(@Nonnull BarStyle style) { + this.style = style; + return this; + } + + @Nonnull + public BossBarInstance setVisible(boolean visible) { + this.visible = visible; + return this; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 0409e0ceb..d61318aee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -2,8 +2,8 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Bukkit; @@ -18,136 +18,132 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeScoreboard { - private final Map objectives = new ConcurrentHashMap<>(); - private BiConsumer content = (scoreboard, player) -> { - }; - - public void setContent(@Nonnull BiConsumer content) { - this.content = content; - } - - public void applyHide(@Nonnull Player player) { - unregister(objectives.remove(player)); - } - - public void update() { - for (Player player : new LinkedList<>(Bukkit.getOnlinePlayers())) { - update(player); - } - } - - public void update(@Nonnull Player player) { - if (!isShown()) { - Logger.warn("Tried to update scoreboard which is not shown"); - return; - } - - try { - if (objectives.containsKey(player)) { - unregister(objectives.remove(player)); - } - - ScoreboardInstance instance = new ScoreboardInstance(); - content.accept(instance, player); - - Collection lines = instance.getLines(); - if (lines.isEmpty()) { - return; - } - - Scoreboard scoreboard = player.getScoreboard(); - if (Bukkit.getScoreboardManager() == null) { - return; - } - if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { - player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); - } - - String name = String.valueOf(player.getUniqueId().hashCode()); - // Unregister any old objective existing - Objective objective1 = scoreboard.getObjective(name); - if (objective1 != null) { - unregister(objective1); - } - - Objective objective = scoreboard.registerNewObjective(name, "dummy", String.valueOf(instance.getTitle())); - int score = lines.size(); - for (String line : lines) { - if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); - score--; - objective.getScore(line).setScore(score); - } - - objective.setDisplaySlot(DisplaySlot.SIDEBAR); - objectives.put(player, objective); - - } catch (Exception ex) { - Logger.error("Unable to update scoreboard for player '{}'", player.getName(), ex); - } - } - - public final void show() { - Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); - } - - public final void hide() { - if (Challenges.getInstance().getScoreboardManager().getCurrentScoreboard() != this) return; - Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(null); - } - - public final boolean isShown() { - return Challenges.getInstance().getScoreboardManager().isShown(this); - } - - private void unregister(@Nullable Objective objective) { - try { - if (objective == null) return; - objective.unregister(); - } catch (Exception ex) { - Logger.error("Unable to unregister objective " + objective.getName()); - } - } - - @ToString - public static final class ScoreboardInstance { - - private final String[] lines = new String[15]; - @Getter - private String title = Message.forName("scoreboard-title").asString(); - private int linesIndex = 0; - - private ScoreboardInstance() { - } - - @Nonnull - public ScoreboardInstance addLine(@Nonnull String text) { - if (linesIndex >= lines.length) - throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); - lines[linesIndex++] = text; - return this; - } - - @Nonnull - public Collection getLines() { - List list = new ArrayList<>(); - for (String line : lines) { - if (line == null) continue; - list.add(line); - } - return list; - } - - @Nonnull - public ScoreboardInstance setTitle(@Nonnull String title) { - this.title = title; - return this; - } - } + private final Map objectives = new ConcurrentHashMap<>(); + private BiConsumer content = (scoreboard, player) -> { + }; + + public void setContent(@Nonnull BiConsumer content) { + this.content = content; + } + + public void applyHide(@Nonnull Player player) { + unregister(objectives.remove(player)); + } + + public void update() { + for (Player player : new LinkedList<>(Bukkit.getOnlinePlayers())) { + update(player); + } + } + + public void update(@Nonnull Player player) { + if (!isShown()) { + Logger.warn("Tried to update scoreboard which is not shown"); + return; + } + + try { + if (objectives.containsKey(player)) { + unregister(objectives.remove(player)); + } + + ScoreboardInstance instance = new ScoreboardInstance(); + content.accept(instance, player); + + Collection lines = instance.getLines(); + if (lines.isEmpty()) { + return; + } + + Scoreboard scoreboard = player.getScoreboard(); + if (Bukkit.getScoreboardManager() == null) { + return; + } + if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { + player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); + } + + String name = String.valueOf(player.getUniqueId().hashCode()); + // Unregister any old objective existing + Objective objective1 = scoreboard.getObjective(name); + if (objective1 != null) { + unregister(objective1); + } + + Objective objective = scoreboard.registerNewObjective(name, "dummy", String.valueOf(instance.getTitle())); + int score = lines.size(); + for (String line : lines) { + if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); + score--; + objective.getScore(line).setScore(score); + } + + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + objectives.put(player, objective); + + } catch (Exception ex) { + Logger.error("Unable to update scoreboard for player '{}'", player.getName(), ex); + } + } + + public void show() { + Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); + } + + public void hide() { + if (Challenges.getInstance().getScoreboardManager().getCurrentScoreboard() != this) return; + Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(null); + } + + public boolean isShown() { + return Challenges.getInstance().getScoreboardManager().isShown(this); + } + + private void unregister(@Nullable Objective objective) { + try { + if (objective == null) return; + objective.unregister(); + } catch (Exception ex) { + Logger.error("Unable to unregister objective " + objective.getName()); + } + } + + @ToString + public static final class ScoreboardInstance { + + private final String[] lines = new String[15]; + @Getter + private String title = Message.forName("scoreboard-title").asString(); + private int linesIndex = 0; + + private ScoreboardInstance() { + } + + @Nonnull + public ScoreboardInstance addLine(@Nonnull String text) { + if (linesIndex >= lines.length) + throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); + lines[linesIndex++] = text; + return this; + } + + @Nonnull + public Collection getLines() { + List list = new ArrayList<>(); + for (String line : lines) { + if (line == null) continue; + list.add(line); + } + return list; + } + + @Nonnull + public ScoreboardInstance setTitle(@Nonnull String title) { + this.title = title; + return this; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java index 7054dbfac..81d8a76a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java @@ -5,20 +5,16 @@ import java.util.EnumMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LeaderboardInfo { - private final Map values = new EnumMap<>(Statistic.class); + private final Map values = new EnumMap<>(Statistic.class); - public void setPlace(@Nonnull Statistic statistic, @Nonnegative int place) { - values.put(statistic, place); - } + public void setPlace(@Nonnull Statistic statistic, @Nonnegative int place) { + values.put(statistic, place); + } - public int getPlace(@Nonnull Statistic statistic) { - return values.getOrDefault(statistic, 1); - } + public int getPlace(@Nonnull Statistic statistic) { + return values.getOrDefault(statistic, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index 35237f673..32f93b00f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; import java.util.EnumMap; @@ -9,61 +9,57 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PlayerStats { - private final Map values = new EnumMap<>(Statistic.class); - private final UUID uuid; - private final String name; + private final Map values = new EnumMap<>(Statistic.class); + private final UUID uuid; + private final String name; - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document document) { - this.uuid = uuid; - this.name = name; - for (Statistic statistic : Statistic.values()) { - values.put(statistic, document.getDouble(statistic.name())); - } - } + public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document document) { + this.uuid = uuid; + this.name = name; + for (Statistic statistic : Statistic.values()) { + values.put(statistic, document.getDouble(statistic.name())); + } + } - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name) { - this.uuid = uuid; - this.name = name; - } + public PlayerStats(@Nonnull UUID uuid, @Nonnull String name) { + this.uuid = uuid; + this.name = name; + } - public void incrementStatistic(@Nonnull Statistic statistic, double amount) { - Logger.debug("Incrementing statistic {} by {} for {}", statistic, amount, name); - double value = values.getOrDefault(statistic, 0d); - values.put(statistic, value + amount); - } + public void incrementStatistic(@Nonnull Statistic statistic, double amount) { + Logger.debug("Incrementing statistic {} by {} for {}", statistic, amount, name); + double value = values.getOrDefault(statistic, 0d); + values.put(statistic, value + amount); + } - @Nonnull - public Document asDocument() { - Document document = Document.create(); - for (Entry entry : values.entrySet()) { - document.set(entry.getKey().name(), entry.getValue()); - } - return document; - } + @Nonnull + public Document asDocument() { + Document document = Document.create(); + for (Entry entry : values.entrySet()) { + document.set(entry.getKey().name(), entry.getValue()); + } + return document; + } - public double getStatisticValue(@Nonnull Statistic statistic) { - return values.getOrDefault(statistic, 0d); - } + public double getStatisticValue(@Nonnull Statistic statistic) { + return values.getOrDefault(statistic, 0d); + } - @Nonnull - public UUID getPlayerUUID() { - return uuid; - } + @Nonnull + public UUID getPlayerUUID() { + return uuid; + } - @Nonnull - public String getPlayerName() { - return name; - } + @Nonnull + public String getPlayerName() { + return name; + } - @Override - public String toString() { - return "PlayerStats" + values; - } + @Override + public String toString() { + return "PlayerStats" + values; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index e00959c3c..c577f2b18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -1,54 +1,50 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import javax.annotation.Nonnull; import java.util.function.Function; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum Statistic { - DRAGON_KILLED(Display.INTEGER), - DEATHS(Display.INTEGER), - DAMAGE_TAKEN(Display.HEARTS), - ENTITY_KILLS(Display.INTEGER), - DAMAGE_DEALT(Display.HEARTS), - BLOCKS_MINED(Display.INTEGER), - BLOCKS_PLACED(Display.INTEGER), - BLOCKS_TRAVELED(Display.INTEGER), - CHALLENGES_PLAYED(Display.INTEGER), - JUMPS(Display.INTEGER); + DRAGON_KILLED(Display.INTEGER), + DEATHS(Display.INTEGER), + DAMAGE_TAKEN(Display.HEARTS), + ENTITY_KILLS(Display.INTEGER), + DAMAGE_DEALT(Display.HEARTS), + BLOCKS_MINED(Display.INTEGER), + BLOCKS_PLACED(Display.INTEGER), + BLOCKS_TRAVELED(Display.INTEGER), + CHALLENGES_PLAYED(Display.INTEGER), + JUMPS(Display.INTEGER); - private final Display display; + private final Display display; - Statistic(@Nonnull Display display) { - this.display = display; - } + Statistic(@Nonnull Display display) { + this.display = display; + } - @Nonnull - public String formatChat(double value) { - return display.formatChat(value); - } + @Nonnull + public String formatChat(double value) { + return display.formatChat(value); + } - public enum Display { + public enum Display { - HEARTS(value -> NumberFormatter.BIG_NUMBER.format(value / 2) + " §c❤"), - INTEGER(NumberFormatter.BIG_NUMBER::format); + HEARTS(value -> NumberFormatter.BIG_NUMBER.format(value / 2) + " §c❤"), + INTEGER(NumberFormatter.BIG_NUMBER::format); - private final Function chatFormat; + private final Function chatFormat; - Display(@Nonnull Function chatFormat) { - this.chatFormat = chatFormat; - } + Display(@Nonnull Function chatFormat) { + this.chatFormat = chatFormat; + } - @Nonnull - public String formatChat(double value) { - return chatFormat.apply(value); - } + @Nonnull + public String formatChat(double value) { + return chatFormat.apply(value); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index d620bd304..6a83e2f97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.stats; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy; @@ -23,168 +23,163 @@ import java.util.function.Function; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public final class StatsManager implements Listener { - @Getter + @Getter private final boolean enabled, noStatsAfterCheating; - private final Map cache = new ConcurrentHashMap<>(); - - private List cachedLeaderboard; - private long leaderboardCacheTimestamp; - - public StatsManager() { - enabled = Challenges.getInstance().getConfigDocument().getBoolean("save-player-stats"); - noStatsAfterCheating = enabled && Challenges.getInstance().getConfigDocument().getBoolean("no-stats-after-cheating"); - } - - @Nonnull - public static Comparator getStatsComparator(@Nonnull Statistic statistic) { - return Comparator.comparingDouble(value -> value.getStatisticValue(statistic)).reversed(); - } - - public void register() { - if (enabled) { - StatsListener listener = new StatsListener(); - ChallengeAPI.registerScheduler(this, listener); - Challenges.getInstance().registerListener(this, listener); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(@Nonnull PlayerQuitEvent event) { - PlayerStats cached = cache.remove(event.getPlayer().getUniqueId()); - if (cached == null) return; - store(event.getPlayer().getUniqueId(), cached); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onJoin(@Nonnull PlayerJoinEvent event) { - getStats(event.getPlayer()); // Cache stats - } - - @ScheduledTask(ticks = 30 * 20, challengePolicy = ChallengeStatusPolicy.ALWAYS) - public void storeCached() { - for (Entry entry : cache.entrySet()) { - store(entry.getKey(), entry.getValue()); - } - } - - private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { - try { - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", uuid) - .set("stats", stats.asDocument()) - .execute(); - Logger.debug("Saved stats for {}: {}", uuid, stats); - } catch (DatabaseException ex) { - Logger.error("Could not save player stats for {}", uuid, ex); - } - } - - @Nonnull - public PlayerStats getStats(@Nonnull Player player) { - return getStats(player.getUniqueId(), player.getName()); - } - - @Nonnull - public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { - PlayerStats cached = cache.get(uuid); - if (cached != null) return cached; - - try { - PlayerStats stats = getStatsFromDatabase(uuid, name); - if (Bukkit.getPlayer(uuid) != null) { - cache.put(uuid, stats); - Logger.debug("Loaded stats for uuid {}: {}", uuid, stats); - } - return stats; - } catch (DatabaseException ex) { - Logger.error("Could not get player stats for {}", uuid, ex); - return new PlayerStats(uuid, name); - } - } - - @Nonnull - private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String name) throws DatabaseException { - return Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("stats", "name") - .where("uuid", uuid) - .execute().first() - .map(result -> new PlayerStats(uuid, result.getString("name"), result.getDocument("stats"))) - .orElse(new PlayerStats(uuid, name)); - } - - @Nonnull - private List getAllStats() throws DatabaseException { - if (cachedLeaderboard != null && System.currentTimeMillis() - leaderboardCacheTimestamp < 3 * 60 * 1000) { - return cachedLeaderboard; - } - - leaderboardCacheTimestamp = System.currentTimeMillis(); - return cachedLeaderboard = getAllStats0(); - } - - @Nonnull - private List getAllStats0() throws DatabaseException { - return Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("uuid", "stats", "name") - .execute().all() - .filter(result -> result.getUUID("uuid") != null) - .map(result -> new PlayerStats(result.getUUID("uuid"), result.getString("name"), result.getDocument("stats"))) - .collect(Collectors.toList()); - } - - @Nonnull - public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { - try { - List stats = getAllStats(); - LeaderboardInfo info = new LeaderboardInfo(); - for (Statistic statistic : Statistic.values()) { - int place = determineIndex(new ArrayList<>(stats), PlayerStats::getPlayerUUID, uuid, getStatsComparator(statistic)) + 1; - info.setPlace(statistic, place); - } - - return info; - } catch (DatabaseException ex) { - Logger.error("Could not get player leaderboard information for {}", uuid, ex); - return new LeaderboardInfo(); - } - } - - @Nonnull - public List getLeaderboard(@Nonnull Statistic statistic) { - try { - List stats = getAllStats(); - stats.sort(getStatsComparator(statistic)); - return stats; - } catch (Exception ex) { - Logger.error("Could not get leaderboard in {}", statistic, ex); - return new ArrayList<>(); - } - } - - private int determineIndex(@Nonnull List list, @Nonnull Function extractor, @Nonnull U target, @Nonnull Comparator sort) { - list.sort(sort); - int index = 0; - for (T t : list) { - U u = extractor.apply(t); - if (target.equals(u)) return index; - index++; - } - return index; - } + private final Map cache = new ConcurrentHashMap<>(); + + private List cachedLeaderboard; + private long leaderboardCacheTimestamp; + + public StatsManager() { + enabled = Challenges.getInstance().getConfigDocument().getBoolean("save-player-stats"); + noStatsAfterCheating = enabled && Challenges.getInstance().getConfigDocument().getBoolean("no-stats-after-cheating"); + } + + @Nonnull + public static Comparator getStatsComparator(@Nonnull Statistic statistic) { + return Comparator.comparingDouble(value -> value.getStatisticValue(statistic)).reversed(); + } + + public void register() { + if (enabled) { + StatsListener listener = new StatsListener(); + ChallengeAPI.registerScheduler(this, listener); + Challenges.getInstance().registerListener(this, listener); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onLeave(@Nonnull PlayerQuitEvent event) { + PlayerStats cached = cache.remove(event.getPlayer().getUniqueId()); + if (cached == null) return; + store(event.getPlayer().getUniqueId(), cached); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(@Nonnull PlayerJoinEvent event) { + getStats(event.getPlayer()); // Cache stats + } + + @ScheduledTask(ticks = 30 * 20, challengePolicy = ChallengeStatusPolicy.ALWAYS) + public void storeCached() { + for (Entry entry : cache.entrySet()) { + store(entry.getKey(), entry.getValue()); + } + } + + private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { + try { + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", uuid) + .set("stats", stats.asDocument()) + .execute(); + Logger.debug("Saved stats for {}: {}", uuid, stats); + } catch (DatabaseException ex) { + Logger.error("Could not save player stats for {}", uuid, ex); + } + } + + @Nonnull + public PlayerStats getStats(@Nonnull Player player) { + return getStats(player.getUniqueId(), player.getName()); + } + + @Nonnull + public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { + PlayerStats cached = cache.get(uuid); + if (cached != null) return cached; + + try { + PlayerStats stats = getStatsFromDatabase(uuid, name); + if (Bukkit.getPlayer(uuid) != null) { + cache.put(uuid, stats); + Logger.debug("Loaded stats for uuid {}: {}", uuid, stats); + } + return stats; + } catch (DatabaseException ex) { + Logger.error("Could not get player stats for {}", uuid, ex); + return new PlayerStats(uuid, name); + } + } + + @Nonnull + private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String name) throws DatabaseException { + return Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("stats", "name") + .where("uuid", uuid) + .execute().first() + .map(result -> new PlayerStats(uuid, Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) + .orElse(new PlayerStats(uuid, name)); + } + + @Nonnull + private List getAllStats() throws DatabaseException { + if (cachedLeaderboard != null && System.currentTimeMillis() - leaderboardCacheTimestamp < 3 * 60 * 1000) { + return cachedLeaderboard; + } + + leaderboardCacheTimestamp = System.currentTimeMillis(); + return cachedLeaderboard = getAllStats0(); + } + + @Nonnull + private List getAllStats0() throws DatabaseException { + return Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("uuid", "stats", "name") + .execute().all() + .filter(result -> result.getUUID("uuid") != null) + .map(result -> new PlayerStats(Objects.requireNonNull(result.getUUID("uuid")), Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) + .collect(Collectors.toList()); + } + + @Nonnull + public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { + try { + List stats = getAllStats(); + LeaderboardInfo info = new LeaderboardInfo(); + for (Statistic statistic : Statistic.values()) { + int place = determineIndex(new ArrayList<>(stats), PlayerStats::getPlayerUUID, uuid, getStatsComparator(statistic)) + 1; + info.setPlace(statistic, place); + } + + return info; + } catch (DatabaseException ex) { + Logger.error("Could not get player leaderboard information for {}", uuid, ex); + return new LeaderboardInfo(); + } + } + + @Nonnull + public List getLeaderboard(@Nonnull Statistic statistic) { + try { + List stats = getAllStats(); + stats.sort(getStatsComparator(statistic)); + return stats; + } catch (Exception ex) { + Logger.error("Could not get leaderboard in {}", statistic, ex); + return new ArrayList<>(); + } + } + + private int determineIndex(@Nonnull List list, @Nonnull Function extractor, @Nonnull U target, @Nonnull Comparator sort) { + list.sort(sort); + int index = 0; + for (T t : list) { + U u = extractor.apply(t); + if (target.equals(u)) return index; + index++; + } + return index; + } public boolean hasDatabaseConnection() { - return Challenges.getInstance().getDatabaseManager().getDatabase() != null && Challenges.getInstance().getDatabaseManager().isConnected(); - } + return Challenges.getInstance().getDatabaseManager().getDatabase() != null && Challenges.getInstance().getDatabaseManager().isConnected(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java new file mode 100644 index 000000000..d7964e938 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java @@ -0,0 +1,37 @@ +package net.codingarea.challenges.plugin.management.team; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.UUID; + +@Getter +@RequiredArgsConstructor +public class CustomTeam implements Team, RegisteredTeam { + + private final UUID uniqueId; + private final String displayName; + + private TeamProvider provider; + + public CustomTeam(String displayName) { + this(UUID.randomUUID(), displayName); + } + + @Override + public void supplyTeamProvider(TeamProvider teamProvider) { + this.provider = teamProvider; + } + + @Override + public List getMembers() { + return provider.getTeamMembers(getUniqueId()); + } + + @Override + public List getOnlineMembers() { + return provider.getOnlineTeamMembers(getUniqueId()); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java new file mode 100644 index 000000000..362319ea5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java @@ -0,0 +1,36 @@ +package net.codingarea.challenges.plugin.management.team; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Player; + +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +@Getter +@RequiredArgsConstructor +public class PlayerTeam implements Team { + + private final Player player; + + @Override + public UUID getUniqueId() { + return player.getUniqueId(); + } + + @Override + public String getDisplayName() { + return player.getDisplayName(); + } + + @Override + public List getMembers() { + return new LinkedList<>(List.of(player.getUniqueId())); + } + + @Override + public List getOnlineMembers() { + return new LinkedList<>(List.of(player)); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java new file mode 100644 index 000000000..4379756dc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java @@ -0,0 +1,7 @@ +package net.codingarea.challenges.plugin.management.team; + +public interface RegisteredTeam { + + void supplyTeamProvider(TeamProvider teamProvider); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java new file mode 100644 index 000000000..01f0698c4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java @@ -0,0 +1,21 @@ +package net.codingarea.challenges.plugin.management.team; + +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.UUID; + +public interface Team { + + UUID getUniqueId(); + + /** + * Todo: replace with components + */ + String getDisplayName(); + + List getMembers(); + + List getOnlineMembers(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java new file mode 100644 index 000000000..a633ec0d7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -0,0 +1,82 @@ +package net.codingarea.challenges.plugin.management.team; + +import net.codingarea.commons.bukkit.utils.logging.Logger; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class TeamProvider { + + private final ConcurrentHashMap registeredTeams = new ConcurrentHashMap<>(); + private final ConcurrentHashMap userTeams = new ConcurrentHashMap<>(); + + public TeamProvider() { + + } + + public Team getPlayerTeam(Player player) { + UUID uuid = userTeams.get(player.getUniqueId()); + if (uuid != null) { + Team team = registeredTeams.get(uuid); + if (team != null) { + return team; + } + } + return new PlayerTeam(player); + } + + public List getAllTeams() { + return new LinkedList<>(List.copyOf(registeredTeams.values())); + } + + public List getTeamMembers(UUID teamId) { + Team team = registeredTeams.get(teamId); + if (team == null) { + return new LinkedList<>(); + } + return team.getMembers(); + } + + public List getOnlineTeamMembers(UUID teamId) { + Team team = registeredTeams.get(teamId); + if (team == null) { + return new LinkedList<>(); + } + return team.getOnlineMembers(); + } + + Optional getRegisteredTeam(UUID uuid) { + return Optional.ofNullable(registeredTeams.get(uuid)); + } + + public void setTeam(Player player, UUID teamId) { + Team team = registeredTeams.get(teamId); + if (!(team instanceof RegisteredTeam)) { + userTeams.remove(player.getUniqueId()); + return; + } + userTeams.put(player.getUniqueId(), teamId); + } + + public void registerTeam(Team team) { + if (!(team instanceof RegisteredTeam registeredTeam)) { + Logger.error("Attempted to register a temporary team as a team!"); + return; + } + registeredTeam.supplyTeamProvider(this); + registeredTeams.put(team.getUniqueId(), team); + } + + public void unregisterTeam(Team team) { + if (!(team instanceof RegisteredTeam)) { + Logger.error("Attempted to unregister a temporary team!"); + return; + } + registeredTeams.remove(team.getUniqueId()); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 786a7ba4e..8f6e7e695 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -23,93 +23,89 @@ import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BackCommand implements PlayerCommand, TabCompleter, Listener { - private final Map> lastLocations = new HashMap<>(); - - // To check if the current teleportation is from the command - private boolean inTeleport = false; - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - - int count = 1; - try { - if (args.length > 0) { - count = Integer.parseInt(args[0]); - } - } catch (NumberFormatException formatException) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "back [count]"); - return; - } - - List list = lastLocations - .getOrDefault(player.getUniqueId(), Lists.newArrayList()); - int savedCount = list.size(); - - if (savedCount == 0) { - Message.forName("command-back-no-locations").send(player, Prefix.CHALLENGES); - return; - } - - int countToTeleport = Math.min(list.size(), count); - - Message.forName("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) - .send(player, Prefix.CHALLENGES, countToTeleport); - Location location = list.get(countToTeleport - 1); - inTeleport = true; - player.teleport(location); - inTeleport = false; - - if (countToTeleport > 0) { - list.subList(0, countToTeleport).clear(); - } - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - if (!(sender instanceof Player)) return Lists.newLinkedList(); - Player player = (Player) sender; - - LinkedList list = Lists.newLinkedList(); - for (int i = 0; i < lastLocations.getOrDefault(player.getUniqueId(), - Lists.newLinkedList()).size(); i++) { - list.add(String.valueOf(i + 1)); - } - return list; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (inTeleport) return; - - // Don't save the teleports of the pregame movement setting - if (!AbstractChallenge.getFirstInstance(PregameMovementSetting.class).isEnabled()) { - if ((event.getPlayer().getGameMode() == GameMode.SURVIVAL || - event.getPlayer().getGameMode() == GameMode.ADVENTURE) && - !ChallengeAPI.isStarted()) { - return; - } - } - if (event.getTo() == null) return; - if (event.getCause() == TeleportCause.ENDER_PEARL || - event.getCause() == TeleportCause.CHORUS_FRUIT) return; - - UUID uuid = event.getPlayer().getUniqueId(); - List locations = lastLocations - .getOrDefault(uuid, Lists.newArrayList()); - lastLocations.putIfAbsent(uuid, locations); - locations.add(0, event.getFrom()); - - if (locations.size() > 30) { - locations.remove(locations.size() - 1); - } - } + private final Map> lastLocations = new HashMap<>(); + + // To check if the current teleportation is from the command + private boolean inTeleport = false; + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + + int count = 1; + try { + if (args.length > 0) { + count = Integer.parseInt(args[0]); + } + } catch (NumberFormatException formatException) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "back [count]"); + return; + } + + List list = lastLocations + .getOrDefault(player.getUniqueId(), Lists.newArrayList()); + int savedCount = list.size(); + + if (savedCount == 0) { + Message.forName("command-back-no-locations").send(player, Prefix.CHALLENGES); + return; + } + + int countToTeleport = Math.min(list.size(), count); + + Message.forName("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) + .send(player, Prefix.CHALLENGES, countToTeleport); + Location location = list.get(countToTeleport - 1); + inTeleport = true; + player.teleport(location); + inTeleport = false; + + if (countToTeleport > 0) { + list.subList(0, countToTeleport).clear(); + } + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + if (!(sender instanceof Player)) return Lists.newLinkedList(); + Player player = (Player) sender; + + LinkedList list = Lists.newLinkedList(); + for (int i = 0; i < lastLocations.getOrDefault(player.getUniqueId(), + Lists.newLinkedList()).size(); i++) { + list.add(String.valueOf(i + 1)); + } + return list; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (inTeleport) return; + + // Don't save the teleports of the pregame movement setting + if (!AbstractChallenge.getFirstInstance(PregameMovementSetting.class).isEnabled()) { + if ((event.getPlayer().getGameMode() == GameMode.SURVIVAL || + event.getPlayer().getGameMode() == GameMode.ADVENTURE) && + !ChallengeAPI.isStarted()) { + return; + } + } + if (event.getTo() == null) return; + if (event.getCause() == TeleportCause.ENDER_PEARL || + event.getCause() == TeleportCause.CHORUS_FRUIT) return; + + UUID uuid = event.getPlayer().getUniqueId(); + List locations = lastLocations + .getOrDefault(uuid, Lists.newArrayList()); + lastLocations.putIfAbsent(uuid, locations); + locations.add(0, event.getFrom()); + + if (locations.size() > 30) { + locations.remove(locations.size() - 1); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index cfa0f993a..729716cad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -16,43 +16,39 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class ChallengesCommand implements PlayerCommand, Completer { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (args.length > 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); - return; - } - - if (args.length == 1) { - String menuName = args[0].toUpperCase(); - try { - MenuType menuType = MenuType.valueOf(menuName); - Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); - } catch (IllegalArgumentException exception) { - Challenges.getInstance().getMenuManager().openGUI(player); - } - return; - } - - Challenges.getInstance().getMenuManager().openGUI(player); - - } - - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return args.length != 1 ? null : Utils.filterRecommendations(args[0], - Arrays.stream(MenuType.values()) - .map(menuType -> menuType.name().toLowerCase()) - .toArray(String[]::new) - ); - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (args.length > 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); + return; + } + + if (args.length == 1) { + String menuName = args[0].toUpperCase(); + try { + MenuType menuType = MenuType.valueOf(menuName); + Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); + } catch (IllegalArgumentException exception) { + Challenges.getInstance().getMenuManager().openGUI(player); + } + return; + } + + Challenges.getInstance().getMenuManager().openGUI(player); + + } + + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return args.length != 1 ? null : Utils.filterRecommendations(args[0], + Arrays.stream(MenuType.values()) + .map(menuType -> menuType.name().toLowerCase()) + .toArray(String[]::new) + ); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index fb3a0bdc1..987cc8bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -20,147 +20,143 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DatabaseCommand implements PlayerCommand, TabCompleter { - private final Map databaseExecutors; - private final boolean savePlayerConfigs; - private final boolean savePlayerChallenges; - - public DatabaseCommand() { - savePlayerConfigs = Challenges.getInstance().getConfigDocument().getBoolean("save-player-configs"); - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player-custom_challenges"); - - databaseExecutors = new HashMap<>(); - databaseExecutors.put("settings", new DatabaseCommandExecutor() { - @Override - public void save(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getChallengeManager().saveSettings(player); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void load(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Document config = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("config") - .where("uuid", player.getUniqueId()) - .execute().firstOrEmpty().getDocument("config"); - Challenges.getInstance().getChallengeManager().loadSettings(config); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void reset(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("config", null) - .execute(); - Message.forName("player-config-reset").send(player, Prefix.CHALLENGES); - } - }); - databaseExecutors.put("customs", new DatabaseCommandExecutor() { - - @Override - public void save(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); - Message.forName("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); - } - - @Override - public void load(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Document config = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("custom_challenges") - .where("uuid", player.getUniqueId()) - .execute().firstOrEmpty().getDocument("custom_challenges"); - Challenges.getInstance().getChallengeManager().loadCustomChallenges(config); - Message.forName("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void reset(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("custom_challenges", null) - .execute(); - Message.forName("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); - } - }); - } - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - - if (checkFeatureDisabled(Challenges.getInstance().getDatabaseManager().isConnected(), player)) { - return; - } - - if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); - return; - } - - String type = args[1].toLowerCase(); - DatabaseCommandExecutor executor = databaseExecutors.get(type); - - switch (args[0].toLowerCase()) { - case "save": - executor.save(player); - break; - case "load": - executor.load(player); - break; - case "reset": - executor.reset(player); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); - } - - } - - /** - * Checks for disabled features and sends a proper messages to indicate that - */ - private boolean checkFeatureDisabled(boolean enabled, @Nonnull Player player) { - if (!enabled) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return true; - } - return false; - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - - if (args.length <= 1) { - return Utils.filterRecommendations(args[0], "save", "load", "reset"); - } else if (args.length <= 2) { - return Utils.filterRecommendations(args[1], databaseExecutors.keySet().toArray(new String[0])); - } - return Lists.newLinkedList(); - } - - - private interface DatabaseCommandExecutor { - void save(Player player) throws Exception; - - void load(Player player) throws Exception; - - void reset(Player player) throws Exception; - } + private final Map databaseExecutors; + private final boolean savePlayerConfigs; + private final boolean savePlayerChallenges; + + public DatabaseCommand() { + savePlayerConfigs = Challenges.getInstance().getConfigDocument().getBoolean("save-player-configs"); + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player-custom_challenges"); + + databaseExecutors = new HashMap<>(); + databaseExecutors.put("settings", new DatabaseCommandExecutor() { + @Override + public void save(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Challenges.getInstance().getChallengeManager().saveSettings(player); + Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void load(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Document config = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("config") + .where("uuid", player.getUniqueId()) + .execute().firstOrEmpty().getDocument("config"); + Challenges.getInstance().getChallengeManager().loadSettings(config); + Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void reset(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("config", null) + .execute(); + Message.forName("player-config-reset").send(player, Prefix.CHALLENGES); + } + }); + databaseExecutors.put("customs", new DatabaseCommandExecutor() { + + @Override + public void save(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); + Message.forName("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); + } + + @Override + public void load(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Document config = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("custom_challenges") + .where("uuid", player.getUniqueId()) + .execute().firstOrEmpty().getDocument("custom_challenges"); + Challenges.getInstance().getChallengeManager().loadCustomChallenges(config); + Message.forName("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void reset(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("custom_challenges", null) + .execute(); + Message.forName("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); + } + }); + } + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + + if (checkFeatureDisabled(Challenges.getInstance().getDatabaseManager().isConnected(), player)) { + return; + } + + if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + return; + } + + String type = args[1].toLowerCase(); + DatabaseCommandExecutor executor = databaseExecutors.get(type); + + switch (args[0].toLowerCase()) { + case "save": + executor.save(player); + break; + case "load": + executor.load(player); + break; + case "reset": + executor.reset(player); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + } + + } + + /** + * Checks for disabled features and sends a proper messages to indicate that + */ + private boolean checkFeatureDisabled(boolean enabled, @Nonnull Player player) { + if (!enabled) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return true; + } + return false; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + + if (args.length <= 1) { + return Utils.filterRecommendations(args[0], "save", "load", "reset"); + } else if (args.length == 2) { + return Utils.filterRecommendations(args[1], databaseExecutors.keySet().toArray(new String[0])); + } + return Lists.newLinkedList(); + } + + + private interface DatabaseCommandExecutor { + void save(Player player) throws Exception; + + void load(Player player) throws Exception; + + void reset(Player player) throws Exception; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index d7ad4f38a..381dff108 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -13,48 +13,44 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FeedCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { - target.setFoodLevel(20); - Message.forName("command-feed-fed").send(target, Prefix.CHALLENGES); + boolean otherPlayers = false; + for (Player target : targets) { + target.setFoodLevel(20); + Message.forName("command-feed-fed").send(target, Prefix.CHALLENGES); - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index bdf981f42..e09e858e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -13,53 +13,49 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FlyCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { + boolean otherPlayers = false; + for (Player target : targets) { - if (target.getAllowFlight()) { - Message.forName("command-fly-disabled").send(target, Prefix.CHALLENGES); - } else { - Message.forName("command-fly-enabled").send(target, Prefix.CHALLENGES); - } - target.setAllowFlight(!target.getAllowFlight()); + if (target.getAllowFlight()) { + Message.forName("command-fly-disabled").send(target, Prefix.CHALLENGES); + } else { + Message.forName("command-fly-enabled").send(target, Prefix.CHALLENGES); + } + target.setAllowFlight(!target.getAllowFlight()); - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 6331305a2..3836680ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -16,84 +16,80 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class GamemodeCommand implements SenderCommand, Completer { - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - List targets = new ArrayList<>(); - - if (args.length <= 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); - return; - } - - GameMode gamemode = getGameMode(args[0]); - - if (gamemode == null) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); - return; - } - - if (args.length > 1) { - targets.addAll(CommandHelper.getPlayers(sender, args[1])); - - } else if (sender instanceof Player) { - targets.add(((Player) sender).getPlayer()); - } - - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } - - boolean otherPlayers = false; - - for (Player player : targets) { - Message.forName("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); - player.setGameMode(gamemode); - if (player != sender) - otherPlayers = true; - - } - if (otherPlayers) { - Message.forName("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); - } - - } - - @Nullable - private GameMode getGameMode(String input) { - switch (input.toLowerCase()) { - case "survival": - case "s": - case "0": - return GameMode.SURVIVAL; - case "spectator": - case "sp": - case "3": - return GameMode.SPECTATOR; - case "adventure": - case "a": - case "2": - return GameMode.ADVENTURE; - case "creative": - case "c": - case "1": - return GameMode.CREATIVE; - } - return null; - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 2) return CommandHelper.getCompletions(sender); - if (args.length > 1) return null; - return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); - } - -} \ No newline at end of file + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + List targets = new ArrayList<>(); + + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + return; + } + + GameMode gamemode = getGameMode(args[0]); + + if (gamemode == null) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + return; + } + + if (args.length > 1) { + targets.addAll(CommandHelper.getPlayers(sender, args[1])); + + } else if (sender instanceof Player) { + targets.add(((Player) sender).getPlayer()); + } + + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } + + boolean otherPlayers = false; + + for (Player player : targets) { + Message.forName("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); + player.setGameMode(gamemode); + if (player != sender) + otherPlayers = true; + + } + if (otherPlayers) { + Message.forName("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); + } + + } + + @Nullable + private GameMode getGameMode(String input) { + switch (input.toLowerCase()) { + case "survival": + case "s": + case "0": + return GameMode.SURVIVAL; + case "spectator": + case "sp": + case "3": + return GameMode.SPECTATOR; + case "adventure": + case "a": + case "2": + return GameMode.ADVENTURE; + case "creative": + case "c": + case "1": + return GameMode.CREATIVE; + } + return null; + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length == 2) return CommandHelper.getCompletions(sender); + if (args.length > 1) return null; + return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 54460ea86..ae464b130 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -14,43 +14,39 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class GamestateCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (args.length != 1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); - return; - } - - FileDocument gamestate = Challenges.getInstance().getConfigManager().getGamestateConfig(); - switch (args[0].toLowerCase()) { - case "reset": - gamestate.clear(); - Challenges.getInstance().getChallengeManager().resetGamestate(); - Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reset").send(sender, Prefix.CHALLENGES); - break; - case "reload": - Challenges.getInstance().getChallengeManager().loadGamestate(gamestate.readonly()); - Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reload").send(sender, Prefix.CHALLENGES); - break; - default: - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return args.length == 1 ? Utils.filterRecommendations(args[0], "reset", "reload") : Collections.emptyList(); - } + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (args.length != 1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + return; + } + + FileDocument gamestate = Challenges.getInstance().getConfigManager().getGamestateConfig(); + switch (args[0].toLowerCase()) { + case "reset": + gamestate.clear(); + Challenges.getInstance().getChallengeManager().resetGamestate(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Message.forName("command-gamestate-reset").send(sender, Prefix.CHALLENGES); + break; + case "reload": + Challenges.getInstance().getChallengeManager().loadGamestate(gamestate.readonly()); + Challenges.getInstance().getScoreboardManager().updateAll(); + Message.forName("command-gamestate-reload").send(sender, Prefix.CHALLENGES); + break; + default: + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return args.length == 1 ? Utils.filterRecommendations(args[0], "reset", "reload") : Collections.emptyList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index d273281f6..cfe48f18d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -19,74 +19,70 @@ import java.util.List; import java.util.UUID; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class GodModeCommand implements SenderCommand, Completer, Listener { - private final List godModePlayers = new ArrayList<>(); + private final List godModePlayers = new ArrayList<>(); - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { - if (godModePlayers.contains(target.getUniqueId())) { - godModePlayers.remove(target.getUniqueId()); - Message.forName("command-god-mode-disabled").send(target, Prefix.CHALLENGES); - } else { - godModePlayers.add(target.getUniqueId()); - Message.forName("command-god-mode-enabled").send(target, Prefix.CHALLENGES); - target.setFoodLevel(20); - } + boolean otherPlayers = false; + for (Player target : targets) { + if (godModePlayers.contains(target.getUniqueId())) { + godModePlayers.remove(target.getUniqueId()); + Message.forName("command-god-mode-disabled").send(target, Prefix.CHALLENGES); + } else { + godModePlayers.add(target.getUniqueId()); + Message.forName("command-god-mode-enabled").send(target, Prefix.CHALLENGES); + target.setFoodLevel(20); + } - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onDamage(EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (godModePlayers.contains(player.getUniqueId())) { - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamage(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (godModePlayers.contains(player.getUniqueId())) { + event.setCancelled(true); } - - @EventHandler - private void onFoodLevelChange(FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (godModePlayers.contains(player.getUniqueId())) { - event.setCancelled(true); - } + } + + @EventHandler + private void onFoodLevelChange(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (godModePlayers.contains(player.getUniqueId())) { + event.setCancelled(true); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index e406f136b..314ba6555 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -15,56 +15,52 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class HealCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player player : targets) { - Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute == null) { - player.setHealth(20); - } else { - player.setHealth(attribute.getValue()); - } - player.setFoodLevel(20); - player.setSaturation(20); - player.setFireTicks(0); - player.setFallDistance(0); - player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); + boolean otherPlayers = false; + for (Player player : targets) { + Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) { + player.setHealth(20); + } else { + player.setHealth(attribute.getValue()); + } + player.setFoodLevel(20); + player.setSaturation(20); + player.setFireTicks(0); + player.setFallDistance(0); + player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); - if (player != sender) - otherPlayers = true; - } + if (player != sender) + otherPlayers = true; + } - if (otherPlayers) - Message.forName("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + if (otherPlayers) + Message.forName("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java index 16edf99c0..d5df6bd58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java @@ -5,14 +5,10 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class HelpCommand implements SenderCommand { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - } + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 07eb9fed9..e32682f0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -28,114 +28,110 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class InvseeCommand implements PlayerCommand, Listener { - private static final int - startBottom = 36, - endBottom = 53, - helmetSlot = 46, - chestPlateSlot = 47, - leggingsSlot = 48, - bootsSlot = 49, - offHandSlot = 52; - - private final Map inventories = new HashMap<>(); - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - - if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); - return; - } - - Player target = Bukkit.getPlayer(args[0]); - - if (target == null) { - Message.forName("command-no-target").send(player, Prefix.CHALLENGES); - return; - } - - player.openInventory(getInventory(target)); - MenuPosition.set(player, new SlottedMenuPosition()); - Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); - } - - public Inventory getInventory(@Nonnull Player player) { - if (inventories.containsKey(player)) { - return inventories.get(player); - } - - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("inventory-color").asString() + NameHelper.getName(player))); - inventories.put(player, inventory); - MenuPosition.set(player, event -> { - }); - updateInventoryContents(inventory, player.getInventory()); - return inventory; - } - - public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull PlayerInventory playerInventory) { - inventory.clear(); - - for (int slot = startBottom; slot <= endBottom; slot++) { - inventory.setItem(slot, ItemBuilder.FILL_ITEM); - } - - inventory.setItem(helmetSlot, playerInventory.getHelmet()); - inventory.setItem(chestPlateSlot, playerInventory.getChestplate()); - inventory.setItem(leggingsSlot, playerInventory.getLeggings()); - inventory.setItem(bootsSlot, playerInventory.getBoots()); - inventory.setItem(offHandSlot, playerInventory.getItemInOffHand()); - - for (int slot = 0; slot < 36; slot++) { - inventory.setItem(slot, playerInventory.getItem(slot)); - } - - } - - public void updateInventory(@Nonnull Player player) { - if (!inventories.containsKey(player)) return; - Inventory inventory = inventories.get(player); - updateInventoryContents(inventory, player.getInventory()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { - Inventory inventory = inventories.remove(event.getPlayer()); - if (inventory == null) return; - for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { - viewer.closeInventory(); - } - - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClose(@Nonnull InventoryCloseEvent event) { - if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - for (Entry entry : inventories.entrySet()) { - Inventory inventory = entry.getValue(); - if (inventory.getViewers().isEmpty()) { - inventories.remove(entry.getKey()); - } - } - }, 1); - } - -} \ No newline at end of file + private static final int + startBottom = 36, + endBottom = 53, + helmetSlot = 46, + chestPlateSlot = 47, + leggingsSlot = 48, + bootsSlot = 49, + offHandSlot = 52; + + private final Map inventories = new HashMap<>(); + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (args.length < 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); + return; + } + + Player target = Bukkit.getPlayer(args[0]); + + if (target == null) { + Message.forName("command-no-target").send(player, Prefix.CHALLENGES); + return; + } + + player.openInventory(getInventory(target)); + MenuPosition.set(player, new SlottedMenuPosition()); + Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); + } + + public Inventory getInventory(@Nonnull Player player) { + if (inventories.containsKey(player)) { + return inventories.get(player); + } + + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("inventory-color").asString() + NameHelper.getName(player))); + inventories.put(player, inventory); + MenuPosition.set(player, event -> { + }); + updateInventoryContents(inventory, player.getInventory()); + return inventory; + } + + public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull PlayerInventory playerInventory) { + inventory.clear(); + + for (int slot = startBottom; slot <= endBottom; slot++) { + inventory.setItem(slot, ItemBuilder.FILL_ITEM); + } + + inventory.setItem(helmetSlot, playerInventory.getHelmet()); + inventory.setItem(chestPlateSlot, playerInventory.getChestplate()); + inventory.setItem(leggingsSlot, playerInventory.getLeggings()); + inventory.setItem(bootsSlot, playerInventory.getBoots()); + inventory.setItem(offHandSlot, playerInventory.getItemInOffHand()); + + for (int slot = 0; slot < 36; slot++) { + inventory.setItem(slot, playerInventory.getItem(slot)); + } + + } + + public void updateInventory(@Nonnull Player player) { + if (!inventories.containsKey(player)) return; + Inventory inventory = inventories.get(player); + updateInventoryContents(inventory, player.getInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { + Inventory inventory = inventories.remove(event.getPlayer()); + if (inventory == null) return; + for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { + viewer.closeInventory(); + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClose(@Nonnull InventoryCloseEvent event) { + if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + for (Entry entry : inventories.entrySet()) { + Inventory inventory = entry.getValue(); + if (inventory.getViewers().isEmpty()) { + inventories.remove(entry.getKey()); + } + } + }, 1); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java new file mode 100644 index 000000000..0b10f5325 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -0,0 +1,46 @@ +package net.codingarea.challenges.plugin.spigot.command; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; +import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.challenges.plugin.utils.misc.Utils; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Objects; + +public class LanguageCommand implements SenderCommand, Completer { + + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + if (args.length < 1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + return; + } + switch (args[0].toLowerCase()) { + case "german": + case "deutsch": + case "de": + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); + break; + case "english": + case "englisch": + case "en": + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); + break; + default: + Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); + } + } + + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "german", "english"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 343fca319..605a0a634 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -24,109 +24,106 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class LeaderboardCommand implements PlayerCommand { - protected static final int[] slots = StatsHelper.getSlots(1); - protected static final int[] navigationSlots = {45, 53}; - protected static final AnimatedInventory loadingInventory; - - static { - loadingInventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 6 * 9, MenuPosition.HOLDER).setEndSound(null).setFrameSound(null); - loadingInventory.createAndAdd().fill(ItemBuilder.FILL_ITEM).setItem(31, new ItemBuilder(Material.BARRIER, "§8» §cLoading..")); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } - - createInventory(player).open(player, Challenges.getInstance()); - } - - @Nonnull - @CheckReturnValue - public AnimatedInventory createInventory(@Nonnull Player player) { - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 4 * 9, MenuPosition.HOLDER); - StatsHelper.setAccent(inventory, 2); - SlottedMenuPosition position = new SlottedMenuPosition(); - for (int i = 0; i < Statistic.values().length; i++) { - Statistic statistic = Statistic.values()[i]; - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); - inventory.cloneLastAndAdd().setItem(slots[i], item.hideAttributes()); - position.setAction(slots[i], () -> openMenu(player, statistic, 0, false)); - } - - MenuPosition.set(player, position); - return inventory; - } - - private void openMenu(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { - loadingInventory.open(player, Challenges.getInstance()); - MenuPosition.setEmpty(player); - Challenges.getInstance().runAsync(() -> openMenu0(player, statistic, page, openInstant)); - } - - private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { - - int[] slots = { - 10, 11, 12, 13, 14, 15, 16, - 19, 20, 21, 22, 23, 24, 25, - 28, 29, 30, 31, 32, 33, 34, - 37, 38, 39, 40, 41, 42, 43 - }; - - String statisticName = StatsHelper.getNameMessage(statistic).asString(); - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(ChatColor.stripColor(statisticName), page + 1), 6 * 9, MenuPosition.HOLDER); - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); - - List leaderboard = Challenges.getInstance().getStatsManager().getLeaderboard(statistic); - int pages = leaderboard.size() / slots.length; - if (leaderboard.size() % slots.length > 0) pages++; - int offset = page * slots.length; - - InventoryUtils.setNavigationItemsToFrame(inventory.cloneLastAndAdd(), navigationSlots, true, page, pages); - SlottedMenuPosition position = new SlottedMenuPosition(); - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - - for (int i = offset; i < leaderboard.size() && i < offset + slots.length; i++) { - int slot = slots[i - offset]; - PlayerStats stats = leaderboard.get(i); - String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); - ItemBuilder item = new SkullBuilder(stats.getPlayerUUID(), stats.getPlayerName()).setName(Message.forName("stats-leaderboard-display") - .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); - inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); - - position.setAction(slot, () -> { - MenuPosition.setEmpty(player); - loadingInventory.open(player, Challenges.getInstance()); - player.performCommand("stats " + stats.getPlayerName()); - }); - } - - position.setAction(navigationSlots[0], info -> { - if (page == 0 || info.isShiftClick()) { - createInventory(player).openNotAnimated(player, true, Challenges.getInstance()); - } else { - openMenu(player, statistic, page - 1, true); - } - }); - if (inventory.getLastFrame().getItemType(navigationSlots[1]) == Material.PLAYER_HEAD) - position.setAction(navigationSlots[1], () -> openMenu(player, statistic, page + 1, true)); - - if (openInstant) inventory.openNotAnimated(player, true, Challenges.getInstance()); - else inventory.open(player, Challenges.getInstance()); - MenuPosition.set(player, position); - } + protected static final int[] slots = StatsHelper.getSlots(1); + protected static final int[] navigationSlots = {45, 53}; + protected static final AnimatedInventory loadingInventory; + + static { + loadingInventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 6 * 9, MenuPosition.HOLDER).setEndSound(null).setFrameSound(null); + loadingInventory.createAndAdd().fill(ItemBuilder.FILL_ITEM).setItem(31, new ItemBuilder(Material.BARRIER, "§8» §cLoading..")); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (!Challenges.getInstance().getStatsManager().isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { + Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } + + createInventory(player).open(player, Challenges.getInstance()); + } + + @Nonnull + @CheckReturnValue + public AnimatedInventory createInventory(@Nonnull Player player) { + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 4 * 9, MenuPosition.HOLDER); + StatsHelper.setAccent(inventory, 2); + SlottedMenuPosition position = new SlottedMenuPosition(); + for (int i = 0; i < Statistic.values().length; i++) { + Statistic statistic = Statistic.values()[i]; + ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); + inventory.cloneLastAndAdd().setItem(slots[i], item.hideAttributes()); + position.setAction(slots[i], () -> openMenu(player, statistic, 0, false)); + } + + MenuPosition.set(player, position); + return inventory; + } + + private void openMenu(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + loadingInventory.open(player, Challenges.getInstance()); + MenuPosition.setEmpty(player); + Challenges.getInstance().runAsync(() -> openMenu0(player, statistic, page, openInstant)); + } + + private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + + int[] slots = { + 10, 11, 12, 13, 14, 15, 16, + 19, 20, 21, 22, 23, 24, 25, + 28, 29, 30, 31, 32, 33, 34, + 37, 38, 39, 40, 41, 42, 43 + }; + + String statisticName = StatsHelper.getNameMessage(statistic).asString(); + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(ChatColor.stripColor(statisticName), page + 1), 6 * 9, MenuPosition.HOLDER); + inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + + List leaderboard = Challenges.getInstance().getStatsManager().getLeaderboard(statistic); + int pages = leaderboard.size() / slots.length; + if (leaderboard.size() % slots.length > 0) pages++; + int offset = page * slots.length; + + InventoryUtils.setNavigationItemsToFrame(inventory.cloneLastAndAdd(), navigationSlots, true, page, pages); + SlottedMenuPosition position = new SlottedMenuPosition(); + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + + for (int i = offset; i < leaderboard.size() && i < offset + slots.length; i++) { + int slot = slots[i - offset]; + PlayerStats stats = leaderboard.get(i); + String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); + ItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) + .setName(Message.forName("stats-leaderboard-display") + .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); + inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); + + position.setAction(slot, () -> { + MenuPosition.setEmpty(player); + loadingInventory.open(player, Challenges.getInstance()); + player.performCommand("stats " + stats.getPlayerName()); + }); + } + + position.setAction(navigationSlots[0], info -> { + if (page == 0 || info.isShiftClick()) { + createInventory(player).openNotAnimated(player, true, Challenges.getInstance()); + } else { + openMenu(player, statistic, page - 1, true); + } + }); + if (inventory.getLastFrame().getItemType(navigationSlots[1]) == Material.PLAYER_HEAD) + position.setAction(navigationSlots[1], () -> openMenu(player, statistic, page + 1, true)); + + if (openInstant) inventory.openNotAnimated(player, true, Challenges.getInstance()); + else inventory.open(player, Challenges.getInstance()); + MenuPosition.set(player, position); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 547e55374..e463a4d51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -16,84 +16,80 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class ResetCommand implements SenderCommand, Completer { - private final boolean confirmReset, seedResetCommand; - - public ResetCommand() { - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - confirmReset = pluginConfig.getBoolean("confirm-reset"); - - Document seedResetConfig = pluginConfig.getDocument("custom-seed"); - seedResetCommand = seedResetConfig.getBoolean("command"); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - - if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { - if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { - Challenges.getInstance().getChallengeManager().restoreDefaults(); - Message.forName("config-reset").broadcast(Prefix.CHALLENGES); - return; - } else if (args.length > 0 && args[0].equalsIgnoreCase("customs")) { - Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); - Message.forName("custom_challenges-reset").broadcast(Prefix.CHALLENGES); - return; - } - - if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - if (confirmReset) { - Message.forName("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); - return; - } - } - - if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - Long seed = null; - - if (seedResetCommand) { - int index = confirmReset ? 1 : 0; - if (args.length > index) { - String seedInput = args[index]; - try { - seed = Long.parseLong(seedInput); - } catch (NumberFormatException exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - Challenges.getInstance().getWorldManager().prepareWorldReset(sender, seed); - - } - - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (confirmReset && args.length == 1) return Utils.filterRecommendations( - args[0], "confirm", "settings", "customs"); - if (seedResetCommand && ((confirmReset && args.length == 2) || args.length == 1)) { - return args.length == 1 ? - Utils.filterRecommendations(args[args.length - 1], "[seed]", "settings", "customs") : - args[0].equalsIgnoreCase("confirm") ? Collections.singletonList("[seed]") : Lists - .newLinkedList(); - } - - return Lists.newLinkedList(); - } + private final boolean confirmReset, seedResetCommand; + + public ResetCommand() { + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + confirmReset = pluginConfig.getBoolean("confirm-reset"); + + Document seedResetConfig = pluginConfig.getDocument("custom-seed"); + seedResetCommand = seedResetConfig.getBoolean("command"); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + + if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { + if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { + Challenges.getInstance().getChallengeManager().restoreDefaults(); + Message.forName("config-reset").broadcast(Prefix.CHALLENGES); + return; + } else if (args.length > 0 && args[0].equalsIgnoreCase("customs")) { + Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); + Message.forName("custom_challenges-reset").broadcast(Prefix.CHALLENGES); + return; + } + + if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { + Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + if (confirmReset) { + Message.forName("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); + return; + } + } + + if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { + Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + Long seed = null; + + if (seedResetCommand) { + int index = confirmReset ? 1 : 0; + if (args.length > index) { + String seedInput = args[index]; + try { + seed = Long.parseLong(seedInput); + } catch (NumberFormatException exception) { + Challenges.getInstance().getILogger().error("", exception); + } + } + } + + Challenges.getInstance().getWorldManager().prepareWorldReset(sender, seed); + + } + + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (confirmReset && args.length == 1) return Utils.filterRecommendations( + args[0], "confirm", "settings", "customs"); + if (seedResetCommand && ((confirmReset && args.length == 2) || args.length == 1)) { + return args.length == 1 ? + Utils.filterRecommendations(args[args.length - 1], "[seed]", "settings", "customs") : + args[0].equalsIgnoreCase("confirm") ? Collections.singletonList("[seed]") : Lists + .newLinkedList(); + } + + return Lists.newLinkedList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index a506664db..c5f7ef062 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -11,27 +11,23 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.4 - */ public class ResultCommand implements PlayerCommand { - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (currentGoal instanceof ForceBattleGoal) { - ForceBattleGoal forceBattleGoal = (ForceBattleGoal) currentGoal; - forceBattleGoal.sendResult(player); - return; - } + if (currentGoal instanceof ForceBattleGoal) { + ForceBattleGoal forceBattleGoal = (ForceBattleGoal) currentGoal; + forceBattleGoal.sendResult(player); + return; + } - Message.forName("command-result-no-battle-active").send(player, Prefix.CHALLENGES); - } + Message.forName("command-result-no-battle-active").send(player, Prefix.CHALLENGES); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 1908296f7..1997de2b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -22,57 +22,53 @@ import java.util.Map.Entry; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class SearchCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); - return; - } + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); + return; + } - String input = String.join("_", args).toUpperCase(); - Material material = Utils.getMaterial(input); + String input = String.join("_", args).toUpperCase(); + Material material = Utils.getMaterial(input); - if (material == null) { - Message.forName("no-such-material").send(sender, Prefix.CHALLENGES); - return; - } - if (!material.isItem()) { - Message.forName("not-an-item").send(sender, Prefix.CHALLENGES, material); - return; - } + if (material == null) { + Message.forName("no-such-material").send(sender, Prefix.CHALLENGES); + return; + } + if (!material.isItem()) { + Message.forName("not-an-item").send(sender, Prefix.CHALLENGES, material); + return; + } - Map allDrops = Challenges.getInstance().getBlockDropManager().getRegisteredDrops(); + Map allDrops = Challenges.getInstance().getBlockDropManager().getRegisteredDrops(); - List blocks = new ArrayList<>(1); - for (Entry entry : allDrops.entrySet()) { - List drops = entry.getValue().getFirst().orElse(new ArrayList<>()); - if (drops.contains(material)) - blocks.add(entry.getKey()); - } + List blocks = new ArrayList<>(1); + for (Entry entry : allDrops.entrySet()) { + List drops = entry.getValue().getFirst().orElse(new ArrayList<>()); + if (drops.contains(material)) + blocks.add(entry.getKey()); + } - if (blocks.isEmpty()) { - Message.forName("command-search-nothing").send(sender, Prefix.CHALLENGES, material); - } else { - Message.forName("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); - } - } + if (blocks.isEmpty()) { + Message.forName("command-search-nothing").send(sender, Prefix.CHALLENGES, material); + } else { + Message.forName("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); + } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return args.length != 1 ? null : - Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(ItemUtils::isObtainableInSurvival) - .filter(Material::isItem) - .map(material -> material.name().toLowerCase()) - .collect(Collectors.toList()); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return args.length != 1 ? null : + Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(ItemUtils::isObtainableInSurvival) + .filter(Material::isItem) + .map(material -> material.name().toLowerCase()) + .collect(Collectors.toList()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 955c71e30..875387c43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -12,27 +12,23 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class SkipTimerCommand implements SenderCommand, Completer { - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { - if (!challenge.isEnabled()) continue; - if (challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; - timedChallenge.setSecondsUntilActivation(0); - } - } - } + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { + if (!challenge.isEnabled()) continue; + if (challenge instanceof TimedChallenge) { + TimedChallenge timedChallenge = (TimedChallenge) challenge; + timedChallenge.setSecondsUntilActivation(0); + } + } + } - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return Collections.emptyList(); - } + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Collections.emptyList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 057a6289b..d14ea9e61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -25,100 +25,95 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public class StatsCommand implements PlayerCommand { - private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } - - if (System.currentTimeMillis() - submitTimeByPlayer.getOrDefault(player, System.currentTimeMillis() - 10 * 1000) < 5 * 1000) { - SoundSample.BASS_OFF.play(player); - return; - } - submitTimeByPlayer.put(player, System.currentTimeMillis()); - - switch (args.length) { - case 0: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); - handleCommand(player); - break; - case 1: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); - handleCommand(player, args[0]); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); - } - } - - private void handleCommand(@Nonnull Player player) { - Challenges.getInstance().runAsync(() -> { - open(player, player.getUniqueId(), player.getName()); - }); - } - - private void handleCommand(@Nonnull Player player, @Nonnull String name) { - Challenges.getInstance().runAsync(() -> { - Player target = Bukkit.getPlayer(name); - if (target != null) { - open(player, target.getUniqueId(), target.getName()); - return; - } - - try { - UUID uuid = Utils.fetchUUID(name); - open(player, uuid, name); - } catch (IOException ex) { - player.sendMessage(Prefix.CHALLENGES + "§7Something went wrong"); - } - }); - } - - private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String name) { - - PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(uuid, name); - name = stats.getPlayerName(); - - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(uuid) ? cloudSupport.getColoredName(uuid) : name; - - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getStatsTitle(name), 5 * 9, MenuPosition.HOLDER); - StatsHelper.setAccent(inventory, 3); - inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(uuid, name, Message.forName("stats-of").asString(coloredName)).build()); - - LeaderboardInfo info = Challenges.getInstance().getStatsManager().getLeaderboardInfo(uuid); - createInventory(stats, info, inventory, StatsHelper.getSlots(2)); - - MenuPosition.setEmpty(player); - inventory.open(player, Challenges.getInstance()); - - submitTimeByPlayer.remove(player); - } - - private void createInventory(@Nonnull PlayerStats stats, @Nonnull LeaderboardInfo info, @Nonnull AnimatedInventory inventory, @Nonnull int... slots) { - for (int i = 0; i < Statistic.values().length; i++) { - Statistic statistic = Statistic.values()[i]; - double value = stats.getStatisticValue(statistic); - String format = statistic.formatChat(value); - - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); - inventory.cloneLastAndAdd().setItem(slots[i], item); - } - } + private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!Challenges.getInstance().getStatsManager().isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { + Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } + + if (System.currentTimeMillis() - submitTimeByPlayer.getOrDefault(player, System.currentTimeMillis() - 10 * 1000) < 5 * 1000) { + SoundSample.BASS_OFF.play(player); + return; + } + submitTimeByPlayer.put(player, System.currentTimeMillis()); + + switch (args.length) { + case 0: + Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + handleCommand(player); + break; + case 1: + Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + handleCommand(player, args[0]); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); + } + } + + private void handleCommand(@Nonnull Player player) { + Challenges.getInstance().runAsync(() -> { + open(player, player.getUniqueId(), player.getName()); + }); + } + + private void handleCommand(@Nonnull Player player, @Nonnull String name) { + Challenges.getInstance().runAsync(() -> { + Player target = Bukkit.getPlayer(name); + if (target != null) { + open(player, target.getUniqueId(), target.getName()); + return; + } + + try { + UUID uuid = Utils.fetchUUID(name); + open(player, uuid, name); + } catch (IOException ex) { + player.sendMessage(Prefix.CHALLENGES + "§7Something went wrong"); + } + }); + } + + private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String name) { + + PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(uuid, name); + name = stats.getPlayerName(); + + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(uuid) ? cloudSupport.getColoredName(uuid) : name; + + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getStatsTitle(name), 5 * 9, MenuPosition.HOLDER); + StatsHelper.setAccent(inventory, 3); + inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(Message.forName("stats-of").asString(coloredName)).setOwner(uuid, name).build()); + + LeaderboardInfo info = Challenges.getInstance().getStatsManager().getLeaderboardInfo(uuid); + createInventory(stats, info, inventory, StatsHelper.getSlots(2)); + + MenuPosition.setEmpty(player); + inventory.open(player, Challenges.getInstance()); + + submitTimeByPlayer.remove(player); + } + + private void createInventory(@Nonnull PlayerStats stats, @Nonnull LeaderboardInfo info, @Nonnull AnimatedInventory inventory, @Nonnull int... slots) { + for (int i = 0; i < Statistic.values().length; i++) { + Statistic statistic = Statistic.values()[i]; + double value = stats.getStatisticValue(statistic); + String format = statistic.formatChat(value); + + ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); + inventory.cloneLastAndAdd().setItem(slots[i], item); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 274cdb835..de37a99cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; @@ -15,130 +15,126 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class TimeCommand implements PlayerCommand, Completer { - private final Map names; + private final Map names; - public TimeCommand() { - names = new HashMap<>(); - names.put(1000L, "Day"); - names.put(6000L, "Noon"); - names.put(13000L, "Night"); - names.put(18000L, "Midnight"); - } + public TimeCommand() { + names = new HashMap<>(); + names.put(1000L, "Day"); + names.put(6000L, "Noon"); + names.put(13000L, "Night"); + names.put(18000L, "Midnight"); + } - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (args.length <= 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); - return; - } - World world = player.getWorld(); + if (args.length == 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); + return; + } + World world = player.getWorld(); - switch (args[0].toLowerCase()) { - case "day": - player.performCommand("time set day"); - break; - case "night": - player.performCommand("time set night"); - break; - case "noon": - player.performCommand("time set noon"); - break; - case "midnight": - player.performCommand("time set midnight"); - break; - case "set": { - if (args.length <= 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); - break; - } - long time = getTime(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); - break; - } - world.setTime(time); - if (names.containsKey(time)) { - String timeName = names.get(time).toLowerCase(); - String timeTranslation = Message.forName("command-time-" + timeName).asString(); - Message.forName("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); - } else { - Message.forName("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); - } - break; - } - case "add": { - if (args.length <= 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); - break; - } - long time = getLongFromString(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); - break; - } - player.performCommand("time set " + (world.getTime() + time)); - break; - } - case "subtract": { - if (args.length <= 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); - break; - } - long time = getLongFromString(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); - break; - } - player.performCommand("time set " + (world.getTime() - time)); - break; - } - case "query": { - Message.forName("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); - break; - } + switch (args[0].toLowerCase()) { + case "day": + player.performCommand("time set day"); + break; + case "night": + player.performCommand("time set night"); + break; + case "noon": + player.performCommand("time set noon"); + break; + case "midnight": + player.performCommand("time set midnight"); + break; + case "set": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + break; + } + long time = getTime(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + break; + } + world.setTime(time); + if (names.containsKey(time)) { + String timeName = names.get(time).toLowerCase(); + String timeTranslation = Message.forName("command-time-" + timeName).asString(); + Message.forName("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); + } else { + Message.forName("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); + } + break; + } + case "add": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + break; + } + long time = getLongFromString(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + break; + } + player.performCommand("time set " + (world.getTime() + time)); + break; + } + case "subtract": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + break; + } + long time = getLongFromString(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + break; + } + player.performCommand("time set " + (world.getTime() - time)); + break; + } + case "query": { + Message.forName("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); + break; + } - } + } - } + } - private String getNearestTime(@Nonnull World world) { - return names.entrySet().stream() - .min(Comparator.comparingLong(entry -> Math.abs(world.getTime() - entry.getKey()))) - .map(Entry::getValue) - .orElse("Day"); - } + private String getNearestTime(@Nonnull World world) { + return names.entrySet().stream() + .min(Comparator.comparingLong(entry -> Math.abs(world.getTime() - entry.getKey()))) + .map(Entry::getValue) + .orElse("Day"); + } - private long getTime(@Nonnull String input) { - for (Entry entry : names.entrySet()) { - if (entry.getValue().equalsIgnoreCase(input)) - return entry.getKey(); - } - return getLongFromString(input); - } + private long getTime(@Nonnull String input) { + for (Entry entry : names.entrySet()) { + if (entry.getValue().equalsIgnoreCase(input)) + return entry.getKey(); + } + return getLongFromString(input); + } - private long getLongFromString(@Nonnull String input) { - try { - return Long.parseLong(input); - } catch (NumberFormatException ex) { - return -1; - } - } + private long getLongFromString(@Nonnull String input) { + try { + return Long.parseLong(input); + } catch (NumberFormatException ex) { + return -1; + } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length <= 1) - return Utils.filterRecommendations(args[0], "set", "subtract", "query", "day", "night", "noon", "midnight"); - if (args[0].equalsIgnoreCase("set")) - return Utils.filterRecommendations(args[1], "day", "night", "noon", "midnight"); - return new ArrayList<>(); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length <= 1) + return Utils.filterRecommendations(args[0], "set", "subtract", "query", "day", "night", "noon", "midnight"); + if (args[0].equalsIgnoreCase("set")) + return Utils.filterRecommendations(args[1], "day", "night", "noon", "midnight"); + return new ArrayList<>(); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index b775201be..c1a6a2e8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -19,99 +19,95 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class TimerCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 0) { - if (sender instanceof Player) { - Player player = (Player) sender; - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.TIMER, 0); - SoundSample.OPEN.play(player); - } - return; - } + if (args.length == 0) { + if (sender instanceof Player) { + Player player = (Player) sender; + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.TIMER, 0); + SoundSample.OPEN.play(player); + } + return; + } - switch (args[0].toLowerCase()) { - default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer "); - return; - case "resume": - case "start": - if (ChallengeAPI.isStarted()) { - Message.forName("timer-already-started").send(sender, Prefix.TIMER); - SoundSample.BASS_OFF.playIfPlayer(sender); - break; - } - Challenges.getInstance().getChallengeTimer().resume(); - break; - case "stop": - case "pause": - if (ChallengeAPI.isPaused()) { - Message.forName("timer-already-paused").send(sender, Prefix.TIMER); - SoundSample.BASS_OFF.playIfPlayer(sender); - break; - } - Challenges.getInstance().getChallengeTimer().pause(true); - break; - case "reset": - Challenges.getInstance().getChallengeTimer().reset(); - break; - case "set": - long seconds = StringUtils.parseSeconds(String.join(" ", args)); - if (seconds >= Integer.MAX_VALUE || seconds < 0) { - seconds = Integer.MAX_VALUE; - } - Challenges.getInstance().getChallengeTimer().setSeconds(seconds); - Message.forName("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); - break; - case "show": - Challenges.getInstance().getChallengeTimer().setHidden(false); - break; - case "hide": - Challenges.getInstance().getChallengeTimer().setHidden(true); - break; - case "mode": - if (args.length != 2) { - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); - break; - } - switch (args[1].toLowerCase()) { - default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); - break; - case "up": - case "forward": - Challenges.getInstance().getChallengeTimer().setCountingUp(true); - break; - case "down": - case "back": - case "backwards": - Challenges.getInstance().getChallengeTimer().setCountingUp(false); - break; - } + switch (args[0].toLowerCase()) { + default: + Message.forName("syntax").send(sender, Prefix.TIMER, "timer "); + return; + case "resume": + case "start": + if (ChallengeAPI.isStarted()) { + Message.forName("timer-already-started").send(sender, Prefix.TIMER); + SoundSample.BASS_OFF.playIfPlayer(sender); + break; + } + Challenges.getInstance().getChallengeTimer().resume(); + break; + case "stop": + case "pause": + if (ChallengeAPI.isPaused()) { + Message.forName("timer-already-paused").send(sender, Prefix.TIMER); + SoundSample.BASS_OFF.playIfPlayer(sender); + break; + } + Challenges.getInstance().getChallengeTimer().pause(true); + break; + case "reset": + Challenges.getInstance().getChallengeTimer().reset(); + break; + case "set": + long seconds = StringUtils.parseSeconds(String.join(" ", args)); + if (seconds >= Integer.MAX_VALUE || seconds < 0) { + seconds = Integer.MAX_VALUE; + } + Challenges.getInstance().getChallengeTimer().setSeconds(seconds); + Message.forName("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); + break; + case "show": + Challenges.getInstance().getChallengeTimer().setHidden(false); + break; + case "hide": + Challenges.getInstance().getChallengeTimer().setHidden(true); + break; + case "mode": + if (args.length != 2) { + Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + break; + } + switch (args[1].toLowerCase()) { + case "up": + case "forward": + Challenges.getInstance().getChallengeTimer().setCountingUp(true); + break; + case "down": + case "back": + case "backwards": + Challenges.getInstance().getChallengeTimer().setCountingUp(false); + break; + default: + Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + break; + } - } + } - } + } - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 0) return new ArrayList<>(); - String last = args[args.length - 1]; - if (args.length == 1) { - return Utils.filterRecommendations(args[0], "resume", "pause", "stop", "start", "reset", "show", "hide", "mode", "set"); - } else if (args.length == 2 && "mode".equalsIgnoreCase(args[0])) { - return Utils.filterRecommendations(args[1], "up", "down"); - } else if ("set".equalsIgnoreCase(args[0])) { - return StringUtils.isNumber(last) ? Utils.filterRecommendations(last, last + "m", last + "h", last + "d", last + "w") : last.isEmpty() ? Arrays.asList("10", "30", "60", "120") : Collections.singletonList(last); - } - return new ArrayList<>(); - } + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length == 0) return new ArrayList<>(); + String last = args[args.length - 1]; + if (args.length == 1) { + return Utils.filterRecommendations(args[0], "resume", "pause", "stop", "start", "reset", "show", "hide", "mode", "set"); + } else if (args.length == 2 && "mode".equalsIgnoreCase(args[0])) { + return Utils.filterRecommendations(args[1], "up", "down"); + } else if ("set".equalsIgnoreCase(args[0])) { + return StringUtils.isNumber(last) ? Utils.filterRecommendations(last, last + "m", last + "h", last + "d", last + "w") : last.isEmpty() ? Arrays.asList("10", "30", "60", "120") : Collections.singletonList(last); + } + return new ArrayList<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index 2fd574faf..41b8f4d89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -12,37 +12,33 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class VillageCommand implements PlayerCommand { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - player.setNoDamageTicks(10); - Message.forName("command-village-search").send(player, Prefix.CHALLENGES); + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + player.setNoDamageTicks(10); + Message.forName("command-village-search").send(player, Prefix.CHALLENGES); - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); - if (village == null) { - Message.forName("command-village-not-found").send(player, Prefix.CHALLENGES); - return; - } + Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); + if (village == null) { + Message.forName("command-village-not-found").send(player, Prefix.CHALLENGES); + return; + } - village = player.getWorld().getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); - village.getChunk().load(true); + village = player.getWorld().getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); + village.getChunk().load(true); - Location finalVillage = village; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - player.teleport(finalVillage); - SoundSample.TELEPORT.play(player); - Message.forName("command-village-teleport").send(player, Prefix.CHALLENGES); - }, 20 /* run after 1 second to give the chunks/world time to load/generate */); + Location finalVillage = village; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + player.teleport(finalVillage); + SoundSample.TELEPORT.play(player); + Message.forName("command-village-teleport").send(player, Prefix.CHALLENGES); + }, 20 /* run after 1 second to give the chunks/world time to load/generate */); - }); + }); - } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index 07726539a..67244e1d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -14,51 +14,47 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class WeatherCommand implements PlayerCommand, Completer { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - - if (args.length == 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); - return; - } - - World world = player.getWorld(); - - switch (args[0].toLowerCase()) { - - case "clear": - case "sun": - world.setStorm(false); - world.setThundering(false); - Message.forName("command-weather-set-clear").send(player, Prefix.CHALLENGES); - break; - case "rain": - world.setThundering(false); - world.setStorm(true); - Message.forName("command-weather-set-rain").send(player, Prefix.CHALLENGES); - break; - case "thunder": - world.setStorm(true); - world.setThundering(true); - Message.forName("command-weather-set-thunder").send(player, Prefix.CHALLENGES); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); - } - -} \ No newline at end of file + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (args.length == 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + return; + } + + World world = player.getWorld(); + + switch (args[0].toLowerCase()) { + + case "clear": + case "sun": + world.setStorm(false); + world.setThundering(false); + Message.forName("command-weather-set-clear").send(player, Prefix.CHALLENGES); + break; + case "rain": + world.setThundering(false); + world.setStorm(true); + Message.forName("command-weather-set-rain").send(player, Prefix.CHALLENGES); + break; + case "thunder": + world.setStorm(true); + world.setThundering(true); + Message.forName("command-weather-set-thunder").send(player, Prefix.CHALLENGES); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index f8f99b2b6..30157b8a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -20,70 +20,66 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class WorldCommand implements PlayerCommand, TabCompleter { - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + if (args.length < 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - String worldName = args[0]; + String worldName = args[0]; - Environment environment = PositionSetting.getWorldEnvironment(worldName); + Environment environment = PositionSetting.getWorldEnvironment(worldName); - boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); - if (environment == null && !targetIsVoidMap) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); + if (environment == null && !targetIsVoidMap) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); - if (world == null) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); + if (world == null) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - Location location = getSpawn(world, player); + Location location = getSpawn(world, player); - Message.forName("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); - player.teleport(location); - } + Message.forName("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); + player.teleport(location); + } - public Location getSpawn(@Nonnull World world, @Nonnull Player player) { - Location location = world.getSpawnLocation(); - Location bedSpawnLocation = player.getBedSpawnLocation(); - if (bedSpawnLocation != null && bedSpawnLocation.getWorld() == world) { - location = bedSpawnLocation; - } else if (world.getEnvironment() == Environment.THE_END) { - location = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); - } - return location; - } + public Location getSpawn(@Nonnull World world, @Nonnull Player player) { + Location location = world.getSpawnLocation(); + Location bedSpawnLocation = player.getBedSpawnLocation(); + if (bedSpawnLocation != null && bedSpawnLocation.getWorld() == world) { + location = bedSpawnLocation; + } else if (world.getEnvironment() == Environment.THE_END) { + location = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); + } + return location; + } - public String getWorldName(@Nonnull Location location) { - if (location.getWorld() == null) return "?"; - switch (location.getWorld().getEnvironment()) { - default: - return "Overworld"; - case NETHER: - return "Nether"; - case THE_END: - return "End"; - } - } + public String getWorldName(@Nonnull Location location) { + if (location.getWorld() == null) return "?"; + switch (location.getWorld().getEnvironment()) { + default: + return "Overworld"; + case NETHER: + return "Nether"; + case THE_END: + return "End"; + } + } - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - return Utils.filterRecommendations(args[0], "Overworld", "Nether", "End", "Void"); - } + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "Overworld", "Nether", "End", "Void"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java index 96c69d567..bff29d436 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java @@ -8,46 +8,42 @@ import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EntityDamageByPlayerEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - @Getter + @Getter private final Player damager; - @Getter + @Getter private final double finalDamage; - private final Cancellable parentEvent; + private final Cancellable parentEvent; - public EntityDamageByPlayerEvent(@NotNull Entity victim, Player damager, double finalDamage, Cancellable parent) { - super(victim); - this.damager = damager; - this.finalDamage = finalDamage; - this.parentEvent = parent; - } + public EntityDamageByPlayerEvent(@NotNull Entity victim, Player damager, double finalDamage, Cancellable parent) { + super(victim); + this.damager = damager; + this.finalDamage = finalDamage; + this.parentEvent = parent; + } - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } @Override - public boolean isCancelled() { - return parentEvent.isCancelled(); - } - - @Override - public void setCancelled(boolean cancel) { - parentEvent.setCancelled(cancel); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + public boolean isCancelled() { + return parentEvent.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) { + parentEvent.setCancelled(cancel); + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java index 5263b12d8..038c48cd1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java @@ -8,43 +8,39 @@ import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EntityDeathByPlayerEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - @Getter - private final Player killer; - private final Cancellable parentEvent; - - public EntityDeathByPlayerEvent(@NotNull Entity victim, Player killer, Cancellable parent) { - super(victim); - this.killer = killer; - this.parentEvent = parent; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return parentEvent.isCancelled(); - } - - @Override - public void setCancelled(boolean cancel) { - parentEvent.setCancelled(cancel); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + private static final HandlerList handlers = new HandlerList(); + + @Getter + private final Player killer; + private final Cancellable parentEvent; + + public EntityDeathByPlayerEvent(@NotNull Entity victim, Player killer, Cancellable parent) { + super(victim); + this.killer = killer; + this.parentEvent = parent; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return parentEvent.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) { + parentEvent.setCancelled(cancel); + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java index ee878c652..93b836718 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java @@ -14,116 +14,112 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class InventoryClickEventWrapper extends Event { - private final InventoryClickEvent event; - - public InventoryClickEventWrapper(@Nonnull InventoryClickEvent event) { - this.event = event; - } - - @Nullable - public Inventory getClickedInventory() { - return event.getClickedInventory(); - } - - @Nonnull - public Inventory getInventory() { - return event.getInventory(); - } - - @Nonnull - public InventoryView getView() { - return event.getView(); - } - - @Nonnull - public ClickType getClick() { - return event.getClick(); - } - - @Nonnull - public HumanEntity getWhoClicked() { - return event.getWhoClicked(); - } - - public int getSlot() { - return event.getSlot(); - } - - public int getRawSlot() { - return event.getRawSlot(); - } - - @Nonnull - public InventoryAction getAction() { - return event.getAction(); - } - - @Nullable - public ItemStack getCursor() { - return event.getCursor(); - } - - public int getHotbarButton() { - return event.getHotbarButton(); - } - - @Nonnull - public SlotType getSlotType() { - return event.getSlotType(); - } - - @Nonnull - public Result getResult() { - return event.getResult(); - } - - public void setResult(@Nonnull Result result) { - event.setResult(result); - } - - @Nullable - public ItemStack getCurrentItem() { - return event.getCurrentItem(); - } - - public void setCurrentItem(@Nullable ItemStack item) { - event.setCurrentItem(item); - } - - @Nonnull - public List getViewers() { - return event.getViewers(); - } - - @Nonnull - public InventoryClickEvent getEvent() { - return event; - } - - public boolean isCancelled() { - return event.isCancelled(); - } - - public void setCancelled(boolean cancel) { - event.setCancelled(cancel); - } - - public boolean isRightClick() { - return event.isRightClick(); - } - - public boolean isLeftClick() { - return event.isLeftClick(); - } - - public boolean isShiftClick() { - return event.isShiftClick(); - } - -} \ No newline at end of file + private final InventoryClickEvent event; + + public InventoryClickEventWrapper(@Nonnull InventoryClickEvent event) { + this.event = event; + } + + @Nullable + public Inventory getClickedInventory() { + return event.getClickedInventory(); + } + + @Nonnull + public Inventory getInventory() { + return event.getInventory(); + } + + @Nonnull + public InventoryView getView() { + return event.getView(); + } + + @Nonnull + public ClickType getClick() { + return event.getClick(); + } + + @Nonnull + public HumanEntity getWhoClicked() { + return event.getWhoClicked(); + } + + public int getSlot() { + return event.getSlot(); + } + + public int getRawSlot() { + return event.getRawSlot(); + } + + @Nonnull + public InventoryAction getAction() { + return event.getAction(); + } + + @Nullable + public ItemStack getCursor() { + return event.getCursor(); + } + + public int getHotbarButton() { + return event.getHotbarButton(); + } + + @Nonnull + public SlotType getSlotType() { + return event.getSlotType(); + } + + @Nonnull + public Result getResult() { + return event.getResult(); + } + + public void setResult(@Nonnull Result result) { + event.setResult(result); + } + + @Nullable + public ItemStack getCurrentItem() { + return event.getCurrentItem(); + } + + public void setCurrentItem(@Nullable ItemStack item) { + event.setCurrentItem(item); + } + + @Nonnull + public List getViewers() { + return event.getViewers(); + } + + @Nonnull + public InventoryClickEvent getEvent() { + return event; + } + + public boolean isCancelled() { + return event.isCancelled(); + } + + public void setCancelled(boolean cancel) { + event.setCancelled(cancel); + } + + public boolean isRightClick() { + return event.isRightClick(); + } + + public boolean isLeftClick() { + return event.isLeftClick(); + } + + public boolean isShiftClick() { + return event.isShiftClick(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java index 32043c476..97da8cd8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java @@ -5,38 +5,34 @@ import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class PlayerIgnoreStatusChangeEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private final boolean isIgnored; + private final boolean isIgnored; - public PlayerIgnoreStatusChangeEvent(@NotNull Player who, boolean isIgnored) { - super(who); - this.isIgnored = isIgnored; - } + public PlayerIgnoreStatusChangeEvent(@NotNull Player who, boolean isIgnored) { + super(who); + this.isIgnored = isIgnored; + } - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } - public boolean isIgnored() { - return isIgnored; - } + public boolean isIgnored() { + return isIgnored; + } - public boolean isNotIgnored() { - return !isIgnored; - } + public boolean isNotIgnored() { + return !isIgnored; + } - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index 9f8bf56ed..ff347c0a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -7,31 +7,27 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ +@Getter public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - @Getter - private final Player player; + private final Player player; - public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { - super(event); - player = ((Player) event.getWhoClicked()); - } + public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { + super(event); + player = ((Player) event.getWhoClicked()); + } - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } - @Nonnull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } + @Nonnull + @Override + public HandlerList getHandlers() { + return getHandlerList(); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java index d3531fcdb..ec02033e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java @@ -8,40 +8,36 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class PlayerJumpEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private final PlayerStatisticIncrementEvent event; + private final PlayerStatisticIncrementEvent event; - public PlayerJumpEvent(@Nonnull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { - super(who); - this.event = statisticIncrementEvent; - } + public PlayerJumpEvent(@Nonnull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { + super(who); + this.event = statisticIncrementEvent; + } - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return event.isCancelled(); - } + @Override + public boolean isCancelled() { + return event.isCancelled(); + } - @Override - public void setCancelled(boolean b) { - event.setCancelled(true); - } + @Override + public void setCancelled(boolean b) { + event.setCancelled(true); + } - @Nonnull - @Override - public HandlerList getHandlers() { - return handlers; - } + @Nonnull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java index 7287968b0..bf1ece3e6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java @@ -9,43 +9,39 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Getter public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private final Item item; - private final int remaining; - private boolean cancel = false; - - public PlayerPickupItemEvent(@Nonnull Player player, @Nonnull Item item, int remaining) { - super(player); - this.item = item; - this.remaining = remaining; - } - - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @Nonnull - @Override - public HandlerList getHandlers() { - return handlers; - } -} \ No newline at end of file + private static final HandlerList handlers = new HandlerList(); + + private final Item item; + private final int remaining; + private boolean cancel = false; + + public PlayerPickupItemEvent(@Nonnull Player player, @Nonnull Item item, int remaining) { + super(player); + this.item = item; + this.remaining = remaining; + } + + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancel; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Nonnull + @Override + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index 20214c166..387af43cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.generator; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -11,114 +11,68 @@ import javax.annotation.Nonnull; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class VoidMapGenerator extends ChunkGenerator { - private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; - -// private static class PortalInfo { -// -// private final int chunkX; -// private final int y; -// private final int chunkZ; -// -// public PortalInfo(int chunkX, int y, int chunkZ) { -// this.chunkX = chunkX; -// this.y = y; -// this.chunkZ = chunkZ; -// } -// -// } - -// private List portalChunks; -// -// public void loadStrongholds(World world) { -// -// for (int i = 0; i < 3; i++) { -// Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { -// Location portal = world -// .locateNearestStructure(new Location(world, 0, 0, 0), StructureType.STRONGHOLD, 180, -// true); -// if (portal != null) { -// Chunk chunk = portal.getChunk(); -// chunk.load(true); -// portalChunks.add(new PortalInfo(chunk.getX(), portal.getBlockY(), chunk.getZ())); -// } -// }, i*5); -// -// } -// -// -// } - - @Override - @Nonnull - public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { - -// if (portalChunks == null) { -// portalChunks = Lists.newLinkedList(); -// Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { -// loadStrongholds(world); -// }); -// } + private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; + + @Override + @Nonnull + public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { + + ChunkData chunkData = createChunkData(world); + if (x == 0 && z == 0) { + chunkData.setBlock(0, 59, 0, Material.BEDROCK); + } - ChunkData chunkData = createChunkData(world); - if (x == 0 && z == 0) { - chunkData.setBlock(0, 59, 0, Material.BEDROCK); - } - - // Stronghold location is weirdly the same for every void map - // TODO: FIX FOLLOWING ISSUES - // Only works in 1.18 worlds - // maybe try to locate the three first strongholds and place portal in chunk (code commented out above) - // Maybe don't generate a portal at all to prevent issues with the feature - if (generateEndPortal) { - if (x == -7 && z == -105) { - generateEndPortal(chunkData); - } - } + // Stronghold location is weirdly the same for every void map + // TODO: FIX FOLLOWING ISSUES + // Only works in 1.18 worlds + // maybe try to locate the three first strongholds and place portal in chunk (code commented out above) + // Maybe don't generate a portal at all to prevent issues with the feature + if (generateEndPortal) { + if (x == -7 && z == -105) { + generateEndPortal(chunkData); + } + } // if (portalChunk.chunkX == x && portalChunk.chunkZ == z) { -// Challenges.getInstance().getLogger().info("Generating End Portal"); +// Challenges.getInstance().getILogger().info("Generating End Portal"); // generateEndPortal(chunkData); // break; // } // } - return chunkData; - } + return chunkData; + } - public void generateEndPortal(@Nonnull ChunkData data) { + public void generateEndPortal(@Nonnull ChunkData data) { - int x = 6; - int y = 29; - int z = 6; - for (int x1 = 0; x1 < 5; x1++) { + int x = 6; + int y = 29; + int z = 6; + for (int x1 = 0; x1 < 5; x1++) { - for (int z1 = 0; z1 < 5; z1++) { - if ((x1 == 0 && z1 == 0) || (x1 == 4 && z1 == 4) || - (x1 == 0 && z1 == 4) || (x1 == 4 && z1 == 0)) continue; - if (x1 > 0 && z1 > 0 && x1 < 4 && z1 < 4) continue; + for (int z1 = 0; z1 < 5; z1++) { + if ((x1 == 0 && z1 == 0) || (x1 == 4 && z1 == 4) || + (x1 == 0 && z1 == 4) || (x1 == 4 && z1 == 0)) continue; + if (x1 > 0 && z1 > 0 && x1 < 4 && z1 < 4) continue; - Directional blockData = (Directional) Bukkit.createBlockData(Material.END_PORTAL_FRAME); + Directional blockData = (Directional) Bukkit.createBlockData(Material.END_PORTAL_FRAME); - if (x1 == 0) { - blockData.setFacing(BlockFace.EAST); - } else if (x1 == 4) { - blockData.setFacing(BlockFace.WEST); - } else if (z1 == 0) { - blockData.setFacing(BlockFace.SOUTH); - } else { - blockData.setFacing(BlockFace.NORTH); - } + if (x1 == 0) { + blockData.setFacing(BlockFace.EAST); + } else if (x1 == 4) { + blockData.setFacing(BlockFace.WEST); + } else if (z1 == 0) { + blockData.setFacing(BlockFace.SOUTH); + } else { + blockData.setFacing(BlockFace.NORTH); + } - data.setBlock(x + x1, y, z + z1, blockData); - } - } + data.setBlock(x + x1, y, z + z1, blockData); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index e80518a57..8457776c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.GameMode; @@ -19,60 +19,56 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class BlockDropListener implements Listener { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (event.getPlayer().getGameMode() == GameMode.CREATIVE) return; - if (!event.isDropItems()) return; - dropCustomDrops(event.getBlock(), () -> event.setDropItems(false)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (event.getPlayer().getGameMode() == GameMode.CREATIVE) return; + if (!event.isDropItems()) return; + dropCustomDrops(event.getBlock(), () -> event.setDropItems(false)); + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockExplosion(@Nonnull BlockExplodeEvent event) { - handleExplosion(event.blockList(), () -> event.setYield(0)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplosion(@Nonnull BlockExplodeEvent event) { + handleExplosion(event.blockList(), () -> event.setYield(0)); + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityExplosion(@Nonnull EntityExplodeEvent event) { - handleExplosion(event.blockList(), () -> event.setYield(0)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityExplosion(@Nonnull EntityExplodeEvent event) { + handleExplosion(event.blockList(), () -> event.setYield(0)); + } - protected void handleExplosion(@Nonnull Iterable blocklist, @Nonnull Runnable dropsExist) { - for (Block block : blocklist) { - dropCustomDrops(block, dropsExist); - } - } + protected void handleExplosion(@Nonnull Iterable blocklist, @Nonnull Runnable dropsExist) { + for (Block block : blocklist) { + dropCustomDrops(block, dropsExist); + } + } - protected void dropCustomDrops(@Nonnull Block block, @Nonnull Runnable dropsExist) { + protected void dropCustomDrops(@Nonnull Block block, @Nonnull Runnable dropsExist) { - Material material = block.getType(); - if (BukkitReflectionUtils.isAir(material)) return; + Material material = block.getType(); + if (BukkitReflectionUtils.isAir(material)) return; - if (!ChallengeAPI.getDropChance(material)) { - dropsExist.run(); - return; - } + if (!ChallengeAPI.getDropChance(material)) { + dropsExist.run(); + return; + } - List drops = Challenges.getInstance().getBlockDropManager().getCustomDrops(material); - if (drops.isEmpty()) return; + List drops = Challenges.getInstance().getBlockDropManager().getCustomDrops(material); + if (drops.isEmpty()) return; - Location location = block.getLocation().clone().add(0.5, 0, 0.5); - if (location.getWorld() == null) return; + Location location = block.getLocation().clone().add(0.5, 0, 0.5); + if (location.getWorld() == null) return; - dropsExist.run(); - for (Material drop : drops) { - try { - location.getWorld().dropItem(location, new ItemStack(drop)); - } catch (Exception ex) { - Logger.warn("Unable to drop custom drop {}", drop, ex); - } - } + dropsExist.run(); + for (Material drop : drops) { + try { + location.getWorld().dropItem(location, new ItemStack(drop)); + } catch (Exception ex) { + Logger.warn("Unable to drop custom drop {}", drop, ex); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java index 38ca8e8ad..6596e1b5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java @@ -12,36 +12,32 @@ import java.util.UUID; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class ChatInputListener implements Listener { - private static Map> inputActions = new HashMap<>(); + private static Map> inputActions = new HashMap<>(); - public ChatInputListener() { - inputActions = new HashMap<>(); - } + public ChatInputListener() { + inputActions = new HashMap<>(); + } - public static void setInputAction(Player player, Consumer event) { - inputActions.put(player.getUniqueId(), event); - } + public static void setInputAction(Player player, Consumer event) { + inputActions.put(player.getUniqueId(), event); + } - @EventHandler(priority = EventPriority.LOW) - public void onChat(AsyncPlayerChatEvent event) { + @EventHandler(priority = EventPriority.LOW) + public void onChat(AsyncPlayerChatEvent event) { - Consumer action = inputActions.remove(event.getPlayer().getUniqueId()); - if (action != null) { - action.accept(event); - event.setCancelled(true); - } + Consumer action = inputActions.remove(event.getPlayer().getUniqueId()); + if (action != null) { + action.accept(event); + event.setCancelled(true); + } - } + } - @EventHandler(priority = EventPriority.LOW) - public void onQuit(PlayerQuitEvent event) { - inputActions.remove(event.getPlayer().getUniqueId()); - } + @EventHandler(priority = EventPriority.LOW) + public void onQuit(PlayerQuitEvent event) { + inputActions.remove(event.getPlayer().getUniqueId()); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 77e1f9086..00de88ed9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -17,91 +17,81 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CheatListener implements Listener { - public CheatListener() { - Bukkit.getOnlinePlayers().stream() - .filter(player -> player.getGameMode() == GameMode.CREATIVE) - .findFirst().ifPresent(this::handleCheatsDetected); - } + public CheatListener() { + Bukkit.getOnlinePlayers().stream() + .filter(player -> player.getGameMode() == GameMode.CREATIVE) + .findFirst().ifPresent(this::handleCheatsDetected); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - if (event.getNewGameMode() == GameMode.CREATIVE) - handleCheatsDetected(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + if (event.getNewGameMode() == GameMode.CREATIVE) + handleCheatsDetected(event.getPlayer()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) return; -// -// StructureManager manager = Bukkit.getStructureManager(); -// Map structures = manager.getStructures(); -// // Entry entry = IRandom.threadLocal().choose(entries); + @EventHandler(priority = EventPriority.MONITOR) + public void onSneak(PlayerToggleSneakEvent event) { + if (!event.isSneaking()) { + } //// Structure structure = entry.getValue(); -// Structure structure = manager.getStructure(new NamespacedKey("minecraft", "shipwreck/rightsideup_backhalf")); -// structure.place(event.getPlayer().getLocation(), true, StructureRotation.NONE, Mirror.NONE, -1, 0, -// ThreadLocalRandom.current()); - } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { - String[] commands = { - "give", - "replaceitem", - "effect", - "i", - "summon", - "enchant", - "heal", - "kill", - "setblock", - "fill" - }; - String message = event.getMessage().toLowerCase(); - if (message.isEmpty()) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + String[] commands = { + "give", + "replaceitem", + "effect", + "i", + "summon", + "enchant", + "heal", + "kill", + "setblock", + "fill" + }; + String message = event.getMessage().toLowerCase(); + if (message.isEmpty()) return; - String[] args = message.substring(1).trim().split(" "); - String commandName = args[0]; - if (commandName.contains(":")) { - commandName = commandName.substring(commandName.indexOf(':') + 1); - } + String[] args = message.substring(1).trim().split(" "); + String commandName = args[0]; + if (commandName.contains(":")) { + commandName = commandName.substring(commandName.indexOf(':') + 1); + } - for (String command : commands) { - if (!commandName.equalsIgnoreCase("/" + command)) continue; - if (!hasPermission(event.getPlayer(), command)) continue; - handleCheatsDetected(event.getPlayer()); - break; - } - } + for (String command : commands) { + if (!commandName.equalsIgnoreCase("/" + command)) continue; + if (!hasPermission(event.getPlayer(), command)) continue; + handleCheatsDetected(event.getPlayer()); + break; + } + } - private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { - String[] prefixes = { - "challenges.", - "minecraft.command.", - "essentials.", - "bukkit." - }; + private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { + String[] prefixes = { + "challenges.", + "minecraft.command.", + "essentials.", + "bukkit." + }; - for (String prefix : prefixes) { - if (player.hasPermission(prefix + command)) - return true; - } + for (String prefix : prefixes) { + if (player.hasPermission(prefix + command)) + return true; + } - return false; - } + return false; + } - private void handleCheatsDetected(@Nonnull Player player) { - if (Challenges.getInstance().getServerManager().hasCheated()) return; - if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; - Challenges.getInstance().getServerManager().setHasCheated(); - Logger.info("Detected cheating: No more stats can be collected"); - Message.forName("cheats-detected").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - } + private void handleCheatsDetected(@Nonnull Player player) { + if (Challenges.getInstance().getServerManager().hasCheated()) return; + if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; + Challenges.getInstance().getServerManager().setHasCheated(); + Logger.info("Detected cheating: No more stats can be collected"); + Message.forName("cheats-detected").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 411e1fde7..82dfe55ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.spigot.events.*; import org.bukkit.Bukkit; @@ -20,78 +20,73 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class CustomEventListener implements Listener { - /** - * Detecting jumps and calls a {@link PlayerJumpEvent} - */ - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent event) { - if (BukkitReflectionUtils.isInWater(event.getPlayer())) return; - if (event.getStatistic() == Statistic.JUMP) { - Bukkit.getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer(), event)); - } - } + /** + * Detecting jumps and calls a {@link PlayerJumpEvent} + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent event) { + if (BukkitReflectionUtils.isInWater(event.getPlayer())) return; + if (event.getStatistic() == Statistic.JUMP) { + Bukkit.getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer(), event)); + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - PlayerInventoryClickEvent eventCall = new PlayerInventoryClickEvent(event); - eventCall.setCancelled(event.isCancelled()); - Bukkit.getPluginManager().callEvent(eventCall); - event.setCancelled(eventCall.isCancelled()); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(@Nonnull InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + PlayerInventoryClickEvent eventCall = new PlayerInventoryClickEvent(event); + eventCall.setCancelled(event.isCancelled()); + Bukkit.getPluginManager().callEvent(eventCall); + event.setCancelled(eventCall.isCancelled()); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { - if (!(event.getEntity() instanceof Player)) return; - PlayerPickupItemEvent eventCall = new PlayerPickupItemEvent(((Player) event.getEntity()), event.getItem(), event.getRemaining()); - eventCall.setCancelled(event.isCancelled()); - Bukkit.getPluginManager().callEvent(eventCall); - event.setCancelled(eventCall.isCancelled()); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player)) return; + PlayerPickupItemEvent eventCall = new PlayerPickupItemEvent(((Player) event.getEntity()), event.getItem(), event.getRemaining()); + eventCall.setCancelled(event.isCancelled()); + Bukkit.getPluginManager().callEvent(eventCall); + event.setCancelled(eventCall.isCancelled()); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - Entity damager = event.getDamager(); - if (damager instanceof Projectile) { - if (((Projectile) damager).getShooter() instanceof Entity) { - damager = (Entity) ((Projectile) damager).getShooter(); - } - } - if (!(damager instanceof Player)) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - LivingEntity entity = (LivingEntity) event.getEntity(); + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + if (damager instanceof Projectile) { + if (((Projectile) damager).getShooter() instanceof Entity) { + damager = (Entity) ((Projectile) damager).getShooter(); + } + } + if (!(damager instanceof Player)) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + LivingEntity entity = (LivingEntity) event.getEntity(); - EntityDamageByPlayerEvent damageEvent = new EntityDamageByPlayerEvent(event.getEntity(), (Player) damager, event.getFinalDamage(), event); - Bukkit.getPluginManager().callEvent(damageEvent); + EntityDamageByPlayerEvent damageEvent = new EntityDamageByPlayerEvent(event.getEntity(), (Player) damager, event.getFinalDamage(), event); + Bukkit.getPluginManager().callEvent(damageEvent); - if (entity.getHealth() - event.getDamage() > 0) return; - EntityDeathByPlayerEvent deathEvent = new EntityDeathByPlayerEvent(event.getEntity(), (Player) damager, event); - Bukkit.getPluginManager().callEvent(deathEvent); - } + if (entity.getHealth() - event.getDamage() > 0) return; + EntityDeathByPlayerEvent deathEvent = new EntityDeathByPlayerEvent(event.getEntity(), (Player) damager, event); + Bukkit.getPluginManager().callEvent(deathEvent); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onGameModeChange(PlayerGameModeChangeEvent event) { - boolean execute = false; - boolean isIgnored = false; - if (AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && !AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { - execute = true; - isIgnored = true; - } else if (!AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { - execute = true; - isIgnored = false; - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onGameModeChange(PlayerGameModeChangeEvent event) { + boolean execute = false; + boolean isIgnored = false; + if (AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && !AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { + execute = true; + isIgnored = true; + } else if (!AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { + execute = true; + } - if (execute) { - PlayerIgnoreStatusChangeEvent statusEvent = new PlayerIgnoreStatusChangeEvent(event.getPlayer(), isIgnored); - Bukkit.getPluginManager().callEvent(statusEvent); - } - } + if (execute) { + PlayerIgnoreStatusChangeEvent statusEvent = new PlayerIgnoreStatusChangeEvent(event.getPlayer(), isIgnored); + Bukkit.getPluginManager().callEvent(statusEvent); + } + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java index 9a2cb4a66..22da2139f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java @@ -13,52 +13,48 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class ExtraWorldRestrictionListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!isInExtraWorld(event.getBlock().getLocation())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isPlaceBlocks()) return; + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!isInExtraWorld(event.getBlock().getLocation())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isPlaceBlocks()) return; - event.setBuild(false); - event.setCancelled(true); - } + event.setBuild(false); + event.setCancelled(true); + } - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!isInExtraWorld(event.getBlock().getLocation())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isDestroyBlocks()) return; + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!isInExtraWorld(event.getBlock().getLocation())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isDestroyBlocks()) return; - event.setCancelled(true); - } + event.setCancelled(true); + } - @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (!isInExtraWorld(event.getPlayer().getWorld())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isDropItems()) return; + @EventHandler(priority = EventPriority.LOW) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (!isInExtraWorld(event.getPlayer().getWorld())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isDropItems()) return; - event.setCancelled(true); - } + event.setCancelled(true); + } - @EventHandler(priority = EventPriority.LOW) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - if (!isInExtraWorld(event.getPlayer().getWorld())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isPickupItems()) return; + @EventHandler(priority = EventPriority.LOW) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + if (!isInExtraWorld(event.getPlayer().getWorld())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isPickupItems()) return; - event.setCancelled(true); - } + event.setCancelled(true); + } - private boolean isInExtraWorld(@Nonnull Location location) { - if (location.getWorld() == null) return false; - return isInExtraWorld(location.getWorld()); - } + private boolean isInExtraWorld(@Nonnull Location location) { + if (location.getWorld() == null) return false; + return isInExtraWorld(location.getWorld()); + } - private boolean isInExtraWorld(@Nonnull World world) { - return Challenges.getInstance().getWorldManager().getExtraWorld().equals(world); - } + private boolean isInExtraWorld(@Nonnull World world) { + return Challenges.getInstance().getWorldManager().getExtraWorld().equals(world); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java index 1d3481cb1..0edfa3bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java @@ -12,48 +12,44 @@ import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GeneratorWorldsListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onChangeWorld(PlayerTeleportEvent event) { - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.LOW) + public void onChangeWorld(PlayerTeleportEvent event) { + if (event.getTo() == null) return; - GeneratorWorldPortalManager worldManager = Challenges.getInstance().getGeneratorWorldPortalManager(); - Player player = event.getPlayer(); - World from = event.getFrom().getWorld(); - World to = event.getTo().getWorld(); - if (from == null || to == null) return; - if (from == to) return; + GeneratorWorldPortalManager worldManager = Challenges.getInstance().getGeneratorWorldPortalManager(); + Player player = event.getPlayer(); + World from = event.getFrom().getWorld(); + World to = event.getTo().getWorld(); + if (from == null || to == null) return; + if (from == to) return; - boolean wasCustomWorld = worldManager.isCustomWorld(from.getName()); - boolean isCustomWorld = worldManager.isCustomWorld(to.getName()); + boolean wasCustomWorld = worldManager.isCustomWorld(from.getName()); + boolean isCustomWorld = worldManager.isCustomWorld(to.getName()); - if (wasCustomWorld && !isCustomWorld) { + if (wasCustomWorld && !isCustomWorld) { - if (to.getEnvironment() == Environment.NETHER || to.getEnvironment() == Environment.THE_END) { - worldManager.setLastLocation(player, event.getFrom()); - } + if (to.getEnvironment() == Environment.NETHER || to.getEnvironment() == Environment.THE_END) { + worldManager.setLastLocation(player, event.getFrom()); + } - } else if (!wasCustomWorld) { + } else if (!wasCustomWorld) { - if (event.getCause() != TeleportCause.END_PORTAL && event.getCause() != TeleportCause.NETHER_PORTAL) { - return; - } + if (event.getCause() != TeleportCause.END_PORTAL && event.getCause() != TeleportCause.NETHER_PORTAL) { + return; + } - if (from.getEnvironment() == Environment.NETHER || from.getEnvironment() == Environment.THE_END) { - Location location = worldManager.getAndRemoveLastWorld(player); - if (location != null) { - location = location.getBlock().getLocation().clone(); - event.setTo(location); - } - } + if (from.getEnvironment() == Environment.NETHER || from.getEnvironment() == Environment.THE_END) { + Location location = worldManager.getAndRemoveLastWorld(player); + if (location != null) { + location = location.getBlock().getLocation().clone(); + event.setTo(location); + } + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index bd818993c..244ca2a48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -16,49 +16,45 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class HelpListener implements Listener { - @EventHandler(priority = EventPriority.MONITOR) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + @EventHandler(priority = EventPriority.MONITOR) + public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { - String message = event.getMessage().toLowerCase(); - if (message.isEmpty()) return; + String message = event.getMessage().toLowerCase(); + if (message.isEmpty()) return; - String[] args = message.substring(1).trim().split(" "); - String commandName = args[0]; - if (commandName.contains(":")) { - commandName = commandName.substring(commandName.indexOf(':') + 1); - } + String[] args = message.substring(1).trim().split(" "); + String commandName = args[0]; + if (commandName.contains(":")) { + commandName = commandName.substring(commandName.indexOf(':') + 1); + } - PluginCommand command = Challenges.getInstance().getCommand("help"); - if (command == null) return; - List names = new ArrayList<>(command.getAliases()); - names.add("help"); + PluginCommand command = Challenges.getInstance().getCommand("help"); + if (command == null) return; + List names = new ArrayList<>(command.getAliases()); + names.add("help"); - if (!names.contains(commandName)) return; + if (!names.contains(commandName)) return; - Player sender = event.getPlayer(); + Player sender = event.getPlayer(); - sendMessage(sender, "§7This server is running §e§lChallenges §ev" + Challenges.getInstance().getVersion()); - sendMessage(sender, ""); - sendMessage(sender, "§7Made by §eCodingArea §8(§eanweisen & KxmischesDomi§8)"); - sendMessage(sender, "§7Visit the source at §egithub.com/anweisen/Challenges"); - sendMessage(sender, "§7Download at §espigotmc.org/resources/80548"); - sendMessage(sender, "§7For more join our discord §ediscord.gg/74Ay5zF"); + sendMessage(sender, "§7This server is running §e§lChallenges §ev" + Challenges.getInstance().getVersion()); + sendMessage(sender, ""); + sendMessage(sender, "§7Made by §eCodingArea §8(§eanweisen & KxmischesDomi§8)"); + sendMessage(sender, "§7Visit the source at §egithub.com/anweisen/Challenges"); + sendMessage(sender, "§7Download at §espigotmc.org/resources/80548"); + sendMessage(sender, "§7For more join our discord §ediscord.gg/74Ay5zF"); - } + } - public void sendMessage(CommandSender sender, String msg) { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader != null && languageLoader.isSmallCapsFont()) { - msg = FontUtils.toSmallCaps(msg); - } - sender.sendMessage(Prefix.CHALLENGES + msg); + public void sendMessage(CommandSender sender, String msg) { + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + if (languageLoader != null && languageLoader.isSmallCapsFont()) { + msg = FontUtils.toSmallCaps(msg); + } + sender.sendMessage(Prefix.CHALLENGES + msg); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 89bccee4d..22ef71374 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import java.util.List; -import javax.annotation.Nonnull; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -20,131 +18,134 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ +import javax.annotation.Nonnull; +import java.util.List; + public class PlayerConnectionListener implements Listener { - private final boolean messages; - private final boolean timerPausedInfo; - private final boolean startTimerOnJoin; - private final boolean resetOnLastQuit; - private final boolean pauseOnLastQuit; - private final boolean restoreDefaultsOnLastQuit; - - public PlayerConnectionListener() { - Document config = Challenges.getInstance().getConfigDocument(); - messages = config.getBoolean("join-quit-messages"); - timerPausedInfo = config.getBoolean("timer-is-paused-info"); - startTimerOnJoin = config.getBoolean("start-on-first-join"); - resetOnLastQuit = config.getBoolean("reset-on-last-leave"); - pauseOnLastQuit = config.getBoolean("pause-on-last-leave"); - restoreDefaultsOnLastQuit = config.getBoolean("restore-defaults-on-last-leave"); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - - Player player = event.getPlayer(); - - player.getLocation().getChunk().load(true); - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), - MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); - Challenges.getInstance().getScoreboardManager().handleJoin(player); - - if (player.hasPermission("challenges.gui")) { - if (Challenges.getInstance().isFirstInstall()) { - player.sendMessage(""); - player.sendMessage(Prefix.CHALLENGES + "§7Thanks for downloading §e§lChallenges§7!"); - player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the §econfig.yml"); - player.sendMessage(Prefix.CHALLENGES + "§7For more join our discord §ediscord.gg/74Ay5zF"); - } - - if (timerPausedInfo && !startTimerOnJoin && ChallengeAPI.isPaused()) { - player.sendMessage(""); - Message.forName("timer-paused-message").send(player, Prefix.CHALLENGES); - } - } - - if (Challenges.getInstance().getStatsManager().isNoStatsAfterCheating() && Challenges.getInstance().getServerManager().hasCheated()) { - player.sendMessage(""); - Message.forName("cheats-already-detected").send(player, Prefix.CHALLENGES); - } - - - if (startTimerOnJoin) { - player.sendMessage(""); - ChallengeAPI.resumeTimer(); - } - - if (player.hasPermission("challenges.gui")) { - if (!UpdateLoader.isNewestConfigVersion()) { - player.sendMessage(""); - Message.forName("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); - } - - List missingConfigSettings = Challenges.getInstance().getConfigManager().getMissingConfigSettings(); - if (!missingConfigSettings.isEmpty()) { - player.sendMessage(""); - String separator = Message.forName("missing-config-settings-separator").asString(); - Message.forName("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); - } else if (!UpdateLoader.isNewestConfigVersion()) { - player.sendMessage(""); - Message.forName("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); - } - if (!UpdateLoader.isNewestPluginVersion()) { - player.sendMessage(""); - Message.forName("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); - } - } - - - if (messages) { - player.sendMessage(""); - event.setJoinMessage(Prefix.CHALLENGES + Message.forName("join-message").asString(NameHelper.getName(event.getPlayer()))); - } - - if (Challenges.getInstance().getDatabaseManager().isConnected()) { - Challenges.getInstance().runAsync(() -> DatabaseHelper.savePlayerData(player)); - } - - } - - @EventHandler(priority = EventPriority.HIGH) - public void onQuit(@Nonnull PlayerQuitEvent event) { - - try { - Player player = event.getPlayer(); - Challenges.getInstance().getScoreboardManager().handleQuit(player); - DatabaseHelper.clearCache(event.getPlayer().getUniqueId()); - - if (Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { - event.setQuitMessage(null); - } else if (messages) { - event.setQuitMessage(null); - Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while handling disconnect", exception); - } - - if (Bukkit.getOnlinePlayers().size() <= 1) { - - if (!Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { - if (resetOnLastQuit && !ChallengeAPI.isFresh()) { - Challenges.getInstance().getWorldManager().prepareWorldReset(Bukkit.getConsoleSender()); - return; - } else if (pauseOnLastQuit && ChallengeAPI.isStarted()) { - ChallengeAPI.pauseTimer(); - } - } - - if (restoreDefaultsOnLastQuit) { - Challenges.getInstance().getChallengeManager().restoreDefaults(); - } - } - - } + private final boolean messages; + private final boolean timerPausedInfo; + private final boolean startTimerOnJoin; + private final boolean resetOnLastQuit; + private final boolean pauseOnLastQuit; + private final boolean restoreDefaultsOnLastQuit; + + public PlayerConnectionListener() { + Document config = Challenges.getInstance().getConfigDocument(); + messages = config.getBoolean("join-quit-messages"); + timerPausedInfo = config.getBoolean("timer-is-paused-info"); + startTimerOnJoin = config.getBoolean("start-on-first-join"); + resetOnLastQuit = config.getBoolean("reset-on-last-leave"); + pauseOnLastQuit = config.getBoolean("pause-on-last-leave"); + restoreDefaultsOnLastQuit = config.getBoolean("restore-defaults-on-last-leave"); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + + Player player = event.getPlayer(); + + player.getLocation().getChunk().load(true); + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); + Challenges.getInstance().getScoreboardManager().handleJoin(player); + + if (Challenges.getInstance().isFirstInstall() && !player.hasPermission("challenges.gui")) { + Message.forName("not-op").send(player, Prefix.CHALLENGES); + } + + if (player.hasPermission("challenges.gui")) { + if (Challenges.getInstance().isFirstInstall()) { + player.sendMessage(""); + player.sendMessage(Prefix.CHALLENGES + "§7Thanks for downloading §e§lChallenges§7!"); + player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the settings or with /setlang [language]"); + player.sendMessage(Prefix.CHALLENGES + "§7For more join our discord §ediscord.gg/74Ay5zF"); + } + + if (timerPausedInfo && !startTimerOnJoin && ChallengeAPI.isPaused()) { + player.sendMessage(""); + Message.forName("timer-paused-message").send(player, Prefix.CHALLENGES); + } + } + + if (Challenges.getInstance().getStatsManager().isNoStatsAfterCheating() && Challenges.getInstance().getServerManager().hasCheated()) { + player.sendMessage(""); + Message.forName("cheats-already-detected").send(player, Prefix.CHALLENGES); + } + + + if (startTimerOnJoin) { + player.sendMessage(""); + ChallengeAPI.resumeTimer(); + } + + if (player.hasPermission("challenges.gui")) { + if (!UpdateLoader.isNewestConfigVersion()) { + player.sendMessage(""); + Message.forName("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); + } + + List missingConfigSettings = Challenges.getInstance().getConfigManager().getMissingConfigSettings(); + if (!missingConfigSettings.isEmpty()) { + player.sendMessage(""); + String separator = Message.forName("missing-config-settings-separator").asString(); + Message.forName("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); + } else if (!UpdateLoader.isNewestConfigVersion()) { + player.sendMessage(""); + Message.forName("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); + } + if (!UpdateLoader.isNewestPluginVersion()) { + player.sendMessage(""); + Message.forName("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); + } + } + + + if (messages) { + player.sendMessage(""); + event.setJoinMessage(Prefix.CHALLENGES + Message.forName("join-message").asString(NameHelper.getName(event.getPlayer()))); + } + + if (Challenges.getInstance().getDatabaseManager().isConnected()) { + Challenges.getInstance().runAsync(() -> DatabaseHelper.savePlayerData(player)); + } + + } + + @EventHandler(priority = EventPriority.HIGH) + public void onQuit(@Nonnull PlayerQuitEvent event) { + + try { + Player player = event.getPlayer(); + Challenges.getInstance().getScoreboardManager().handleQuit(player); + DatabaseHelper.clearCache(event.getPlayer().getUniqueId()); + + if (Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { + event.setQuitMessage(null); + } else if (messages) { + event.setQuitMessage(null); + Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + } + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Error while handling disconnect", exception); + } + + if (Bukkit.getOnlinePlayers().size() <= 1) { + + if (!Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { + if (resetOnLastQuit && !ChallengeAPI.isFresh()) { + Challenges.getInstance().getWorldManager().prepareWorldReset(Bukkit.getConsoleSender()); + return; + } else if (pauseOnLastQuit && ChallengeAPI.isStarted()) { + ChallengeAPI.pauseTimer(); + } + } + + if (restoreDefaultsOnLastQuit) { + Challenges.getInstance().getChallengeManager().restoreDefaults(); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java index b73b68131..f111ace66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java @@ -23,149 +23,144 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RestrictionListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isStarted()) return; - Entity entity = event.getEntity(); - if (entity instanceof Player && ((Player) entity).getGameMode() == GameMode.CREATIVE) { - return; - } - - if (event.getCause() != DamageCause.VOID && (entity instanceof Player || event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE)) { - entity.setFireTicks(entity instanceof Player ? 0 : entity.getFireTicks()); - event.setCancelled(true); - ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityDeath(@Nonnull EntityDeathEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!(event.getEntity() instanceof Player)) return; - event.getDrops().clear(); - event.setDroppedExp(0); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onFoodLevelChange(@Nonnull FoodLevelChangeEvent event) { - if (ChallengeAPI.isPaused()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { - if (ChallengeAPI.isPaused()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onItemPickup(@Nonnull EntityPickupItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (player.getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractAtEntityEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onOffHandItemSwitch(@Nonnull PlayerSwapHandItemsEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDamageEvent event) { - if (ChallengeAPI.isStarted()) return; - Entity entity = event.getVehicle(); - event.setCancelled(true); - if (event.getAttacker() instanceof Player) { - if (((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE) - event.setCancelled(false); - ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDestroyEvent event) { - if (ChallengeAPI.isPaused() && !(event.getAttacker() instanceof Player && ((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE)) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onWeatherChange(@Nonnull WeatherChangeEvent event) { - if (ChallengeAPI.isPaused() && event.toWeatherState()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onThunderChange(@Nonnull ThunderChangeEvent event) { - if (ChallengeAPI.isPaused() && event.toThunderState()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onTarget(@Nonnull EntityTargetEvent event) { - if (ChallengeAPI.isPaused() && event.getTarget() != null) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onClick(@Nonnull InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ChallengeAPI.isPaused() && player.getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { - if (ChallengeAPI.isStarted()) return; - event.setCancelled(true); - - } + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isStarted()) return; + Entity entity = event.getEntity(); + if (entity instanceof Player && ((Player) entity).getGameMode() == GameMode.CREATIVE) { + return; + } + + if (event.getCause() != DamageCause.VOID && (entity instanceof Player || event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE)) { + entity.setFireTicks(entity instanceof Player ? 0 : entity.getFireTicks()); + event.setCancelled(true); + ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDeath(@Nonnull EntityDeathEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!(event.getEntity() instanceof Player)) return; + event.getDrops().clear(); + event.setDroppedExp(0); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onFoodLevelChange(@Nonnull FoodLevelChangeEvent event) { + if (ChallengeAPI.isPaused()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + if (ChallengeAPI.isPaused()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemPickup(@Nonnull EntityPickupItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (player.getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractAtEntityEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onOffHandItemSwitch(@Nonnull PlayerSwapHandItemsEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onDamage(@Nonnull VehicleDamageEvent event) { + if (ChallengeAPI.isStarted()) return; + Entity entity = event.getVehicle(); + event.setCancelled(true); + if (event.getAttacker() instanceof Player) { + if (((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE) + event.setCancelled(false); + ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onDamage(@Nonnull VehicleDestroyEvent event) { + if (ChallengeAPI.isPaused() && !(event.getAttacker() instanceof Player && ((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE)) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onWeatherChange(@Nonnull WeatherChangeEvent event) { + if (ChallengeAPI.isPaused() && event.toWeatherState()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onThunderChange(@Nonnull ThunderChangeEvent event) { + if (ChallengeAPI.isPaused() && event.toThunderState()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onTarget(@Nonnull EntityTargetEvent event) { + if (ChallengeAPI.isPaused() && event.getTarget() != null) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ChallengeAPI.isPaused() && player.getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + if (ChallengeAPI.isStarted()) return; + event.setCancelled(true); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java index 3e4ea849b..2e9e7b5d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java @@ -7,22 +7,18 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class ScoreboardUpdateListener implements Listener { - @EventHandler - public void onIgnoredChange(PlayerIgnoreStatusChangeEvent event) { + @EventHandler + public void onIgnoredChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - ChallengeScoreboard currentScoreboard = Challenges.getInstance().getScoreboardManager().getCurrentScoreboard(); - if (currentScoreboard != null) { - currentScoreboard.update(); - } - }); + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + ChallengeScoreboard currentScoreboard = Challenges.getInstance().getScoreboardManager().getCurrentScoreboard(); + if (currentScoreboard != null) { + currentScoreboard.update(); + } + }); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java index 1e23c0883..163aaac8e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java @@ -33,119 +33,114 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @see net.codingarea.challenges.plugin.management.stats.StatsManager - * @since 2.0 - */ public class StatsListener implements Listener { - private final List dragonDamager = new ArrayList<>(); - - @TimerTask(status = TimerStatus.RUNNING, freshnessPolicy = FreshnessPolicy.FRESH, async = false) - public void onStart() { - if (!Challenges.getInstance().getStatsManager().isEnabled()) return; - - for (Player player : Bukkit.getOnlinePlayers()) { - Challenges.getInstance().getStatsManager().getStats(player).incrementStatistic(Statistic.CHALLENGES_PLAYED, 1); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (countNoStats()) return; - if (!(event.getEntity() instanceof Player)) return; - if (event.getCause() == DamageCause.VOID) return; - - Player player = (Player) event.getEntity(); - if (AbstractChallenge.ignorePlayer(player)) return; - incrementStatistic(player, Statistic.DAMAGE_TAKEN, event.getFinalDamage()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageByEntityEvent event) { - if (countNoStats()) return; - - if (event.getDamager() instanceof Player) { - Player player = (Player) event.getDamager(); - if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) - return; - incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); - - if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) - dragonDamager.add(player); - } else if (event.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) event.getDamager(); - if (!((projectile.getShooter()) instanceof Player)) return; - Player player = (Player) projectile.getShooter(); - if (AbstractChallenge.ignorePlayer(player)) return; - incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); - - if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) - dragonDamager.add(player); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_PLACED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (countNoStats()) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_MINED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (countNoStats()) return; - incrementStatistic(event.getEntity(), Statistic.DEATHS, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (countNoStats()) return; - LivingEntity entity = event.getEntity(); - Player player = entity.getKiller(); - if (player == null) return; - if (AbstractChallenge.ignorePlayer(player)) return; - - incrementStatistic(player, Statistic.ENTITY_KILLS, 1); - if (entity instanceof EnderDragon && entity.getWorld().getEnvironment() == Environment.THE_END) { - dragonDamager.forEach(damager -> incrementStatistic(damager, Statistic.DRAGON_KILLED, 1)); - dragonDamager.clear(); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isPaused()) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_TRAVELED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isPaused()) return; - incrementStatistic(event.getPlayer(), Statistic.JUMPS, 1); - } - - private void incrementStatistic(@Nonnull Player player, @Nonnull Statistic statistic, double amount) { - PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(player); - stats.incrementStatistic(statistic, amount); - } - - private boolean countNoStats() { - return Challenges.getInstance().getServerManager().hasCheated() && Challenges.getInstance().getStatsManager().isNoStatsAfterCheating(); - } + private final List dragonDamager = new ArrayList<>(); + + @TimerTask(status = TimerStatus.RUNNING, freshnessPolicy = FreshnessPolicy.FRESH, async = false) + public void onStart() { + if (!Challenges.getInstance().getStatsManager().isEnabled()) return; + + for (Player player : Bukkit.getOnlinePlayers()) { + Challenges.getInstance().getStatsManager().getStats(player).incrementStatistic(Statistic.CHALLENGES_PLAYED, 1); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (countNoStats()) return; + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() == DamageCause.VOID) return; + + Player player = (Player) event.getEntity(); + if (AbstractChallenge.ignorePlayer(player)) return; + incrementStatistic(player, Statistic.DAMAGE_TAKEN, event.getFinalDamage()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageByEntityEvent event) { + if (countNoStats()) return; + + if (event.getDamager() instanceof Player) { + Player player = (Player) event.getDamager(); + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) + return; + incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); + + if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) + dragonDamager.add(player); + } else if (event.getDamager() instanceof Projectile) { + Projectile projectile = (Projectile) event.getDamager(); + if (!((projectile.getShooter()) instanceof Player)) return; + Player player = (Player) projectile.getShooter(); + if (AbstractChallenge.ignorePlayer(player)) return; + incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); + + if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) + dragonDamager.add(player); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_PLACED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (countNoStats()) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_MINED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (countNoStats()) return; + incrementStatistic(event.getEntity(), Statistic.DEATHS, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (countNoStats()) return; + LivingEntity entity = event.getEntity(); + Player player = entity.getKiller(); + if (player == null) return; + if (AbstractChallenge.ignorePlayer(player)) return; + + incrementStatistic(player, Statistic.ENTITY_KILLS, 1); + if (entity instanceof EnderDragon && entity.getWorld().getEnvironment() == Environment.THE_END) { + dragonDamager.forEach(damager -> incrementStatistic(damager, Statistic.DRAGON_KILLED, 1)); + dragonDamager.clear(); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isPaused()) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_TRAVELED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isPaused()) return; + incrementStatistic(event.getPlayer(), Statistic.JUMPS, 1); + } + + private void incrementStatistic(@Nonnull Player player, @Nonnull Statistic statistic, double amount) { + PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(player); + stats.incrementStatistic(statistic, amount); + } + + private boolean countNoStats() { + return Challenges.getInstance().getServerManager().hasCheated() && Challenges.getInstance().getStatsManager().isNoStatsAfterCheating(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java index 623717492..685acfe58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java @@ -8,18 +8,14 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface Completer extends TabCompleter { - @Override - @Nullable - default List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - return onTabComplete(sender, args); - } + @Override + @Nullable + default List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + return onTabComplete(sender, args); + } - @Nullable - List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args); + @Nullable + List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java index 8b4fe018f..258830152 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java @@ -10,33 +10,29 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class ForwardingCommand implements SenderCommand, TabCompleter { - private final String forwardCommand; - private final boolean overrideTab; + private final String forwardCommand; + private final boolean overrideTab; - public ForwardingCommand(@Nonnull String forwardCommand) { - this(forwardCommand, true); - } + public ForwardingCommand(@Nonnull String forwardCommand) { + this(forwardCommand, true); + } - public ForwardingCommand(@Nonnull String forwardCommand, boolean overrideTab) { - this.forwardCommand = forwardCommand; - this.overrideTab = overrideTab; - } + public ForwardingCommand(@Nonnull String forwardCommand, boolean overrideTab) { + this.forwardCommand = forwardCommand; + this.overrideTab = overrideTab; + } - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - Bukkit.dispatchCommand(sender, forwardCommand + " " + String.join(" ", args)); - } + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + Bukkit.dispatchCommand(sender, forwardCommand + " " + String.join(" ", args)); + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - return overrideTab ? new ArrayList<>() : null; - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + return overrideTab ? new ArrayList<>() : null; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 5ef0b43dd..650a3e5f7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; @@ -10,27 +10,23 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface PlayerCommand extends CommandExecutor { - @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - if (sender instanceof Player) { - try { - onCommand((Player) sender, args); - } catch (Exception ex) { - sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); - Logger.error("Something went wrong while processing the command '{}'", label, ex); - } - } else { - Message.forName("player-command").send(sender, Prefix.CHALLENGES); - } - return true; - } + @Override + default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + if (sender instanceof Player) { + try { + onCommand((Player) sender, args); + } catch (Exception ex) { + sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); + Logger.error("Something went wrong while processing the command '{}'", label, ex); + } + } else { + Message.forName("player-command").send(sender, Prefix.CHALLENGES); + } + return true; + } - void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception; + void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 1fc276e71..776df6c8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -8,23 +8,19 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface SenderCommand extends CommandExecutor { - @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - try { - onCommand(sender, args); - } catch (Exception ex) { - sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); - Logger.error("Something went wrong while processing the command '{}'", label, ex); - } - return true; - } + @Override + default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + try { + onCommand(sender, args); + } catch (Exception ex) { + sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); + Logger.error("Something went wrong while processing the command '{}'", label, ex); + } + return true; + } - void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception; + void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java index b3396201c..3de673ac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java @@ -11,149 +11,140 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class BukkitSerialization { - /** - * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. - * - * @param playerInventory to turn into an array of strings. - * @return Array of strings: [ main content, armor content ] - * @throws IllegalStateException - */ - public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { - //get the main content part, this doesn't return the armor - String content = toBase64(playerInventory); - String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); - - return new String[]{content, armor}; - } - - /** - * A method to serialize an {@link ItemStack} array to Base64 String. - *

- *

- *

- * Based off of {@link #toBase64(Inventory)}. - * - * @param items to turn into a Base64 String. - * @return Base64 string of the items. - * @throws IllegalStateException - */ - public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Write the size of the inventory - dataOutput.writeInt(items.length); - - // Save every element in the list - for (int i = 0; i < items.length; i++) { - dataOutput.writeObject(items[i]); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * A method to serialize an inventory to Base64 string. - *

- *

- *

- * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param inventory to serialize - * @return Base64 string of the provided inventory - * @throws IllegalStateException - */ - public static String toBase64(Inventory inventory) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Save every element in the list - for (int i = 0; i < inventory.getSize(); i++) { - dataOutput.writeObject(inventory.getItem(i)); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * A method to get an {@link Inventory} from an encoded, Base64, string. - *

- *

- *

- * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param data Base64 string of data containing an inventory. - * @return Inventory created from the Base64 string. - * @throws IOException - */ - public static Inventory fromBase64(Inventory inventory, String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - - // Read the serialized inventory - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, (ItemStack) dataInput.readObject()); - } - - dataInput.close(); - return inventory; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } - - /** - * Gets an array of ItemStacks from Base64 string. - *

- *

- *

- * Base off of {@link #fromBase64(String)}. - * - * @param data Base64 string to convert to ItemStack array. - * @return ItemStack array created from the Base64 string. - * @throws IOException - */ - public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - ItemStack[] items = new ItemStack[dataInput.readInt()]; - - // Read the serialized inventory - for (int i = 0; i < items.length; i++) { - items[i] = (ItemStack) dataInput.readObject(); - } - - dataInput.close(); - return items; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } + /** + * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. + * + * @param playerInventory to turn into an array of strings. + * @return Array of strings: [ main content, armor content ] + */ + public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { + //get the main content part, this doesn't return the armor + String content = toBase64(playerInventory); + String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); + + return new String[]{content, armor}; + } + + /** + * A method to serialize an {@link ItemStack} array to Base64 String. + *

+ *

+ *

+ * Based off of {@link #toBase64(Inventory)}. + * + * @param items to turn into a Base64 String. + * @return Base64 string of the items. + */ + public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(items.length); + + // Save every element in the list + for (int i = 0; i < items.length; i++) { + dataOutput.writeObject(items[i]); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to serialize an inventory to Base64 string. + *

+ *

+ *

+ * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param inventory to serialize + * @return Base64 string of the provided inventory + */ + public static String toBase64(Inventory inventory) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Save every element in the list + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to get an {@link Inventory} from an encoded, Base64, string. + *

+ *

+ *

+ * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param data Base64 string of data containing an inventory. + * @return Inventory created from the Base64 string. + */ + public static Inventory fromBase64(Inventory inventory, String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + + // Read the serialized inventory + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + + dataInput.close(); + return inventory; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + /** + * Gets an array of ItemStacks from Base64 string. + *

+ *

+ *

+ * Base off of . + * + * @param data Base64 string to convert to ItemStack array. + * @return ItemStack array created from the Base64 string. + */ + public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack[] items = new ItemStack[dataInput.readInt()]; + + // Read the serialized inventory + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + + dataInput.close(); + return items; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java index d67dc877d..07c18695f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.utils.bukkit.container; -import java.util.Collection; -import javax.annotation.Nonnull; import lombok.Data; import org.bukkit.GameMode; import org.bukkit.Location; @@ -9,83 +7,82 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +import javax.annotation.Nonnull; +import java.util.Collection; + @Data public final class PlayerData { - private final GameMode gamemode; - private final Location location; - private final ItemStack[] inventory; - private final ItemStack[] armor; - private final Collection effects; + private final GameMode gamemode; + private final Location location; + private final ItemStack[] inventory; + private final ItemStack[] armor; + private final Collection effects; - private final double health; - private final int food; - private final float saturation; - private final int heldItemSlot; - private final boolean allowedFlight; - private final boolean flying; + private final double health; + private final int food; + private final float saturation; + private final int heldItemSlot; + private final boolean allowedFlight; + private final boolean flying; - public PlayerData(@Nonnull Player player) { - this( - player.getGameMode(), - player.getLocation(), - player.getInventory().getContents(), - player.getInventory().getArmorContents(), - player.getActivePotionEffects(), - player.getHealth(), - player.getFoodLevel(), - player.getSaturation(), - player.getInventory().getHeldItemSlot(), - player.getAllowFlight(), - player.isFlying() - ); - } + public PlayerData(@Nonnull Player player) { + this( + player.getGameMode(), + player.getLocation(), + player.getInventory().getContents(), + player.getInventory().getArmorContents(), + player.getActivePotionEffects(), + player.getHealth(), + player.getFoodLevel(), + player.getSaturation(), + player.getInventory().getHeldItemSlot(), + player.getAllowFlight(), + player.isFlying() + ); + } - public PlayerData( - @Nonnull GameMode gamemode, - @Nonnull Location location, - @Nonnull ItemStack[] inventory, - @Nonnull ItemStack[] armor, - @Nonnull Collection effects, - double health, - int food, - float saturation, - int heldItemSlot, - boolean allowedFlight, - boolean flying - ) { - this.gamemode = gamemode; - this.location = location; - this.inventory = inventory; - this.armor = armor; - this.effects = effects; - this.health = health; - this.food = food; - this.saturation = saturation; - this.heldItemSlot = heldItemSlot; - this.allowedFlight = allowedFlight; - this.flying = allowedFlight && flying; - } + public PlayerData( + @Nonnull GameMode gamemode, + @Nonnull Location location, + @Nonnull ItemStack[] inventory, + @Nonnull ItemStack[] armor, + @Nonnull Collection effects, + double health, + int food, + float saturation, + int heldItemSlot, + boolean allowedFlight, + boolean flying + ) { + this.gamemode = gamemode; + this.location = location; + this.inventory = inventory; + this.armor = armor; + this.effects = effects; + this.health = health; + this.food = food; + this.saturation = saturation; + this.heldItemSlot = heldItemSlot; + this.allowedFlight = allowedFlight; + this.flying = allowedFlight && flying; + } - public void apply(@Nonnull Player player) { - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.setGameMode(gamemode); - player.teleport(location); - player.setHealth(health); - player.setFoodLevel(food); - player.setSaturation(saturation); - player.getInventory().setContents(inventory); - player.getInventory().setArmorContents(armor); - player.getInventory().setHeldItemSlot(heldItemSlot); - player.addPotionEffects(effects); - player.setAllowFlight(allowedFlight); - player.setFlying(flying); - } + public void apply(@Nonnull Player player) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + player.setGameMode(gamemode); + player.teleport(location); + player.setHealth(health); + player.setFoodLevel(food); + player.setSaturation(saturation); + player.getInventory().setContents(inventory); + player.getInventory().setArmorContents(armor); + player.getInventory().setHeldItemSlot(heldItemSlot); + player.addPotionEffects(effects); + player.setAllowFlight(allowedFlight); + player.setFlying(flying); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index 458297fc4..f403eeceb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -1,20 +1,16 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @FunctionalInterface public interface IJumpGenerator { - @Nonnull - @CheckReturnValue - Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); + @Nonnull + @CheckReturnValue + Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index 4bf485b51..fe582fe7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -1,62 +1,58 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class RandomJumpGenerator implements IJumpGenerator { - @Nonnull - @Override - @CheckReturnValue - public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { + @Nonnull + @Override + @CheckReturnValue + public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { - int layer = random.nextInt(includeUpGoing ? 3 : 2) - 1; - int range = layer == 0 ? 4 : 3; + int layer = random.nextInt(includeUpGoing ? 3 : 2) - 1; + int range = layer == 0 ? 4 : 3; - int mainDirection = random.nextInt(range * 2) - range; - int mainDirectionValue = Math.abs(mainDirection); - if (mainDirectionValue < 2) { - mainDirection = random.choose(-range, range); - mainDirectionValue = Math.abs(mainDirection); - } + int mainDirection = random.nextInt(range * 2) - range; + int mainDirectionValue = Math.abs(mainDirection); + if (mainDirectionValue < 2) { + mainDirection = random.choose(-range, range); + mainDirectionValue = Math.abs(mainDirection); + } - int secondDirection = determineSecondDirection(random, mainDirectionValue, range); - return translate(startingPoint, random, layer, mainDirection, secondDirection); + int secondDirection = determineSecondDirection(random, mainDirectionValue, range); + return translate(startingPoint, random, layer, mainDirection, secondDirection); - } + } - protected int determineSecondDirection(@Nonnull IRandom random, int mainDirection, int range) { - if (mainDirection == range || mainDirection == range - 1) { - return random.choose(-1, 0, 1); - } else if (mainDirection == range - 2) { - return random.choose(-2, -1, 0, 1, 2); - } else if (mainDirection == range - 3) { - return random.choose(-3, -2, -1, 0, 1, 2, 3); - } else if (mainDirection == range - 4 || mainDirection == range - 5) { - return random.choose(-4, -3, -2, -1, 0, 1, 2, 3, 4); - } - throw new IllegalArgumentException("Could not determine second direction for main direction " + mainDirection + ", range " + range); - } + protected int determineSecondDirection(@Nonnull IRandom random, int mainDirection, int range) { + if (mainDirection == range || mainDirection == range - 1) { + return random.choose(-1, 0, 1); + } else if (mainDirection == range - 2) { + return random.choose(-2, -1, 0, 1, 2); + } else if (mainDirection == range - 3) { + return random.choose(-3, -2, -1, 0, 1, 2, 3); + } else if (mainDirection == range - 4 || mainDirection == range - 5) { + return random.choose(-4, -3, -2, -1, 0, 1, 2, 3, 4); + } + throw new IllegalArgumentException("Could not determine second direction for main direction " + mainDirection + ", range " + range); + } - @Nonnull - @CheckReturnValue - protected Block translate(@Nonnull Block startingPoint, @Nonnull IRandom random, int layer, int mainDirection, int secondDirection) { + @Nonnull + @CheckReturnValue + protected Block translate(@Nonnull Block startingPoint, @Nonnull IRandom random, int layer, int mainDirection, int secondDirection) { - boolean intoX = random.nextBoolean(); + boolean intoX = random.nextBoolean(); - int x = intoX ? mainDirection : secondDirection; - int z = intoX ? secondDirection : mainDirection; + int x = intoX ? mainDirection : secondDirection; + int z = intoX ? secondDirection : mainDirection; - return startingPoint.getRelative(x, layer, z); + return startingPoint.getRelative(x, layer, z); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index dbb121a81..c5f73691e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.logging.ILogger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; import net.codingarea.challenges.plugin.content.Prefix; import net.md_5.bungee.api.chat.*; import org.bukkit.*; @@ -14,278 +14,278 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; import java.util.concurrent.Callable; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class BukkitStringUtils { - @Nonnull - public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] array, @Nonnull Object... args) { - List results = new ArrayList<>(); - for (String value : array) { - String s = value; - if (!s.trim().isEmpty() && prefix != null) { - s = prefix + s; - } - BaseComponent comp = null; - for (BaseComponent component : format(s, args)) { - if (comp == null) { - comp = component; - } else { - comp.addExtra(component); - } - } - results.add(comp); - } - return results.toArray(new BaseComponent[0]); - } - - @Nonnull - public static List format(@Nonnull String sequence, @Nonnull Object... args) { - - args = replaceArguments(args, false); - - List results = new ArrayList<>(); - char start = '{', end = '}'; - boolean inArgument = false; - - boolean lastWasParagraph = false; - ChatColor currentColor = null; - List currentFormatting = new LinkedList<>(); - - StringBuilder argument = new StringBuilder(); - TextComponent currentText = new TextComponent(); - for (char c : sequence.toCharArray()) { - - if (c == '§') { - lastWasParagraph = true; - } else { - if (lastWasParagraph) { - ChatColor newColor = ChatColor.getByChar(c); - if (!newColor.isColor()) { - if (newColor == ChatColor.RESET) { - currentFormatting.clear(); - currentColor = null; - } else { - currentFormatting.add(newColor); - } - } else { - currentColor = newColor; - currentFormatting.clear(); - } - } - lastWasParagraph = false; - } - - if (c == end && inArgument) { - inArgument = false; - try { - int arg = Integer.parseInt(argument.toString()); - Object current = args[arg]; - BaseComponent replacement = - current instanceof BaseComponent ? (BaseComponent) current : - current instanceof Supplier ? new TextComponent(String.valueOf(((Supplier) current).get())) : - current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : - new TextComponent(String.valueOf(current)); - - if (replacement instanceof TextComponent) { - currentText.setText(currentText.getText() + ((TextComponent) replacement).getText()); - } else { - results.add(currentText); - currentText = new TextComponent(); - - if (currentColor != null && replacement.getColor() == net.md_5.bungee.api.ChatColor.WHITE) { - replacement.setColor(currentColor.asBungee()); - } - for (ChatColor color : currentFormatting) { - switch (color) { - case BOLD: - replacement.setBold(true); - break; - case MAGIC: - replacement.setObfuscated(true); - break; - case ITALIC: - replacement.setItalic(true); - break; - case STRIKETHROUGH: - replacement.setStrikethrough(true); - break; - case UNDERLINE: - replacement.setUnderlined(true); - break; - } - } - results.add(replacement); - } - - currentColor = null; - } catch (NumberFormatException | IndexOutOfBoundsException ex) { - ILogger.forThisClass().warn("Invalid argument index '{}'", argument); - results.add(new TextComponent(String.valueOf(start))); - results.add(new TextComponent(String.valueOf(argument))); - results.add(new TextComponent(String.valueOf(end))); - } catch (Exception ex) { - throw new WrappedException(ex); - } - argument = new StringBuilder(); - continue; - } - if (c == start && !inArgument) { - inArgument = true; - continue; - } - if (inArgument) { - argument.append(c); - continue; - } - currentText = new TextComponent(currentText.getText() + c); - } - if (!currentText.getText().isEmpty()) { - results.add(currentText); - } - if (argument.length() > 0) { - results.add(new TextComponent(String.valueOf(start))); - results.add(new TextComponent(String.valueOf(argument))); - } - return results; - } - - public static Object[] replaceArguments(Object[] args, boolean toStrings) { - args = Arrays.copyOf(args, args.length); - for (int i = 0; i < args.length; i++) { - Object arg = args[i]; - - arg = arg instanceof Material ? getItemComponent((Material) arg) : - arg instanceof EntityType ? getEntityName((EntityType) arg) : - arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : - arg instanceof Biome ? getBiomeName((Biome) arg) : - arg instanceof GameMode ? getGameModeName((GameMode) arg) : - arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : - arg instanceof LootTable ? getEntityName((LootTable) arg) : - arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : - arg; - - if (toStrings) { - if (arg instanceof BaseComponent) { - arg = ((BaseComponent) arg).toPlainText(); - } - } - args[i] = arg; - - } - return args; - } - - public static TranslatableComponent getItemName(@Nonnull Material material) { - NamespacedKey key = material.getKey(); - return new TranslatableComponent((material.isBlock() ? "block" : "item") + "." + key.getNamespace() + "." + key.getKey()); - } - - public static @Nullable BaseComponent getMusicDiscName(@Nonnull Material material) { - if (!material.name().startsWith("MUSIC_DISC")) return null; - String key = "item.minecraft." + material.name().toLowerCase() + ".desc"; - return new TranslatableComponent(key); - } - - public static BaseComponent getItemComponent(@Nonnull Material material) { - BaseComponent component = getItemName(material); - BaseComponent musicDiscName = getMusicDiscName(material); - if (musicDiscName != null) { - component.addExtra(" ("); - component.addExtra(musicDiscName); - component.addExtra(")"); - } - return component; - } - - - public static TranslatableComponent getEntityName(@Nonnull EntityType type) { - - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = type.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = type.getName(); - } - - return new TranslatableComponent("entity." + namespace + "." + key); - } - - public static TranslatableComponent getEntityName(@Nonnull LootTable type) { - NamespacedKey key = type.getKey(); - return new TranslatableComponent("entity." + key.getNamespace() + "." + key.getKey().replace("entities/", "")); - } - - public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectType type) { - - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = type.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = type.getName().toLowerCase(); - } - - - return new TranslatableComponent("effect." + namespace + "." + key); - } - - public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = biome.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = biome.name().toLowerCase(); - } - - return new TranslatableComponent("biome." + namespace + "." + key); - } - - public static TranslatableComponent getGameModeName(@Nonnull GameMode gameMode) { - return new TranslatableComponent("selectWorld.gameMode." + gameMode.name().toLowerCase()); - } - - public static BaseComponent getAdvancementTitle(@Nonnull Advancement advancement) { - String replace = advancement.getKey().getKey().replace("/", "."); - return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".title"); - } - - public static BaseComponent getAdvancementDescription(@Nonnull Advancement advancement) { - String replace = advancement.getKey().getKey().replace("/", "."); - return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".description"); - } - - public static BaseComponent getAdvancementComponent(@Nonnull Advancement advancement) { - BaseComponent title = getAdvancementTitle(advancement); - BaseComponent description = getAdvancementDescription(advancement); - description.setColor(net.md_5.bungee.api.ChatColor.GREEN); - title.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(description).create())); - return title; - } - - private static String correctAdvancementKeys(String s) { - return s.replace("bred_all_animals", "breed_all_animals").replace("obtain_netherite_hoe", "netherite_hoe"); // mc sucks - } - - public static TranslatableComponent getDifficultyName(@Nonnull Difficulty difficulty) { - return new TranslatableComponent("options.difficulty." + difficulty.name().toLowerCase()); - } + @Nonnull + public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] array, @Nonnull Object... args) { + List results = new ArrayList<>(); + for (String value : array) { + String s = value; + if (!s.trim().isEmpty() && prefix != null) { + s = prefix + s; + } + BaseComponent comp = null; + for (BaseComponent component : format(s, args)) { + if (comp == null) { + comp = component; + } else { + comp.addExtra(component); + } + } + results.add(comp); + } + return results.toArray(new BaseComponent[0]); + } + + @Nonnull + public static List format(@Nonnull String sequence, @Nonnull Object... args) { + + args = replaceArguments(args, false); + + List results = new ArrayList<>(); + char start = '{', end = '}'; + boolean inArgument = false; + + boolean lastWasParagraph = false; + ChatColor currentColor = null; + List currentFormatting = new LinkedList<>(); + + StringBuilder argument = new StringBuilder(); + TextComponent currentText = new TextComponent(); + for (char c : sequence.toCharArray()) { + + if (c == '§') { + lastWasParagraph = true; + } else { + if (lastWasParagraph) { + ChatColor newColor = ChatColor.getByChar(c); + assert newColor != null; + if (!newColor.isColor()) { + if (newColor == ChatColor.RESET) { + currentFormatting.clear(); + currentColor = null; + } else { + currentFormatting.add(newColor); + } + } else { + currentColor = newColor; + currentFormatting.clear(); + } + } + lastWasParagraph = false; + } + + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + BaseComponent replacement = + current instanceof BaseComponent ? (BaseComponent) current : + current instanceof Supplier ? new TextComponent(String.valueOf(((Supplier) current).get())) : + current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : + new TextComponent(String.valueOf(current)); + + if (replacement instanceof TextComponent) { + currentText.setText(currentText.getText() + ((TextComponent) replacement).getText()); + } else { + results.add(currentText); + currentText = new TextComponent(); + + if (currentColor != null && replacement.getColor() == net.md_5.bungee.api.ChatColor.WHITE) { + replacement.setColor(currentColor.asBungee()); + } + for (ChatColor color : currentFormatting) { + switch (color) { + case BOLD: + replacement.setBold(true); + break; + case MAGIC: + replacement.setObfuscated(true); + break; + case ITALIC: + replacement.setItalic(true); + break; + case STRIKETHROUGH: + replacement.setStrikethrough(true); + break; + case UNDERLINE: + replacement.setUnderlined(true); + break; + } + } + results.add(replacement); + } + + currentColor = null; + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + ILogger.forThisClass().warn("Invalid argument index '{}'", argument); + results.add(new TextComponent(String.valueOf(start))); + results.add(new TextComponent(String.valueOf(argument))); + results.add(new TextComponent(String.valueOf(end))); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + currentText = new TextComponent(currentText.getText() + c); + } + if (!currentText.getText().isEmpty()) { + results.add(currentText); + } + if (argument.length() > 0) { + results.add(new TextComponent(String.valueOf(start))); + results.add(new TextComponent(String.valueOf(argument))); + } + return results; + } + + public static Object[] replaceArguments(Object[] args, boolean toStrings) { + args = Arrays.copyOf(args, args.length); + for (int i = 0; i < args.length; i++) { + Object arg = args[i]; + + arg = arg instanceof Material ? getItemComponent((Material) arg) : + arg instanceof EntityType ? getEntityName((EntityType) arg) : + arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : + arg instanceof Biome ? getBiomeName((Biome) arg) : + arg instanceof GameMode ? getGameModeName((GameMode) arg) : + arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : + arg instanceof LootTable ? getEntityName((LootTable) arg) : + arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : + arg; + + if (toStrings) { + if (arg instanceof BaseComponent) { + arg = ((BaseComponent) arg).toPlainText(); + } + } + args[i] = arg; + + } + return args; + } + + public static TranslatableComponent getItemName(@Nonnull Material material) { + NamespacedKey key = material.getKey(); + return new TranslatableComponent((material.isBlock() ? "block" : "item") + "." + key.getNamespace() + "." + key.getKey()); + } + + public static @Nullable BaseComponent getMusicDiscName(@Nonnull Material material) { + if (!material.name().startsWith("MUSIC_DISC")) return null; + String key = "item.minecraft." + material.name().toLowerCase() + ".desc"; + return new TranslatableComponent(key); + } + + public static BaseComponent getItemComponent(@Nonnull Material material) { + BaseComponent component = getItemName(material); + BaseComponent musicDiscName = getMusicDiscName(material); + if (musicDiscName != null) { + component.addExtra(" ("); + component.addExtra(musicDiscName); + component.addExtra(")"); + } + return component; + } + + + public static TranslatableComponent getEntityName(@Nonnull EntityType type) { + + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = type.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = type.getName(); + } + + return new TranslatableComponent("entity." + namespace + "." + key); + } + + public static TranslatableComponent getEntityName(@Nonnull LootTable type) { + NamespacedKey key = type.getKey(); + return new TranslatableComponent("entity." + key.getNamespace() + "." + key.getKey().replace("entities/", "")); + } + + public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectType type) { + + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = type.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = type.getName().toLowerCase(); + } + + + return new TranslatableComponent("effect." + namespace + "." + key); + } + + public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = biome.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = biome.name().toLowerCase(); + } + + return new TranslatableComponent("biome." + namespace + "." + key); + } + + public static TranslatableComponent getGameModeName(@Nonnull GameMode gameMode) { + return new TranslatableComponent("selectWorld.gameMode." + gameMode.name().toLowerCase()); + } + + public static BaseComponent getAdvancementTitle(@Nonnull Advancement advancement) { + String replace = advancement.getKey().getKey().replace("/", "."); + return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".title"); + } + + public static BaseComponent getAdvancementDescription(@Nonnull Advancement advancement) { + String replace = advancement.getKey().getKey().replace("/", "."); + return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".description"); + } + + public static BaseComponent getAdvancementComponent(@Nonnull Advancement advancement) { + BaseComponent title = getAdvancementTitle(advancement); + BaseComponent description = getAdvancementDescription(advancement); + description.setColor(net.md_5.bungee.api.ChatColor.GREEN); + title.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(description).create())); + return title; + } + + private static String correctAdvancementKeys(String s) { + return s.replace("bred_all_animals", "breed_all_animals").replace("obtain_netherite_hoe", "netherite_hoe"); // mc sucks + } + + public static TranslatableComponent getDifficultyName(@Nonnull Difficulty difficulty) { + return new TranslatableComponent("options.difficulty." + difficulty.name().toLowerCase()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 9358640a4..4b941e688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import lombok.Getter; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.*; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.BorderPacketFactory_1_17; @@ -12,112 +13,111 @@ import org.bukkit.World; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class NMSProvider { - private final static int majorVersion; - private static final BorderPacketFactory borderPacketFactory; + private final static int majorVersion; + /** + * -- GETTER -- + * + * @return A border packet factory + */ + @Getter + private static final BorderPacketFactory borderPacketFactory; - static { - majorVersion = ReflectionUtil.getMajorVersion(); - if (versionIsAtLeast(17)) { - borderPacketFactory = new BorderPacketFactory_1_17(); - } else if (versionIsAtLeast(13)) { - borderPacketFactory = new BorderPacketFactory_1_13(); - } else { - throw new IllegalStateException("Could not find a BorderPacketFactory implementation for version " + getFormattedVersion()); - } + static { + majorVersion = ReflectionUtil.getMajorVersion(); + if (versionIsAtLeast(17)) { + borderPacketFactory = new BorderPacketFactory_1_17(); + } else if (versionIsAtLeast(13)) { + borderPacketFactory = new BorderPacketFactory_1_13(); + } else { + throw new IllegalStateException("Could not find a BorderPacketFactory implementation for version " + getFormattedVersion()); } + } - /** - * Creates a world server for the given world - * @param world The world - * @return The world server - * @throws IllegalStateException If no implementation was found for the current version - */ - public static WorldServer createWorldServer(World world) { - try { - if (versionIsAtLeast(13)) { - return new WorldServer_1_13(world); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); - } - throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); + /** + * Creates a world server for the given world + * + * @param world The world + * @return The world server + * @throws IllegalStateException If no implementation was found for the current version + */ + public static WorldServer createWorldServer(World world) { + try { + if (versionIsAtLeast(13)) { + return new WorldServer_1_13(world); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getILogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); } + throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); + } - /** - * Creates a craft player for the given player - * @param player The player - * @return The craft player - * @throws IllegalStateException If no implementation was found for the current version - */ - public static CraftPlayer createCraftPlayer(Player player) { - try { - if (versionIsAtLeast(17)) { - return new CraftPlayer_1_17(player); - } else if (versionIsAtLeast(13)) { - return new CraftPlayer_1_13(player); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); - } - throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); + /** + * Creates a craft player for the given player + * + * @param player The player + * @return The craft player + * @throws IllegalStateException If no implementation was found for the current version + */ + public static CraftPlayer createCraftPlayer(Player player) { + try { + if (versionIsAtLeast(17)) { + return new CraftPlayer_1_17(player); + } else if (versionIsAtLeast(13)) { + return new CraftPlayer_1_13(player); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); } + throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); + } - /** - * Creates a player connection for the given CraftPlayer - * @param player The CraftPlayer - * @return The player connection - * @throws IllegalStateException If no implementation was found for the current version - */ - public static PlayerConnection createPlayerConnection(CraftPlayer player) { - try { - if (versionIsAtLeast(18)) { - return new PlayerConnection_1_18(player.getPlayerConnectionObject()); - } else if (versionIsAtLeast(13)) { - return new PlayerConnection_1_13(player.getPlayerConnectionObject()); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); - } - - throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); + /** + * Creates a player connection for the given CraftPlayer + * + * @param player The CraftPlayer + * @return The player connection + * @throws IllegalStateException If no implementation was found for the current version + */ + public static PlayerConnection createPlayerConnection(CraftPlayer player) { + try { + if (versionIsAtLeast(18)) { + return new PlayerConnection_1_18(player.getPlayerConnectionObject()); + } else if (versionIsAtLeast(13)) { + return new PlayerConnection_1_13(player.getPlayerConnectionObject()); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getILogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); } - /** Creates a packet border for the given world - * @param world The world - * @return The packet border - * @throws IllegalStateException If no implementation was found for the current version - */ - public static PacketBorder createPacketBorder(World world) { - if (versionIsAtLeast(18)) { - return new PacketBorder_1_18(world); - } else if (versionIsAtLeast(17)) { - return new PacketBorder_1_17(world); - } else if (versionIsAtLeast(13)) { - return new PacketBorder_1_13(world); - } - throw new IllegalStateException("Could not find a PacketBorder implementation for version " + getFormattedVersion()); - } + throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); + } - /** - * @return A border packet factory - * @throws IllegalStateException If no implementation was found for the current version - */ - public static BorderPacketFactory getBorderPacketFactory() { - return borderPacketFactory; + /** + * Creates a packet border for the given world + * + * @param world The world + * @return The packet border + * @throws IllegalStateException If no implementation was found for the current version + */ + public static PacketBorder createPacketBorder(World world) { + if (versionIsAtLeast(18)) { + return new PacketBorder_1_18(world); + } else if (versionIsAtLeast(17)) { + return new PacketBorder_1_17(world); + } else if (versionIsAtLeast(13)) { + return new PacketBorder_1_13(world); } + throw new IllegalStateException("Could not find a PacketBorder implementation for version " + getFormattedVersion()); + } - private static boolean versionIsAtLeast(int majorVersion) { - return NMSProvider.majorVersion >= majorVersion; - } + private static boolean versionIsAtLeast(int majorVersion) { + return NMSProvider.majorVersion >= majorVersion; + } - private static String getFormattedVersion() { - return MinecraftVersion.current().format(); - } + private static String getFormattedVersion() { + return MinecraftVersion.current().format(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java index f051f5944..65ac625ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java @@ -6,70 +6,66 @@ import org.bukkit.boss.BossBar; import org.bukkit.entity.Entity; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public final class NMSUtils { - public static void setEntityName(Entity entity, BaseComponent baseComponent) { - String json = ComponentSerializer.toString(baseComponent); + public static void setEntityName(Entity entity, BaseComponent baseComponent) { + String json = ComponentSerializer.toString(baseComponent); - try { - Class componentClass = getClass("network.chat.IChatBaseComponent"); - Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); - Object componentObject = ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); - Class entityClass = getClass("world.entity.Entity"); - Class craftEntityClass = ReflectionUtil.getBukkitClass("entity.CraftEntity"); - Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); - ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{ componentClass }, new Object[]{componentObject}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } + try { + Class componentClass = getClass("network.chat.IChatBaseComponent"); + Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); + Object componentObject = ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); + Class entityClass = getClass("world.entity.Entity"); + Class craftEntityClass = ReflectionUtil.getBukkitClass("entity.CraftEntity"); + Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); + ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{componentClass}, new Object[]{componentObject}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); } + } - public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) { - Object component = toIChatBaseComponent(baseComponent); - - try { - Class bossBattleClass = getClass("world.BossBattle"); - Class craftBossBarClass = ReflectionUtil.getBukkitClass("boss.CraftBossBar"); - Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); - ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{ getComponentClass() }, new Object[]{component}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } + public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) { + Object component = toIChatBaseComponent(baseComponent); + try { + Class bossBattleClass = getClass("world.BossBattle"); + Class craftBossBarClass = ReflectionUtil.getBukkitClass("boss.CraftBossBar"); + Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); + ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{getComponentClass()}, new Object[]{component}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); } - public static Object toIChatBaseComponent(BaseComponent baseComponent) { - String json = ComponentSerializer.toString(baseComponent); - try { - Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); - return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - return null; - } + } - public static Class getComponentClass() { - return getClass("network.chat.IChatBaseComponent"); + public static Object toIChatBaseComponent(BaseComponent baseComponent) { + String json = ComponentSerializer.toString(baseComponent); + try { + Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); + return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); } + return null; + } - public static Class getClass(String path) { - try { - if (ReflectionUtil.isUseNewSpigotPackaging()) { - return ReflectionUtil.getMinecraftClass(path); - } else { - String[] split = path.split("\\."); - String className = split.length == 1 ? path : split[split.length - 1]; - return ReflectionUtil.getNmsClass(className); - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - return null; + public static Class getComponentClass() { + return getClass("network.chat.IChatBaseComponent"); + } + + public static Class getClass(String path) { + try { + if (ReflectionUtil.isUseNewSpigotPackaging()) { + return ReflectionUtil.getMinecraftClass(path); + } else { + String[] split = path.split("\\."); + String className = split.length == 1 ? path : split[split.length - 1]; + return ReflectionUtil.getNmsClass(className); + } + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); } - + return null; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index b8e2705c0..b989752b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -1,500 +1,450 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.StringJoiner; -import java.util.regex.Pattern; import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; +import java.lang.reflect.*; +import java.util.StringJoiner; +import java.util.regex.Pattern; + /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public class ReflectionUtil { - public static String SERVER_VERSION; + public static String SERVER_VERSION; /** * -- GETTER -- - * Check if the new way of packaging Spigot is used
- * For >=1.17 this will be true, for =<1.16 this will be false.
- *

- * This dictates if you should use - * (<=1.16) or - * (>=1.17). - * - * @return Returns true if it is, false if it is now + * Check if the new way of packaging Spigot is used
+ * For >=1.17 this will be true, for =<1.16 this will be false.
+ *

+ * This dictates if you should use + * (<=1.16) or + * (>=1.17). */ @Getter private static boolean useNewSpigotPackaging; /** * -- GETTER -- - * Get the current major Minecraft version. - *

- * E.g for Minecraft 1.18 this is 18. - * - * @return The current major Minecraft version + * Get the current major Minecraft version. + *

+ * E.g for Minecraft 1.18 this is 18. */ @Getter private static int majorVersion; /** * -- GETTER -- - * Get the current minor Minecraft version. - *

- * E.g. for Minecraft 1.18.2 this is 2. - * - * @return The current minor Minecraft version + * Get the current minor Minecraft version. + *

+ * E.g. for Minecraft 1.18.2 this is 2. */ @Getter private static int minorVersion; - static { - try { - // Legacy support - Class bukkitClass = Class.forName("org.bukkit.Bukkit"); - Object serverObject = getMethod(bukkitClass, "getServer").invoke(null); - String serverPackageName = serverObject.getClass().getPackage().getName(); + static { + try { + // Legacy support + Class bukkitClass = Class.forName("org.bukkit.Bukkit"); + Object serverObject = getMethod(bukkitClass, "getServer").invoke(null); + String serverPackageName = serverObject.getClass().getPackage().getName(); + + SERVER_VERSION = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); + + // example: Bukkit version: 3638-Spigot-d90018e-7dcb59b (MC: 1.19.3) + String version = Bukkit.getVersion(); + + String[] parts = version.split(Pattern.quote("(MC: ")); + String[] versionParts = parts[1].split(Pattern.quote(".")); + + // There's a minor version + String major, minor; + if (versionParts.length > 2) { + major = versionParts[1]; + minor = versionParts[2].replace(")", ""); + } else { + major = versionParts[1].replace(")", ""); + minor = "0"; + } + + majorVersion = Integer.parseInt(major); + minorVersion = Integer.parseInt(minor); + + useNewSpigotPackaging = majorVersion >= 17; + + } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | + NoSuchMethodException e) { + Challenges.getInstance().getILogger().error("Failed to initialize the ReflectionUtil:", e); + } + } + + /** + * Get a Class from the org.bukkit.craftbukkit.SERVER_VERSION. package + * + * @param className The name of the class + * @return Returns the Class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + public static Class getBukkitClass(String className) throws ClassNotFoundException { + return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + className); + } + + /** + * 1.16 and older only + *

+ * Get a Class from the net.minecraft.server.SERVER_VERSION. package + * + * @param className The name of the class + * @return Returns the Class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + @Deprecated + public static Class getNmsClass(String className) throws ClassNotFoundException { + return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + className); + } + + /** + * 1.17 and newer only + *

+ * Get a Class from the net.minecraft package + * + * @param className The name of the class + * @return Returns the class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + public static Class getMinecraftClass(String className) throws ClassNotFoundException { + return Class.forName("net.minecraft." + className); + } + + /** + * Get the Constructor of a Class + * + * @param clazz The Class in which the Constructor is defined + * @param args Arguments taken by the Constructor + * @return Returns the Constructor + * @throws NoSuchMethodException Thrown when no Constructor in the Class was found with the provided combination of arguments + */ + public static Constructor getConstructor(Class clazz, Class... args) throws NoSuchMethodException { + Constructor con = clazz.getConstructor(args); + con.setAccessible(true); - SERVER_VERSION = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); + return con; + } - // example: Bukkit version: 3638-Spigot-d90018e-7dcb59b (MC: 1.19.3) - String version = Bukkit.getVersion(); + /** + * Get an Enum from an Enum constant + * + * @param clazz The Class in which the Enum is defined + * @param constant The name of the Enum Constant + * @return Returns the Enum or null if the Enum does not have a member called constant + */ + public static Enum getEnum(Class clazz, String constant) { + Enum[] constants = (Enum[]) clazz.getEnumConstants(); - String[] parts = version.split(Pattern.quote("(MC: ")); - String[] versionParts = parts[1].split(Pattern.quote(".")); + for (Enum e : constants) { + if (e.name().equalsIgnoreCase(constant)) { + return e; + } + } - // There's a minor version - String major, minor; - if(versionParts.length > 2) { - major = versionParts[1]; - minor = versionParts[2].replace(")", ""); - } else { - major = versionParts[1].replace(")", ""); - minor = "0"; - } + return null; + } - majorVersion = Integer.parseInt(major); - minorVersion = Integer.parseInt(minor); + /** + * Get an Enum constant by it's name and constant + * + * @param clazz The Class in which the Enum is defined + * @param enumname The name of the Enum + * @param constant The name of the Constant + * @return Returns the Enum or null if the Enum does not have a member called constant + * @throws ClassNotFoundException If the Class does not have an Enum called enumname + */ + public static Enum getEnum(Class clazz, String enumname, String constant) throws ClassNotFoundException { + Class c = Class.forName(clazz.getName() + "$" + enumname); + return getEnum(c, constant); + } - useNewSpigotPackaging = majorVersion >= 17; + /** + * Get a Field + * + * @param clazz The Class in which the Field is defined + * @param fieldName The name of the Field + * @return Returns the Field + * @throws NoSuchFieldException Thrown when the Field was not present in the Class + */ + public static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { + Field f = clazz.getDeclaredField(fieldName); + f.setAccessible(true); + return f; + } + + /** + * Sets the value of a field + * + * @param instance The instance of the class in which the field is defined + * @param fieldName The name of the field + * @param value The value the field should be set to + */ + public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { + Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } - } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { - Challenges.getInstance().getLogger().error("Failed to initialize the ReflectionUtil:", e); - } - } + /** + * Get a Method + * + * @param clazz The Class in which the Method is defined + * @param methodName The name of the method + * @param args The argument types the method takes + * @return Returns the Method + */ + public static Method getMethod(Class clazz, String methodName, Class... args) throws NoSuchMethodException { + Method m = clazz.getDeclaredMethod(methodName, args); + m.setAccessible(true); + return m; + } /** - * Get a Class from the org.bukkit.craftbukkit.SERVER_VERSION. package - * - * @param className The name of the class - * @return Returns the Class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - public static Class getBukkitClass(String className) throws ClassNotFoundException { - return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + className); - } - - /** - * 1.16 and older only - *

- * Get a Class from the net.minecraft.server.SERVER_VERSION. package - * - * @param className The name of the class - * @return Returns the Class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - @Deprecated - public static Class getNmsClass(String className) throws ClassNotFoundException { - return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + className); - } - - /** - * 1.17 and newer only - *

- * Get a Class from the net.minecraft package - * - * @param className The name of the class - * @return Returns the class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - public static Class getMinecraftClass(String className) throws ClassNotFoundException { - return Class.forName("net.minecraft." + className); - } - - /** - * Get the Constructor of a Class - * - * @param clazz The Class in which the Constructor is defined - * @param args Arguments taken by the Constructor - * @return Returns the Constructor - * @throws NoSuchMethodException Thrown when no Constructor in the Class was found with the provided combination of arguments - */ - public static Constructor getConstructor(Class clazz, Class... args) throws NoSuchMethodException { - Constructor con = clazz.getConstructor(args); - con.setAccessible(true); - - return con; - } - - /** - * Get an Enum from an Enum constant - * - * @param clazz The Class in which the Enum is defined - * @param constant The name of the Enum Constant - * @return Returns the Enum or null if the Enum does not have a member called constant - */ - public static Enum getEnum(Class clazz, String constant) { - Enum[] constants = (Enum[]) clazz.getEnumConstants(); - - for (Enum e : constants) { - if (e.name().equalsIgnoreCase(constant)) { - return e; - } - } - - return null; - } - - /** - * Get an Enum constant by it's name and constant - * - * @param clazz The Class in which the Enum is defined - * @param enumname The name of the Enum - * @param constant The name of the Constant - * @return Returns the Enum or null if the Enum does not have a member called constant - * @throws ClassNotFoundException If the Class does not have an Enum called enumname - */ - public static Enum getEnum(Class clazz, String enumname, String constant) throws ClassNotFoundException { - Class c = Class.forName(clazz.getName() + "$" + enumname); - return getEnum(c, constant); - } - - /** - * Get a Field - * - * @param clazz The Class in which the Field is defined - * @param fieldName The name of the Field - * @return Returns the Field - * @throws NoSuchFieldException Thrown when the Field was not present in the Class - */ - public static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { - Field f = clazz.getDeclaredField(fieldName); - f.setAccessible(true); - return f; - } - - /** - * Sets the value of a field - * @param instance The instance of the class in which the field is defined - * @param fieldName The name of the field - * @param value The value the field should be set to - * @throws NoSuchFieldException - * @throws IllegalAccessException - */ - public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - field.set(instance, value); - } - - /** - * Get a Method - * - * @param clazz The Class in which the Method is defined - * @param methodName The name of the method - * @param args The argument types the method takes - * @return Returns the Method - * @throws NoSuchMethodException - */ - public static Method getMethod(Class clazz, String methodName, Class... args) throws NoSuchMethodException { - Method m = clazz.getDeclaredMethod(methodName, args); - m.setAccessible(true); - return m; - } - - /** - * Invoke a Method which takes no arguments. The Class in which the Method is defined is derived from the provided Object - * - * @param obj The object to invoke the method on - * @param methodName The name of the Method - * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeMethod(Object obj, String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName); - } - - /** - * Invoke a Method where the argument types are derived from the provided arguments. The Class in which the Method is defined is derived from the provided Object - * - * @param obj The object to invoke the method on - * @param methodName The name of the Method - * @param args The arguments to pass to the Method - * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeMethod(Object obj, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName, args); - } - - /** - * Invoke a Method where the argument types are explicitly given (Helpful when working with primitives). The Class in which the Method is defined is derived from the provided Object. - * - * @param obj The Object to invoke the method on - * @param methodName The name of the Method - * @param argTypes The types of arguments as a Class array - * @param args The arguments as an object array - * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeMethod(Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName, argTypes, args); - } - - /** - * Invoke a Method where the Class where to find the method is explicitly given (Helpful if the method is located in a superclass). The argument types are derived from the provided arguments - * - * @param clazz The Class where the method is located - * @param obj The Object to invoke the method on - * @param methodName The name of the method - * @param args The arguments to be passed to the method - * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeMethod(Class clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class[] argTypes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argTypes[i] = args[i].getClass(); - } - - return invokeMethod(clazz, obj, methodName, argTypes, args); - } - - /** - * Invoke a Method where the Class where the Method is defined is explicitly given, and the argument types are explicitly given - * - * @param clazz The Class in which the Method is located - * @param obj The Object on which to invoke the Method - * @param methodName The name of the Method - * @param argTypes Argument types - * @param args Arguments to pass to the method - * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = getMethod(clazz, methodName, argTypes); - return m.invoke(obj, args); - } - - /** - * Get the value of a Field, where the Class in which the field is defined is derived from the provided Object - * - * @param obj The object in which the field is located, and from which to get the value - * @param name The name of the Field to get the value from - * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ - public static Object getObject(Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - return getObject(obj.getClass(), obj, name); - } - - /** - * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) - * - * @param obj The Object to get the value from - * @param clazz The Class in which the Field is defined - * @param name The name of the Field - * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @deprecated Use {@link #getObject(Class, Object, String)} instead - */ - @Deprecated - public static Object getObject(Object obj, Class clazz, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - return getObject(clazz, obj, name); - } - - /** - * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) - * - * @param clazz The Class in which the Field is defined - * @param obj The Object to get the value from - * @param name The name of the Field - * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ - public static Object getObject(Class clazz, Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - Field f = getField(clazz, name); - f.setAccessible(true); - return f.get(obj); - } - - /** - * Invoke a Class' constructor. The argument types are derived from the provided arguments - * - * @param clazz The Class in which the Constructor is defined - * @param args The arguments to pass to the Constructor - * @return Returns an instance of the provided Class in which the Constructor is located - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeConstructor(Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class[] argTypes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argTypes[i] = args[i].getClass(); - } - - return invokeConstructor(clazz, argTypes, args); - } - - /** - * Invoke a Class' Constructor, where the argument types are explicitly given (Helpful when working with primitives) - * - * @param clazz The Class in which the Constructor is defined - * @param argTypes The argument types - * @param args The arguments to pass to the constructor - * @return Returns an instance of the provided Class in which the Constructor is located - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ - public static Object invokeConstructor(Class clazz, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Constructor con = getConstructor(clazz, argTypes); - return con.newInstance(args); - } - - /** - * Print all Methods in a Class with their parameters. Will print the Method's modifiers, return type, name and arguments and their types - * - * @param clazz The class to get methods from - */ - public static void printMethodsInClass(Class clazz) { - System.out.println("Methods in " + clazz.getName() + ":"); - - for (Method m : clazz.getDeclaredMethods()) { - StringBuilder print = new StringBuilder(128); - print.append(getModifiers(m.getModifiers())).append(" "); - print.append(m.getReturnType().getName()).append(" "); - print.append(m.getName()).append("("); - - Class[] parameterTypes = m.getParameterTypes(); - int parameterTypesLength = parameterTypes.length; - for (int i = 0; i < parameterTypesLength; i++) { - print.append(parameterTypes[i].getName()); - - if (i != parameterTypesLength - 1) { - print.append(", "); - } - } - - print.append(")"); - System.out.println(print.toString().trim()); - } - } - - /** - * Print all Fields in a Class. Will print the Field's modifiers, type and name - * - * @param clazz The class to get fields from - */ - public static void printFieldsInClass(Class clazz) { - System.out.println("Fields in " + clazz.getName() + ":"); - for (Field f : clazz.getDeclaredFields()) { - String print = getModifiers(f.getModifiers()) + " " + f.getType().getName() + " " + f.getName(); - System.out.println(print.trim()); - } - } - - /** - * Get modifiers as a String - * - * @param modifiers int value of the modifiers - * @return Returns the modifiers as a String - * @see Field#getModifiers() - * @see Class#getModifiers() - * @see Method#getModifiers() - */ - private static String getModifiers(int modifiers) { - StringJoiner modifiersStr = new StringJoiner(" "); - if (Modifier.isPrivate(modifiers)) { - modifiersStr.add("private"); - } - - if (Modifier.isProtected(modifiers)) { - modifiersStr.add("protected"); - } - - if (Modifier.isPublic(modifiers)) { - modifiersStr.add("public"); - } - - if (Modifier.isAbstract(modifiers)) { - modifiersStr.add("abstract"); - } - - if (Modifier.isStatic(modifiers)) { - modifiersStr.add("static"); - } - - if (Modifier.isFinal(modifiers)) { - modifiersStr.add("final"); - } - - if (Modifier.isTransient(modifiers)) { - modifiersStr.add("transient"); - } - - if (Modifier.isVolatile(modifiers)) { - modifiersStr.add("volatile"); - } - - if (Modifier.isNative(modifiers)) { - modifiersStr.add("native"); - } - - if (Modifier.isStrict(modifiers)) { - modifiersStr.add("strictfp"); - } - - if (Modifier.isSynchronized(modifiers)) { - modifiersStr.add("synchronized"); - } - - if (Modifier.isInterface(modifiers)) { - modifiersStr.add("interface"); - } - - return modifiersStr.toString().trim(); - } -} \ No newline at end of file + * Invoke a Method which takes no arguments. The Class in which the Method is defined is derived from the provided Object + * + * @param obj The object to invoke the method on + * @param methodName The name of the Method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName); + } + + /** + * Invoke a Method where the argument types are derived from the provided arguments. The Class in which the Method is defined is derived from the provided Object + * + * @param obj The object to invoke the method on + * @param methodName The name of the Method + * @param args The arguments to pass to the Method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName, args); + } + + /** + * Invoke a Method where the argument types are explicitly given (Helpful when working with primitives). The Class in which the Method is defined is derived from the provided Object. + * + * @param obj The Object to invoke the method on + * @param methodName The name of the Method + * @param argTypes The types of arguments as a Class array + * @param args The arguments as an object array + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName, argTypes, args); + } + + /** + * Invoke a Method where the Class where to find the method is explicitly given (Helpful if the method is located in a superclass). The argument types are derived from the provided arguments + * + * @param clazz The Class where the method is located + * @param obj The Object to invoke the method on + * @param methodName The name of the method + * @param args The arguments to be passed to the method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Class clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class[] argTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argTypes[i] = args[i].getClass(); + } + + return invokeMethod(clazz, obj, methodName, argTypes, args); + } + + /** + * Invoke a Method where the Class where the Method is defined is explicitly given, and the argument types are explicitly given + * + * @param clazz The Class in which the Method is located + * @param obj The Object on which to invoke the Method + * @param methodName The name of the Method + * @param argTypes Argument types + * @param args Arguments to pass to the method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = getMethod(clazz, methodName, argTypes); + return m.invoke(obj, args); + } + + /** + * Get the value of a Field, where the Class in which the field is defined is derived from the provided Object + * + * @param obj The object in which the field is located, and from which to get the value + * @param name The name of the Field to get the value from + * @return Returns the value of the Field + */ + public static Object getObject(Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + return getObject(obj.getClass(), obj, name); + } + + /** + * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) + * + * @param obj The Object to get the value from + * @param clazz The Class in which the Field is defined + * @param name The name of the Field + * @return Returns the value of the Field + * @deprecated Use {@link #getObject(Class, Object, String)} instead + */ + @Deprecated + public static Object getObject(Object obj, Class clazz, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + return getObject(clazz, obj, name); + } + + /** + * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) + * + * @param clazz The Class in which the Field is defined + * @param obj The Object to get the value from + * @param name The name of the Field + * @return Returns the value of the Field + */ + public static Object getObject(Class clazz, Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + Field f = getField(clazz, name); + f.setAccessible(true); + return f.get(obj); + } + + /** + * Invoke a Class' constructor. The argument types are derived from the provided arguments + * + * @param clazz The Class in which the Constructor is defined + * @param args The arguments to pass to the Constructor + * @return Returns an instance of the provided Class in which the Constructor is located + */ + public static Object invokeConstructor(Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class[] argTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argTypes[i] = args[i].getClass(); + } + + return invokeConstructor(clazz, argTypes, args); + } + + /** + * Invoke a Class' Constructor, where the argument types are explicitly given (Helpful when working with primitives) + * + * @param clazz The Class in which the Constructor is defined + * @param argTypes The argument types + * @param args The arguments to pass to the constructor + * @return Returns an instance of the provided Class in which the Constructor is located + */ + public static Object invokeConstructor(Class clazz, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Constructor con = getConstructor(clazz, argTypes); + return con.newInstance(args); + } + + /** + * Print all Methods in a Class with their parameters. Will print the Method's modifiers, return type, name and arguments and their types + * + * @param clazz The class to get methods from + */ + public static void printMethodsInClass(Class clazz) { + System.out.println("Methods in " + clazz.getName() + ":"); + + for (Method m : clazz.getDeclaredMethods()) { + StringBuilder print = new StringBuilder(128); + print.append(getModifiers(m.getModifiers())).append(" "); + print.append(m.getReturnType().getName()).append(" "); + print.append(m.getName()).append("("); + + Class[] parameterTypes = m.getParameterTypes(); + int parameterTypesLength = parameterTypes.length; + for (int i = 0; i < parameterTypesLength; i++) { + print.append(parameterTypes[i].getName()); + + if (i != parameterTypesLength - 1) { + print.append(", "); + } + } + + print.append(")"); + System.out.println(print.toString().trim()); + } + } + + /** + * Print all Fields in a Class. Will print the Field's modifiers, type and name + * + * @param clazz The class to get fields from + */ + public static void printFieldsInClass(Class clazz) { + System.out.println("Fields in " + clazz.getName() + ":"); + for (Field f : clazz.getDeclaredFields()) { + String print = getModifiers(f.getModifiers()) + " " + f.getType().getName() + " " + f.getName(); + System.out.println(print.trim()); + } + } + + /** + * Get modifiers as a String + * + * @param modifiers int value of the modifiers + * @return Returns the modifiers as a String + * @see Field#getModifiers() + * @see Class#getModifiers() + * @see Method#getModifiers() + */ + private static String getModifiers(int modifiers) { + StringJoiner modifiersStr = new StringJoiner(" "); + if (Modifier.isPrivate(modifiers)) { + modifiersStr.add("private"); + } + + if (Modifier.isProtected(modifiers)) { + modifiersStr.add("protected"); + } + + if (Modifier.isPublic(modifiers)) { + modifiersStr.add("public"); + } + + if (Modifier.isAbstract(modifiers)) { + modifiersStr.add("abstract"); + } + + if (Modifier.isStatic(modifiers)) { + modifiersStr.add("static"); + } + + if (Modifier.isFinal(modifiers)) { + modifiersStr.add("final"); + } + + if (Modifier.isTransient(modifiers)) { + modifiersStr.add("transient"); + } + + if (Modifier.isVolatile(modifiers)) { + modifiersStr.add("volatile"); + } + + if (Modifier.isNative(modifiers)) { + modifiersStr.add("native"); + } + + if (Modifier.isStrict(modifiers)) { + modifiersStr.add("strictfp"); + } + + if (Modifier.isSynchronized(modifiers)) { + modifiersStr.add("synchronized"); + } + + if (Modifier.isInterface(modifiers)) { + modifiersStr.add("interface"); + } + + return modifiersStr.toString().trim(); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index a9f99d719..325144b6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -6,44 +6,41 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.BorderPacketFactory; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BorderPacketFactory_1_13 extends BorderPacketFactory { - @Override - public Object center(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_CENTER"); - } + @Override + public Object center(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_CENTER"); + } - @Override - public Object size(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_SIZE"); - } + @Override + public Object size(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_SIZE"); + } - @Override - public Object warningDelay(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_WARNING_TIME"); - } + @Override + public Object warningDelay(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_WARNING_TIME"); + } - @Override - public Object warningDistance(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_WARNING_BLOCKS"); - } + @Override + public Object warningDistance(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_WARNING_BLOCKS"); + } - private Object createPacket(PacketBorder packetBorder, String worldBorderAction) { - try { - Class clazz = NMSUtils.getClass("PacketPlayOutWorldBorder"); - Class actionClazz = NMSUtils.getClass("PacketPlayOutWorldBorder$EnumWorldBorderAction"); - for (Object enumConstant : actionClazz.getEnumConstants()) { - if (enumConstant.toString().equalsIgnoreCase(worldBorderAction)) { - return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass(), actionClazz}, new Object[]{packetBorder.getWorldBorderObject(), enumConstant}); - } - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet for action {}:", worldBorderAction, exception); + private Object createPacket(PacketBorder packetBorder, String worldBorderAction) { + try { + Class clazz = NMSUtils.getClass("PacketPlayOutWorldBorder"); + Class actionClazz = NMSUtils.getClass("PacketPlayOutWorldBorder$EnumWorldBorderAction"); + assert actionClazz != null; + for (Object enumConstant : actionClazz.getEnumConstants()) { + if (enumConstant.toString().equalsIgnoreCase(worldBorderAction)) { + return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass(), actionClazz}, new Object[]{packetBorder.getWorldBorderObject(), enumConstant}); } - return null; + } + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to create packet for action {}:", worldBorderAction, exception); } + return null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java index f744646f1..efaefb83c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java @@ -5,46 +5,42 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class CraftPlayer_1_13 extends CraftPlayer { - /** - * @param player The player to create the CraftPlayer for - */ - public CraftPlayer_1_13(Player player) throws ClassNotFoundException { - super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); - } + /** + * @param player The player to create the CraftPlayer for + */ + public CraftPlayer_1_13(Player player) throws ClassNotFoundException { + super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); + } - /** - * Creates an NMS object of the specified player - * - * @param player The player to create the CraftPlayer for - * @return The NMS object - */ - @Override - public Object get(Player player) { - Object craftPlayer; - try { - craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer:", exception); - craftPlayer = null; - } - return craftPlayer; + /** + * Creates an NMS object of the specified player + * + * @param player The player to create the CraftPlayer for + * @return The NMS object + */ + @Override + public Object get(Player player) { + Object craftPlayer; + try { + craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer:", exception); + craftPlayer = null; } + return craftPlayer; + } - /** - * @return The PlayerConnection of the Player as an object - */ - @Override - public Object getPlayerConnectionObject() { - try { - return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get the playerConnection object:", exception); - return null; - } + /** + * @return The PlayerConnection of the Player as an object + */ + @Override + public Object getPlayerConnectionObject() { + try { + return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to get the playerConnection object:", exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java index d38986f12..1cb6959a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java @@ -9,113 +9,111 @@ import org.bukkit.World; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_13 extends PacketBorder { - /** - * Creates a new packet border. - * Use this constructor if you override this implementation. - * @param nmsClass The NMS class - * @param world The world the border is in - */ - protected PacketBorder_1_13(World world, Class nmsClass) { - super( - nmsClass, - world - ); - } + /** + * Creates a new packet border. + * Use this constructor if you override this implementation. + * + * @param nmsClass The NMS class + * @param world The world the border is in + */ + protected PacketBorder_1_13(World world, Class nmsClass) { + super( + nmsClass, + world + ); + } - /** - * Creates a new packet border. - * @param world The world the border is in. - */ - public PacketBorder_1_13(World world) { - this( - world, - NMSUtils.getClass("WorldBorder") - ); - } + /** + * Creates a new packet border. + * + * @param world The world the border is in. + */ + public PacketBorder_1_13(World world) { + this( + world, + NMSUtils.getClass("WorldBorder") + ); + } - @Override - protected Object createWorldBorder() { - try { - return ReflectionUtil.invokeConstructor(nmsClass); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); - return null; - } + @Override + protected Object createWorldBorder() { + try { + return ReflectionUtil.invokeConstructor(nmsClass); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to create world border:", exception); + return null; } + } - /** - * Sets the world the border is in - * - * @param world The world - */ - @Override - protected void setWorld(World world) { - try { - ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set world:", exception); - } + /** + * Sets the world the border is in + * + * @param world The world + */ + @Override + protected void setWorld(World world) { + try { + ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set world:", exception); } + } - @Override - protected void setSizeField(double size) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[] {double.class}, new Object[]{size}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); - } + @Override + protected void setSizeField(double size) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[]{double.class}, new Object[]{size}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } + } - @Override - protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); - } + @Override + protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } + } - @Override - protected void setCenterField(double x, double z) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[] {double.class, double.class}, new Object[]{x, z}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border center:", exception); - } + @Override + protected void setCenterField(double x, double z) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[]{double.class, double.class}, new Object[]{x, z}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set border center:", exception); } + } - @Override - protected void setWarningTimeField(int warningTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[] {int.class}, new Object[]{warningTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning time:", exception); - } + @Override + protected void setWarningTimeField(int warningTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[]{int.class}, new Object[]{warningTime}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set border warning time:", exception); } + } - @Override - protected void setWarningDistanceField(int warningDistance) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[] {int.class}, new Object[]{warningDistance}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning distance:", exception); - } + @Override + protected void setWarningDistanceField(int warningDistance) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[]{int.class}, new Object[]{warningDistance}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set border warning distance:", exception); } + } - @Override - public void send(Player player, UpdateType updateType) { - try { - Object packet = updateType.createPacket(this); - CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); - craftPlayer.getConnection().sendPacket(packet); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); - } + @Override + public void send(Player player, UpdateType updateType) { + try { + Object packet = updateType.createPacket(this); + CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); + craftPlayer.getConnection().sendPacket(packet); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java index 6cf52e01c..6166e17ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java @@ -5,21 +5,17 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PlayerConnection; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PlayerConnection_1_13 extends PlayerConnection { - public PlayerConnection_1_13(Object connection) throws ClassNotFoundException { - super(NMSUtils.getClass("network.protocol.Packet"), connection); - } + public PlayerConnection_1_13(Object connection) throws ClassNotFoundException { + super(NMSUtils.getClass("network.protocol.Packet"), connection); + } - @Override - public void sendPacket(Object packet) { - try { - ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); - } + @Override + public void sendPacket(Object packet) { + try { + ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java index 101b6e094..353622778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java @@ -5,34 +5,30 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.WorldServer; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class WorldServer_1_13 extends WorldServer { - /** - * @param object The instance of the specified bukkit type - */ - public WorldServer_1_13(World object) throws ClassNotFoundException { - super(object, ReflectionUtil.getBukkitClass("CraftWorld")); - } + /** + * @param object The instance of the specified bukkit type + */ + public WorldServer_1_13(World object) throws ClassNotFoundException { + super(object, ReflectionUtil.getBukkitClass("CraftWorld")); + } - /** - * Creates an NMS object of the specified bukkit type object - * - * @param world An instance of the specified bukkit type - * @return The NMS object - */ - @Override - public Object get(World world) { - Object worldServer; - try { - worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get WorldServer:", exception); - worldServer = null; - } - return worldServer; + /** + * Creates an NMS object of the specified bukkit type object + * + * @param world An instance of the specified bukkit type + * @return The NMS object + */ + @Override + public Object get(World world) { + Object worldServer; + try { + worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to get WorldServer:", exception); + worldServer = null; } + return worldServer; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java index e4eb93d55..07fc1f75c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java @@ -6,39 +6,35 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.BorderPacketFactory; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BorderPacketFactory_1_17 extends BorderPacketFactory { - @Override - public Object center(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderCenterPacket"); - } + @Override + public Object center(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderCenterPacket"); + } - @Override - public Object size(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderSizePacket"); - } + @Override + public Object size(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderSizePacket"); + } - @Override - public Object warningDelay(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderWarningDelayPacket"); - } + @Override + public Object warningDelay(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderWarningDelayPacket"); + } - @Override - public Object warningDistance(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderWarningDistancePacket"); - } + @Override + public Object warningDistance(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderWarningDistancePacket"); + } - private Object createPacket(PacketBorder packetBorder, String className) { - Class clazz = NMSUtils.getClass("network.protocol.game." + className); - try { - return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet {}:", className, exception); - return null; - } + private Object createPacket(PacketBorder packetBorder, String className) { + Class clazz = NMSUtils.getClass("network.protocol.game." + className); + try { + return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to create packet {}:", className, exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java index 59b650c0b..0b816a0c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java @@ -1,44 +1,40 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; +import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class CraftPlayer_1_17 extends CraftPlayer { - /** - * Create a new CraftPlayer - * - * @param player The Player - */ - public CraftPlayer_1_17(Player player) throws ClassNotFoundException { - super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); - } + /** + * Create a new CraftPlayer + * + * @param player The Player + */ + public CraftPlayer_1_17(Player player) throws ClassNotFoundException { + super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); + } - @Override - public Object get(Player player) { - Object craftPlayer; - try { - craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get CraftPlayer:", exception); - craftPlayer = null; - } - return craftPlayer; + @Override + public Object get(Player player) { + Object craftPlayer; + try { + craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to get CraftPlayer:", exception); + craftPlayer = null; } + return craftPlayer; + } - @Override - public Object getPlayerConnectionObject() { - try { - return ReflectionUtil.getObject(this.nmsObject, "b"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get player connection object:", exception); - return null; - } + @Override + public Object getPlayerConnectionObject() { + try { + return ReflectionUtil.getObject(this.nmsObject, "b"); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to get player connection object:", exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java index c251270f5..fb5429065 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java @@ -1,33 +1,17 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17; -import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSUtils; -import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.PacketBorder_1_13; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_17 extends PacketBorder_1_13 { - public PacketBorder_1_17(World world) { - super( - world, - NMSUtils.getClass("world.level.border.WorldBorder") - ); - } + public PacketBorder_1_17(World world) { + super( + world, + NMSUtils.getClass("world.level.border.WorldBorder") + ); + } - @Override - protected Object createWorldBorder() { - try { - return ReflectionUtil.invokeConstructor(nmsClass); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); - return null; - } - } - -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java index 56345b44a..f812aad10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java @@ -5,58 +5,54 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.PacketBorder_1_17; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_18 extends PacketBorder_1_17 { - public PacketBorder_1_18(World world) { - super(world); - } + public PacketBorder_1_18(World world) { + super(world); + } - @Override - protected void setCenterField(double x, double z) { - try { - ReflectionUtil.invokeMethod(worldBorder, "c", new Class[] {double.class, double.class}, new Object[]{x, z}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set center:", exception); - } + @Override + protected void setCenterField(double x, double z) { + try { + ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{double.class, double.class}, new Object[]{x, z}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set center:", exception); } - - @Override - protected void setSizeField(double size) { - try { - ReflectionUtil.invokeMethod(worldBorder, "a", new Class[] {double.class}, new Object[]{size}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); - } + } + + @Override + protected void setSizeField(double size) { + try { + ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class}, new Object[]{size}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } - - @Override - protected void setWarningDistanceField(int warningDistance) { - try { - ReflectionUtil.invokeMethod(worldBorder, "c", new Class[] {int.class}, new Object[]{warningDistance}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning distance:", exception); - } + } + + @Override + protected void setWarningDistanceField(int warningDistance) { + try { + ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{int.class}, new Object[]{warningDistance}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set warning distance:", exception); } - - @Override - protected void setWarningTimeField(int warningTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "b", new Class[] {int.class}, new Object[]{warningTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning time:", exception); - } + } + + @Override + protected void setWarningTimeField(int warningTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "b", new Class[]{int.class}, new Object[]{warningTime}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set warning time:", exception); } - - @Override - protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); - } + } + + @Override + protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java index fadc1c6a7..c254cc8d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java @@ -4,22 +4,18 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.PlayerConnection_1_13; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PlayerConnection_1_18 extends PlayerConnection_1_13 { - public PlayerConnection_1_18(Object connection) throws ClassNotFoundException { - super(connection); - } + public PlayerConnection_1_18(Object connection) throws ClassNotFoundException { + super(connection); + } - @Override - public void sendPacket(Object packet) { - try { - ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); - } + @Override + public void sendPacket(Object packet) { + try { + ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java index 889900976..d759cf87b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java @@ -1,23 +1,17 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; -/** - * An abstract class for other classes that represent NMS classes - - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class AbstractNMSClass { - protected final Class nmsClass; + protected final Class nmsClass; - /** - * @param nmsClass The NMS class - */ - public AbstractNMSClass(Class nmsClass) { - this.nmsClass = nmsClass; - } + /** + * @param nmsClass The NMS class + */ + public AbstractNMSClass(Class nmsClass) { + this.nmsClass = nmsClass; + } - public Class getNMSClass() { - return nmsClass; - } + public Class getNMSClass() { + return nmsClass; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java index 4d7a4b239..2a17b2de9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java @@ -1,14 +1,13 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class BorderPacketFactory { - public abstract Object center(PacketBorder packetBorder); - public abstract Object size(PacketBorder packetBorder); - public abstract Object warningDelay(PacketBorder packetBorder); - public abstract Object warningDistance(PacketBorder packetBorder); + public abstract Object center(PacketBorder packetBorder); + + public abstract Object size(PacketBorder packetBorder); + + public abstract Object warningDelay(PacketBorder packetBorder); + + public abstract Object warningDistance(PacketBorder packetBorder); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java index 998e1774a..7ea0c31ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java @@ -2,26 +2,24 @@ /** * Used for nms classes that are represented by a bukkit class - * @param The bukkit type that represents the NMS class - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 */ public abstract class BukkitNMSClass extends AbstractNMSClass { - public Object nmsObject; + public Object nmsObject; - /** - * @param nmsClass The NMS class - */ - public BukkitNMSClass(Class nmsClass, T bukkitObject) { - super(nmsClass); - this.nmsObject = get(bukkitObject); - } + /** + * @param nmsClass The NMS class + */ + public BukkitNMSClass(Class nmsClass, T bukkitObject) { + super(nmsClass); + this.nmsObject = get(bukkitObject); + } - /** - * Creates an NMS object of the specified bukkit type object - * @param bukkitObject An instance of the specified bukkit type - * @return The NMS object - */ - public abstract Object get(T bukkitObject); + /** + * Creates an NMS object of the specified bukkit type object + * + * @param bukkitObject An instance of the specified bukkit type + * @return The NMS object + */ + public abstract Object get(T bukkitObject); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java index 2f2999bf6..5c241b23a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java @@ -4,31 +4,30 @@ import org.bukkit.entity.Player; /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class CraftPlayer extends BukkitNMSClass { - /** - * @param player The player to create the CraftPlayer for - * @param nmsClass The NMS class - */ - public CraftPlayer(Class nmsClass, Player player) { - super(nmsClass, player); - } + /** + * @param player The player to create the CraftPlayer for + * @param nmsClass The NMS class + */ + public CraftPlayer(Class nmsClass, Player player) { + super(nmsClass, player); + } - /** - * @return The PlayerConnection of the Player as an object - */ - public abstract Object getPlayerConnectionObject(); + /** + * @return The PlayerConnection of the Player as an object + */ + public abstract Object getPlayerConnectionObject(); - /** - * Get a connection to the Player - * - * @return The PlayerConnection - */ - public PlayerConnection getConnection() { - return NMSProvider.createPlayerConnection(this); - } -} \ No newline at end of file + /** + * Get a connection to the Player + * + * @return The PlayerConnection + */ + public PlayerConnection getConnection() { + return NMSProvider.createPlayerConnection(this); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java index 6d35b748b..21f84f094 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java @@ -11,145 +11,155 @@ /** * Provides a WorldBorder that can be sent to the client via packets - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 */ public abstract class PacketBorder extends AbstractNMSClass { - protected Object worldBorder; - - protected final World world; - @Getter - protected double size = 0; - @Getter - protected double centerX = 0; - @Getter - protected double centerZ = 0; - @Getter - protected int warningTime = 0; - @Getter - protected int warningDistance = 0; - - /** - * @param nmsClass The NMS class - * @param world The world the border is in - */ - public PacketBorder(Class nmsClass, World world) { - super(nmsClass); - this.world = world; - - worldBorder = createWorldBorder(); - setWorld(world); + protected Object worldBorder; + + protected final World world; + @Getter + protected double size = 0; + @Getter + protected double centerX = 0; + @Getter + protected double centerZ = 0; + @Getter + protected int warningTime = 0; + @Getter + protected int warningDistance = 0; + + /** + * @param nmsClass The NMS class + * @param world The world the border is in + */ + public PacketBorder(Class nmsClass, World world) { + super(nmsClass); + this.world = world; + + worldBorder = createWorldBorder(); + setWorld(world); + } + + protected abstract Object createWorldBorder(); + + /** + * Sets the world the border is in + * + * @param world The world + */ + protected abstract void setWorld(World world); + + /** + * Sets the size of the border + * + * @param size The size of the border + */ + public void setSize(double size) { + this.size = size; + setSizeField(size); + } + + /** + * Sets the size of the border with an animation + * + * @param size The size of the border + * @param animationTime The time the animation should take (in seconds) + */ + public void setSize(double size, long animationTime) { + animationTime *= 1000; // Convert to milliseconds + transitionSizeBetween(this.size, size, animationTime); + this.size = size; + } + + protected abstract void setSizeField(double size); + + protected abstract void transitionSizeBetween(double oldSize, double newSize, long animationTime); + + /** + * Sets the center of the border + * + * @param x The x coordinate of the center + * @param z The z coordinate of the center + */ + public void setCenter(double x, double z) { + this.centerX = x; + this.centerZ = z; + setCenterField(x, z); + } + + protected abstract void setCenterField(double x, double z); + + /** + * Sets the warning time of the border + * + * @param warningTime The warning time + */ + public void setWarningTime(int warningTime) { + this.warningTime = warningTime; + setWarningTimeField(warningTime); + } + + protected abstract void setWarningTimeField(int warningTime); + + /** + * Sets the warning distance of the border + * + * @param warningDistance The warning distance + */ + public void setWarningDistance(int warningDistance) { + this.warningDistance = warningDistance; + setWarningDistanceField(warningDistance); + } + + protected abstract void setWarningDistanceField(int warningDistance); + + /** + * @param world The world + * @return The world server of the world + */ + protected Object getWorldServer(World world) { + return NMSProvider.createWorldServer(world).getWorldServerObject(); + } + + public void reset(Player player) { + WorldBorder border = player.getWorld().getWorldBorder(); + setSize(border.getSize()); + setCenter(border.getCenter().getX(), border.getCenter().getZ()); + setWarningTime(border.getWarningTime()); + setWarningDistance(border.getWarningDistance()); + send(player, PacketBorder_1_17.UpdateType.values()); + } + + public void send(Player player) { + send(player, UpdateType.values()); + } + + public void send(Player player, UpdateType... updateTypes) { + for (UpdateType updateType : updateTypes) { + send(player, updateType); } + } - protected abstract Object createWorldBorder(); - - /** - * Sets the world the border is in - * @param world The world - */ - protected abstract void setWorld(World world); - - /** - * Sets the size of the border - * @param size The size of the border - */ - public void setSize(double size) { - this.size = size; - setSizeField(size); - } - - /** - * Sets the size of the border with an animation - * @param size The size of the border - * @param animationTime The time the animation should take (in seconds) - */ - public void setSize(double size, long animationTime) { - animationTime *= 1000; // Convert to milliseconds - transitionSizeBetween(this.size, size, animationTime); - this.size = size; - } - - protected abstract void setSizeField(double size); - protected abstract void transitionSizeBetween(double oldSize, double newSize, long animationTime); - - /** - * Sets the center of the border - * @param x The x coordinate of the center - * @param z The z coordinate of the center - */ - public void setCenter(double x, double z) { - this.centerX = x; - this.centerZ = z; - setCenterField(x, z); - } - protected abstract void setCenterField(double x, double z); - - /** - * Sets the warning time of the border - * @param warningTime The warning time - */ - public void setWarningTime(int warningTime) { - this.warningTime = warningTime; - setWarningTimeField(warningTime); - } - protected abstract void setWarningTimeField(int warningTime); - - /** - * Sets the warning distance of the border - * @param warningDistance The warning distance - */ - public void setWarningDistance(int warningDistance) { - this.warningDistance = warningDistance; - setWarningDistanceField(warningDistance); - } - protected abstract void setWarningDistanceField(int warningDistance); - - /** - * @param world The world - * @return The world server of the world - */ - protected Object getWorldServer(World world) { - return NMSProvider.createWorldServer(world).getWorldServerObject(); - } - - public void reset(Player player) { - WorldBorder border = player.getWorld().getWorldBorder(); - setSize(border.getSize()); - setCenter(border.getCenter().getX(), border.getCenter().getZ()); - setWarningTime(border.getWarningTime()); - setWarningDistance(border.getWarningDistance()); - send(player, PacketBorder_1_17.UpdateType.values()); - } - - public void send(Player player) { - send(player, UpdateType.values()); - } - public void send(Player player, UpdateType... updateTypes) { - for (UpdateType updateType : updateTypes) { - send(player, updateType); - } - } - public abstract void send(Player player, PacketBorder_1_17.UpdateType updateType); + public abstract void send(Player player, PacketBorder_1_17.UpdateType updateType); public Object getWorldBorderObject() { - return worldBorder; - } + return worldBorder; + } - public enum UpdateType { - CENTER(NMSProvider.getBorderPacketFactory()::center), - SIZE(NMSProvider.getBorderPacketFactory()::size), - WARNING_DELAY(NMSProvider.getBorderPacketFactory()::warningDelay), - WARNING_DISTANCE(NMSProvider.getBorderPacketFactory()::warningDistance); + public enum UpdateType { + CENTER(NMSProvider.getBorderPacketFactory()::center), + SIZE(NMSProvider.getBorderPacketFactory()::size), + WARNING_DELAY(NMSProvider.getBorderPacketFactory()::warningDelay), + WARNING_DISTANCE(NMSProvider.getBorderPacketFactory()::warningDistance); - private final Function packetFactory; + private final Function packetFactory; - UpdateType(Function packetFactory) { - this.packetFactory = packetFactory; - } + UpdateType(Function packetFactory) { + this.packetFactory = packetFactory; + } - public Object createPacket(PacketBorder border) { - return packetFactory.apply(border); - } + public Object createPacket(PacketBorder border) { + return packetFactory.apply(border); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java index fbc1526e4..d78c28323 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java @@ -1,25 +1,24 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class PlayerConnection extends AbstractNMSClass { - protected final Object connection; + protected final Object connection; - public PlayerConnection(Class nmsClass, Object connection) { - super(nmsClass); - this.connection = connection; - } + public PlayerConnection(Class nmsClass, Object connection) { + super(nmsClass); + this.connection = connection; + } - /** - * Send a packet - *

- * The caller must guarantee the passed in object is a Packet - * - * @param packet The packet to send - */ - public abstract void sendPacket(Object packet); -} \ No newline at end of file + /** + * Send a packet + *

+ * The caller must guarantee the passed in object is a Packet + * + * @param packet The packet to send + */ + public abstract void sendPacket(Object packet); +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java index 7737f65ed..6cf82f8ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java @@ -2,20 +2,16 @@ import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class WorldServer extends BukkitNMSClass { - /** - * @param object The instance of the specified bukkit type - * @param nmsClass The NMS class - */ - protected WorldServer(World object, Class nmsClass) { - super(nmsClass, object); - } + /** + * @param object The instance of the specified bukkit type + * @param nmsClass The NMS class + */ + protected WorldServer(World object, Class nmsClass) { + super(nmsClass, object); + } - public Object getWorldServerObject() { - return nmsObject; - } -} \ No newline at end of file + public Object getWorldServerObject() { + return nmsObject; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 4f865e494..942aa4f58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.utils.item; -import java.util.UUID; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -8,86 +7,80 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DefaultItem { - // Owner: MHF_ArrowLeft - private static final UUID ARROW_LEFT_UUID = UUID.fromString("a68f0b64-8d14-4000-a95f-4b9ba14f8df9"); - // Owner: MHF_ArrowRight - private static final UUID ARROW_RIGHT_UUID = UUID.fromString("50c8510b-5ea0-4d60-be9a-7d542d6cd156"); - - @Nonnull - public static String getItemPrefix() { - return Message.forName("item-prefix").asString() + "§e"; - } - - @Nonnull - public static ItemBuilder navigateBack() { - return new SkullBuilder(ARROW_LEFT_UUID, "MHF_ArrowLeft").setName(Message.forName("navigate-back")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder navigateNext() { - return new SkullBuilder(ARROW_RIGHT_UUID, "MHF_ArrowRight").setName(Message.forName("navigate-next")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder navigateBackMainMenu() { - return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder status(boolean enabled) { - return enabled ? enabled() : disabled(); - } - - @Nonnull - public static ItemBuilder enabled() { - return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder disabled() { - return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder customize() { - return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder value(int value) { - return value(value, "§e"); - } - - @Nonnull - public static ItemBuilder value(int value, @Nonnull String prefix) { - return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); - } - - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull String name) { - return new ItemBuilder(material, getTitle(name)); - } - - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull Message message) { - ItemBuilder itemBuilder = new ItemBuilder(material, message); - return itemBuilder.setName(getTitle(message)); - } - - @Nonnull - private static String getTitle(@Nonnull Message message) { - return getTitle(message.asString()); - } - - @Nonnull - private static String getTitle(@Nonnull String text) { - return Message.forName("item-setting-info").asString(text); - } + private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", + ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; + + @Nonnull + public static String getItemPrefix() { + return Message.forName("item-prefix").asString() + "§e"; + } + + @Nonnull + public static ItemBuilder navigateBack() { + return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder navigateNext() { + return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder navigateBackMainMenu() { + return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder status(boolean enabled) { + return enabled ? enabled() : disabled(); + } + + @Nonnull + public static ItemBuilder enabled() { + return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder disabled() { + return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder customize() { + return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder value(int value) { + return value(value, "§e"); + } + + @Nonnull + public static ItemBuilder value(int value, @Nonnull String prefix) { + return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); + } + + @Nonnull + public static ItemBuilder create(@Nonnull Material material, @Nonnull String name) { + return new ItemBuilder(material, getTitle(name)); + } + + @Nonnull + public static ItemBuilder create(@Nonnull Material material, @Nonnull Message message) { + ItemBuilder itemBuilder = new ItemBuilder(material, message); + return itemBuilder.setName(getTitle(message)); + } + + @Nonnull + private static String getTitle(@Nonnull Message message) { + return getTitle(message.asString()); + } + + @Nonnull + private static String getTitle(@Nonnull String text) { + return Message.forName("item-setting-info").asString(text); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 341ac8904..b457a897e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -1,16 +1,11 @@ package net.codingarea.challenges.plugin.utils.item; -import net.anweisen.utilities.bukkit.utils.item.BannerPattern; -import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; -import net.anweisen.utilities.common.annotations.DeprecatedSince; -import net.anweisen.utilities.common.annotations.ReplaceWith; -import net.codingarea.challenges.plugin.Challenges; +import com.google.gson.JsonParser; +import lombok.NonNull; +import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; +import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; @@ -18,436 +13,426 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; +import org.bukkit.profile.PlayerProfile; +import org.bukkit.profile.PlayerTextures; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import java.util.Collection; import java.util.List; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ -public class ItemBuilder extends net.anweisen.utilities.bukkit.utils.item.ItemBuilder { - - public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); - - protected ItemDescription builtByItemDescription; - - public ItemBuilder(@Nonnull ItemStack item) { - super(item); - } - - public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { - super(item, meta); - } - - public ItemBuilder() { - this(Material.BARRIER, ItemDescription.empty()); - } - - public ItemBuilder(@Nonnull Material material) { - super(material); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull Message message) { - this(material, message.asItemDescription()); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull Message message, Object... args) { - this(material, message.asItemDescription(args)); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { - this(material); - applyFormat(description); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull Message message) { - return setLore(message.asArray()); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull List lore) { - return (ItemBuilder) super.setLore(lore); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull String... lore) { - return (ItemBuilder) super.setLore(lore); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull String... lore) { - return (ItemBuilder) super.appendLore(lore); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull Collection lore) { - return (ItemBuilder) super.appendLore(lore); - } - - @Nonnull - public ItemBuilder setName(@Nullable String name) { - return (ItemBuilder) super.setName(name); - } - - @Nonnull - public ItemBuilder setName(@Nullable Object name) { - return (ItemBuilder) super.setName(name); - } - - @Nonnull - public ItemBuilder setName(@Nonnull String... content) { - return (ItemBuilder) super.setName(content); - } - - @Nonnull - public ItemBuilder appendName(@Nullable Object sequence) { - return (ItemBuilder) super.appendName(sequence); - } - - @Nonnull - public ItemBuilder name(@Nullable Object name) { - return (ItemBuilder) super.name(name); - } - - @Nonnull - public ItemBuilder name(@Nonnull String... content) { - return (ItemBuilder) super.name(content); - } - - @Nonnull - public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { - return (ItemBuilder) super.addEnchantment(enchantment, level); - } - - @Nonnull - public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { - return (ItemBuilder) super.enchant(enchantment, level); - } - - @Nonnull - public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { - return (ItemBuilder) super.addFlag(flags); - } - - @Nonnull - public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { - return (ItemBuilder) super.removeFlag(flags); - } - - @Nonnull - public ItemBuilder hideAttributes() { - return (ItemBuilder) super.hideAttributes(); - } - - @Nonnull - public ItemBuilder showAttributes() { - return (ItemBuilder) super.showAttributes(); - } - - @Nonnull - public ItemBuilder setUnbreakable(boolean unbreakable) { - return (ItemBuilder) super.setUnbreakable(unbreakable); - } - - @Nonnull - public ItemBuilder unbreakable() { - return (ItemBuilder) super.unbreakable(); - } - - @Nonnull - public ItemBuilder breakable() { - return (ItemBuilder) super.breakable(); - } - - @Nonnull - public ItemBuilder setAmount(int amount) { - return (ItemBuilder) super.setAmount(amount); - } - - @Nonnull - public ItemBuilder amount(int amount) { - return (ItemBuilder) super.amount(amount); - } - - @Nonnull - public ItemBuilder setDamage(int damage) { - return (ItemBuilder) super.setDamage(damage); - } - - @Nonnull - public ItemBuilder damage(int damage) { - return (ItemBuilder) super.damage(damage); - } - - @Nonnull - public ItemBuilder setType(@Nonnull Material material) { - return (ItemBuilder) super.setType(material); - } - - @Nonnull - public ItemBuilder applyFormat(@Nonnull ItemDescription description) { - builtByItemDescription = description; - setName(description.getName()); - setLore(description.getLore()); - return this; - } - - @Nullable - public ItemDescription getBuiltByItemDescription() { - return builtByItemDescription; - } - - @Override - public ItemBuilder clone() { - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); - builder.builtByItemDescription = builtByItemDescription; - return builder; - } - - public static class BannerBuilder extends ItemBuilder { - - public BannerBuilder(@Nonnull Material material) { - super(material); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { - super(material, description); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public BannerBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { - return addPattern(pattern.getPatternType(), color); - } - - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { - getMeta().addPattern(new Pattern(color, pattern)); - return this; - } - - @Nonnull - @Override - public BannerMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class SkullBuilder extends ItemBuilder { - - public SkullBuilder() { - super(Material.PLAYER_HEAD); - } - - /** - * @deprecated Use uuid and name to be able to access database cached textures to reduce loading time - */ - @Deprecated - @DeprecatedSince("2.0") - public SkullBuilder(@Nonnull String owner) { - super(Material.PLAYER_HEAD); - setOwner(owner); - } - - /** - * @deprecated Use uuid and name to be able to access database cached textures to reduce loading time - */ - @Deprecated - @DeprecatedSince("2.0") - public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { - super(Material.PLAYER_HEAD, name, lore); - setOwner(owner); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName) { - super(Material.PLAYER_HEAD); - setOwner(ownerUUID, ownerName); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull Message message) { - super(Material.PLAYER_HEAD, message); - setOwner(ownerUUID, ownerName); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull ItemDescription description) { - super(Material.PLAYER_HEAD, description); - setOwner(ownerUUID, ownerName); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull String name, @Nonnull String... lore) { - super(Material.PLAYER_HEAD, name, lore); - setOwner(ownerUUID, ownerName); - } - - @Nonnull - @Deprecated - @DeprecatedSince("2.0") - @ReplaceWith("setOwner(UUID)") - public ItemBuilder.SkullBuilder setOwner(@Nonnull String owner) { - getMeta().setOwner(owner); - return this; - } - - @Nonnull - public ItemBuilder.SkullBuilder setOwner(@Nonnull UUID uuid, @Nonnull String name) { - if (Challenges.getInstance().getDatabaseManager().isEnabled()) { - String textures = DatabaseHelper.getTextures(uuid); - if (textures != null) { - GameProfileUtils.applyTextures(getMeta(), uuid, name, textures); - return this; - } - } - - setOwner(name); - return this; - } - - @Nonnull - @Override - public SkullMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class PotionBuilder extends ItemBuilder { - - public PotionBuilder(@Nonnull Material material) { - super(material); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public PotionBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - @CheckReturnValue - public static ItemBuilder createWaterBottle() { - return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); - } - - @Nonnull - public ItemBuilder.PotionBuilder addEffect(@Nonnull PotionEffect effect) { - getMeta().addCustomEffect(effect, true); - return this; - } - - @Nonnull - public ItemBuilder.PotionBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public ItemBuilder.PotionBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public PotionMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class LeatherArmorBuilder extends ItemBuilder { - - public LeatherArmorBuilder(@Nonnull Material material) { - super(material); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public LeatherArmorBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public ItemBuilder.LeatherArmorBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public ItemBuilder.LeatherArmorBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public LeatherArmorMeta getMeta() { - return getCastedMeta(); - } - - } +public class ItemBuilder extends net.codingarea.commons.bukkit.utils.item.ItemBuilder { + + public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); + + protected ItemDescription builtByItemDescription; + + public ItemBuilder(@Nonnull ItemStack item) { + super(item); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + super(item, meta); + } + + public ItemBuilder() { + this(Material.BARRIER, ItemDescription.empty()); + } + + public ItemBuilder(@Nonnull Material material) { + super(material); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull Message message) { + this(material, message.asItemDescription()); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull Message message, Object... args) { + this(material, message.asItemDescription(args)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + this(material); + applyFormat(description); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull Message message) { + return setLore(message.asArray()); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + return (ItemBuilder) super.setLore(lore); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return (ItemBuilder) super.setLore(lore); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return (ItemBuilder) super.appendLore(lore); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + return (ItemBuilder) super.appendLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + return (ItemBuilder) super.setName(name); + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return (ItemBuilder) super.setName(name); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + return (ItemBuilder) super.setName(content); + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + return (ItemBuilder) super.appendName(sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return (ItemBuilder) super.name(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return (ItemBuilder) super.name(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + return (ItemBuilder) super.addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return (ItemBuilder) super.enchant(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + return (ItemBuilder) super.addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + return (ItemBuilder) super.removeFlag(flags); + } + + @Nonnull + public ItemBuilder hideAttributes() { + return (ItemBuilder) super.hideAttributes(); + } + + @Nonnull + public ItemBuilder showAttributes() { + return (ItemBuilder) super.showAttributes(); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + return (ItemBuilder) super.setUnbreakable(unbreakable); + } + + @Nonnull + public ItemBuilder unbreakable() { + return (ItemBuilder) super.unbreakable(); + } + + @Nonnull + public ItemBuilder breakable() { + return (ItemBuilder) super.breakable(); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + return (ItemBuilder) super.setAmount(amount); + } + + @Nonnull + public ItemBuilder amount(int amount) { + return (ItemBuilder) super.amount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + return (ItemBuilder) super.setDamage(damage); + } + + @Nonnull + public ItemBuilder damage(int damage) { + return (ItemBuilder) super.damage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + return (ItemBuilder) super.setType(material); + } + + @Nonnull + public ItemBuilder applyFormat(@Nonnull ItemDescription description) { + builtByItemDescription = description; + setName(description.getName()); + setLore(description.getLore()); + return this; + } + + @Nullable + public ItemDescription getBuiltByItemDescription() { + return builtByItemDescription; + } + + @Override + public ItemBuilder clone() { + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + builder.builtByItemDescription = builtByItemDescription; + return builder; + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + super(material, description); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public ItemBuilder.BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public ItemBuilder.BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(Message message) { + super(Material.PLAYER_HEAD, message); + } + + public SkullBuilder(String name, String... lore) { + super(Material.PLAYER_HEAD, name, lore); + } + + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull OfflinePlayer owner) { + getMeta().setOwningPlayer(owner); + return this; + } + + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull UUID uuid, @NonNull String name) { + PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); + getMeta().setOwnerProfile(profile); + return this; + } + + public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { + UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); + + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + PlayerTextures texture = profile.getTextures(); + + try { + texture.setSkin(new URL(textureUrl)); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid texture url", e); + } + + profile.setTextures(texture); + getMeta().setOwnerProfile(profile); + return this; + } + + public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), + StandardCharsets.UTF_8); + + String textureUrl = JsonParser.parseString(textureUrlJson) + .getAsJsonObject() + .get("textures").getAsJsonObject() + .get("SKIN").getAsJsonObject() + .get("url").getAsString(); + + return setTexture(textureUrl); + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + @Nonnull + public ItemBuilder.PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public ItemBuilder.PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public ItemBuilder.PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public ItemBuilder.LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public ItemBuilder.LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java deleted file mode 100644 index b7afc6b48..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ /dev/null @@ -1,123 +0,0 @@ -package net.codingarea.challenges.plugin.utils.item; - -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; - -import javax.annotation.Nonnull; - -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ -public class ItemUtils { - - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { - try { - return Material.valueOf("COOKED_" + material.name()); - } catch (Exception ex) { - return material; // No cooked material is available - } - } - - public static boolean isObtainableInSurvival(@Nonnull Material material) { - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.endsWith("_SPAWN_EGG")) return false; - if (name.startsWith("INFESTED_")) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "BEDROCK": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL_FRAME": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "LAVA": - case "WATER": - case "LARGE_FERN": - case "TALL_GRASS": - case "TALL_SEAGRASS": - case "PATH_BLOCK": - case "CHORUS_PLANT": - case "PETRIFIED_OAK_SLAB": - case "FARMLAND": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "SPAWNER": - case "AMETHYST_CLUSTER": - case "BUDDING_AMETHYST": - case "POWDER_SNOW": - case "LIGHT": - case "BUNDLE": - case "REINFORCED_DEEPSLATE": - case "FROGSPAWN": - return false; - } - - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - if (name.equals("SCULK_SENSOR")) { - return false; - } - } - - return true; - } - - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { - if (!material.isBlock()) return false; - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "PETRIFIED_OAK_SLAB": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "LIGHT": - case "BUNDLE": - return false; - } - - return true; - } - - public static void damageItem(@Nonnull ItemStack item) { - damageItem(item, 1); - } - - public static void damageItem(@Nonnull ItemStack item, int amount) { - ItemMeta meta = item.getItemMeta(); - if (meta == null) return; - if (!(meta instanceof Damageable)) return; - Damageable damageable = (Damageable) meta; - damageable.setDamage(damageable.getDamage() + amount); - item.setItemMeta(meta); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 66c2eeeca..771eb1737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -1,83 +1,79 @@ package net.codingarea.challenges.plugin.utils.logging; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ConsolePrint { - private ConsolePrint() { - } + private ConsolePrint() { + } - public static void notSpigot() { - log(""); - log("============================================================================================="); - log(""); - log("Your server does NOT run an instance of spigot (Your server: " + Bukkit.getVersion() + ")"); - log("Please use an instance of spigot or paper to be able to use this plugin!"); - log(""); - log("Paper Download: https://papermc.io/downloads"); - log(""); - log("============================================================================================="); - log(""); - } + public static void notSpigot() { + log(""); + log("============================================================================================="); + log(""); + log("Your server does NOT run an instance of spigot (Your server: " + Bukkit.getVersion() + ")"); + log("Please use an instance of spigot or paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================================================================================="); + log(""); + } - public static void unknownLanguage(@Nullable String language) { - log(""); - log("Found unknown language '" + language + "'!"); - log("Defaulting to en (English)"); - log(""); - } + public static void unknownLanguage(@Nullable String language) { + log(""); + log("Found unknown language '" + language + "'!"); + log("Defaulting to en (English)"); + log(""); + } - public static void unableToGetLanguages() { - log(""); - log("No languages found to load"); - log("Is the server / plugin set up correctly?"); - log(""); - } + public static void unableToGetLanguages() { + log(""); + log("No languages found to load"); + log("Is the server / plugin set up correctly?"); + log(""); + } - public static void alreadyExecutingContentLoader() { - log(""); - log("Cannot load contents; Already loading contents?"); - log("Are you reloading too fast?"); - log(""); - } + public static void alreadyExecutingContentLoader() { + log(""); + log("Cannot load contents; Already loading contents?"); + log("Are you reloading too fast?"); + log(""); + } - public static void accessBlocked() { - log(" "); - log(" "); - log("██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗███████╗██████╗░"); - log("██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝██╔════╝██╔══██╗"); - log("██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░█████╗░░██║░░██║"); - log("██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░██╔══╝░░██║░░██║"); - log("██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗███████╗██████╔╝"); - log("╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░"); - log(" "); - log("Your server's access is blocked."); - log("For more information and support visit our discord server: https://discord.coding-area.net"); - log(" "); - log(" "); - } + public static void accessBlocked() { + log(" "); + log(" "); + log("██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗███████╗██████╗░"); + log("██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝██╔════╝██╔══██╗"); + log("██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░█████╗░░██║░░██║"); + log("██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░██╔══╝░░██║░░██║"); + log("██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗███████╗██████╔╝"); + log("╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░"); + log(" "); + log("Your server's access is blocked."); + log("For more information and support visit our discord server: https://discord.coding-area.net"); + log(" "); + log(" "); + } - public static void noMongoDependencies() { - log(""); - log("============================================================================================="); - log(""); - log("Cannot use MongoDB as database without the Challenges-MongoConnector dependency plugin."); - log("Please add this plugin in order to be able to access a mongodb database."); - log(""); - log("============================================================================================="); - log(""); - } + public static void noMongoDependencies() { + log(""); + log("============================================================================================="); + log(""); + log("Cannot use MongoDB as database without the Challenges-MongoConnector dependency plugin."); + log("Please add this plugin in order to be able to access a mongodb database."); + log(""); + log("============================================================================================="); + log(""); + } - private static void log(@Nonnull String message) { - Logger.error(message); - } + private static void log(@Nonnull String message) { + Logger.error(message); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java index fa142bc00..44db4456d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java @@ -2,26 +2,22 @@ import org.bukkit.Material; -/** - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public final class ArmorUtils { - private ArmorUtils() { - } + private ArmorUtils() { + } - public static Material[] getArmor() { - return new Material[]{ - Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.IRON_HELMET, - Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.DIAMOND_HELMET, - Material.GOLDEN_CHESTPLATE, Material.GOLDEN_LEGGINGS, Material.GOLDEN_BOOTS, Material.GOLDEN_HELMET, - Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.LEATHER_HELMET, - Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_HELMET, - Utils.getMaterial("NETHERITE_CHESTPLATE"), Utils.getMaterial("NETHERITE_LEGGINGS"), - Utils.getMaterial("NETHERITE_BOOTS"), Utils.getMaterial("NETHERITE_HELMET"), - Material.TURTLE_HELMET - }; - } + public static Material[] getArmor() { + return new Material[]{ + Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.IRON_HELMET, + Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.DIAMOND_HELMET, + Material.GOLDEN_CHESTPLATE, Material.GOLDEN_LEGGINGS, Material.GOLDEN_BOOTS, Material.GOLDEN_HELMET, + Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.LEATHER_HELMET, + Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_HELMET, + Utils.getMaterial("NETHERITE_CHESTPLATE"), Utils.getMaterial("NETHERITE_LEGGINGS"), + Utils.getMaterial("NETHERITE_BOOTS"), Utils.getMaterial("NETHERITE_HELMET"), + Material.TURTLE_HELMET + }; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index c79abf8e1..dc533cbb8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -11,216 +11,215 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class BlockUtils { - private static final BlockFace[] faces = { - BlockFace.UP, BlockFace.DOWN, - BlockFace.NORTH, BlockFace.EAST, - BlockFace.SOUTH, BlockFace.WEST - }; - - private BlockUtils() { - } - - public static boolean isSameBlockLocation(@Nullable Location loc1, @Nullable Location loc2) { - if (loc1 == null || loc2 == null) return true; - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getBlockX() == loc2.getBlockX() - && loc1.getBlockY() == loc2.getBlockY() - && loc1.getBlockZ() == loc2.getBlockZ(); - } - - public static boolean isSameBlockLocationIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { - if (loc1 == null || loc2 == null) return false; - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getBlockX() == loc2.getBlockX() - && loc1.getBlockZ() == loc2.getBlockZ(); - } - - public static boolean isSameLocation(@Nonnull Location loc1, @Nonnull Location loc2) { - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.distance(loc2) < 0.1; - } - - public static boolean isSameLocationIgnoreHeight(@Nonnull Location loc1, @Nonnull Location loc2) { - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getX() == loc2.getX() - && loc1.getZ() == loc2.getZ(); - } - - public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) { - if (chunk1.getWorld() != chunk2.getWorld()) return false; - return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); - } - - /** - * @param block middle block - * @return the block above, under, in the front, behind, to the left and to the right of the middle block - */ - @Nonnull - public static List getBlocksAroundBlock(@Nonnull Block block) { - List list = new ArrayList<>(); - for (BlockFace face : faces) { - list.add(block.getRelative(face)); - } - return list; - } - - public static Material getTerracotta(int subId) { - switch (subId) { - case 2: - return Material.ORANGE_TERRACOTTA; - case 3: - return Material.MAGENTA_TERRACOTTA; - case 4: - return Material.LIGHT_BLUE_TERRACOTTA; - case 5: - return Material.YELLOW_TERRACOTTA; - case 6: - return Material.LIME_TERRACOTTA; - case 7: - return Material.PINK_TERRACOTTA; - case 8: - return Material.GRAY_TERRACOTTA; - case 9: - return Material.LIGHT_GRAY_TERRACOTTA; - case 10: - return Material.CYAN_TERRACOTTA; - case 11: - return Material.PURPLE_TERRACOTTA; - case 12: - return Material.BLUE_TERRACOTTA; - case 13: - return Material.BROWN_TERRACOTTA; - case 14: - return Material.GREEN_TERRACOTTA; - case 15: - return Material.RED_TERRACOTTA; - case 16: - return Material.BLACK_TERRACOTTA; - default: - return Material.WHITE_TERRACOTTA; - } - } - - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type) { - createBlockPath(from, to, type, true); - } - - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type, boolean playSound) { - if (from == null || to == null) return; - if (isSameBlockLocationIgnoreHeight(from, to)) return; - - setBlockNatural(getBlockBelow(to), type, playSound); - } - - /** - * Sets the material of the block and breaks snow or other not solid blocks on top of it - * - * @param block the block of block to replace - * @param type the type to set as the block type - */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate) { - setBlockNatural(block, type, blockUpdate, true); - } - - /** - * Sets the material of the block and breaks snow or other not solid blocks on top of it - * - * @param block the block of block to replace - * @param type the type to set as the block type - * @param playSound if a breaking sound for the block on top should be played - */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate, boolean playSound) { - if (block == null || !block.getType().isSolid()) return; - - Block upperBlock = block.getLocation().add(0, 1, 0).getBlock(); - - if (!upperBlock.getType().isSolid()) { - upperBlock.breakNaturally(); - if (playSound) { - // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK - } - - } - - block.setType(type, blockUpdate); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location) { - return getBlockBelow(location, 0.1); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonSolid) { - return getBlockBelow(location, 0.1, ignoreNonSolid); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset) { - return getBlockBelow(location, offset, true); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset, boolean ignoreNonSolid) { - - Block block; - if (offset == -1) { - block = getBlockBelow(location, 0.1, ignoreNonSolid); - if (block == null) { - block = getBlockBelow(location, 1, ignoreNonSolid); - if (block == null) { - block = getBlockBelow(location, 1.5, ignoreNonSolid); - } - } - - } else { - block = location.clone().subtract(0, offset, 0).getBlock(); - } - - if (block == null) return null; - if (ignoreNonSolid && !block.getType().isSolid()) { - return null; - } - return block; - } - - public static boolean isEndItem(Material material) { - String name = material.name(); - return material == Material.ELYTRA || - name.contains("PURPUR") || - name.contains("SHULKER") || - name.contains("END"); - } - - public static boolean isTooHardToGet(Material material) { - String name = material.name(); - return name.contains("EXPOSED") || - name.contains("WEATHERED") || - name.contains("OXIDIZED") || - name.contains("BUD"); - } + private static final BlockFace[] faces = { + BlockFace.UP, BlockFace.DOWN, + BlockFace.NORTH, BlockFace.EAST, + BlockFace.SOUTH, BlockFace.WEST + }; + + private BlockUtils() { + } + + public static boolean isSameBlockLocation(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return true; + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockY() == loc2.getBlockY() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + public static boolean isSameBlockLocationIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return false; + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + public static boolean isSameLocation(@Nonnull Location loc1, @Nonnull Location loc2) { + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.distance(loc2) < 0.1; + } + + public static boolean isSameLocationIgnoreHeight(@Nonnull Location loc1, @Nonnull Location loc2) { + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getX() == loc2.getX() + && loc1.getZ() == loc2.getZ(); + } + + public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) { + if (chunk1.getWorld() != chunk2.getWorld()) return false; + return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); + } + + public static boolean isSameBlockIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + /** + * @param block middle block + * @return the block above, under, in the front, behind, to the left and to the right of the middle block + */ + @Nonnull + public static List getBlocksAroundBlock(@Nonnull Block block) { + List list = new ArrayList<>(); + for (BlockFace face : faces) { + list.add(block.getRelative(face)); + } + return list; + } + + public static Material getTerracotta(int subId) { + switch (subId) { + case 2: + return Material.ORANGE_TERRACOTTA; + case 3: + return Material.MAGENTA_TERRACOTTA; + case 4: + return Material.LIGHT_BLUE_TERRACOTTA; + case 5: + return Material.YELLOW_TERRACOTTA; + case 6: + return Material.LIME_TERRACOTTA; + case 7: + return Material.PINK_TERRACOTTA; + case 8: + return Material.GRAY_TERRACOTTA; + case 9: + return Material.LIGHT_GRAY_TERRACOTTA; + case 10: + return Material.CYAN_TERRACOTTA; + case 11: + return Material.PURPLE_TERRACOTTA; + case 12: + return Material.BLUE_TERRACOTTA; + case 13: + return Material.BROWN_TERRACOTTA; + case 14: + return Material.GREEN_TERRACOTTA; + case 15: + return Material.RED_TERRACOTTA; + case 16: + return Material.BLACK_TERRACOTTA; + default: + return Material.WHITE_TERRACOTTA; + } + } + + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type) { + createBlockPath(from, to, type, true); + } + + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type, boolean playSound) { + if (from == null || to == null) return; + if (isSameBlockLocationIgnoreHeight(from, to)) return; + + setBlockNatural(getBlockBelow(to), type, playSound); + } + + /** + * Sets the material of the block and breaks snow or other not solid blocks on top of it + * + * @param block the block of block to replace + * @param type the type to set as the block type + */ + public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate) { + setBlockNatural(block, type, blockUpdate, true); + } + + /** + * Sets the material of the block and breaks snow or other not solid blocks on top of it + * + * @param block the block of block to replace + * @param type the type to set as the block type + * @param playSound if a breaking sound for the block on top should be played + */ + public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate, boolean playSound) { + if (block == null || !block.getType().isSolid()) return; + + Block upperBlock = block.getLocation().add(0, 1, 0).getBlock(); + + if (!upperBlock.getType().isSolid()) { + upperBlock.breakNaturally(); + // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK + + } + + block.setType(type, blockUpdate); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location) { + return getBlockBelow(location, 0.1); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonSolid) { + return getBlockBelow(location, 0.1, ignoreNonSolid); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, double offset) { + return getBlockBelow(location, offset, true); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, double offset, boolean ignoreNonSolid) { + + Block block; + if (offset == -1) { + block = getBlockBelow(location, 0.1, ignoreNonSolid); + if (block == null) { + block = getBlockBelow(location, 1, ignoreNonSolid); + if (block == null) { + block = getBlockBelow(location, 1.5, ignoreNonSolid); + } + } + + } else { + block = location.clone().subtract(0, offset, 0).getBlock(); + } + + if (block == null) return null; + if (ignoreNonSolid && !block.getType().isSolid()) { + return null; + } + return block; + } + + public static boolean isEndItem(Material material) { + String name = material.name(); + return material == Material.ELYTRA || + name.contains("PURPUR") || + name.contains("SHULKER") || + name.contains("END"); + } + + public static boolean isTooHardToGet(Material material) { + String name = material.name(); + return name.contains("EXPOSED") || + name.contains("WEATHERED") || + name.contains("OXIDIZED") || + name.contains("BUD"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java index 2078261ed..86d28fe59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java @@ -10,154 +10,150 @@ import java.util.Map; import java.util.Optional; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ColorConversions { - private static final Map colorsByChatColor = new HashMap<>(); - - static { - colorsByChatColor.put(ChatColor.BLACK, Color.decode("#000000")); - colorsByChatColor.put(ChatColor.DARK_BLUE, Color.decode("#0000A8")); - colorsByChatColor.put(ChatColor.DARK_GREEN, Color.decode("#00A800")); - colorsByChatColor.put(ChatColor.DARK_AQUA, Color.decode("#00A8A8")); - colorsByChatColor.put(ChatColor.DARK_RED, Color.decode("#A80000")); - colorsByChatColor.put(ChatColor.DARK_PURPLE, Color.decode("#A800A8")); - colorsByChatColor.put(ChatColor.GOLD, Color.decode("#FBA800")); - colorsByChatColor.put(ChatColor.GRAY, Color.decode("#A8A8A8")); - colorsByChatColor.put(ChatColor.DARK_GRAY, Color.decode("#545454")); - colorsByChatColor.put(ChatColor.BLUE, Color.decode("#5454FB")); - colorsByChatColor.put(ChatColor.GREEN, Color.decode("#54FB54")); - colorsByChatColor.put(ChatColor.AQUA, Color.decode("#54FBFB")); - colorsByChatColor.put(ChatColor.RED, Color.decode("#FB5454")); - colorsByChatColor.put(ChatColor.LIGHT_PURPLE, Color.decode("#FB54FB")); - colorsByChatColor.put(ChatColor.YELLOW, Color.decode("#FBFB54")); - colorsByChatColor.put(ChatColor.WHITE, Color.decode("#FBFBFB")); - } - - private ColorConversions() { - } - - @Nonnull - public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { - switch (color) { - case RED: - return ChatColor.RED; - case BLUE: - return ChatColor.DARK_BLUE; - case CYAN: - return ChatColor.DARK_AQUA; - case GRAY: - return ChatColor.DARK_GRAY; - case LIME: - return ChatColor.GREEN; - case GREEN: - return ChatColor.DARK_GREEN; - case PURPLE: - return ChatColor.DARK_PURPLE; - case YELLOW: - return ChatColor.YELLOW; - case LIGHT_BLUE: - return ChatColor.BLUE; - case LIGHT_GRAY: - return ChatColor.GRAY; - case BLACK: - return ChatColor.BLACK; - case BROWN: - case ORANGE: - return ChatColor.GOLD; - case PINK: - case MAGENTA: - return ChatColor.LIGHT_PURPLE; - case WHITE: - default: - return ChatColor.WHITE; - } - } - - @Nonnull - public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { - switch (color) { - case YELLOW: - return MinecraftNameWrapper.YELLOW_DYE; - case RED: - return MinecraftNameWrapper.RED_DYE; - case GREEN: - return MinecraftNameWrapper.GREEN_DYE; - case BLACK: - return Material.INK_SAC; - case GRAY: - return Material.GRAY_DYE; - case LIGHT_GRAY: - return Material.LIGHT_GRAY_DYE; - case BLUE: - return Material.LAPIS_LAZULI; - case LIGHT_BLUE: - return Material.LIGHT_BLUE_DYE; - case MAGENTA: - return Material.MAGENTA_DYE; - case BROWN: - return Material.COCOA_BEANS; - case PURPLE: - return Material.PURPLE_DYE; - case ORANGE: - return Material.ORANGE_DYE; - case PINK: - return Material.PINK_DYE; - case LIME: - return Material.LIME_DYE; - case CYAN: - return Material.CYAN_DYE; - case WHITE: - default: - return Material.BONE_MEAL; - } - } - - @Nonnull - public static ChatColor convertAwtColorToChatColor(@Nonnull Color color) { - return colorsByChatColor.entrySet().stream() - .min((o1, o2) -> (int) ((calculateDifferenceBetweenColors(color, o1.getValue()) - calculateDifferenceBetweenColors(color, o2.getValue())) * 100)) - .orElseThrow(() -> new IllegalStateException("Could not find a ChatColor for the given input")) - .getKey(); - } - - @Nonnull - public static Color convertChatColorToAwtColor(@Nonnull ChatColor color) { - return Optional.ofNullable(colorsByChatColor.get(color)).orElseThrow(() -> new IllegalStateException("Could not find a color for ChatColor." + color.name())); - } - - @Nonnull - public static float[] convertAwtColorToHSB(@Nonnull Color color) { - return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); - } - - public static double calculateDifferenceBetweenColors(@Nonnull Color color1, @Nonnull Color color2) { - - int diffRed = Math.abs(color1.getRed() - color2.getRed()); - int diffGreen = Math.abs(color1.getGreen() - color2.getGreen()); - int diffBlue = Math.abs(color1.getBlue() - color2.getBlue()); - - float pctDiffRed = (float) diffRed / 255f; - float pctDiffGreen = (float) diffGreen / 255f; - float pctDiffBlue = (float) diffBlue / 255f; - - return (pctDiffRed + pctDiffGreen + pctDiffBlue) / 3f * 100; - } - - public static boolean isValidColorCode(char code) { - for (ChatColor color : ChatColor.values()) { - if (color.isColor() && color.getChar() == code) - return true; - } - return false; - } - - public static boolean isValidColorCode(@Nonnull String code) { - if (code.length() != 1) return false; - return isValidColorCode(code.toCharArray()[0]); - } + private static final Map colorsByChatColor = new HashMap<>(); + + static { + colorsByChatColor.put(ChatColor.BLACK, Color.decode("#000000")); + colorsByChatColor.put(ChatColor.DARK_BLUE, Color.decode("#0000A8")); + colorsByChatColor.put(ChatColor.DARK_GREEN, Color.decode("#00A800")); + colorsByChatColor.put(ChatColor.DARK_AQUA, Color.decode("#00A8A8")); + colorsByChatColor.put(ChatColor.DARK_RED, Color.decode("#A80000")); + colorsByChatColor.put(ChatColor.DARK_PURPLE, Color.decode("#A800A8")); + colorsByChatColor.put(ChatColor.GOLD, Color.decode("#FBA800")); + colorsByChatColor.put(ChatColor.GRAY, Color.decode("#A8A8A8")); + colorsByChatColor.put(ChatColor.DARK_GRAY, Color.decode("#545454")); + colorsByChatColor.put(ChatColor.BLUE, Color.decode("#5454FB")); + colorsByChatColor.put(ChatColor.GREEN, Color.decode("#54FB54")); + colorsByChatColor.put(ChatColor.AQUA, Color.decode("#54FBFB")); + colorsByChatColor.put(ChatColor.RED, Color.decode("#FB5454")); + colorsByChatColor.put(ChatColor.LIGHT_PURPLE, Color.decode("#FB54FB")); + colorsByChatColor.put(ChatColor.YELLOW, Color.decode("#FBFB54")); + colorsByChatColor.put(ChatColor.WHITE, Color.decode("#FBFBFB")); + } + + private ColorConversions() { + } + + @Nonnull + public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { + switch (color) { + case RED: + return ChatColor.RED; + case BLUE: + return ChatColor.DARK_BLUE; + case CYAN: + return ChatColor.DARK_AQUA; + case GRAY: + return ChatColor.DARK_GRAY; + case LIME: + return ChatColor.GREEN; + case GREEN: + return ChatColor.DARK_GREEN; + case PURPLE: + return ChatColor.DARK_PURPLE; + case YELLOW: + return ChatColor.YELLOW; + case LIGHT_BLUE: + return ChatColor.BLUE; + case LIGHT_GRAY: + return ChatColor.GRAY; + case BLACK: + return ChatColor.BLACK; + case BROWN: + case ORANGE: + return ChatColor.GOLD; + case PINK: + case MAGENTA: + return ChatColor.LIGHT_PURPLE; + case WHITE: + default: + return ChatColor.WHITE; + } + } + + @Nonnull + public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { + switch (color) { + case YELLOW: + return MinecraftNameWrapper.YELLOW_DYE; + case RED: + return MinecraftNameWrapper.RED_DYE; + case GREEN: + return MinecraftNameWrapper.GREEN_DYE; + case BLACK: + return Material.INK_SAC; + case GRAY: + return Material.GRAY_DYE; + case LIGHT_GRAY: + return Material.LIGHT_GRAY_DYE; + case BLUE: + return Material.LAPIS_LAZULI; + case LIGHT_BLUE: + return Material.LIGHT_BLUE_DYE; + case MAGENTA: + return Material.MAGENTA_DYE; + case BROWN: + return Material.COCOA_BEANS; + case PURPLE: + return Material.PURPLE_DYE; + case ORANGE: + return Material.ORANGE_DYE; + case PINK: + return Material.PINK_DYE; + case LIME: + return Material.LIME_DYE; + case CYAN: + return Material.CYAN_DYE; + case WHITE: + default: + return Material.BONE_MEAL; + } + } + + @Nonnull + public static ChatColor convertAwtColorToChatColor(@Nonnull Color color) { + return colorsByChatColor.entrySet().stream() + .min((o1, o2) -> (int) ((calculateDifferenceBetweenColors(color, o1.getValue()) - calculateDifferenceBetweenColors(color, o2.getValue())) * 100)) + .orElseThrow(() -> new IllegalStateException("Could not find a ChatColor for the given input")) + .getKey(); + } + + @Nonnull + public static Color convertChatColorToAwtColor(@Nonnull ChatColor color) { + return Optional.ofNullable(colorsByChatColor.get(color)).orElseThrow(() -> new IllegalStateException("Could not find a color for ChatColor." + color.name())); + } + + @Nonnull + public static float[] convertAwtColorToHSB(@Nonnull Color color) { + return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); + } + + public static double calculateDifferenceBetweenColors(@Nonnull Color color1, @Nonnull Color color2) { + + int diffRed = Math.abs(color1.getRed() - color2.getRed()); + int diffGreen = Math.abs(color1.getGreen() - color2.getGreen()); + int diffBlue = Math.abs(color1.getBlue() - color2.getBlue()); + + float pctDiffRed = (float) diffRed / 255f; + float pctDiffGreen = (float) diffGreen / 255f; + float pctDiffBlue = (float) diffBlue / 255f; + + return (pctDiffRed + pctDiffGreen + pctDiffBlue) / 3f * 100; + } + + public static boolean isValidColorCode(char code) { + for (ChatColor color : ChatColor.values()) { + if (color.isColor() && color.getChar() == code) + return true; + } + return false; + } + + public static boolean isValidColorCode(@Nonnull String code) { + if (code.length() != 1) return false; + return isValidColorCode(code.toCharArray()[0]); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java index 6bbe268ee..2d9965ee3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java @@ -14,85 +14,81 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public final class CommandHelper { - private CommandHelper() { - } + private CommandHelper() { + } - public static List getCompletions(CommandSender sender) { - LinkedList list = new LinkedList<>(); - Player player = sender instanceof Player ? ((Player) sender) : null; - Bukkit.getOnlinePlayers().forEach(player1 -> { - if (player == null || player.canSee(player1)) { - list.add(player1.getName()); - } - }); - list.addAll(Arrays.asList("@a", "@r", "@p", "@s")); - return list; - } + public static List getCompletions(CommandSender sender) { + LinkedList list = new LinkedList<>(); + Player player = sender instanceof Player ? ((Player) sender) : null; + Bukkit.getOnlinePlayers().forEach(player1 -> { + if (player == null || player.canSee(player1)) { + list.add(player1.getName()); + } + }); + list.addAll(Arrays.asList("@a", "@r", "@p", "@s")); + return list; + } - public static List getPlayers(@Nonnull CommandSender sender, @Nonnull String input) { - ArrayList list = new ArrayList<>(); - Location senderLocation = getSenderLocation(sender); + public static List getPlayers(@Nonnull CommandSender sender, @Nonnull String input) { + ArrayList list = new ArrayList<>(); + Location senderLocation = getSenderLocation(sender); - switch (input) { - case "@a": { - list.addAll(Bukkit.getOnlinePlayers()); - break; - } - case "@r": { - list.add(new ArrayList(Bukkit.getOnlinePlayers()).get(ThreadLocalRandom.current().nextInt(Bukkit.getOnlinePlayers().size()))); - break; - } - case "@p": { - if (senderLocation != null) { - Player nearestPlayer = getNearestPlayer(senderLocation); - if (nearestPlayer != null) list.add(nearestPlayer); - } - break; - } - case "@s": { - if (sender instanceof Player) list.add(((Player) sender)); - break; - } - default: { - Player player = Bukkit.getPlayer(input); - if (player != null) list.add(player); - } + switch (input) { + case "@a": { + list.addAll(Bukkit.getOnlinePlayers()); + break; + } + case "@r": { + list.add(new ArrayList(Bukkit.getOnlinePlayers()).get(ThreadLocalRandom.current().nextInt(Bukkit.getOnlinePlayers().size()))); + break; + } + case "@p": { + if (senderLocation != null) { + Player nearestPlayer = getNearestPlayer(senderLocation); + if (nearestPlayer != null) list.add(nearestPlayer); + } + break; + } + case "@s": { + if (sender instanceof Player) list.add(((Player) sender)); + break; + } + default: { + Player player = Bukkit.getPlayer(input); + if (player != null) list.add(player); + } - } + } - return list; - } + return list; + } - @Nullable - public static Location getSenderLocation(@Nonnull CommandSender sender) { - if (sender instanceof Player) return ((Player) sender).getLocation(); - if (sender instanceof BlockCommandSender) - return ((BlockCommandSender) sender).getBlock().getLocation(); - return null; - } + @Nullable + public static Location getSenderLocation(@Nonnull CommandSender sender) { + if (sender instanceof Player) return ((Player) sender).getLocation(); + if (sender instanceof BlockCommandSender) + return ((BlockCommandSender) sender).getBlock().getLocation(); + return null; + } - @Nullable - public static Player getNearestPlayer(@Nonnull Location location) { - if (location.getWorld() == null) return null; - Player currentPlayer = null; - double playersDistance = -1; + @Nullable + public static Player getNearestPlayer(@Nonnull Location location) { + if (location.getWorld() == null) return null; + Player currentPlayer = null; + double playersDistance = -1; - for (Player player : Bukkit.getOnlinePlayers()) { - if (location.getWorld() != player.getWorld()) continue; - double distance = location.distance(player.getLocation()); - if (playersDistance == -1 || distance < playersDistance) { - currentPlayer = player; - playersDistance = distance; - } - } + for (Player player : Bukkit.getOnlinePlayers()) { + if (location.getWorld() != player.getWorld()) continue; + double distance = location.distance(player.getLocation()); + if (playersDistance == -1 || distance < playersDistance) { + currentPlayer = player; + playersDistance = distance; + } + } - return currentPlayer; - } + return currentPlayer; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index a19871374..348a43631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -3,8 +3,8 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.GameProfileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -13,77 +13,73 @@ import javax.annotation.Nullable; import java.util.*; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DatabaseHelper { - private static final Map cachedTextures = new HashMap<>(); - - private DatabaseHelper() { - } - - @Nullable - public static String getPlayerTextures(@Nonnull Player player) { - GameProfile profile = GameProfileUtils.getGameProfile(player); - PropertyMap properties = profile.getProperties(); - List textures = new ArrayList<>(properties.get("textures")); - return textures.isEmpty() ? null : textures.get(0).getValue(); - } - - public static void savePlayerData(@Nonnull Player player) { - try { - - String textures = getPlayerTextures(player); - if (textures != null) cachedTextures.put(player.getUniqueId(), textures); - - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .set("textures", textures) - .set("name", player.getName()) - .where("uuid", player.getUniqueId()) - .execute(); - - } catch (Exception ex) { - Logger.error("Unable to update textures for {} | {}", player.getName(), player.getUniqueId(), ex); - } - } - - @Nullable - public static String getTextures(@Nonnull UUID uuid) { - String cached = cachedTextures.get(uuid); - if (cached != null) return cached; - - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - String textures = getPlayerTextures(player); - if (textures != null) { - cachedTextures.put(uuid, textures); - return textures; - } - } - - if (!Challenges.getInstance().getDatabaseManager().isConnected()) - return null; - - try { - String textures = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("textures") - .where("uuid", uuid) - .execute().firstOrEmpty() - .getString("textures"); - cachedTextures.put(uuid, textures); - return textures; - } catch (Exception ex) { - Logger.error("Unable to get textures for {}", uuid, ex); - return null; - } - } - - public static void clearCache(@Nonnull UUID uuid) { - cachedTextures.remove(uuid); - } + private static final Map cachedTextures = new HashMap<>(); + + private DatabaseHelper() { + } + + @Nullable + public static String getPlayerTextures(@Nonnull Player player) { + GameProfile profile = GameProfileUtils.getGameProfile(player); + PropertyMap properties = profile.getProperties(); + List textures = new ArrayList<>(properties.get("textures")); + return textures.isEmpty() ? null : textures.get(0).getValue(); + } + + public static void savePlayerData(@Nonnull Player player) { + try { + + String textures = getPlayerTextures(player); + if (textures != null) cachedTextures.put(player.getUniqueId(), textures); + + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .set("textures", textures) + .set("name", player.getName()) + .where("uuid", player.getUniqueId()) + .execute(); + + } catch (Exception ex) { + Logger.error("Unable to update textures for {} | {}", player.getName(), player.getUniqueId(), ex); + } + } + + @Nullable + public static String getTextures(@Nonnull UUID uuid) { + String cached = cachedTextures.get(uuid); + if (cached != null) return cached; + + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + String textures = getPlayerTextures(player); + if (textures != null) { + cachedTextures.put(uuid, textures); + return textures; + } + } + + if (!Challenges.getInstance().getDatabaseManager().isConnected()) + return null; + + try { + String textures = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("textures") + .where("uuid", uuid) + .execute().firstOrEmpty() + .getString("textures"); + cachedTextures.put(uuid, textures); + return textures; + } catch (Exception ex) { + Logger.error("Unable to get textures for {}", uuid, ex); + return null; + } + } + + public static void clearCache(@Nonnull UUID uuid) { + cachedTextures.remove(uuid); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java index 80ea08eaf..54fe92a8a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java @@ -8,43 +8,39 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class EntityUtils { - private EntityUtils() { - } - - public static Vector getSucceedingVelocity(@Nonnull Vector vector) { - return new Vector(vector.getX(), getSucceedingVelocity(vector.getY()), vector.getX()); - } - - public static double getSucceedingVelocity(double currentYVelocity) { - return 0.98 * ((currentYVelocity) - 0.08); - } - - public static boolean isStandingOnBlock(@Nonnull Entity entity, Material block) { - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = -1; y <= 1; y++) { - Material type = entity.getLocation().add(x, y, z).getBlock().getType(); - if (type == block) return true; - } - } - } - return false; - } - - @Nullable - public static Material getSpawnEgg(EntityType type) { - if (!type.isSpawnable() || !type.isAlive()) return null; - try { - return Material.valueOf(type.name() + "_SPAWN_EGG"); - } catch (Exception ex) { - return null; - } - } + private EntityUtils() { + } + + public static Vector getSucceedingVelocity(@Nonnull Vector vector) { + return new Vector(vector.getX(), getSucceedingVelocity(vector.getY()), vector.getX()); + } + + public static double getSucceedingVelocity(double currentYVelocity) { + return 0.98 * ((currentYVelocity) - 0.08); + } + + public static boolean isStandingOnBlock(@Nonnull Entity entity, Material block) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = -1; y <= 1; y++) { + Material type = entity.getLocation().add(x, y, z).getBlock().getType(); + if (type == block) return true; + } + } + } + return false; + } + + @Nullable + public static Material getSpawnEgg(EntityType type) { + if (!type.isSpawnable() || !type.isAlive()) return null; + try { + return Material.valueOf(type.name() + "_SPAWN_EGG"); + } catch (Exception ex) { + return null; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java index bacbadfe2..97dd467bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java @@ -1,12 +1,13 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.util.LinkedList; -import java.util.List; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; +import java.util.LinkedList; +import java.util.List; + public class ExperimentalUtils { private static Material[] materials; @@ -27,7 +28,8 @@ private static void loadMaterials() { if (!material.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { continue; } - } catch (NoSuchMethodError ignored) {} // only NoSuchMethodException + } catch (NoSuchMethodError ignored) { + } // only NoSuchMethodException materials.add(material); } @@ -49,7 +51,8 @@ private static void loadEntityTypes() { if (!type.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { continue; } - } catch (NoSuchMethodError | IllegalArgumentException ignored) {} // only NoSuchMethodException + } catch (NoSuchMethodError | IllegalArgumentException ignored) { + } // only NoSuchMethodException entityTypes.add(type); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java index 72a417e32..4ecf028e7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java @@ -4,46 +4,42 @@ import java.util.LinkedList; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FontUtils { - private static final char[] SMALL_CAPS_ALPHABET = "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ".toCharArray(); + private static final char[] SMALL_CAPS_ALPHABET = "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ".toCharArray(); - public static String[] toSmallCaps(String[] text) { - LinkedList strings = new LinkedList<>(); - for (String s : text) { - strings.add(toSmallCaps(s)); - } - return strings.toArray(new String[0]); - } + public static String[] toSmallCaps(String[] text) { + LinkedList strings = new LinkedList<>(); + for (String s : text) { + strings.add(toSmallCaps(s)); + } + return strings.toArray(new String[0]); + } - public static String toSmallCaps(String text) { - if (null == text) { - return null; - } - int length = text.length(); - StringBuilder smallCaps = new StringBuilder(length); - for (int i = 0; i < length; ++i) { - char c = text.charAt(i); - if (c >= 'a' && c <= 'z') { - if (i >= 1) { - char charBefore = text.charAt(i - 1); - if (charBefore == '§') { - if (ChatColor.getByChar(c) != null) { - smallCaps.append(c); - continue; - } - } - } - smallCaps.append(SMALL_CAPS_ALPHABET[c - 'a']); - } else { - smallCaps.append(c); - } - } - return smallCaps.toString(); - } + public static String toSmallCaps(String text) { + if (null == text) { + return null; + } + int length = text.length(); + StringBuilder smallCaps = new StringBuilder(length); + for (int i = 0; i < length; ++i) { + char c = text.charAt(i); + if (c >= 'a' && c <= 'z') { + if (i >= 1) { + char charBefore = text.charAt(i - 1); + if (charBefore == '§') { + if (ChatColor.getByChar(c) != null) { + smallCaps.append(c); + continue; + } + } + } + smallCaps.append(SMALL_CAPS_ALPHABET[c - 'a']); + } else { + smallCaps.append(c); + } + } + return smallCaps.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index b0d52e334..f81f27ba2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -11,40 +11,36 @@ import java.net.HttpURLConnection; import java.net.URL; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ImageUtils { - public static final char IMAGE_CHAR = '█'; - - private ImageUtils() { - } - - @Nullable - public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); - return ImageIO.read(connection.getInputStream()); - } - - public static BufferedImage getPlayerHead(@Nonnull Player player, int size) throws IOException { - String url = "https://crafatar.com/avatars/" + player.getUniqueId() + "?size=" + size + "&overlay"; - return getImage(url); - } - - public static String[] convertImageToText(@Nonnull BufferedImage image) { - String[] output = new String[image.getHeight()]; - for (int y = 0; y < output.length; y++) { - StringBuilder text = new StringBuilder(); - for (int x = 0; x < image.getWidth(); x++) { - text.append(ColorConversions.convertAwtColorToChatColor(new Color(image.getRGB(x, y)))) - .append(IMAGE_CHAR); - } - output[y] = text.toString(); - } - return output; - } + public static final char IMAGE_CHAR = '█'; + + private ImageUtils() { + } + + @Nullable + public static BufferedImage getImage(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage getPlayerHead(@Nonnull Player player, int size) throws IOException { + String url = "https://crafatar.com/avatars/" + player.getUniqueId() + "?size=" + size + "&overlay"; + return getImage(url); + } + + public static String[] convertImageToText(@Nonnull BufferedImage image) { + String[] output = new String[image.getHeight()]; + for (int y = 0; y < output.length; y++) { + StringBuilder text = new StringBuilder(); + for (int x = 0; x < image.getWidth(); x++) { + text.append(ColorConversions.convertAwtColorToChatColor(new Color(image.getRGB(x, y)))) + .append(IMAGE_CHAR); + } + output[y] = text.toString(); + } + return output; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index e055de09c..56c365fd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; @@ -23,208 +23,203 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class InventoryUtils { - private static final IRandom random; - private static final List items; - - static { - random = IRandom.create(); - items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - items.removeIf(material -> !material.isItem()); - } - - private InventoryUtils() { - } - - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item) { - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, item); - } - } - - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item, @Nonnull int... slots) { - for (int i : slots) { - inventory.setItem(i, item); - } - } - - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots) { - setNavigationItemsToInventory(inventories, navigationSlots, true); - } - - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { - setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.INVENTORY); - } - - public static void setNavigationItemsToFrame(@Nonnull List frames, @Nonnull int[] navigationSlots) { - setNavigationItemsToFrame(frames, navigationSlots, true); - } - - public static void setNavigationItemsToFrame(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { - setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.FRAME); - } - - public static void setNavigationItemsToFrame(@Nonnull AnimationFrame frame, @Nonnull int[] navigationSlots, boolean goBackExit, int index, int size) { - setNavigationItems(frame, navigationSlots, goBackExit, InventorySetter.FRAME, index, size); - } - - public static void setNavigationItems(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter) { - for (int i = 0; i < inventories.size(); i++) { - setNavigationItems(inventories.get(i), navigationSlots, goBackExit, setter, i, inventories.size()); - } - } - - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size) { - setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); - } - - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { - if (navigationSlots.length >= 1) { - ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; - setter.set(inventory, navigationSlots[0], left); - } - if (navigationSlots.length >= 2 && index < (size - 1)) - setter.set(inventory, navigationSlots[1], navigateNext); - } - - public static boolean isEmpty(@Nonnull Inventory inventory) { - for (ItemStack content : inventory.getContents()) { - if (content != null) return false; - } - return true; - } - - public static int getRandomEmptySlot(@Nonnull Inventory inventory) { - List emptySlots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - if (inventory.getItem(slot) == null) { - emptySlots.add(slot); - } - - } - - if (emptySlots.isEmpty()) return -1; - return emptySlots.get(ThreadLocalRandom.current().nextInt(emptySlots.size())); - } - - public static int getRandomFullSlot(@Nonnull Inventory inventory) { - List fullSlots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - fullSlots.add(slot); - } - } - - if (fullSlots.isEmpty()) return -1; - - return fullSlots.get(ThreadLocalRandom.current().nextInt(fullSlots.size())); - } - - public static int getRandomSlot(@Nonnull Inventory inventory) { - List slots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) continue; - slots.add(slot); - - } - - if (slots.isEmpty()) return -1; - return slots.get(ThreadLocalRandom.current().nextInt(slots.size())); - } - - public static void dropItemByPlayer(@Nonnull Location location, @Nonnull ItemStack itemStack) { - if (location.getWorld() == null) return; - Item droppedItem = location.getWorld().dropItem(location.clone().add(0, 1.4, 0), itemStack); - droppedItem.setVelocity(location.getDirection().multiply(0.4)); - } - - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull Material material) { - dropOrGiveItem(inventory, location, new ItemStack(material)); - } - - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull ItemStack itemStack) { - location = location.clone(); - if (inventory.firstEmpty() == -1) { - if (location.getWorld() == null) - location.setWorld(ChallengeAPI.getGameWorld(Environment.NORMAL)); - location.getWorld().dropItem(location, itemStack); - return; - } - inventory.addItem(itemStack); - } - - public static void removeRandomItem(@Nonnull Inventory inventory) { - int slot = InventoryUtils.getRandomFullSlot(inventory); - if (slot == -1) return; - inventory.setItem(slot, null); - } - - public static void giveItem(@Nonnull Player player, @Nonnull ItemStack itemStack) { - giveItem(player.getInventory(), player.getLocation(), itemStack); - } - - public static void giveItem(@Nonnull Inventory inventory, @Nonnull Location locationToDrop, @Nonnull ItemStack itemStack) { - if (inventory.firstEmpty() == -1) { - dropItemByPlayer(locationToDrop, itemStack); - return; - } - inventory.addItem(itemStack); - } - - public static ItemStack getRandomItem(boolean onlyOne, boolean respectMaxStackSize) { - Material material = random.choose(items); - int stackSize = onlyOne ? 1 : (respectMaxStackSize && material.getMaxStackSize() == 1 ? 1 : random.range(1, respectMaxStackSize ? material.getMaxStackSize() : 64)); - return new ItemStack(material, stackSize); - } - - /** - * @return if a navigation item was clicked - */ - public static boolean handleNavigationClicking(MenuGenerator generator, int[] navigationSlots, int page, MenuClickInfo info, Runnable onDoorClick) { - int pagesSwitching = info.isShiftClick() ? 5 : 1; - if (navigationSlots.length >= 1 && info.getSlot() == navigationSlots[0]) { - if (page <= 0) { - if (page == 0) { - onDoorClick.run(); - } else { - SoundSample.CLICK.play(info.getPlayer()); - } - return page == 0; - } else { - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), Math.max(page - pagesSwitching, 0)); - return true; - } - } else if (navigationSlots.length >= 2 && info.getSlot() == navigationSlots[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (generator.getInventories().size())) { - generator.open(info.getPlayer(), Math.min(page + pagesSwitching, generator.getInventories().size())); - return true; - } - return false; - } - return false; - } - - @FunctionalInterface - public interface InventorySetter { - - InventorySetter FRAME = AnimationFrame::setItem; - InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); - - void set(@Nonnull I inventory, int slot, @Nonnull ItemBuilder item); - - } + private static final IRandom random; + private static final List items; + + static { + random = IRandom.create(); + items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + items.removeIf(material -> !material.isItem()); + } + + private InventoryUtils() { + } + + public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item) { + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, item); + } + } + + public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item, @Nonnull int... slots) { + for (int i : slots) { + inventory.setItem(i, item); + } + } + + public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots) { + setNavigationItemsToInventory(inventories, navigationSlots, true); + } + + public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.INVENTORY); + } + + public static void setNavigationItemsToFrame(@Nonnull List frames, @Nonnull int[] navigationSlots) { + setNavigationItemsToFrame(frames, navigationSlots, true); + } + + public static void setNavigationItemsToFrame(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.FRAME); + } + + public static void setNavigationItemsToFrame(@Nonnull AnimationFrame frame, @Nonnull int[] navigationSlots, boolean goBackExit, int index, int size) { + setNavigationItems(frame, navigationSlots, goBackExit, InventorySetter.FRAME, index, size); + } + + public static void setNavigationItems(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter) { + for (int i = 0; i < inventories.size(); i++) { + setNavigationItems(inventories.get(i), navigationSlots, goBackExit, setter, i, inventories.size()); + } + } + + public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size) { + setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); + } + + public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { + if (navigationSlots.length >= 1) { + ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; + setter.set(inventory, navigationSlots[0], left); + } + if (navigationSlots.length >= 2 && index < (size - 1)) + setter.set(inventory, navigationSlots[1], navigateNext); + } + + public static boolean isEmpty(@Nonnull Inventory inventory) { + for (ItemStack content : inventory.getContents()) { + if (content != null) return false; + } + return true; + } + + public static int getRandomEmptySlot(@Nonnull Inventory inventory) { + List emptySlots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + if (inventory.getItem(slot) == null) { + emptySlots.add(slot); + } + + } + + if (emptySlots.isEmpty()) return -1; + return emptySlots.get(ThreadLocalRandom.current().nextInt(emptySlots.size())); + } + + public static int getRandomFullSlot(@Nonnull Inventory inventory) { + List fullSlots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + fullSlots.add(slot); + } + } + + if (fullSlots.isEmpty()) return -1; + + return fullSlots.get(ThreadLocalRandom.current().nextInt(fullSlots.size())); + } + + public static int getRandomSlot(@Nonnull Inventory inventory) { + List slots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) continue; + slots.add(slot); + + } + + if (slots.isEmpty()) return -1; + return slots.get(ThreadLocalRandom.current().nextInt(slots.size())); + } + + public static void dropItemByPlayer(@Nonnull Location location, @Nonnull ItemStack itemStack) { + if (location.getWorld() == null) return; + Item droppedItem = location.getWorld().dropItem(location.clone().add(0, 1.4, 0), itemStack); + droppedItem.setVelocity(location.getDirection().multiply(0.4)); + } + + public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull Material material) { + dropOrGiveItem(inventory, location, new ItemStack(material)); + } + + public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull ItemStack itemStack) { + location = location.clone(); + if (inventory.firstEmpty() == -1) { + if (location.getWorld() == null) + location.setWorld(ChallengeAPI.getGameWorld(Environment.NORMAL)); + location.getWorld().dropItem(location, itemStack); + return; + } + inventory.addItem(itemStack); + } + + public static void removeRandomItem(@Nonnull Inventory inventory) { + int slot = InventoryUtils.getRandomFullSlot(inventory); + if (slot == -1) return; + inventory.setItem(slot, null); + } + + public static void giveItem(@Nonnull Player player, @Nonnull ItemStack itemStack) { + giveItem(player.getInventory(), player.getLocation(), itemStack); + } + + public static void giveItem(@Nonnull Inventory inventory, @Nonnull Location locationToDrop, @Nonnull ItemStack itemStack) { + if (inventory.firstEmpty() == -1) { + dropItemByPlayer(locationToDrop, itemStack); + return; + } + inventory.addItem(itemStack); + } + + public static ItemStack getRandomItem(boolean onlyOne, boolean respectMaxStackSize) { + Material material = random.choose(items); + int stackSize = onlyOne ? 1 : (respectMaxStackSize && material.getMaxStackSize() == 1 ? 1 : random.range(1, respectMaxStackSize ? material.getMaxStackSize() : 64)); + return new ItemStack(material, stackSize); + } + + /** + * @return if a navigation item was clicked + */ + public static boolean handleNavigationClicking(MenuGenerator generator, int[] navigationSlots, int page, MenuClickInfo info, Runnable onDoorClick) { + int pagesSwitching = info.isShiftClick() ? 5 : 1; + if (navigationSlots.length >= 1 && info.getSlot() == navigationSlots[0]) { + if (page <= 0) { + if (page == 0) { + onDoorClick.run(); + } else { + SoundSample.CLICK.play(info.getPlayer()); + } + return page == 0; + } else { + SoundSample.CLICK.play(info.getPlayer()); + generator.open(info.getPlayer(), Math.max(page - pagesSwitching, 0)); + return true; + } + } else if (navigationSlots.length >= 2 && info.getSlot() == navigationSlots[1]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page < (generator.getInventories().size())) { + generator.open(info.getPlayer(), Math.min(page + pagesSwitching, generator.getInventories().size())); + return true; + } + return false; + } + return false; + } + + @FunctionalInterface + public interface InventorySetter { + + InventorySetter FRAME = AnimationFrame::setItem; + InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); + + void set(@Nonnull I inventory, int slot, @Nonnull ItemBuilder item); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java index 95eb84774..21162ef90 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java @@ -7,73 +7,69 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ListBuilder { - private final List list = new ArrayList<>(); - - @SafeVarargs - public ListBuilder(T... t) { - list.addAll(Arrays.asList(t)); - } - - public ListBuilder fill(Consumer> consumer) { - consumer.accept(this); - return this; - } - - @SafeVarargs - public final ListBuilder addAll(T... t) { - return addAll(Arrays.asList(t)); - } - - public final ListBuilder addAll(Collection collection) { - list.addAll(collection); - return this; - } - - @SafeVarargs - public final ListBuilder addAllIfNotContains(T... t) { - return addAllIfNotContains(Arrays.asList(t)); - } - - public final ListBuilder addAllIfNotContains(Collection collection) { - for (T t : collection) { - if (!list.contains(t)) list.add(t); - } - return this; - } - - public ListBuilder add(T t) { - list.add(t); - return this; - } - - public ListBuilder addIfNotContains(T t) { - if (list.contains(t)) return this; - return add(t); - } - - public ListBuilder remove(T t) { - list.remove(t); - return this; - } - - public ListBuilder forEach(Consumer action) { - list.forEach(action); - return this; - } - - public ListBuilder removeIf(Predicate action) { - list.removeIf(action); - return this; - } - - public List build() { - return list; - } - -} \ No newline at end of file + private final List list = new ArrayList<>(); + + @SafeVarargs + public ListBuilder(T... t) { + list.addAll(Arrays.asList(t)); + } + + public ListBuilder fill(Consumer> consumer) { + consumer.accept(this); + return this; + } + + @SafeVarargs + public final ListBuilder addAll(T... t) { + return addAll(Arrays.asList(t)); + } + + public ListBuilder addAll(Collection collection) { + list.addAll(collection); + return this; + } + + @SafeVarargs + public final ListBuilder addAllIfNotContains(T... t) { + return addAllIfNotContains(Arrays.asList(t)); + } + + public ListBuilder addAllIfNotContains(Collection collection) { + for (T t : collection) { + if (!list.contains(t)) list.add(t); + } + return this; + } + + public ListBuilder add(T t) { + list.add(t); + return this; + } + + public ListBuilder addIfNotContains(T t) { + if (list.contains(t)) return this; + return add(t); + } + + public ListBuilder remove(T t) { + list.remove(t); + return this; + } + + public ListBuilder forEach(Consumer action) { + list.forEach(action); + return this; + } + + public ListBuilder removeIf(Predicate action) { + list.removeIf(action); + return this; + } + + public List build() { + return list; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index fc334406b..cf6e7c1f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -1,50 +1,46 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class MapUtils { - public static Map createStringMap(String... data) { - Map map = new HashMap<>(); - for (int i = 1; i < data.length; i += 2) { - String key = data[i - 1]; - String value = data[i]; - map.put(key, value); - } - return map; - } - - public static Map createStringArrayMap(String key, String... values) { - Map map = new HashMap<>(); - map.put(key, values); - return map; - } - - public static Map> createStringListMap(String key, String... values) { - Map> map = new HashMap<>(); - map.put(key, new ArrayList<>(Arrays.asList(values))); - return map; - } - - public static Map createSubSettingsMapFromDocument(Document document) { - if (document == null) return new HashMap<>(); - Map map = new HashMap<>(); - for (Entry entry : document.entrySet()) { - try { - map.put(entry.getKey(), document.getStringArray(entry.getKey())); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - return map; - } + public static Map createStringMap(String... data) { + Map map = new HashMap<>(); + for (int i = 1; i < data.length; i += 2) { + String key = data[i - 1]; + String value = data[i]; + map.put(key, value); + } + return map; + } + + public static Map createStringArrayMap(String key, String... values) { + Map map = new HashMap<>(); + map.put(key, values); + return map; + } + + public static Map> createStringListMap(String key, String... values) { + Map> map = new HashMap<>(); + map.put(key, new ArrayList<>(Arrays.asList(values))); + return map; + } + + public static Map createSubSettingsMapFromDocument(Document document) { + if (document == null) return new HashMap<>(); + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + try { + map.put(entry.getKey(), document.getStringArray(entry.getKey())); + } catch (Exception exception) { + Challenges.getInstance().getILogger().error("", exception); + } + } + return map; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java index 51915d714..5be104fe1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java @@ -2,10 +2,10 @@ public class MemoryConverter { - private static final long GIGABYTE = 1024L * 1024L * 1024L; + private static final long GIGABYTE = 1024L * 1024L * 1024L; - public static int getGB(long bytes) { - return (int) (bytes / GIGABYTE); - } + public static int getGB(long bytes) { + return (int) (bytes / GIGABYTE); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 6d167b4a0..023f90fa7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,9 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.lang.reflect.Field; -import java.util.Arrays; -import javax.annotation.Nonnull; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import org.bukkit.Material; import org.bukkit.Particle; @@ -11,6 +8,10 @@ import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; +import javax.annotation.Nonnull; +import java.lang.reflect.Field; +import java.util.Arrays; + public class MinecraftNameWrapper { public static final Material GREEN_DYE = getItemByNames("CACTUS_GREEN", "GREEN_DYE"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java index 2534de3eb..3d3e251a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java @@ -6,31 +6,27 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class NameHelper { - private NameHelper() { - } - - @Nonnull - public static String getName(@Nonnull OfflinePlayer player) { - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { - if (player.isOnline() && player.getPlayer() != null) { - return cloudSupport.getColoredName(player.getPlayer()); - } else { - return cloudSupport.getColoredName(player.getUniqueId()); - } - } - - if (player.getName() == null) { - return ""; - } - - return player.getName(); - } + private NameHelper() { + } + + @Nonnull + public static String getName(@Nonnull OfflinePlayer player) { + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { + if (player.isOnline() && player.getPlayer() != null) { + return cloudSupport.getColoredName(player.getPlayer()); + } else { + return cloudSupport.getColoredName(player.getUniqueId()); + } + } + + if (player.getName() == null) { + return ""; + } + + return player.getName(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 46efced22..985a65410 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,16 +1,8 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.util.Objects; -import java.util.function.BiConsumer; -import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.World; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; +import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; @@ -18,105 +10,102 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.Nullable; -/** - * This class contains util methods to create fancy particles. - * Most of these methods were found in {@link Utils} previously (pre 2.0). - * - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.BiConsumer; + public final class ParticleUtils { - private static final IRandom iRandom = IRandom.create(); - - private ParticleUtils() { - } - - private static void spawnParticleCircle(@Nonnull Location location, int points, double radius, @Nonnull BiConsumer player) { - World world = location.getWorld(); - if (world == null) return; - - for (int i = 0; i < points; i++) { - double angle = 2 * Math.PI * i / points; - Location point = location.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); - player.accept(world, point); - } - } - - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Effect particle, int points, double radius) { - spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); - } - - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Particle particle, int points, double radius) { - spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); - } - - private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, int points, double radius, double height, @Nonnull BiConsumer player) { - for (double y = 0, i = 0; y < height; y += .25, i++) { - final double Y = y; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, player); - }, (long) i); - } - } - - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Effect effect, int points, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); - } - - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, int points, double radius, double height) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - for (double y = 0, i = 0; y < height; y += .25, i++) { - final double Y = y; - - Color color = Color.fromRGB( - iRandom.range(0, 255), - iRandom.range(0, 255), - iRandom.range(0, 255) - ); - - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - if (particle == Particle.ENTITY_EFFECT) { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1, color)); - } else { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1)); - } - }, (long) i); - } - } else { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.spawnParticle(particle, point, 1)); - } - } - - public static void spawnParticleCircleAroundEntity(@Nonnull JavaPlugin plugin, @Nonnull Entity entity) { - spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); - } - - public static void spawnParticleCircleAroundBoundingBox(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, @Nonnull BoundingBox box, double height) { - spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); - } - - public static void spawnParticleCircleAroundRadius(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); - } - - public static void drawLine(@Nonnull Player player, @Nonnull Location point1, @Nonnull Location point2, @Nonnull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { - World world = point1.getWorld(); - if (!Objects.equals(world, point2.getWorld())) return; - double distance = point1.distance(point2); - Vector p1 = point1.toVector(); - Vector p2 = point2.toVector(); - Vector vector = p2.clone().subtract(p1).normalize().multiply(space); - double length = 0; - int current = 0; - for (; length < distance; p1.add(vector)) { - player.spawnParticle(particle, p1.getX(), p1.getY(), p1.getZ(), count, dustOptions); - length += space; - - current++; - if (current >= max) break; - } - - } + private static final IRandom iRandom = IRandom.create(); + + private ParticleUtils() { + } + + private static void spawnParticleCircle(@Nonnull Location location, int points, double radius, @Nonnull BiConsumer player) { + World world = location.getWorld(); + if (world == null) return; + + for (int i = 0; i < points; i++) { + double angle = 2 * Math.PI * i / points; + Location point = location.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); + player.accept(world, point); + } + } + + public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Effect particle, int points, double radius) { + spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); + } + + public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Particle particle, int points, double radius) { + spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); + } + + private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, int points, double radius, double height, @Nonnull BiConsumer player) { + for (double y = 0, i = 0; y < height; y += .25, i++) { + final double Y = y; + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, player); + }, (long) i); + } + } + + public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Effect effect, int points, double radius, double height) { + spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); + } + + public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, int points, double radius, double height) { + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { + for (double y = 0, i = 0; y < height; y += .25, i++) { + final double Y = y; + + Color color = Color.fromRGB( + iRandom.range(0, 255), + iRandom.range(0, 255), + iRandom.range(0, 255) + ); + + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + if (particle == Particle.ENTITY_EFFECT) { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1, color)); + } else { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1)); + } + }, (long) i); + } + } else { + spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.spawnParticle(particle, point, 1)); + } + } + + public static void spawnParticleCircleAroundEntity(@Nonnull JavaPlugin plugin, @Nonnull Entity entity) { + spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); + } + + public static void spawnParticleCircleAroundBoundingBox(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, @Nonnull BoundingBox box, double height) { + spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); + } + + public static void spawnParticleCircleAroundRadius(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, double radius, double height) { + spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); + } + + public static void drawLine(@Nonnull Player player, @Nonnull Location point1, @Nonnull Location point2, @Nonnull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { + World world = point1.getWorld(); + if (!Objects.equals(world, point2.getWorld())) return; + double distance = point1.distance(point2); + Vector p1 = point1.toVector(); + Vector p2 = point2.toVector(); + Vector vector = p2.clone().subtract(p1).normalize().multiply(space); + double length = 0; + int current = 0; + for (; length < distance; p1.add(vector)) { + player.spawnParticle(particle, p1.getX(), p1.getY(), p1.getZ(), count, dustOptions); + length += space; + + current++; + if (current >= max) break; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 7c1e91f32..18fe9135a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; @@ -8,65 +8,61 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class StatsHelper { - private StatsHelper() { - } + private StatsHelper() { + } - @Nonnull - public static int[] getSlots(int row) { - int[] slots = {1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15}; - for (int i = 0; i < slots.length; i++) { - slots[i] += row * 9; - } - return slots; - } + @Nonnull + public static int[] getSlots(int row) { + int[] slots = {1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15}; + for (int i = 0; i < slots.length; i++) { + slots[i] += row * 9; + } + return slots; + } - public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); - int offset = row * 9; - inventory.cloneLastAndAdd().setAccent(offset, offset + 8); - inventory.cloneLastAndAdd().setAccent(offset + 1, offset + 7); - inventory.cloneLastAndAdd().setAccent(offset + 10, offset + 16); - inventory.cloneLastAndAdd().setAccent(offset + 11, offset + 15); - inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); - } + public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { + inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + int offset = row * 9; + inventory.cloneLastAndAdd().setAccent(offset, offset + 8); + inventory.cloneLastAndAdd().setAccent(offset + 1, offset + 7); + inventory.cloneLastAndAdd().setAccent(offset + 10, offset + 16); + inventory.cloneLastAndAdd().setAccent(offset + 11, offset + 15); + inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); + } - @Nonnull - public static Message getNameMessage(@Nonnull Statistic statistic) { - return Message.forName("stat-" + statistic.name().toLowerCase().replace('_', '-')); - } + @Nonnull + public static Message getNameMessage(@Nonnull Statistic statistic) { + return Message.forName("stat-" + statistic.name().toLowerCase().replace('_', '-')); + } - @Nonnull - public static Material getMaterial(@Nonnull Statistic statistic) { - switch (statistic) { - default: - return Material.PAPER; - case DEATHS: - return Material.STONE_SHOVEL; - case BLOCKS_MINED: - return Material.GOLDEN_PICKAXE; - case BLOCKS_PLACED: - return Material.DIRT; - case DAMAGE_DEALT: - return Material.STONE_SWORD; - case DAMAGE_TAKEN: - return Material.LEATHER_CHESTPLATE; - case ENTITY_KILLS: - return Material.IRON_SWORD; - case DRAGON_KILLED: - return Material.DRAGON_EGG; - case BLOCKS_TRAVELED: - return Material.MINECART; - case CHALLENGES_PLAYED: - return Material.GOLD_INGOT; - case JUMPS: - return Material.GOLDEN_BOOTS; - } - } + @Nonnull + public static Material getMaterial(@Nonnull Statistic statistic) { + switch (statistic) { + default: + return Material.PAPER; + case DEATHS: + return Material.STONE_SHOVEL; + case BLOCKS_MINED: + return Material.GOLDEN_PICKAXE; + case BLOCKS_PLACED: + return Material.DIRT; + case DAMAGE_DEALT: + return Material.STONE_SWORD; + case DAMAGE_TAKEN: + return Material.LEATHER_CHESTPLATE; + case ENTITY_KILLS: + return Material.IRON_SWORD; + case DRAGON_KILLED: + return Material.DRAGON_EGG; + case BLOCKS_TRAVELED: + return Material.MINECART; + case CHALLENGES_PLAYED: + return Material.GOLD_INGOT; + case JUMPS: + return Material.GOLDEN_BOOTS; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java index 831820d5c..a1c20de3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java @@ -3,53 +3,49 @@ import org.bukkit.Material; import org.bukkit.StructureType; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class StructureUtils { - public static Material getStructureIcon(StructureType structureType) { + public static Material getStructureIcon(StructureType structureType) { - switch (structureType.getName()) { - case "nether_fossil": - return Material.BONE_BLOCK; - case "jungle_pyramid": - return Material.LEVER; - case "monument": - return Material.SEA_LANTERN; - case "desert_pyramid": - return Material.SANDSTONE_STAIRS; - case "mineshaft": - return Material.RAIL; - case "ocean_ruin": - return Material.DROWNED_SPAWN_EGG; - case "bastion_remnant": - return Material.BLACKSTONE; - case "shipwreck": - return Material.OAK_BOAT; - case "fortress": - return Material.NETHER_BRICK_FENCE; - case "buried_treasure": - return Material.CHEST; - case "pillager_outpost": - return Material.CROSSBOW; - case "swamp_hut": - return Material.CAULDRON; - case "igloo": - return Material.SNOW_BLOCK; - case "village": - return Material.VILLAGER_SPAWN_EGG; - case "stronghold": - return Material.END_PORTAL_FRAME; - case "end_city": - return Material.PURPUR_PILLAR; - case "mansion": - return Material.TOTEM_OF_UNDYING; - case "ruined_portal": - return Material.CRYING_OBSIDIAN; - default: - return Material.STRUCTURE_VOID; - } + switch (structureType.getName()) { + case "nether_fossil": + return Material.BONE_BLOCK; + case "jungle_pyramid": + return Material.LEVER; + case "monument": + return Material.SEA_LANTERN; + case "desert_pyramid": + return Material.SANDSTONE_STAIRS; + case "mineshaft": + return Material.RAIL; + case "ocean_ruin": + return Material.DROWNED_SPAWN_EGG; + case "bastion_remnant": + return Material.BLACKSTONE; + case "shipwreck": + return Material.OAK_BOAT; + case "fortress": + return Material.NETHER_BRICK_FENCE; + case "buried_treasure": + return Material.CHEST; + case "pillager_outpost": + return Material.CROSSBOW; + case "swamp_hut": + return Material.CAULDRON; + case "igloo": + return Material.SNOW_BLOCK; + case "village": + return Material.VILLAGER_SPAWN_EGG; + case "stronghold": + return Material.END_PORTAL_FRAME; + case "end_city": + return Material.PURPUR_PILLAR; + case "mansion": + return Material.TOTEM_OF_UNDYING; + case "ruined_portal": + return Material.CRYING_OBSIDIAN; + default: + return Material.STRUCTURE_VOID; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java index 278dbc026..3cb89fbbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java @@ -1,11 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public interface TriConsumer { - void accept(A a, B b, C c); + void accept(A a, B b, C c); -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java new file mode 100644 index 000000000..5235277c9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java @@ -0,0 +1,16 @@ +package net.codingarea.challenges.plugin.utils.misc; + +import java.util.Objects; +import java.util.function.Function; + +@FunctionalInterface +public interface TriFunction { + + R apply(A a, B b, C c); + + default TriFunction andThen(Function after) { + Objects.requireNonNull(after); + return (A a, B b, C c) -> after.apply(apply(a, b, c)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index ea856217c..c4df7e13a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; import org.bukkit.entity.EntityType; @@ -14,57 +14,52 @@ import java.util.*; import java.util.regex.Pattern; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public final class Utils { - private Utils() { - } + private Utils() { + } - @Nonnull - public static List filterRecommendations(@Nonnull String argument, @Nonnull String... recommendations) { - argument = argument.toLowerCase(); - List list = new ArrayList<>(); - for (String current : recommendations) { - if (current.toLowerCase().startsWith(argument)) - list.add(current); - } - return list; - } + @Nonnull + public static List filterRecommendations(@Nonnull String argument, @Nonnull String... recommendations) { + argument = argument.toLowerCase(); + List list = new ArrayList<>(); + for (String current : recommendations) { + if (current.toLowerCase().startsWith(argument)) + list.add(current); + } + return list; + } - @Nonnull - public static UUID fetchUUID(@Nonnull String name) throws IOException { - String url = "https://api.mojang.com/users/profiles/minecraft/" + name; - String content = IOUtils.toString(new URL(url)); - Document document = Document.parseJson(content); - return Optional.ofNullable(matchUUID(document.getString("id"))).orElseThrow(IOException::new); - } + @Nonnull + public static UUID fetchUUID(@Nonnull String name) throws IOException { + String url = "https://api.mojang.com/users/profiles/minecraft/" + name; + String content = IOUtils.toString(new URL(url)); + Document document = Document.parseJson(content); + return Optional.ofNullable(matchUUID(document.getString("id"))).orElseThrow(IOException::new); + } - @Nullable - public static UUID matchUUID(@Nullable String uuid) { - if (uuid == null) return null; - Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})"); - return UUID.fromString(pattern.matcher(uuid).replaceAll("$1-$2-$3-$4-$5")); - } + @Nullable + public static UUID matchUUID(@Nullable String uuid) { + if (uuid == null) return null; + Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})"); + return UUID.fromString(pattern.matcher(uuid).replaceAll("$1-$2-$3-$4-$5")); + } - @Nullable - @CheckReturnValue - public static Material getMaterial(@Nullable String name) { - return ReflectionUtils.getEnumOrNull(name, Material.class); - } + @Nullable + @CheckReturnValue + public static Material getMaterial(@Nullable String name) { + return ReflectionUtils.getEnumOrNull(name, Material.class); + } - @Nullable - @CheckReturnValue - public static EntityType getEntityType(@Nullable String name) { - return ReflectionUtils.getEnumOrNull(name, EntityType.class); - } + @Nullable + @CheckReturnValue + public static EntityType getEntityType(@Nullable String name) { + return ReflectionUtils.getEnumOrNull(name, EntityType.class); + } - public static > void removeEnums(@Nonnull Collection collection, @Nonnull String... names) { - List nameList = Arrays.asList(names); - collection.removeIf(element -> nameList.contains(element.name())); - } + public static > void removeEnums(@Nonnull Collection collection, @Nonnull String... names) { + List nameList = Arrays.asList(names); + collection.removeIf(element -> nameList.contains(element.name())); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java new file mode 100644 index 000000000..c90eea42b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -0,0 +1,375 @@ +package net.codingarea.commons.bukkit.core; + +import com.google.common.base.Charsets; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.wrapper.ActionListener; +import net.codingarea.commons.bukkit.utils.wrapper.SimpleEventExecutor; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.internal.BukkitLoggerWrapper; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import java.util.logging.Level; + +public abstract class BukkitModule extends JavaPlugin { + + private static volatile BukkitModule firstInstance; + private static boolean setFirstInstance = true; + private static boolean wasShutdown; + + private final Map commands = new HashMap<>(); + private final List listeners = new ArrayList<>(); + private final SimpleConfigManager configManager = new SimpleConfigManager(this); + + private JavaILogger logger; + private ExecutorService executorService; + private Document config, pluginConfig; + private Version version; + private boolean devMode; + private boolean firstInstall; + private boolean isReloaded; + private boolean isLoaded; + + private boolean requirementsMet = true; + + @Override + public final void onLoad() { + isLoaded = true; + + if (!requirementsMet || !(requirementsMet = new RequirementsChecker(this).checkBoolean(getPluginDocument().getDocument("require")))) + return; + + if (setFirstInstance || firstInstance == null) { + setFirstInstance(this); + } + + ILogger.setConstantFactory(this.getILogger()); + trySaveDefaultConfig(); + if (wasShutdown) isReloaded = true; + if (firstInstall = !getDataFolder().exists()) { + getILogger().info("Detected first install!"); + } + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + getILogger().setLevel(Level.ALL); + getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); + } else { + getILogger().setLevel(Level.INFO); + } + + injectInstance(); + + try { + handleLoad(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onEnable() { + if (!requirementsMet) return; + + commands.forEach((name, executor) -> registerCommand0(executor, name)); + listeners.forEach(this::registerListener); + + + try { + handleEnable(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onDisable() { + Throwable error = null; + try { + handleDisable(); + } catch (Throwable ex) { + error = ex; + } + + setFirstInstance = true; + wasShutdown = true; + isLoaded = false; + commands.clear(); + listeners.clear(); + + if (executorService != null) + executorService.shutdown(); + + for (Player player : Bukkit.getOnlinePlayers()) { + InventoryView view = player.getOpenInventory(); + Inventory inventory = view.getTopInventory(); + if (inventory.getHolder() == MenuPosition.HOLDER) + view.close(); + } + + if (error != null) + throw new WrappedException(error); + } + + protected void handleLoad() throws Exception {} + protected void handleEnable() throws Exception {} + protected void handleDisable() throws Exception {} + + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { + return firstInstall; + } + + public final boolean isReloaded() { + return isReloaded; + } + + public final boolean isLoaded() { + return isLoaded; + } + + public final boolean isFirstInstance() { + return firstInstance == this; + } + + @Nonnull + public JavaILogger getILogger() { + return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); + } + + @Nonnull + public Document getConfigDocument() { + checkLoaded(); + return config != null ? config : (config = new YamlDocument(super.getConfig())); + } + + @Override + public void reloadConfig() { + config = null; + super.reloadConfig(); + } + + /** + * @return the plugin configuration (plugin.yml) as document + */ + @Nonnull + public Document getPluginDocument() { + return pluginConfig != null ? pluginConfig : + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + } + + @Nonnull + public FileDocument getConfig(@Nonnull String filename) { + return configManager.getDocument(filename); + } + + @Nonnull + public Version getVersion() { + return version != null ? version : (version = Version.parse(getDescription().getVersion())); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.current()") + public MinecraftVersion getServerVersion() { + return MinecraftVersion.current(); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.currentExact()") + public Version getServerVersionExact() { + return MinecraftVersion.currentExact(); + } + + @Nonnull + @Override + @Deprecated + @ReplaceWith("getConfigDocument()") + public FileConfiguration getConfig() { + return super.getConfig(); + } + + @Override + @Deprecated + public void saveConfig() { + super.saveConfig(); + } + + public void setRequirementsFailed() { + this.requirementsMet = false; + } + + public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { + registerCommand(listenerAndExecutor, names); + registerListener(listenerAndExecutor); + } + + public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { + for (String name : names) { + if (isEnabled()) { + registerCommand0(executor, name); + } else { + commands.put(name, executor); + } + } + } + + private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { + PluginCommand command = getCommand(name); + if (command == null) { + getILogger().warn("Tried to register invalid command '{}'", name); + } else { + command.setExecutor(executor); + } + } + + public final void registerListener(@Nonnull Listener... listeners) { + if (isEnabled()) { + for (Listener listener : listeners) { + registerListener0(listener); + } + } else { + this.listeners.addAll(Arrays.asList(listeners)); + } + } + + private void registerListener0(@Nonnull Listener listener) { + if (listener instanceof ActionListener) { + ActionListener actionListener = (ActionListener) listener; + getServer().getPluginManager().registerEvent( + actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), + new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() + ); + } else { + getServer().getPluginManager().registerEvents(listener, this); + } + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + on(classOfEvent, EventPriority.NORMAL, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { + on(classOfEvent, priority, false, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { + registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); + } + + public final void disablePlugin() { + getServer().getPluginManager().disablePlugin(this); + } + + @Nonnull + public final File getDataFile(@Nonnull String filename) { + return new File(getDataFolder(), filename); + } + + @Nonnull + public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { + return new File(getDataFile(subfolder), filename); + } + + @Nonnull + public ExecutorService getExecutor() { + return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); + } + + public void runAsync(@Nonnull Runnable task) { + getExecutor().submit(task); + } + + public final void checkLoaded() { + if (!isLoaded()) + throw new IllegalStateException("Plugin (" + getName() + ") is not loaded yet"); + } + + public final void checkEnabled() { + if (!isEnabled()) + throw new IllegalStateException("Plugin (" + getName() + ") is not enabled yet"); + } + + private void registerAsFirstInstance() { + getILogger().info(getName() + " was loaded as the first BukkitModule"); + registerListener( + new MenuPositionListener() + ); + getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); + } + + private void trySaveDefaultConfig() { + try { + saveDefaultConfig(); + } catch (IllegalArgumentException ex) { + // No default config exists + } + } + + private void injectInstance() { + try { + Field instanceField = this.getClass().getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, this); + } catch (Throwable ex) { + } + } + + @Nonnull + public static BukkitModule getFirstInstance() { + if (firstInstance == null) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException("No BukkitModule was initialized yet & BukkitModule class was not loaded by a BukkitModule"); + firstInstance = (BukkitModule) provider; + } + + return firstInstance; + } + + private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { + setFirstInstance = false; + firstInstance = module; + module.registerAsFirstInstance(); + } + + @Nonnull + public static BukkitModule getProvidingModule(@Nonnull Class clazz) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); + return (BukkitModule) provider; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java new file mode 100644 index 000000000..87cae1721 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -0,0 +1,94 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.Nonnull; + +public final class RequirementsChecker { + + private final BukkitModule module; + + public RequirementsChecker(@Nonnull BukkitModule module) { + this.module = module; + } + + public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { + if (requirements.getBoolean("spigot")) requireSpigot(); + if (requirements.getBoolean("paper")) requirePaper(); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + } + + public boolean checkBoolean(@Nonnull Document requirements) { + try { + checkExceptionally(requirements); + return true; + } catch (IllegalStateException ex) { + return false; + } + } + + private void requireSpigot() { + try { + Bukkit.spigot(); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of Spigot (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Spigot or Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requirePaper() { + try { + Class.forName("com.destroystokyo.paper.VersionHistoryManager"); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of PaperMC (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requireVersion(@Nonnull Version required) { + if (MinecraftVersion.currentExact().isOlderThan(required)) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("This plugin requires the server version {} (You have: {})", required.format(), MinecraftVersion.currentExact().format()); + log("Please use this version (or an newer version) to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void log(@Nonnull String line, @Nonnull Object... args) { + module.getILogger().error(line, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java new file mode 100644 index 000000000..a4570ad3f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; + +import javax.annotation.Nonnull; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class SimpleConfigManager { + + protected final Map configs = new HashMap<>(); + protected final BukkitModule module; + + public SimpleConfigManager(@Nonnull BukkitModule module) { + this.module = module; + } + + @Nonnull + public FileDocument getDocument(@Nonnull String filename) { + if (!filename.contains(".")) filename += ".json"; + return getDocument(module.getDataFile(filename)); + } + + public synchronized FileDocument getDocument(@Nonnull File file) { + String extension = FileUtils.getFileExtension(file); + return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); + } + + @Nonnull + public static Class resolveType(@Nonnull String extension) { + switch (extension.toLowerCase()) { + case "json": return GsonDocument.class; + case "yml": + case "yaml": return YamlDocument.class; + default: throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java new file mode 100644 index 000000000..3bd67d790 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -0,0 +1,168 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +public class AnimatedInventory { + + private final List frames = new ArrayList<>(); + private final InventoryHolder holder; + private final int size; + private final String title; + private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; + private int frameDelay = 1; + + public AnimatedInventory(@Nonnull String title, int size) { + this(title, size, null); + } + + public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { + this.title = title; + this.size = size; + this.holder = holder; + } + + public void open(@Nonnull Player player) { + open(player, BukkitModule.getFirstInstance()); + } + + public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); + return; + } + + Inventory inventory = createInventory(); + applyFrame(inventory, 0, player); + player.openInventory(inventory); + + AtomicInteger index = new AtomicInteger(1); + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + + boolean opened = inventory.getViewers().contains(player); + if (index.get() >= frames.size() || !opened) { + task.cancel(); + return; + } + + applyFrame(inventory, index.get(), player); + + index.incrementAndGet(); + + }, frameDelay, frameDelay); + + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound) { + openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); + return; + } + + Inventory inventory = createInventory(); + + if (!frames.isEmpty()) { + AnimationFrame frame = getLastFrame(); + inventory.setContents(frame.getContent()); + } + + player.openInventory(inventory); + + if (playSound && endSound != null) endSound.play(player); + + } + + private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { + AnimationFrame frame = frames.get(index); + inventory.setContents(frame.getContent()); + + if (index == frames.size() - 1 && endSound != null) endSound.play(viewer); + else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); + } + + @Nonnull + public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { + if (size != frame.getSize()) throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); + frames.add(frame); + return this; + } + + @Nonnull + public AnimationFrame createAndAdd() { + AnimationFrame frame = new AnimationFrame(size); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getFrame(int index) { + return frames.get(index); + } + + @Nonnull + public AnimationFrame getOrCreateFrame(int index) { + while (frames.size() <= index) { + cloneLastAndAdd(); + } + return getFrame(index); + } + + @Nonnull + public AnimationFrame cloneAndAdd(int index) { + AnimationFrame frame = getFrame(index).clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getLastFrame() { + if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); + return getFrame(frames.size() - 1); + } + + @Nonnull + public AnimationFrame cloneLastAndAdd() { + AnimationFrame frame = getLastFrame().clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { + this.endSound = endSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { + this.frameSound = frameSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameDelay(int delay) { + if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); + this.frameDelay = delay; + return this; + } + + @Nonnull + private Inventory createInventory() { + return Bukkit.createInventory(holder, size, title); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java new file mode 100644 index 000000000..130785522 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -0,0 +1,84 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.utils.item.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public class AnimationFrame implements Cloneable { + + private final ItemStack[] content; + private boolean sound = true; + + public AnimationFrame(@Nonnull ItemStack[] content) { + this.content = Arrays.copyOf(content, content.length); + } + + public AnimationFrame(int size) { + this.content = new ItemStack[size]; + } + + @Nonnull + public AnimationFrame fill(@Nonnull ItemStack item) { + Arrays.fill(content, item); + return this; + } + + @Nonnull + public AnimationFrame setAccent(int... slots) { + for (int slot : slots) { + content[slot] = ItemBuilder.FILL_ITEM_2; + } + return this; + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { + return setItem(slot, item.build()); + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { + content[slot] = item; + return this; + } + + @Nonnull + public AnimationFrame setSound(boolean play) { + this.sound = play; + return this; + } + + @Nullable + public ItemStack getItem(int slot) { + return content[slot]; + } + + @Nullable + public Material getItemType(int slot) { + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + } + + @Nonnull + public ItemStack[] getContent() { + return content; + } + + public boolean shouldPlaySound() { + return sound; + } + + public int getSize() { + return content.length; + } + + @Nonnull + @Override + public AnimationFrame clone() { + return new AnimationFrame(content); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java new file mode 100644 index 000000000..8991960e0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -0,0 +1,113 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public final class SoundSample { + + public static final SoundSample + CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), + BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), + BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), + PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), + KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), + LEVEL_UP = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 1.1f), + PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 2), + LOW_PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 1.3f), + DEATH = new SoundSample().addSound(Sound.ENTITY_BAT_DEATH, 0.7F), + TELEPORT = new SoundSample().addSound(Sound.ITEM_CHORUS_FRUIT_TELEPORT, 0.9F), + OPEN = new SoundSample().addSound(KLING).addSound(PLOP), + EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), + BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), + BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), + WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), + DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); + + public static void playStatusSound(@Nonnull Player player, boolean enabled) { + (enabled ? BASS_ON : BASS_OFF).play(player); + } + + private static final class SoundFrame { + + private final float pitch, volume; + private final Sound sound; + + public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { + this.volume = volume; + this.pitch = pitch; + this.sound = sound; + } + + public SoundFrame(@Nonnull Sound sound, float volume) { + this(sound, volume, 1); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + player.playSound(location, sound, volume, pitch); + } + + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull + public Sound getSound() { + return sound; + } + + } + + private final List frames = new ArrayList<>(); + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { + frames.add(new SoundFrame(sound, volume, pitch)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume) { + frames.add(new SoundFrame(sound, volume)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull SoundSample sound) { + frames.addAll(sound.frames); + return this; + } + + public void play(@Nonnull Player player) { + play(player, player.getLocation()); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + for (SoundFrame frame : frames) { + frame.play(player, location); + } + } + + public void playIfPlayer(@Nonnull Object target) { + if (target instanceof Player) + play((Player) target); + } + + public void broadcast() { + Bukkit.getOnlinePlayers().forEach(this::play); + } + + public void broadcast(@Nonnull Location location) { + Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java new file mode 100644 index 000000000..172e2e4ff --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -0,0 +1,210 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ +public class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java new file mode 100644 index 000000000..60574d3fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java @@ -0,0 +1,333 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import net.codingarea.commons.bukkit.utils.bstats.chart.CustomChart; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +public class Metrics { + + private final Plugin plugin; + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + true, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "2.2.1"; + + private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final String platform; + private final String serverUuid; + private final int serviceId; + private final Consumer appendPlatformDataConsumer; + private final Consumer appendServiceDataConsumer; + private final Consumer submitTaskConsumer; + private final Supplier checkServiceEnabledSupplier; + private final BiConsumer errorLogger; + private final Consumer infoLogger; + private final boolean logErrors; + private final boolean logSentData; + private final boolean logResponseStatusText; + private final Set customCharts = new HashSet<>(); + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution + // of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial + // and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or + // frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + sendData(data); + } catch (Exception e) { + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little + // "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong package + // names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java new file mode 100644 index 000000000..48063d475 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java new file mode 100644 index 000000000..afdba71ee --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java new file mode 100644 index 000000000..3897be5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.function.BiConsumer; + +public abstract class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObject getChartData() throws Exception; +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java new file mode 100644 index 000000000..d0cb2ff19 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java @@ -0,0 +1,51 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java new file mode 100644 index 000000000..0d62864af --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java new file mode 100644 index 000000000..aa7d49220 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java new file mode 100644 index 000000000..e42f4a5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java new file mode 100644 index 000000000..8e4d91259 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java new file mode 100644 index 000000000..4901ae38d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -0,0 +1,64 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.block.banner.PatternType; + +import javax.annotation.Nonnull; + +public enum BannerPattern { + + BASE_DEXTER_CANTON(PatternType.SQUARE_BOTTOM_LEFT), + BASE_SINISTER_CANTON(PatternType.SQUARE_BOTTOM_RIGHT), + CHIEF_DEXTER_CANTON(PatternType.SQUARE_TOP_LEFT), + CHIEF_SINISTER_CANTON(PatternType.SQUARE_TOP_RIGHT), + BASE(PatternType.STRIPE_BOTTOM), + CHIEF(PatternType.STRIPE_TOP), + PALE_DEXTER(PatternType.STRIPE_LEFT), + PALE_SINISTER(PatternType.STRIPE_RIGHT), + PALE(PatternType.STRIPE_CENTER), + FESS(PatternType.STRIPE_MIDDLE), + BEND(PatternType.STRIPE_DOWNRIGHT), + BEND_SINISTER(PatternType.STRIPE_DOWNLEFT), + PALY(PatternType.SMALL_STRIPES), + SALTIRE(PatternType.CROSS), + CROSS(PatternType.STRAIGHT_CROSS), + CHEVRON(PatternType.TRIANGLE_BOTTOM), + INVERTED_CHEVRON(PatternType.TRIANGLE_TOP), + BASE_INDENTED(PatternType.TRIANGLES_BOTTOM), + CHIEF_INDENTED(PatternType.TRIANGLES_TOP), + PER_BEND_SINISTER(PatternType.DIAGONAL_LEFT), + PER_BEND_SINISTER_INVERTED(PatternType.DIAGONAL_RIGHT), + PER_BEND_INVERTED(PatternType.DIAGONAL_UP_LEFT), + PER_BEND(PatternType.DIAGONAL_UP_RIGHT), + ROUNDEL(PatternType.CIRCLE), + LOZENGE(PatternType.STRIPE_MIDDLE), + PER_PALE(PatternType.HALF_VERTICAL), + PER_FESS(PatternType.HALF_HORIZONTAL), + PER_PALE_INVERTED(PatternType.HALF_VERTICAL_RIGHT), + PER_FESS_INVERTED(PatternType.HALF_HORIZONTAL_BOTTOM), + BORDURE(PatternType.BORDER), + BORDURE_INDENTED(PatternType.CURLY_BORDER), + GRADIENT(PatternType.GRADIENT), + BASE_GRADIENT(PatternType.GRADIENT_UP), + FIELD_MASONED(PatternType.BRICKS), + CREEPER_CHARGE(PatternType.CREEPER), + SKULL_CHARGE(PatternType.SKULL), + FLOWER_CHARGE(PatternType.FLOWER), + MOJANG(PatternType.MOJANG); + + private final PatternType patternType; + + BannerPattern(@Nonnull PatternType patternType) { + this.patternType = patternType; + } + + @Nonnull + public PatternType getPatternType() { + return patternType; + } + + @Nonnull + public String getIdentifier() { + return patternType.getKeyOrThrow().getKey(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java new file mode 100644 index 000000000..339bbaba2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -0,0 +1,424 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.PotionEffect; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public class ItemBuilder { + + public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), + FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), + BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), + AIR = new ItemStack(Material.AIR); + + protected ItemStack item; + protected ItemMeta meta; + + public ItemBuilder(@Nonnull ItemStack item) { + this(item, item.getItemMeta()); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + this.item = item; + this.meta = meta; + } + + public ItemBuilder(@Nonnull Material material) { + this(new ItemStack(material)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + this(material); + setName(name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + this(material); + setName(name); + setLore(lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + this(material); + setName(name); + setAmount(amount); + } + + @Nonnull + public ItemMeta getMeta() { + return getCastedMeta(); + } + + @Nonnull + @SuppressWarnings("unchecked") + public final M getCastedMeta() { + return (M) (meta == null ? meta = item.getItemMeta() : meta); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + getMeta().setLore(lore); + return this; + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return setLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return appendLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + List newLore = getMeta().getLore(); + if (newLore == null) newLore = new ArrayList<>(); + newLore.addAll(lore); + setLore(newLore); + return this; + } + + @Nonnull + public ItemBuilder lore(@Nonnull String... lore) { + return setLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + getMeta().setDisplayName(name); + return this; + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return setName(name == null ? null : name.toString()); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + if (content.length > 0) setName(content[0]); + if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); + return this; + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + String name = getMeta().getDisplayName(); + return setName(name + sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return setName(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return setName(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + getMeta().addEnchant(enchantment, level, true); + return this; + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + getMeta().addItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder flag(@Nonnull ItemFlag... flags) { + return addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + getMeta().removeItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder hideAttributes() { + return addFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder showAttributes() { + return removeFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + getMeta().setUnbreakable(unbreakable); + return this; + } + + @Nonnull + public ItemBuilder unbreakable() { + return setUnbreakable(true); + } + + @Nonnull + public ItemBuilder breakable() { + return setUnbreakable(false); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + item.setAmount(Math.min(Math.max(amount, 0), 64)); + return this; + } + + @Nonnull + public ItemBuilder amount(int amount) { + return setAmount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + this.getCastedMeta().setDamage(damage); + return this; + } + + @Nonnull + public ItemBuilder damage(int damage) { + return setDamage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + item.setType(material); + meta = item.getItemMeta(); + return this; + } + + @Nonnull + public String getName() { + return getMeta().getDisplayName(); + } + + @Nonnull + public List getLore() { + List lore = getMeta().getLore(); + return lore == null ? new ArrayList<>() : lore; + } + + @Nonnull + public Material getType() { + return item.getType(); + } + + public int getAmount() { + return item.getAmount(); + } + + public int getDamage() { + return this.getCastedMeta().getDamage(); + } + + @Nonnull + public ItemStack build() { + item.setItemMeta(getMeta()); // Call to getter to prevent null value + return item; + } + + @Nonnull + public ItemStack toItem() { + return build(); + } + + @Override + public ItemBuilder clone() { + return new ItemBuilder(item.clone(), getMeta().clone()); + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(@Nonnull String owner) { + super(Material.PLAYER_HEAD); + setOwner(owner); + } + + public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + super(Material.PLAYER_HEAD, name, lore); + setOwner(owner); + } + + public SkullBuilder setOwner(@Nonnull String owner) { + getMeta().setOwner(owner); + return this; + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java new file mode 100644 index 000000000..e967429a8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -0,0 +1,117 @@ +package net.codingarea.commons.bukkit.utils.item; + +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import javax.annotation.Nonnull; + +public class ItemUtils { + + @Nonnull + public static Material convertFoodToCookedFood(@Nonnull Material material) { + try { + return Material.valueOf("COOKED_" + material.name()); + } catch (Exception ex) { + return material; // No cooked material is available + } + } + + public static boolean isObtainableInSurvival(@Nonnull Material material) { + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.endsWith("_SPAWN_EGG")) return false; + if (name.startsWith("INFESTED_")) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "BEDROCK": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL_FRAME": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "LAVA": + case "WATER": + case "LARGE_FERN": + case "TALL_GRASS": + case "TALL_SEAGRASS": + case "PATH_BLOCK": + case "CHORUS_PLANT": + case "PETRIFIED_OAK_SLAB": + case "FARMLAND": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "SPAWNER": + case "AMETHYST_CLUSTER": + case "BUDDING_AMETHYST": + case "POWDER_SNOW": + case "LIGHT": + case "BUNDLE": + case "REINFORCED_DEEPSLATE": + case "FROGSPAWN": + return false; + } + + if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { + return !name.equals("SCULK_SENSOR"); + } + + return true; + } + + public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + if (!material.isBlock()) return false; + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "PETRIFIED_OAK_SLAB": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "LIGHT": + case "BUNDLE": + return false; + } + + return true; + } + + public static void damageItem(@Nonnull ItemStack item) { + damageItem(item, 1); + } + + public static void damageItem(@Nonnull ItemStack item, int amount) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + if (!(meta instanceof Damageable)) return; + Damageable damageable = (Damageable) meta; + damageable.setDamage(damageable.getDamage() + amount); + item.setItemMeta(meta); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java new file mode 100644 index 000000000..ac6f766f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.bukkit.utils.logging; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public final class Logger { + + private Logger() {} + + @Nonnull + public static ILogger getInstance() { + return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); + } + + public static void error(@Nullable Object message, @Nonnull Object... args) { + getInstance().error(message, args); + } + + public static void warn(@Nullable Object message, @Nonnull Object... args) { + getInstance().warn(message, args); + } + + public static void info(@Nullable Object message, @Nonnull Object... args) { + getInstance().info(message, args); + } + + public static void debug(@Nullable Object message, @Nonnull Object... args) { + getInstance().debug(message, args); + } + + public static void trace(@Nullable Object message, @Nonnull Object... args) { + getInstance().trace(message, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java new file mode 100644 index 000000000..5753ad174 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -0,0 +1,75 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class MenuClickInfo { + + protected final Player player; + protected final Inventory inventory; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; + + public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { + this.player = player; + this.inventory = inventory; + this.shiftClick = shiftClick; + this.rightClick = rightClick; + this.slot = slot; + } + + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } + + public boolean isRightClick() { + return rightClick; + } + + public boolean isLeftClick() { + return !rightClick; + } + + public boolean isShiftClick() { + return shiftClick; + } + + public int getSlot() { + return slot; + } + + @Nullable + public ItemStack getClickedItem() { + return inventory.getItem(slot); + } + + @Nonnull + public Material getClickedMaterial() { + return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); + } + + @Override + public String toString() { + return "MenuClickInfo{" + + "player=" + player + + ", inventory=" + inventory + + ", shiftClick=" + shiftClick + + ", rightClick=" + rightClick + + ", slot=" + slot + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java new file mode 100644 index 000000000..527cc844f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@FunctionalInterface +public interface MenuPosition { + + final class Holder { + + private Holder() {} + + private static final Map positions = new ConcurrentHashMap<>(); + + } + + InventoryHolder HOLDER = new MenuPositionHolder(); + + static void set(@Nonnull Player player, @Nullable MenuPosition position) { + Holder.positions.put(player, position); + } + + static void remove(@Nonnull Player player) { + Holder.positions.remove(player); + } + + @Nullable + static MenuPosition get(@Nonnull Player player) { + return Holder.positions.get(player); + } + + static void setEmpty(@Nonnull Player player) { + set(player, new EmptyMenuPosition()); + } + + void handleClick(@Nonnull MenuClickInfo info); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java new file mode 100644 index 000000000..669b1367f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; + +class MenuPositionHolder implements InventoryHolder { + + @Nonnull + @Override + public Inventory getInventory() { + return null; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java new file mode 100644 index 000000000..8addddaca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; + +import javax.annotation.Nonnull; + +public final class MenuPositionListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { + + HumanEntity human = event.getWhoClicked(); + if (!(human instanceof Player)) return; + Player player = (Player) human; + + Inventory inventory = event.getClickedInventory(); + if (inventory == null) return; + + if (inventory == CompatibilityUtils.getTopInventory(event)) { + + if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + MenuPosition position = MenuPosition.get(player); + if (position == null) return; // Currently in no menu + + event.setCancelled(true); + position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); + + } else if (event.isShiftClick()) { // Player inventory was clicked + + Inventory topInventory = event.getInventory(); + if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + event.setCancelled(true); + + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java new file mode 100644 index 000000000..dfe653abf --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; + +import javax.annotation.Nonnull; + +public class EmptyMenuPosition implements MenuPosition { + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java new file mode 100644 index 000000000..8ea854148 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +public class SlottedMenuPosition implements MenuPosition { + + protected final Map> actions = new HashMap<>(); + protected boolean emptySound = true; + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + Consumer action = actions.get(info.getSlot()); + if (action == null) { + if (emptySound) SoundSample.CLICK.play(info.getPlayer()); + return; + } + + action.accept(info); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { + actions.put(slot, action); + return this; + } + + @Nonnull + public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { + return setAction(slot, info -> action.accept(info.getPlayer())); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { + return setAction(slot, info -> action.run()); + } + + public SlottedMenuPosition setEmptySound(boolean playSound) { + this.emptySound = playSound; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java new file mode 100644 index 000000000..36284f5e3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -0,0 +1,170 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Method; +import java.util.regex.Pattern; + +/** + * This class gives access to + * - api functions which are not directly implemented in some versions of bukkit or spigot + * - some basic nms functionality. + */ +public final class BukkitReflectionUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private BukkitReflectionUtils() { + } + + public static double getAbsorptionAmount(@Nonnull Player player) { + Class classOfPlayer = player.getClass(); + + try { + return player.getAbsorptionAmount(); + } catch (Throwable ignored) { + } + + try { + Method getHandleMethod = classOfPlayer.getMethod("getHandle"); + getHandleMethod.setAccessible(true); + + Object handle = getHandleMethod.invoke(player); + Class classOfHandle = handle.getClass(); + + Method getAbsorptionMethod = classOfHandle.getMethod("getAbsorptionHearts"); + getAbsorptionMethod.setAccessible(true); + return (double) (float) getAbsorptionMethod.invoke(handle); + } catch (Throwable ignored) { + } + + logger.warn("Could not get absorption amount for player of class {}", classOfPlayer.getName()); + return 0; + } + + public static boolean isAir(@Nonnull Material material) { + try { + return material.isAir(); + } catch (Throwable ignored) { + } + + switch (material.name()) { + case "AIR": + case "VOID_AIR": + case "CAVE_AIR": + case "LEGACY_AIR": + return true; + default: + return false; + } + } + + public static int getMinHeight(@Nonnull World world) { + try { + return world.getMinHeight(); + } catch (Throwable ignored) { + } + + return 0; + } + + /** + * @return if the entity is in water, {@code false} otherwise or if not implemented + * @deprecated not implemented in all forks of bukkit + */ + @Deprecated + public static boolean isInWater(@Nonnull Entity entity) { + try { + return entity.isInWater(); + } catch (Throwable ignored) { + } + + return false; + } + + private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); + + /** + * Get a NamespacedKey from the supplied string. + * + * The default namespace will be Minecraft's (i.e. + * {@link NamespacedKey#minecraft(String)}). + * + * @param key the key to convert to a NamespacedKey + * @return the created NamespacedKey. null if invalid + * @see #fromString(String, Plugin) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String key) { + return fromString(key, null); + } + + /** + * Does not exists in versions prior to 1.14 + * + * Get a NamespacedKey from the supplied string with a default namespace if + * a namespace is not defined. This is a utility method meant to fetch a + * NamespacedKey from user input. Please note that casing does matter and + * any instance of uppercase characters will be considered invalid. The + * input contract is as follows: + *

+	 * fromString("foo", plugin) -{@literal >} "plugin:foo"
+	 * fromString("foo:bar", plugin) -{@literal >} "foo:bar"
+	 * fromString(":foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("Foo", plugin) -{@literal >} null
+	 * fromString(":Foo", plugin) -{@literal >} null
+	 * fromString("foo:bar:bazz", plugin) -{@literal >} null
+	 * fromString("", plugin) -{@literal >} null
+	 * 
+ * + * @param string the string to convert to a NamespacedKey + * @param defaultNamespace the default namespace to use if none was + * supplied. If null, the {@code minecraft} namespace + * ({@link NamespacedKey#minecraft(String)}) will be used + * @return the created NamespacedKey. null if invalid key + * @see #fromString(String) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + + String[] components = string.split(":", 3); + if (components.length > 2) { + return null; + } + + String key = (components.length == 2) ? components[1] : ""; + if (components.length == 1) { + String value = components[0]; + if (value.isEmpty() || !VALID_KEY.matcher(value).matches()) { + return null; + } + + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, value) : NamespacedKey.minecraft(value); + } else if (components.length == 2 && !VALID_KEY.matcher(key).matches()) { + return null; + } + + String namespace = components[0]; + if (namespace.isEmpty()) { + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, key) : NamespacedKey.minecraft(key); + } + + if (!VALID_KEY.matcher(namespace).matches()) { + return null; + } + + return new NamespacedKey(namespace, key); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java new file mode 100644 index 000000000..47cd94c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/* + * In API version 1.20.6 and earlier, InventoryView is an abstract class + * In API version 1.21, InventoryView is an interface + */ +public class CompatibilityUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + private static final Logger log = LoggerFactory.getLogger(CompatibilityUtils.class); + + private CompatibilityUtils() { + } + + public static Inventory getTopInventory(@Nonnull Player player) { + InventoryView view = player.getOpenInventory(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } + + public static Inventory getTopInventory(@Nonnull InventoryClickEvent event) { + InventoryView view = event.getView(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java new file mode 100644 index 000000000..44d8d380f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java @@ -0,0 +1,91 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.SkullMeta; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.UUID; + +public final class GameProfileUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private GameProfileUtils() {} + + @Nonnull + public static GameProfile getGameProfile(@Nonnull Player player) { + try { + + Class classOfPlayer = player.getClass(); + + Method getProfileMethod = classOfPlayer.getMethod("getProfile"); + getProfileMethod.setAccessible(true); + return (GameProfile) getProfileMethod.invoke(player); + + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { + applyTextures(meta, uuid, name, texture, null); + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { + if (texture == null || texture.isEmpty()) return; + + GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); + profile.getProperties().put("textures", new Property("textures", texture, signature)); + + Class classOfMeta = meta.getClass(); + try { + Method setProfileMethod = classOfMeta.getDeclaredMethod("setProfile", GameProfile.class); + setProfileMethod.setAccessible(true); + setProfileMethod.invoke(meta, profile); + return; + } catch (Exception ignored) { + } + + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + field.set(meta, profile); + + // This field is not implemented in every version + try { + field = classOfMeta.getDeclaredField("serializedProfile"); + field.setAccessible(true); + field.set(meta, profile); + } catch (Exception ignored) { + } + + return; + } catch (Exception ignored) { + } + + logger.warn("Unable to apply textures to item"); + + } + + @Nonnull + public static GameProfile getTextures(@Nonnull SkullMeta meta) { + + Class classOfMeta = meta.getClass(); + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + return (GameProfile) field.get(meta); + } catch (Exception ex) { + throw new WrappedException(ex); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java new file mode 100644 index 000000000..16e369a67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -0,0 +1,115 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public enum MinecraftVersion implements Version { + + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static MinecraftVersion current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java new file mode 100644 index 000000000..8faa0993b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -0,0 +1,57 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.Consumer; + +public final class ActionListener implements Listener { + + private final Class classOfEvent; + private final Consumer listener; + private final EventPriority priority; + private final boolean ignoreCancelled; + + public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { + this.classOfEvent = classOfEvent; + this.listener = listener; + this.priority = priority; + this.ignoreCancelled = ignoreCancelled; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ActionListener that = (ActionListener) o; + return listener.equals(that.listener); + } + + @Override + public int hashCode() { + return Objects.hash(listener); + } + + @Nonnull + public Consumer getListener() { + return listener; + } + + @Nonnull + public EventPriority getPriority() { + return priority; + } + + @Nonnull + public Class getClassOfEvent() { + return classOfEvent; + } + + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java new file mode 100644 index 000000000..ea2a13e3f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java @@ -0,0 +1,23 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import org.bukkit.attribute.Attribute; + +public class AttributeWrapper { + + public static final Attribute MAX_HEALTH = wrap("MAX_HEALTH", "GENERIC_MAX_HEALTH"), + ATTACK_SPEED = wrap("ATTACK_SPEED", "GENERIC_ATTACK_SPEED"); + + public static Attribute wrap(String name, String legacyName) { + return wrap(name, legacyName, MinecraftVersion.V1_21_2); + } + + public static Attribute wrap(String name, String legacyName, MinecraftVersion since) { + if (MinecraftVersion.current().isNewerOrEqualThan(since)) { + return Attribute.valueOf(name); + } else { + return Attribute.valueOf(legacyName); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java new file mode 100644 index 000000000..d073dd81f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.bukkit.Material; + +import javax.annotation.Nonnull; + +/** + * This class allows you to use materials, whose names are changed at some point, in most versions. + * For example the red dye was first named {@code ROSE_RED} but then renamed to {@code RED_DYE}. + * To prevent unwanted {@link NoSuchFieldError NoSuchFieldErrors}, you should use this wrapper instead of a direct call to the material enum {@link Material}. + */ +public final class MaterialWrapper { + + private MaterialWrapper() {} + + public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); + public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); + public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); + public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); + + @Nonnull + private static Material getMaterialByNames(@Nonnull String... names) { + return ReflectionUtils.getFirstEnumByNames(Material.class, names); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java new file mode 100644 index 000000000..2b3055417 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.bukkit.plugin.EventExecutor; + +import javax.annotation.Nonnull; +import java.util.function.Consumer; + +public class SimpleEventExecutor implements EventExecutor { + + private final Class classOfEvent; + private final Consumer action; + + public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + this.classOfEvent = classOfEvent; + this.action = action; + } + + @Override + public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { + if (!classOfEvent.isAssignableFrom(event.getClass())) return; + try { + action.accept(event); + } catch (Throwable ex) { + throw new EventException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java new file mode 100644 index 000000000..685852b83 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * Used to declare alternate names which are used in used or similar libraries. + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) +public @interface AlsoKnownAs { + + @Nonnull + String[] value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java new file mode 100644 index 000000000..72fb1e113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface DeprecatedSince { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java new file mode 100644 index 000000000..469355d3b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface ReplaceWith { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java new file mode 100644 index 000000000..0f27a0c69 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +@Documented +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PACKAGE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Since { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java new file mode 100644 index 000000000..23ba208f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java @@ -0,0 +1,56 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.lang.reflect.Array; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.function.Consumer; + +public class ArrayWalker implements Iterable { + + protected final Object array; + protected final int length; + + protected ArrayWalker(@Nonnull Object array) { + if (!array.getClass().isArray()) throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); + this.array = array; + this.length = Array.getLength(array); + } + + public static ArrayWalker walk(@Nonnull Object array) { + return new ArrayWalker<>(array); + } + + public static ArrayWalker walk(@Nonnull T... array) { + return new ArrayWalker<>(array); + } + + @Override + public Iterator iterator() { + return new Iterator() { + + private int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < length; + } + + @Override + @SuppressWarnings("unchecked") + public T next() { + if (!hasNext()) throw new NoSuchElementException(); + return (T) Array.get(array, cursor++); + } + + }; + } + + @Override + @SuppressWarnings("unchecked") + public void forEach(Consumer action) { + for (int i = 0; i < length; i++) { + action.accept((T) Array.get(array, i)); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java new file mode 100644 index 000000000..d71f0df71 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -0,0 +1,65 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.*; + +/** + * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java + */ +public class ClassWalker implements Iterable> { + + protected final Class clazz; + protected final Class end; + + protected ClassWalker(@Nonnull Class clazz) { + this(clazz, Object.class); + } + + protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { + this.clazz = clazz; + this.end = end; + } + + public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { + return new ClassWalker(start, end); + } + + public static ClassWalker walk(@Nonnull Class start) { + return new ClassWalker(start); + } + + @Nonnull + @Override + public Iterator> iterator() { + return new Iterator>() { + + private final Set> done = new HashSet<>(); + private final Deque> work = new LinkedList<>(); + + { + work.addLast(clazz); + done.add(end); + } + + @Override + public boolean hasNext() { + return !work.isEmpty(); + } + + @Override + public Class next() { + Class current = work.removeFirst(); + done.add(current); + for (Class parent : current.getInterfaces()) { + if (!done.contains(parent)) + work.addLast(parent); + } + + Class parent = current.getSuperclass(); + if (parent != null && !done.contains(parent)) + work.addLast(parent); + return current; + } + }; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java new file mode 100644 index 000000000..dc7950c10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; + +import static java.awt.Color.decode; + +public final class Colors { + + private Colors() {} + + public static final Color + ONLINE = decode("#40AC7B"), + DO_NOT_DISTURB = decode("#E84444"), + IDLE = decode("#F09F19"), + OFFLINE = decode("#747F8D"), + STREAMING = decode("#573591"), + + EMBED = decode("#2F3136"), + NO_RANK = decode("#CCD8DE"), + + LIGHT_BLACK = decode("#1c1c1c") + ; + + @Nonnull + @CheckReturnValue + public static String asHex(@Nonnull Color color) { + String red = Integer.toHexString(color.getRed()); + String green = Integer.toHexString(color.getGreen()); + String blue = Integer.toHexString(color.getBlue()); + return "#" + (red.length() == 1 ? "0" + red : red) + + (green.length() == 1 ? "0" + green : green) + + (blue.length() == 1 ? "0" + blue : blue); + } + + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java new file mode 100644 index 000000000..4625c3347 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java @@ -0,0 +1,93 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.Objects; + +public class FontBuilder { + + private Font font; + + public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { + this(file, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, file); + } + + public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { + this(resource, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); + } + + @Nonnull + @CheckReturnValue + public FontBuilder bold() { + return style(Font.BOLD); + } + + @Nonnull + @CheckReturnValue + public FontBuilder italic() { + return style(Font.ITALIC); + } + + @Nonnull + @CheckReturnValue + public FontBuilder style(int style) { + font = font.deriveFont(style); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder size(float size) { + font = font.deriveFont(size); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder derive(int style, float size) { + font = font.deriveFont(style, size); + return this; + } + + @Nonnull + public Font build() { + registerFont(font); + return font; + } + + public static void registerFont(@Nonnull Font font) { + GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromFile(@Nonnull String filename) { + try { + return new FontBuilder(new File(filename)); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromResource(@Nonnull String resource) { + try { + return new FontBuilder(resource); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java new file mode 100644 index 000000000..54c8675fe --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java @@ -0,0 +1,43 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public final class IOUtils { + + private IOUtils() {} + + public static String toString(@Nonnull String url) throws IOException { + return toString(new URL(url)); + } + + public static String toString(@Nonnull URL url) throws IOException { + InputStream input = url.openStream(); + String string = toString(input); + input.close(); + return string; + } + + public static String toString(@Nonnull InputStream input) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); + reader.lines().forEach(builder::append); + return builder.toString(); + } + + @Nonnull + @CheckReturnValue + public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return connection; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java new file mode 100644 index 000000000..cfd4a96bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -0,0 +1,152 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public interface IRandom { + + @Nonnull + @CheckReturnValue + static IRandom create() { + return new SeededRandomWrapper(); + } + + @Nonnull + @CheckReturnValue + static IRandom create(long seed) { + return new SeededRandomWrapper(seed); + } + + @Nonnull + @CheckReturnValue + static IRandom wrap(@Nonnull Random random) { + return new RandomWrapper(random); + } + + @Nonnull + @CheckReturnValue + static IRandom threadLocal() { + return wrap(ThreadLocalRandom.current()); + } + + @Nonnull + @CheckReturnValue + static IRandom secure() { + return wrap(new SecureRandom()); + } + + @Nonnull + @CheckReturnValue + static IRandom singleton() { + return SingletonRandom.INSTANCE; + } + + long getSeed(); + + void setSeed(long seed); + + void nextBytes(@Nonnull byte[] bytes); + + boolean nextBoolean(); + + int nextInt(); + + int nextInt(int bound); + + @Nonnull + @CheckReturnValue + IntStream ints(); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + IntStream ints(int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(); + + long nextLong(); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + LongStream longs(long randomNumberOrigin, long randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); + + double nextDouble(); + + double nextGaussian(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); + + float nextFloat(); + + default T choose(@Nonnull T... array) { + return array[nextInt(array.length)]; + } + + default T choose(@Nonnull List list) { + return list.get(nextInt(list.size())); + } + + default T choose(@Nonnull Collection collection) { + return choose(new ArrayList<>(collection)); + } + + default void shuffle(@Nonnull List list) { + Collections.shuffle(list, asRandom()); + } + + default int around(int value, @Nonnegative int range) { + return range(value - range, value + range); + } + + default int range(int min, int max) { + if (min >= max) throw new IllegalArgumentException("min >= max"); + return nextInt(max - min) + min; + } + + @Nonnull + @CheckReturnValue + default Random asRandom() { + if (!(this instanceof Random)) + throw new IllegalStateException(this.getClass().getName() + " cannot be converted a java.util.Random"); + return (Random) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java new file mode 100644 index 000000000..624f2508f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntFunction; + +public class NamedThreadFactory implements ThreadFactory { + + private static final AtomicInteger poolNumber = new AtomicInteger(1); + + protected final int id = poolNumber.getAndIncrement(); + protected final IntFunction nameFunction; + protected final ThreadGroup group; + protected final AtomicInteger threadNumber = new AtomicInteger(1); + + public NamedThreadFactory(@Nonnull IntFunction nameFunction) { + SecurityManager securityManager = System.getSecurityManager(); + this.group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); + this.nameFunction = nameFunction; + } + + public NamedThreadFactory(@Nonnull String prefix) { + this(id -> prefix + "-" + id); + } + + @Override + public Thread newThread(@Nonnull Runnable task) { + Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); + if (thread.isDaemon()) + thread.setDaemon(false); + if (thread.getPriority() != Thread.NORM_PRIORITY) + thread.setPriority(Thread.NORM_PRIORITY); + return thread; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java new file mode 100644 index 000000000..4a734b55b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -0,0 +1,357 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.function.Consumer; + +public interface NumberFormatter { + + @Nonnull + @CheckReturnValue + String format(double value); + + @Nonnull + @CheckReturnValue + default String format(float value) { + return format(Float.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(long value) { + return format(Long.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(int value) { + return format(Integer.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(short value) { + return format(Short.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(byte value) { + return format(Byte.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(@Nonnull Number number) { + return format(number.doubleValue()); + } + + public static final NumberFormatter + DEFAULT = fromPattern("0.##", null, false), + INTEGER = value -> (int) value + "", + SPACE_SPLIT = fromPattern("###,##0.###############", null, false, + init -> updateSymbols(init, symbols -> symbols.setGroupingSeparator(' '))), + FLOATING_POINT = fromPattern("0.0", null, false), + DOUBLE_FLOATING_POINT = fromPattern("0.00", null, false), + BIG_FLOATING_POINT = fromPattern("###,##0.00000", null, false), + PERCENTAGE = fromPattern("0.##", "%", true), + FLOATING_PERCENTAGE = fromPattern("0.00", "%", true), + MIDDLE_NUMBER = fromPattern("###,###,##0.#", null, false), + + /** + * days, hours, minutes, seconds + */ + TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 ? minutes + "m " : "") + + (seconds > 0 || (years == 0 && days == 0 && hours == 0 && minutes == 0) ? seconds + "s" : "")).trim(); + + }, + + /** + * days, hours, minutes + */ + BIG_TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 || (years == 0 && days == 0 && hours == 0) ? minutes + "m " : "")).trim(); + + }, + + /** + * input: millis + * 1 Tag, H:M:S + */ + GERMAN_TIME = value -> { + + DecimalFormat format = new DecimalFormat("00"); + + long millis = (long) value; + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + seconds %= 60; + minutes %= 60; + hours %= 24; + + return (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? format.format(hours) + ":" : "") + + format.format(minutes) + ":" + + format.format(seconds); + + }, + /** + * input: seconds + * 1 Tag, H:M:S + */ + FULL_GERMAN_TIME_HOURS = value -> { + + long seconds = (long) (value); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); + }, + + FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "") + + (seconds > 0 || years == 0 && hours == 0 && minutes == 0 ? (seconds == 1 ? "1 Sekunde" : seconds + " Sekunden") : "")).trim(); + + }, + + NORMAL_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 || value == 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "")).trim(); + + }, + + BIG_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 || years == 0 && days == 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : "")).trim(); + + }, + + /** + * billion, million, thousand, number + */ + BIG_NUMBER = value -> { + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending = ""; + + // Normal number + if (value < 1000) { + divide = 1; + format = new DecimalFormat("0.#"); + // Thousand + } else if (value < 1000000) { + divide = 1000; + ending = "k"; + // Million + } else if (value < 1000000000) { + divide = 1000000; + ending = "m"; + // Billion (Milliarde) + } else if (value < 1000000000000D) { + divide = 1000000000; + ending = "b"; + // Trillion (Billion) + } else { + divide = 1000000000000D; + ending = "t"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * kilobyte, megabyte, gigabyte, terrabyte + */ + DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // KiloByte + if (value < 1000000L) { + divide = 1000; + format = new DecimalFormat("0.#"); + ending = "KB"; + } else if (value < 1000000000L) { + // MegaByte + divide = 1000000L; + ending = "MB"; + // GigaByte + } else if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else { + divide = 1000000000000L; + ending = "TB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * gigabyte, terrabyte, petabyte + */ + BIG_DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // GigaByte + if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else if (value < 1000000000000000L) { + divide = 1000000000000L; + ending = "TB"; + // PetaByte + } else { + divide = 1000000000000000L; + ending = "PB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + ORDINAL = value -> { + + String string = String.valueOf(((long) value)); + int number = Integer.parseInt(string.substring(string.length() - 1)); + String ending = "th"; + + if (value != 11 && value != 12 && value != 13) { + switch (number) { + case 1: + ending = "st"; + break; + case 2: + ending = "nd"; + break; + case 3: + ending = "rd"; + break; + } + } + + return string + ending; + + }, + GERMAN_ORDINAL = fromPattern("0", ".", false); + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + return fromPattern(pattern, ending, positive, null); + } + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + DecimalFormat format = new DecimalFormat(pattern); + if (init != null) init.accept(format); + return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); + } + + @Nonnull + @CheckReturnValue + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + action.accept(symbols); + return symbols; + } + + @CheckReturnValue + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java new file mode 100644 index 000000000..b561b6bf8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; + +public class PublicSecurityManager extends SecurityManager { + + @Nonnull + public Class[] getPublicClassContext() { + return getClassContext(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java new file mode 100644 index 000000000..a845fbc10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java @@ -0,0 +1,149 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.Random; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public class RandomWrapper implements IRandom { + + private final Random random; + + public RandomWrapper(@Nonnull Random random) { + this.random = random; + } + + @Override + public long getSeed() { + throw new UnsupportedOperationException("Random.getSeed()"); + } + + @Override + public void setSeed(long seed) { + random.setSeed(seed); + } + + @Override + public void nextBytes(@Nonnull byte[] bytes) { + random.nextBytes(bytes); + } + + @Override + public boolean nextBoolean() { + return random.nextBoolean(); + } + + @Override + public int nextInt() { + return random.nextInt(); + } + + @Override + public int nextInt(int bound) { + return random.nextInt(bound); + } + + @Nonnull + @Override + public IntStream ints() { + return random.ints(); + } + + @Nonnull + @Override + public IntStream ints(long streamSize) { + return random.ints(streamSize); + } + + @Nonnull + @Override + public IntStream ints(int randomNumberOrigin, int randomNumberBound) { + return random.ints(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { + return random.ints(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs() { + return random.longs(); + } + + @Override + public long nextLong() { + return random.nextLong(); + } + + @Nonnull + @Override + public LongStream longs(long streamSize) { + return random.longs(streamSize); + } + + @Nonnull + @Override + public LongStream longs(long randomNumberOrigin, long randomNumberBound) { + return random.longs(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { + return random.longs(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public double nextDouble() { + return random.nextDouble(); + } + + @Override + public double nextGaussian() { + return random.nextGaussian(); + } + + @Nonnull + @Override + public DoubleStream doubles() { + return random.doubles(); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize) { + return random.doubles(streamSize); + } + + @Nonnull + @Override + public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { + return random.doubles(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { + return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public float nextFloat() { + return random.nextFloat(); + } + + @Nonnull + @Override + public Random asRandom() { + return random; + } + + @Override + public String toString() { + return "Random[wrapped=" + random.getClass().getSimpleName() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java new file mode 100644 index 000000000..e1401ba5e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TreeMap; + +public final class RomanNumerals { + + public static final class IllegalRomanNumeralException extends IllegalArgumentException { + + private IllegalRomanNumeralException(int number) { + super("Number " + number + " out of bounds for 0 to 3999"); + } + + } + + private static final TreeMap values = new TreeMap<>(); + + static { + values.put(1000, "M" ); + values.put(900, "CM"); + values.put(500, "D" ); + values.put(400, "CD"); + values.put(100, "C" ); + values.put(90, "XC"); + values.put(50, "L" ); + values.put(40, "XL"); + values.put(10, "X" ); + values.put(9, "IX"); + values.put(5, "V" ); + values.put(4, "IV"); + values.put(1, "I" ); + } + + private RomanNumerals() {} + + @Nonnull + public static String forNumber(int number) { + if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); + if (number == 0) return ""; + int i = values.floorKey(number); + if (number == i) { + return values.get(number); + } + return values.get(i) + forNumber(number - i); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java new file mode 100644 index 000000000..540c375f1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TimerTask; + +public class RunnableTimerTask extends TimerTask { + + protected final Runnable action; + + public RunnableTimerTask(@Nonnull Runnable action) { + this.action = action; + } + + @Override + public void run() { + action.run(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java new file mode 100644 index 000000000..a9fcb48f2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -0,0 +1,35 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +/** + * Since there is no way of getting the seed of a {@link Random} we create a wrapper + * which will save seed. This allows us to save randomization and reload it. + */ +public class SeededRandomWrapper extends Random implements IRandom { + + protected long seed; + + public SeededRandomWrapper() { + super(); + } + + public SeededRandomWrapper(long seed) { + super(seed); + } + + @Override + public void setSeed(long seed) { + super.setSeed(seed); + this.seed = seed; + } + + public long getSeed() { + return seed; + } + + @Override + public String toString() { + return "Random[seed=" + seed + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java new file mode 100644 index 000000000..93a2ce6ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +public class SingletonRandom extends RandomWrapper { + + public static final SingletonRandom INSTANCE = new SingletonRandom(); + + private SingletonRandom() { + super(new Random()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java new file mode 100644 index 000000000..2d0e45d21 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.io.PrintWriter; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderPrintWriter extends PrintWriter { + + protected final StringBuilderWriter writer; + + public StringBuilderPrintWriter() { + super(new StringBuilderWriter()); + writer = (StringBuilderWriter) out; + } + + @Nonnull + public StringBuilder getBuilder() { + return writer.getBuilder(); + } + + @Override + public String toString() { + return getBuilder().toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java new file mode 100644 index 000000000..5ad40651c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java @@ -0,0 +1,68 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.Writer; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderWriter extends Writer { + + private final StringBuilder builder; + + public StringBuilderWriter() { + this.builder = new StringBuilder(); + } + + public StringBuilderWriter(int capacity) { + this.builder = new StringBuilder(capacity); + } + + public StringBuilderWriter(@Nullable StringBuilder builder) { + this.builder = builder != null ? builder : new StringBuilder(); + } + + public Writer append(char value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value, int start, int end) { + builder.append(value, start, end); + return this; + } + + public void close() { + } + + public void flush() { + } + + public void write(@Nonnull String value) { + builder.append(value); + } + + public void write(@Nullable char[] value, int offset, int length) { + if (value != null) { + builder.append(value, offset, length); + } + } + + @Nonnull + public StringBuilder getBuilder() { + return this.builder; + } + + @Override + public String toString() { + return this.builder.toString(); + } + +} + diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java new file mode 100644 index 000000000..b480031d2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java @@ -0,0 +1,20 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +@Deprecated +public class Triple extends net.codingarea.commons.common.collection.pair.Triple { + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + super(first, second, third); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java new file mode 100644 index 000000000..8e9077907 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + */ +@Deprecated +public class Tuple extends net.codingarea.commons.common.collection.pair.Tuple { + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + super(first, second); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java new file mode 100644 index 000000000..1e8999988 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * This class is used to rethrow signed exception as unsigned exceptions. + */ +public class WrappedException extends RuntimeException { + + public static class SilentWrappedException extends WrappedException { + + public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public SilentWrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + } + + public WrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public WrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Nonnull + @Override + public Throwable getCause() { + return super.getCause(); + } + + @Nonnull + public static RuntimeException rethrow(@Nonnull Throwable ex) { + if (ex instanceof Error) + throw (Error) ex; + if (ex instanceof RuntimeException) + throw (RuntimeException) ex; + throw silent(ex); + } + + @Nonnull + public static WrappedException silent(@Nonnull Throwable cause) { + return new SilentWrappedException(cause); + } + + @Nonnull + public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { + return new SilentWrappedException(message, cause); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java new file mode 100644 index 000000000..bb4c23a4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Tuple + * @see Triple + * @see Quadro + */ +public interface Pair { + + /** + * @return The amount of values + */ + @Nonnegative + int amount(); + + @Nonnull + Object[] values(); + + /** + * @return {@code true} when all of the values are null, {@code false} otherwise + */ + boolean allNull(); + + /** + * @return {@code true} when none of the values are null, {@code false} otherwise + */ + boolean noneNull(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java new file mode 100644 index 000000000..df07b890d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + * @param The type of the fourth value + */ +public class Quadro implements Pair { + + protected F first; + protected S second; + protected T third; + protected FF fourth; + + public Quadro() { + } + + public Quadro(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + this.first = first; + this.second = second; + this.third = third; + this.fourth = fourth; + } + + @Override + public final int amount() { + return 4; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third, first }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + public void setFourth(@Nullable FF fourth) { + this.fourth = fourth; + } + + @Nonnull + @CheckReturnValue + public Quadro map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper, + @Nonnull Function fourthMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); + } + + public boolean noneNull() { + return first != null && second != null && third != null && fourth != null; + } + + public boolean allNull() { + return first == null && second == null && third == null && fourth != null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quadro quadro = (Quadro) o; + return Objects.equals(first, quadro.first) && Objects.equals(second, quadro.second) && Objects.equals(third, quadro.third) && Objects.equals(fourth, quadro.fourth); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third, fourth); + } + + @Override + public String toString() { + return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; + } + + @Nonnull + public static Quadro ofFirst(@Nullable F first) { + return of(first, null, null, null); + } + + @Nonnull + public static Quadro ofSecond(@Nullable S second) { + return of(null, second, null, null); + } + + @Nonnull + public static Quadro ofThird(@Nullable T third) { + return of(null, null, third, null); + } + + @Nonnull + public static Quadro ofFourth(@Nullable FF fourth) { + return of(null, null, null, fourth); + } + + @Nonnull + public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + return new Quadro<>(first, second, third, fourth); + } + + @Nonnull + public static Quadro empty() { + return new Quadro<>(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java new file mode 100644 index 000000000..48c8dfcde --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -0,0 +1,123 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +public class Triple implements Pair { + + protected F first; + protected S second; + protected T third; + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + this.first = first; + this.second = second; + this.third = third; + } + + @Override + public final int amount() { + return 3; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + @Nonnull + @CheckReturnValue + public Triple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); + } + + public boolean noneNull() { + return first != null && second != null && third != null; + } + + public boolean allNull() { + return first == null && second == null && third == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Triple triple = (Triple) o; + return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third); + } + + @Override + public String toString() { + return "Triple[" + first + ", " + second + ", " + third + "]"; + } + + @Nonnull + public static Triple ofFirst(@Nullable F first) { + return of(first, null, null); + } + + @Nonnull + public static Triple ofSecond(@Nullable S second) { + return of(null, second, null); + } + + @Nonnull + public static Triple ofThird(@Nullable T third) { + return of(null, null, third); + } + + @Nonnull + public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { + return new Triple<>(first, second, third); + } + + @Nonnull + public static Triple empty() { + return new Triple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java new file mode 100644 index 000000000..9d320ba6e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -0,0 +1,106 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + */ +public class Tuple implements Pair { + + protected F first; + protected S second; + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + this.first = first; + this.second = second; + } + + @Override + public final int amount() { + return 2; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + @Nonnull + @CheckReturnValue + public Tuple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second)); + } + + public boolean noneNull() { + return first != null && second != null; + } + + public boolean allNull() { + return first == null && second == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Tuple tuple = (Tuple) o; + return Objects.equals(first, tuple.first) && Objects.equals(second, tuple.second); + } + + @Override + public int hashCode() { + return Objects.hash(first, second); + } + + @Override + public String toString() { + return "Tuple[" + first + ", " + second + "]"; + } + + @Nonnull + public static Tuple ofFirst(@Nullable F frist) { + return new Tuple<>(frist, null); + } + + @Nonnull + public static Tuple ofSecond(@Nullable S second) { + return new Tuple<>(null, second); + } + + @Nonnull + public static Tuple of(@Nullable F first, @Nullable S second) { + return new Tuple<>(first, second); + } + + @Nonnull + public static Tuple empty() { + return new Tuple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java new file mode 100644 index 000000000..87bf70c77 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java @@ -0,0 +1,118 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; + +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public class CleanAndWriteDatabaseCache implements DatabaseCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final Predicate check; + protected final Function query; + protected final Function fallback; + protected final BiConsumer writer; + protected final long unusedTimeBeforeClean; + protected final long cleanAndWriteInterval; + protected final ILogger logger; + + public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, + @Nonnull Predicate check, @Nonnull Function fallback, + @Nonnull Function query, @Nonnull BiConsumer writer) { + this.logger = logger; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + this.cleanAndWriteInterval = cleanAndWriteInterval; + this.check = check; + this.query = query; + this.fallback = fallback; + this.writer = writer; + + EXECUTOR.scheduleAtFixedRate(this::writeCache, cleanAndWriteInterval, cleanAndWriteInterval, TimeUnit.MILLISECONDS); + Runtime.getRuntime().addShutdownHook(new Thread(this::writeCache)); + } + + public void writeCache() { + if (logger != null ) logger.debug("Writing & Cleaning cache"); + cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); + } + + @Nonnull + @Override + public V getData(@Nonnull K key) { + Tuple cached = cache.get(key); + if (cached != null) { + cached.setFirst(System.currentTimeMillis()); + return cached.getSecond(); + } + + try { + V data = query.apply(key); + if (logger != null ) logger.trace("Queried data {} for {}", data, key); + cache.put(key, new Tuple<>(System.currentTimeMillis(), data)); + return data; + } catch (Exception ex) { + if (logger != null ) logger.error("Could not get data for {}", key, ex); + return fallback.apply(key); + } + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, + @Nonnull Predicate check, @Nonnull BiConsumer writer) { + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + try { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + + V value = pair.getSecond(); + if (!check.test(value)) return; + + if (logger != null ) logger.trace("Writing {}", value); + writer.accept(key, value); + } catch (Exception ex) { + if (logger != null ) logger.error("Unable to write cache for {}", key, ex); + } + }); + remove.forEach(cache::remove); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java new file mode 100644 index 000000000..6cf0779c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public class CleanWriteableCache implements WriteableCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final long cleanInterval; + protected final long unusedTimeBeforeClean; + + public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { + this.logger = logger; + this.cleanInterval = cleanInterval; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + + EXECUTOR.scheduleAtFixedRate(this::cleanCache, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS); + } + + public void cleanCache() { + if (logger != null ) logger.debug("Cleaning cache"); + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + @Nullable + @Override + public V getData(@Nonnull K key) { + Tuple pair = cache.get(key); + if (pair == null) return null; + pair.setFirst(System.currentTimeMillis()); + return pair.getSecond(); + } + + @Override + public void setData(@Nonnull K key, @Nullable V value) { + cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java new file mode 100644 index 000000000..1279ae1f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.collection.RunnableTimerTask; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Timer; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.ToLongFunction; + +public class CoolDownCache { + + protected final Map cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final ToLongFunction cooldownTime; + protected final long cleanInterval; + + public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { + this.logger = logger; + this.cooldownTime = cooldownTime; + this.cleanInterval = cleanInterval; + + new Timer(taskName).schedule(new RunnableTimerTask(this::cleanCache), cleanInterval, cleanInterval); + } + + public void cleanCache() { + logger.debug("Cleaning cooldown cache"); + + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, time) -> { + if (time == null || !isOnCoolDown(now, time, key)) { + logger.trace("Removing {} from cooldown cache", key); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { + long difference = now - suspect; + return difference < getCoolDownTime(key); + } + + public boolean isOnCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return false; + return isOnCoolDown(System.currentTimeMillis(), time, key); + } + + public boolean checkCoolDown(@Nonnull K key) { + boolean cooldown = isOnCoolDown(key); + if (!cooldown) setOnCoolDown(key); + return cooldown; + } + + public void setOnCoolDown(@Nonnull K key) { + cache.put(key, System.currentTimeMillis()); + } + + public long getCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return 0; + return System.currentTimeMillis() - time; + } + + public float getCoolDownSeconds(@Nonnull K key) { + return getCoolDown(key) / 1000f; + } + + public long getCoolDownTime(@Nonnull K key) { + return cooldownTime.applyAsLong(key); + } + + public int size() { + return cache.size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java new file mode 100644 index 000000000..5afc4e461 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; + +/** + * @deprecated Use {@link com.google.common.cache.LoadingCache} instead + * + * @see com.google.common.cache.LoadingCache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public interface DatabaseCache extends ICache { + + @Nonnull + V getData(@Nonnull K key); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java new file mode 100644 index 000000000..4a6b49f7f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.BiConsumer; + +/** + * @deprecated Use {@link com.google.common.cache.Cache} instead + * + * @see com.google.common.cache.Cache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface ICache { + + ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); + + boolean contains(@Nonnull K key); + + int size(); + + default boolean isEmpty() { + return size() == 0; + } + + void clear(); + + @Nonnull + Map values(); + + default void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java new file mode 100644 index 000000000..a2c887e25 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface WriteableCache extends ICache { + + @Nullable + V getData(@Nonnull K key); + + void setData(@Nonnull K key, @Nullable V value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java new file mode 100644 index 000000000..37b71703f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -0,0 +1,169 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletableTask implements Task { + + static final ExecutorService SERVICE = Executors.newCachedThreadPool(new NamedThreadFactory("TaskProcessor")); + + private final Collection> listeners = new ArrayList<>(); + private final CompletableFuture future; + + private Throwable failure; + + public CompletableTask() { + this(new CompletableFuture<>()); + } + + private CompletableTask(@Nonnull CompletableFuture future) { + this.future = future; + this.future.exceptionally(ex -> { + this.failure = ex; + return null; + }); + } + + @Nonnull + public static Task callAsync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + SERVICE.execute(() -> { + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + }); + return task; + } + + @Nonnull + public static Task callSync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + return task; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (future.isDone()) { + V value = future.getNow(null); + if (future.isCancelled() || value != null) { + listener.onCancelled(this); + } else if (failure != null) { + listener.onFailure(this, failure); + } else { + listener.onComplete(this, value); + } + return this; + } + + listeners.add(listener); + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + this.listeners.clear(); + return this; + } + + public void fail(Throwable throwable) { + this.failure = throwable; + this.future.completeExceptionally(throwable); + for (TaskListener listener : this.listeners) { + listener.onFailure(this, throwable); + } + } + + @Override + public V call() { + if (this.future.isDone()) { + return this.future.getNow(null); + } + throw new UnsupportedOperationException("Use #complete in the CompletableTask"); + } + + public void complete(@Nullable V value) { + future.complete(value); + if (value != null) { + for (TaskListener listener : listeners) { + listener.onComplete(this, value); + } + } else { + for (TaskListener listener : listeners) { + listener.onCancelled(this); + } + } + + } + + @Override + public boolean cancel(boolean b) { + if (this.future.isCancelled()) { + return false; + } + + if (this.future.cancel(b)) { + for (TaskListener listener : this.listeners) { + listener.onCancelled(this); + } + return true; + } + return false; + } + + @Override + public boolean isCancelled() { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() { + return this.future.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + CompletableTask task = new CompletableTask<>(); + this.future.thenAccept(v -> { + try { + task.complete(mapper == null ? null : mapper.apply(v)); + } catch (Throwable ex) { + task.fail(ex); + } + }); + this.onFailure(task.future::completeExceptionally); + this.onCancelled(otherTask -> task.cancel(true)); + return task; + } + + @Nonnull + @Override + public CompletionStage stage() { + return future; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java new file mode 100644 index 000000000..aed5684ba --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletedTask implements Task { + + private final V value; + private final Throwable failure; + + private CompletableFuture future; + + public CompletedTask(@Nullable V value) { + this.value = value; + this.failure = null; + } + + public CompletedTask(@Nullable Throwable failure) { + this.value = null; + this.failure = failure; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (failure != null) { + listener.onFailure(this, failure); + } else if (value != null) { + listener.onComplete(this, value); + } else { + listener.onCancelled(this); + } + + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + return this; + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + if (failure != null) + return new CompletedTask<>(failure); + + return new CompletedTask<>(value == null || mapper == null ? null : mapper.apply(value)); + } + + @Override + public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + if (value != null) + return value; + + return def; + } + + @Override + public V call() throws Exception { + return value; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return value; + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return value; + } + + @Nonnull + @Override + public CompletionStage stage() { + if (future == null) { + future = new CompletableFuture<>(); + + if (failure != null) { + future.completeExceptionally(failure); + } else { + future.complete(value); + } + } + + return future; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java new file mode 100644 index 000000000..8b43122ec --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java @@ -0,0 +1,228 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyFunction; +import net.codingarea.commons.common.function.ExceptionallyRunnable; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * A task that may complete (done / failed / cancelled) in the future or may already be done. + * + * For the completion can be listened by calling {@link #onComplete(Consumer)}, for the cancellation by {@link #onCancelled(Runnable)} and for failure by {@link #onFailure(Consumer)}. + * + * @see #asyncCall(Callable) + * @see #completed(Object) + */ +public interface Task extends Future, Callable { + + @Nonnull + static ExecutorService getAsyncExecutor() { + return CompletableTask.SERVICE; + } + + @Nonnull + static Task empty() { + return completed(null); + } + + @Nonnull + static Task completed(@Nullable V value) { + return new CompletedTask<>(value); + } + + @Nonnull + static Task completedVoid() { + return empty(); + } + + @Nonnull + static Task failed(@Nonnull Throwable failure) { + return new CompletedTask<>(failure); + } + + @Nonnull + static CompletableTask completable() { + return new CompletableTask<>(); + } + + @Nonnull + static Task asyncCall(@Nonnull Callable callable) { + return CompletableTask.callAsync(callable); + } + + @Nonnull + static Task asyncSupply(@Nonnull Supplier supplier) { + return asyncCall(supplier::get); + } + + @Nonnull + static Task asyncRun(@Nonnull Runnable runnable) { + return asyncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return asyncRun(runnable); + } + + @Nonnull + static Task syncCall(@Nonnull Callable callable) { + return CompletableTask.callSync(callable); + } + + @Nonnull + static Task syncSupply(@Nonnull Supplier supplier) { + return syncCall(supplier::get); + } + + @Nonnull + static Task syncRun(@Nonnull Runnable runnable) { + return syncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return syncRun(runnable); + } + + @Nonnull + default Task onComplete(@Nonnull Runnable action) { + return onComplete(v -> action.run()); + } + + @Nonnull + default Task onComplete(@Nonnull Consumer action) { + return onComplete((task, value) -> action.accept(value)); + } + + @Nonnull + default Task onComplete(@Nonnull BiConsumer, ? super V> action) { + return addListener(new TaskListener() { + @Override + public void onComplete(@Nonnull Task task, @Nonnull V value) { + action.accept(task, value); + } + }); + } + + @Nonnull + default Task onFailure(@Nonnull Runnable action) { + return onFailure(ex -> action.run()); + } + + @Nonnull + default Task onFailure(@Nonnull Consumer action) { + return onFailure((task, ex) -> action.accept(ex)); + } + + @Nonnull + default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { + return addListener(new TaskListener() { + @Override + public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + action.accept(task, ex); + } + }); + } + + @Nonnull + default Task throwOnFailure() { + return onFailure(ex -> ex.printStackTrace()); + } + + @Nonnull + default Task onCancelled(@Nonnull Runnable action) { + return onCancelled(task -> action.run()); + } + + @Nonnull + default Task onCancelled(@Nonnull Consumer> action) { + return addListener(new TaskListener() { + @Override + public void onCancelled(@Nonnull Task task) { + action.accept(task); + } + }); + } + + @Nonnull + default Task addListeners(@Nonnull TaskListener... listeners) { + for (TaskListener listener : listeners) + addListener(listener); + + return this; + } + + @Nonnull + Task addListener(@Nonnull TaskListener listener); + + @Nonnull + Task clearListeners(); + + @Override + V get() throws InterruptedException, ExecutionException; + + @Override + V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + + default V getOrDefault(V def) { + try { + return get(); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException ex) { + return def; + } + } + + default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + try { + return this.get(timeout, unit); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException | TimeoutException ex) { + return def; + } + } + + default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { + try { + return get(timeout, unit); + } catch (ExecutionException | InterruptedException ex) { + throw new WrappedException(ex); + } catch (TimeoutException ex) { + throw new IllegalStateException("Operation timed out (" + timeout + " " + unit + ")"); + } + } + + @Nonnull + Task map(@Nullable Function mapper); + + @Nonnull + default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { + return map(mapper); + } + + @Nonnull + default Task mapVoid() { + return map(v -> null); + } + + @Nonnull + default Task map(@Nonnull Class target) { + return map(target::cast); + } + + @Nonnull + @CheckReturnValue + CompletionStage stage(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java new file mode 100644 index 000000000..f800ae95a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; + +public interface TaskListener { + + default void onComplete(@Nonnull Task task, @Nonnull T value) { + } + + default void onCancelled(@Nonnull Task task) { + } + + default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java new file mode 100644 index 000000000..54462d54a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java @@ -0,0 +1,97 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.function.Consumer; + +/** + * @see Document + */ +public interface Config extends Propertyable { + + /** + * Sets the value at the given path. + * + * Setting a value to {@code null} has the same effect as {@link #remove(String) removing} it. + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @param value The value to change to, {@code null} to remove + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config set(@Nonnull String path, @Nullable Object value); + + /** + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config clear(); + + /** + * Removing a value has the same effect as {@link #set(String, Object) setting} it to {@code null} + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config remove(@Nonnull String path); + + boolean isReadonly(); + + /** + * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} + */ + @Nonnull + @CheckReturnValue + Config readonly(); + + @Nonnull + @Override + default Config apply(@Nonnull Consumer action) { + return (Config) Propertyable.super.apply(action); + } + + @Nonnull + @Override + default Config applyIf(boolean expression, @Nonnull Consumer action) { + return (Config) Propertyable.super.applyIf(expression, action); + } + + @Nonnull + default Config increment(@Nonnull String path, double amount) { + return set(path, getDouble(path) + amount); + } + + @Nonnull + default Config decrement(@Nonnull String path, double amount) { + return set(path, getDouble(path) - amount); + } + + @Nonnull + default Config multiply(@Nonnull String path, double factor) { + return set(path, getDouble(path) * factor); + } + + @Nonnull + default Config divide(@Nonnull String path, double divisor) { + return set(path, getDouble(path) / divisor); + } + + @Nonnull + default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + if (!contains(path)) + set(path, defaultValue); + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java new file mode 100644 index 000000000..17c4a0b4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -0,0 +1,345 @@ +package net.codingarea.commons.common.config; + +import com.google.gson.JsonArray; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +public interface Document extends Config, Json { + + /** + * Gets the document located at the given path. + * If there is no document assigned to this path, + * a new document is being created and assigned to this path. + * + * @return the document assigned to this path + */ + @Nonnull + Document getDocument(@Nonnull String path); + + /** + * Returns the list of documents located at the given path. + * The returned list will not contain any null elements. + * If there are no documents, the list will be empty. + * Elements which are no documents in the original list will be skipped. + * If an element is {@code null} an empty document will be added + * if this document is not {@link #isReadonly() readonly}. + * + * @return the list of documents assigned to this path + */ + @Nonnull + List getDocumentList(@Nonnull String path); + + @Nonnull + default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { + List documents = getDocumentList(path); + List result = new ArrayList<>(documents.size()); + for (Document document : documents) { + result.add(document.toInstanceOf(classOfT)); + } + return result; + } + + @Nonnull + List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + T getSerializable(@Nonnull String path, @Nonnull Class classOfT); + + @Nonnull + T getSerializable(@Nonnull String path, @Nonnull T def); + + @Nonnull + Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + R mapDocument(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + T toInstanceOf(@Nonnull Class classOfT); + + /** + * Returns the parent document of this document. + * If {@code this} is the {@link #getRoot() root} this method will return {@code null}. + * + * @return the parent document of this document + */ + @Nullable + Document getParent(); + + /** + * Returns the root document of this document. + * If the {@link #getParent() parent} is {@code null} this will return {@code this}. + * + * @return the root document of this document + */ + @Nonnull + Document getRoot(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document apply(@Nonnull Consumer action) { + return (Document) Config.super.apply(action); + } + + @Nonnull + @Override + default Document applyIf(boolean expression, @Nonnull Consumer action) { + return (Document) Config.super.applyIf(expression, action); + } + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (Document) Config.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + Document set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + @CheckReturnValue + Document readonly(); + + @Nonnull + Map children(); + + boolean isDocument(@Nonnull String path); + + boolean hasChildren(@Nonnull String path); + + void write(@Nonnull Writer writer) throws IOException; + + default void saveToFile(@Nonnull File file) throws IOException { + FileUtils.createFilesIfNecessary(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + default void saveToFile(@Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull File file) { + return (this instanceof FileDocument && ((FileDocument)this).getFile().equals(file)) + ? (FileDocument) this : FileDocument.wrap(this, file); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull Path file) { + return asFileDocument(file.toFile()); + } + + @Nonnull + @CheckReturnValue + default Document copyJson() { + Document document = create(); + this.forEach(document::set); + return document; + } + + /** + * @return an empty and immutable document + * + * @see EmptyDocument + */ + @Nonnull + @CheckReturnValue + static Document empty() { + return EmptyDocument.ROOT; + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + try { + if (file.exists()) { + Constructor constructor = classOfDocument.getConstructor(File.class); + return constructor.newInstance(file); + } else { + Constructor constructor = classOfDocument.getConstructor(); + return constructor.newInstance(); + } + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException ex) { + throw new UnsupportedOperationException(classOfDocument.getName() + " does not support File creation"); + } catch (InvocationTargetException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return readFile(classOfDocument, file.toFile()); + } + + /** + * @return a json document parsed by the input + * + * @see GsonDocument + */ + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull String jsonInput) { + return new GsonDocument(jsonInput); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull Reader reader) throws IOException { + return new GsonDocument(reader); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull InputStream input) throws IOException { + return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); + } + + @Nonnull + @CheckReturnValue + static List parseJsonArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + @Nonnull + @CheckReturnValue + static List parseStringArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); + (GsonDocument.isWritePrettyJson() ? GsonDocument.GSON_PRETTY_PRINT : GsonDocument.GSON).toJson(array, writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull Path file) { + return readJsonFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static List readJsonArrayFile(@Nonnull Path file) { + try { + JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + array.forEach(element -> documents.add(new GsonDocument(element.getAsJsonObject()))); + return documents; + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull Path file) { + return readPropertiesFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static Document create() { + return new GsonDocument(); + } + + @Nonnull + @CheckReturnValue + static Document of(@Nonnull Object object) { + return new GsonDocument(object); + } + + @Nullable + @CheckReturnValue + static Document ofNullable(@Nullable Object object) { + return object == null ? null : of(object); + } + + @Nonnull + @CheckReturnValue + static List arrayOf(@Nonnull Collection objects) { + List documents = new ArrayList<>(objects.size()); + objects.forEach(object -> documents.add(Document.of(object))); + return documents; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java new file mode 100644 index 000000000..b6d73f26b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java @@ -0,0 +1,172 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.function.Consumer; + +public interface FileDocument extends Document { + + /** + * Logger used to log errors which are caught in the safe version of an exceptionally method + */ + ILogger LOGGER = ILogger.forThisClass(); + + default void saveExceptionally() throws IOException { + saveToFile(getFile()); + } + + /** + * Executes {@link #saveExceptionally()} and prints all caught errors to {@link #LOGGER} + * + * @see #saveExceptionally() + */ + default void save() { + try { + saveExceptionally(); + } catch (IOException ex) { + LOGGER.error("Could not save config to file \"{}\"", getFile(), ex); + } + } + + @Nonnull + default Task saveAsync() { + return Task.asyncRunExceptionally(this::save); + } + + /** + * @param async whether this should be saved asynchronously or synchronously + * + * @see #save() + * @see #saveAsync() + */ + default void save(boolean async) { + if (async) saveAsync(); + else save(); + } + + @Nonnull + File getFile(); + + @Nonnull + Path getPath(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default FileDocument apply(@Nonnull Consumer action) { + return (FileDocument) Document.super.apply(action); + } + + @Nonnull + @Override + default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (FileDocument) Document.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + @Override + default FileDocument increment(@Nonnull String path, double amount) { + return (FileDocument) Document.super.increment(path, amount); + } + + @Nonnull + @Override + default FileDocument decrement(@Nonnull String path, double amount) { + return (FileDocument) Document.super.decrement(path, amount); + } + + @Nonnull + @Override + default FileDocument multiply(@Nonnull String path, double factor) { + return (FileDocument) Document.super.multiply(path, factor); + } + + @Nonnull + @Override + default FileDocument divide(@Nonnull String path, double divisor) { + return (FileDocument) Document.super.divide(path, divisor); + } + + @Nonnull + @CheckReturnValue + static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { + return new FileDocumentWrapper(file, document); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull Path file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull Path file) { + return readFile(PropertiesDocument.class, file); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java new file mode 100644 index 000000000..efcfb495c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java @@ -0,0 +1,48 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Supplier; + +/** + * @see Document + */ +public interface Json { + + @Nonnull + String toJson(); + + @Nonnull + String toPrettyJson(); + + @Nonnull + @CheckReturnValue + static Json empty() { + return constant("{}", "{}"); + } + + @Nonnull + @CheckReturnValue + static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { + return new Json() { + @Nonnull + @Override + public String toJson() { + return normal.get(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return pretty.get(); + } + }; + } + + @Nonnull + @CheckReturnValue + static Json constant(@Nonnull String json, @Nonnull String prettyJson) { + return supply(() -> json, () -> prettyJson); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java new file mode 100644 index 000000000..bab183bc2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.Nullable; +import java.awt.*; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +public final class PropertyHelper { + + private PropertyHelper() {} + + private static final Map> getters = new HashMap<>(); + + static { + getters.put(Character.class, Propertyable::getChar); + getters.put(Boolean.class, Propertyable::getBoolean); + getters.put(Byte.class, Propertyable::getByte); + getters.put(Short.class, Propertyable::getShort); + getters.put(Integer.class, Propertyable::getInt); + getters.put(Long.class, Propertyable::getLong); + getters.put(Float.class, Propertyable::getFloat); + getters.put(Double.class, Propertyable::getDouble); + getters.put(String.class, Propertyable::getString); + getters.put(CharSequence.class, Propertyable::getString); + getters.put(List.class, Propertyable::getStringList); + getters.put(Document.class, (BiFunction) Document::getDocument); + getters.put(String[].class, Propertyable::getStringArray); + getters.put(Date.class, Propertyable::getDate); + getters.put(OffsetDateTime.class, Propertyable::getDateTime); + getters.put(Color.class, Propertyable::getColor); + getters.put(byte[].class, Propertyable::getBinary); + } + + @Nullable + public static Date parseDate(@Nullable String string) { + try { + return DateFormat.getDateTimeInstance().parse(string); + } catch (Exception ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java new file mode 100644 index 000000000..1149b7be1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java @@ -0,0 +1,199 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * @see Document + * @see Config + */ +public interface Propertyable { + + T getInstance(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + Object getObject(@Nonnull String path); + + @Nonnull + Object getObject(@Nonnull String path, @Nonnull Object def); + + @Nonnull + @SuppressWarnings("unchecked") + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.ofNullable(extractor.apply((O) this, key)); + } + + @Nonnull + @SuppressWarnings("unchecked") + default Propertyable apply(@Nonnull Consumer action) { + action.accept((O) this); + return this; + } + + @Nonnull + default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { + if (expression) + apply(action); + return this; + } + + @Nullable + String getString(@Nonnull String path); + + @Nonnull + String getString(@Nonnull String path, @Nonnull String def); + + @Nullable + byte[] getBinary(@Nonnull String path); + + char getChar(@Nonnull String path); + + char getChar(@Nonnull String path, char def); + + long getLong(@Nonnull String path); + + long getLong(@Nonnull String path, long def); + + int getInt(@Nonnull String path); + + int getInt(@Nonnull String path, int def); + + short getShort(@Nonnull String path); + + short getShort(@Nonnull String path, short def); + + byte getByte(@Nonnull String path); + + byte getByte(@Nonnull String path, byte def); + + float getFloat(@Nonnull String path); + + float getFloat(@Nonnull String path, float def); + + double getDouble(@Nonnull String path); + + double getDouble(@Nonnull String path, double def); + + boolean getBoolean(@Nonnull String path); + + boolean getBoolean(@Nonnull String path, boolean def); + + @Nonnull + List getStringList(@Nonnull String path); + + @Nonnull + String[] getStringArray(@Nonnull String path); + + @Nonnull + > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + List getUUIDList(@Nonnull String path); + + @Nonnull + List getCharacterList(@Nonnull String path); + + @Nonnull + List getByteList(@Nonnull String path); + + @Nonnull + List getShortList(@Nonnull String path); + + @Nonnull + List getIntegerList(@Nonnull String path); + + @Nonnull + List getLongList(@Nonnull String path); + + @Nonnull + List getFloatList(@Nonnull String path); + + @Nonnull + List getDoubleList(@Nonnull String path); + + @Nullable + UUID getUUID(@Nonnull String path); + + @Nonnull + UUID getUUID(@Nonnull String path, @Nonnull UUID def); + + @Nullable + OffsetDateTime getDateTime(@Nonnull String path); + + @Nonnull + OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); + + @Nullable + Date getDate(@Nonnull String path); + + @Nonnull + Date getDate(@Nonnull String path, @Nonnull Date def); + + @Nullable + Color getColor(@Nonnull String path); + + @Nonnull + Color getColor(@Nonnull String path, @Nonnull Color def); + + @Nullable + > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + > E getEnum(@Nonnull String path, @Nonnull E def); + + @Nullable + Class getClass(@Nonnull String path); + + @Nonnull + Class getClass(@Nonnull String path, @Nonnull Class def); + + @Nullable + Version getVersion(@Nonnull String path); + + @Nonnull + Version getVersion(@Nonnull String path, @Nonnull Version def); + + boolean isList(@Nonnull String path); + + boolean isObject(@Nonnull String path); + + boolean contains(@Nonnull String path); + + boolean isEmpty(); + + @Nonnegative + int size(); + + @Nonnull + Map values(); + + @Nonnull + Map valuesAsStrings(); + + @Nonnull + Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + List mapList(@Nonnull String path, @Nonnull Function mapper); + + @Nonnull + Collection keys(); + + @Nonnull + Set> entrySet(); + + void forEach(@Nonnull BiConsumer action); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java new file mode 100644 index 000000000..cce0be2e8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -0,0 +1,278 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Config; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.function.Supplier; + +public abstract class AbstractConfig implements Config { + + protected static final ILogger logger = ILogger.forThisClass(); + + @Nonnull + protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { + T value = getter.get(); + return value == null ? def : value; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = getObject(path); + return value == null ? def : value; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return getDef(def, () -> getString(path)); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | IndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return getDouble(path, 0); + } + + @Override + public float getFloat(@Nonnull String path) { + return getFloat(path, 0); + } + + @Override + public long getLong(@Nonnull String path) { + return getLong(path, 0); + } + + @Override + public int getInt(@Nonnull String path) { + return getInt(path, 0); + } + + @Override + public short getShort(@Nonnull String path) { + return getShort(path, (short) 0); + } + + @Override + public byte getByte(@Nonnull String path) { + return getByte(path, (byte) 0); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return getBoolean(path, false); + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getDef(def, () -> getUUID(path)); + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getDef(def, () -> getDateTime(path)); + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return getDef(def, () -> getDate(path)); + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return getDef(def, () -> getColor(path)); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + E value = getEnum(path, def.getDeclaringClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + try { + return Class.forName(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return getDef(def, () -> getClass(path)); + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return Version.parse(getString(path), null); + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getDef(def, () -> getVersion(path)); + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + String string = getString(path); + if (string == null) return null; + return Base64.getDecoder().decode(string); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return getStringList(path).toArray(new String[0]); + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return mapList(path, UUID::fromString); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return mapList(path, Byte::parseByte); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return mapList(path, Short::parseShort); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return mapList(path, Integer::parseInt); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return mapList(path, Long::parseLong); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return mapList(path, Float::parseFloat); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return mapList(path, Double::parseDouble); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + List list = getStringList(path); + List result = new ArrayList<>(list.size()); + for (String string : list) { + try { + result.add(mapper.apply(string)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'", string, ex); + } + } + return result; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Nonnull + @Override + public Map valuesAsStrings() { + Map map = new HashMap<>(); + values().forEach((key, value) -> map.put(key, String.valueOf(value))); + return map; + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(valuesAsStrings(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public Set> entrySet() { + return values().entrySet(); + } + + @Nonnull + public Map map(@Nonnull Map values, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + values.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'='{}'", key, value, ex); + } + }); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java new file mode 100644 index 000000000..6f13c5f75 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java @@ -0,0 +1,162 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.readonly.ReadOnlyDocumentWrapper; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class AbstractDocument extends AbstractConfig implements Document { + + protected final Document root, parent; + + public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public AbstractDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + T value = getSerializable(path, (Class) def.getClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + if (!contains(path)) return null; + return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getDocumentList(path).stream() + .map(Document::values) + .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) + .collect(Collectors.toList()); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(children(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + Document document = getDocument(path); + return mapper.apply(document); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + if (!contains(path)) return null; + return mapDocument(path, mapper); + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + Document document = getDocument0(path, root, this); + return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + if (value instanceof byte[]) + value = Base64.getEncoder().encodeToString((byte[]) value); + + set0(path, value); + return this; + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + Document.of(object).forEach(this::set); + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + if (isReadonly()) throw new ConfigReadOnlyException("remove"); + remove0(path); + return this; + } + + @Nonnull + @Override + public Document clear() { + if (isReadonly()) throw new ConfigReadOnlyException("clear"); + clear0(); + return this; + } + + @Nonnull + @CheckReturnValue + public Document readonly() { + return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); + } + + @Nonnull + protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); + + protected abstract void set0(@Nonnull String path, @Nullable Object value); + + protected abstract void remove0(@Nonnull String path); + + protected abstract void clear0(); + + @Nonnull + @Override + public Map children() { + Map map = new HashMap<>(); + keys().forEach(key -> { + if (!isDocument(key)) return; + map.put(key, getDocument(key)); + }); + return map; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return !getDocument(path).isEmpty(); + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java new file mode 100644 index 000000000..21deb8ae5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java @@ -0,0 +1,518 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class EmptyDocument implements Document { + + public static final EmptyDocument ROOT = new EmptyDocument(); + + protected final Document root, parent; + + public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public EmptyDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + return new EmptyDocument(); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return mapper.apply(Document.empty()); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return null; + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document set(@Nonnull Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document clear() { + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + return this; + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); + } + + @Override + public void saveToFile(@Nonnull File file) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.save(File)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + return def; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + throw new UnsupportedOperationException(); + } + + @Nonnull + @Override + public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.empty(); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return def; + } + + @Override + public char getChar(@Nonnull String path) { + return 0; + } + + @Override + public char getChar(@Nonnull String path, char def) { + return def; + } + + @Override + public long getLong(@Nonnull String path) { + return 0; + } + + @Override + public long getLong(@Nonnull String path, long def) { + return def; + } + + @Override + public int getInt(@Nonnull String path) { + return 0; + } + + @Override + public int getInt(@Nonnull String path, int def) { + return def; + } + + @Override + public short getShort(@Nonnull String path) { + return 0; + } + + @Override + public short getShort(@Nonnull String path, short def) { + return def; + } + + @Override + public byte getByte(@Nonnull String path) { + return 0; + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return def; + } + + @Override + public float getFloat(@Nonnull String path) { + return 0; + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return def; + } + + @Override + public double getDouble(@Nonnull String path) { + return 0; + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return def; + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return false; + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return def; + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return new String[0]; + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return def; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return def; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return def; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return def; + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return null; + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + return def; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + return def; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return def; + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return def; + } + + @Override + public boolean contains(@Nonnull String path) { + return false; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return false; + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return false; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return 0; + } + + @Nonnull + @Override + public Map values() { + return Collections.emptyMap(); + } + + @Nonnull + @Override + public Map valuesAsStrings() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map children() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Collection keys() { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + } + + @Nonnull + @Override + public String toJson() { + return "{}"; + } + + @Nonnull + @Override + public String toPrettyJson() { + return "{}"; + } + + @Nonnull + @Override + public String toString() { + return "{}"; + } + + @Override + public boolean isReadonly() { + return true; + } + + @Nonnull + @Override + public Document readonly() { + return this; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java new file mode 100644 index 000000000..50262eaf0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -0,0 +1,508 @@ +package net.codingarea.commons.common.config.document; + +import com.google.gson.*; +import com.google.gson.internal.LazilyParsedNumber; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.gson.*; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class GsonDocument extends AbstractDocument { + + static { + GsonBuilder builder = new GsonBuilder() + .disableHtmlEscaping() + .registerTypeAdapterFactory(GsonTypeAdapter.newPredictableFactory(BukkitReflectionSerializationUtils::isSerializable, new BukkitReflectionSerializableTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Document.class, new DocumentTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Pair.class, new PairTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Class.class, new ClassTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Color.class, new ColorTypeAdapter())) + ; + + GSON = builder.create(); + GSON_PRETTY_PRINT = builder.setPrettyPrinting().create(); + } + + // Not implemented in some versions of gson + TypeAdapter NUMBER = new TypeAdapter() { + @Override + public void write(JsonWriter out, Number value) throws IOException { + out.value(value); + } + @Override + public Number read(JsonReader in) throws IOException { + JsonToken jsonToken = in.peek(); + switch (jsonToken) { + case NUMBER: + case STRING: + return new LazilyParsedNumber(in.nextString()); + case BOOLEAN: + default: + throw new JsonSyntaxException("Expecting number, got: " + jsonToken); + case NULL: + in.nextNull(); + return null; + } + } + }; + + public static final Gson GSON, GSON_PRETTY_PRINT; + + private static boolean cleanupEmptyObjects = false; + private static boolean cleanupEmptyArrays = false; + private static boolean writePrettyJson = true; + + public static void setCleanupEmptyArrays(boolean clean) { + cleanupEmptyArrays = clean; + } + + public static void setCleanupEmptyObjects(boolean clean) { + cleanupEmptyObjects = clean; + } + + public static void setWritePrettyJson(boolean pretty) { + writePrettyJson = pretty; + } + + public static boolean isWritePrettyJson() { + return writePrettyJson; + } + + @Nonnull + public static List convertArrayToDocuments(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(new GsonDocument(element.getAsJsonObject())); + } + return list; + } + + @Nonnull + public static List convertArrayToStrings(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(element.getAsString()); + } + return list; + } + + protected JsonObject jsonObject; + + public GsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public GsonDocument(@Nonnull Reader reader) throws IOException { + this(new BufferedReader(reader)); + } + + public GsonDocument(@Nonnull BufferedReader reader) throws IOException { + this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); + } + + public GsonDocument(@Nonnull String json) { + this(GSON.fromJson(json, JsonObject.class)); + } + + public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { + this(GSON.fromJson(json, JsonObject.class), root, parent); + } + + public GsonDocument(@Nullable JsonObject jsonObject) { + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nonnull Map values) { + this(); + GsonUtils.setDocumentProperties(GSON, jsonObject, values); + } + + public GsonDocument() { + this(new JsonObject()); + } + + public GsonDocument(@Nonnull Object object) { + this(GSON.toJsonTree(object).getAsJsonObject()); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.convertJsonElementToString(element); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.unpackJsonElement(element); + } + + @Nullable + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { + JsonElement element = getElement(path).orElse(null); + return GSON.fromJson(element, classOfType); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + if (isEmpty()) return null; + return GSON.fromJson(jsonObject, classOfT); + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getInstance(path, classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + JsonElement element = getElement(path).orElse(null); + if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); + return new GsonDocument(element.getAsJsonObject(), root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(new JsonArray()); + if (element.isJsonNull()) return new ArrayList<>(); + JsonArray array = element.getAsJsonArray(); + List documents = new ArrayList<>(array.size()); + for (JsonElement current : array) { + if (current == null || current.isJsonNull()) documents.add(new GsonDocument((JsonObject) null, root, this)); + else if (current.isJsonObject()) documents.add(new GsonDocument(current.getAsJsonObject(), root, this)); + } + return documents; + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + if (element == null || element.isJsonNull()) return new ArrayList<>(); + if (element.isJsonPrimitive()) return new ArrayList<>(Collections.singletonList(GsonUtils.convertJsonElementToString(element))); + if (element.isJsonObject()) throw new IllegalStateException("Cannot extract list out of json object at '" + path + "'"); + return GsonUtils.convertJsonArrayToStringList(element.getAsJsonArray()); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return getInstance(path, UUID.class); + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return getInstance(path, Date.class); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return getInstance(path, OffsetDateTime.class); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return getInstance(path, Color.class); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getInstance(path, classOfEnum); + } + + @Override + public boolean isList(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonArray); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonObject); + } + + @Override + public boolean isObject(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonPrimitive); + } + + private boolean checkElement(@Nonnull String path, @Nonnull Function check) { + return getElement(path).map(check).orElse(false); + } + + @Override + public boolean contains(@Nonnull String path) { + return getElement(path).isPresent(); + } + + @Override + public int size() { + return GsonUtils.getSize(jsonObject); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + setElement(path, value); + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); + for (Entry entry : json.entrySet()) { + jsonObject.add(entry.getKey(), entry.getValue()); + } + return this; + } + + @Override + public void clear0() { + jsonObject = new JsonObject(); + } + + @Override + public void remove0(@Nonnull String path) { + setElement(path, null); + } + + @Nonnull + @Override + public Map values() { + return GsonUtils.convertJsonObjectToMap(jsonObject); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Nonnull + @Override + public Collection keys() { + Collection keys = new ArrayList<>(size()); + for (Entry entry : jsonObject.entrySet()) { + keys.add(entry.getKey()); + } + return keys; + } + + @Nonnull + private Optional getPrimitive(@Nonnull String path) { + return getElement(path) + .filter(JsonPrimitive.class::isInstance) + .map(JsonPrimitive.class::cast); + } + + @Nonnull + private Optional getElement(@Nonnull String path) { + return getElement(path, jsonObject); + } + + @Nonnull + private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { + + JsonElement fullPathElement = object.get(path); + if (fullPathElement != null) return Optional.of(fullPathElement); + + int index = path.indexOf('.'); + if (index == -1) return Optional.empty(); + + String child = path.substring(0, index); + String newPath = path.substring(index + 1); + + JsonElement element = object.get(child); + if (element == null || element.isJsonNull()) return Optional.empty(); + + return getElement(newPath, element.getAsJsonObject()); + + } + + private void setElement(@Nonnull String path, @Nullable Object value) { + + LinkedList paths = determinePath(path); + JsonObject object = jsonObject; + + for (int i = 0; i < paths.size() - 1; i++) { + + String current = paths.get(i); + JsonElement element = object.get(current); + if (element == null || element.isJsonNull()) { + if (value == null) return; // There's noting to remove + object.add(current, element = new JsonObject()); + } + + if (!element.isJsonObject()) throw new IllegalArgumentException("Cannot replace '" + current + "' on '" + path + "'; It's not an object (" + element.getClass().getName() + ")"); + object = element.getAsJsonObject(); + + } + + String lastPath = paths.getLast(); + JsonElement jsonValue = + value instanceof JsonElement ? (JsonElement) value + : value == null ? JsonNull.INSTANCE + : value instanceof Number ? NUMBER.toJsonTree((Number) value) + : value instanceof Boolean ? TypeAdapters.BOOLEAN.toJsonTree((boolean) value) + : value instanceof Character ? TypeAdapters.CHARACTER.toJsonTree((char) value) + : GSON.toJsonTree(value); + object.add(lastPath, jsonValue); + + } + + @Nonnull + private LinkedList determinePath(@Nonnull String path) { + + LinkedList paths = new LinkedList<>(); + String pathCopy = path; + int index; + while ((index = pathCopy.indexOf('.')) != -1) { + String child = pathCopy.substring(0, index); + pathCopy = pathCopy.substring(index + 1); + paths.add(child); + } + paths.add(pathCopy); + + return paths; + + } + + @Nonnull + @Override + public String toJson() { + return GSON.toJson(jsonObject); + } + + @Nonnull + @Override + public String toPrettyJson() { + return GSON_PRETTY_PRINT.toJson(jsonObject); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GsonDocument that = (GsonDocument) o; + return jsonObject.equals(that.jsonObject); + } + + @Override + public int hashCode() { + return jsonObject.hashCode(); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + cleanup(); + (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); + } + + @Nonnull + public JsonObject getJsonObject() { + return jsonObject; + } + + @Override + public boolean isReadonly() { + return false; + } + + public void cleanup() { + cleanup(jsonObject); + } + + public static void cleanup(@Nonnull JsonObject jsonObject) { + Iterator> iterator = jsonObject.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + JsonElement value = entry.getValue(); + if (value.isJsonObject()) cleanup(value.getAsJsonObject()); +// if (cleanupNulls && value.isJsonNull()) iterator.remove(); + if (cleanupEmptyObjects && value.isJsonObject() && GsonUtils.getSize(value.getAsJsonObject()) == 0) iterator.remove(); + if (cleanupEmptyArrays && value.isJsonArray() && value.getAsJsonArray().size() == 0) iterator.remove(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java new file mode 100644 index 000000000..b0b194d05 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -0,0 +1,292 @@ +package net.codingarea.commons.common.config.document; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonArray; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +/** + * This class is not thread safe. + * Documents of this type are not able to be saved or loaded. + */ +public class MapDocument extends AbstractDocument { + + private final Map values; + + public MapDocument(@Nonnull Map values) { + Preconditions.checkNotNull(values, "Map cannot be null"); + this.values = values; + } + + public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.values = values; + } + + public MapDocument() { + this(new LinkedHashMap<>()); + } + + @Override + public boolean isReadonly() { + return false; + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); + if (value instanceof Map) return new MapDocument((Map) value, root, parent); + if (value instanceof Document) return (Document) value; + if (value instanceof String) return new GsonDocument((String) value, root, parent); + throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List documents = new ArrayList<>(); + Object value = values.get(path); + if (value instanceof List) { + List list = (List) value; + for (Object object : list) { + if (object instanceof Map) documents.add(new MapDocument((Map) object, root, parent)); + if (object instanceof Document) documents.add((Document) object); + if (object instanceof String) documents.add(new GsonDocument((String) object, root, this)); + } + } + return documents; + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + values.put(path, value); + } + + @Override + public void clear0() { + values.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + values.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + new GsonDocument(values).write(writer); + } + + @Nonnull + @Override + public String toJson() { + return new GsonDocument(values).toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return new GsonDocument(values).toPrettyJson(); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return values.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = values.get(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + if (!contains(path)) return def; + switch (getString(path).toLowerCase()) { + case "true": + case "1": + return true; + default: + return false; + } + } catch (Exception ex) { + return def; + } + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + Object object = getObject(path); + if (object == null) return Collections.emptyList(); + if (object instanceof Iterable) return StreamSupport.stream(((Iterable)object).spliterator(), false).map(String::valueOf).collect(Collectors.toList()); + if (object instanceof String) return GsonUtils.convertJsonArrayToStringList(GsonDocument.GSON.fromJson((String) object, JsonArray.class)); + throw new IllegalStateException("Cannot convert " + object.getClass() + " to a list"); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object object = getObject(path); + if (object instanceof UUID) return (UUID) object; + return UUID.fromString(String.valueOf(object)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof String) return PropertyHelper.parseDate((String) object); + if (object instanceof Date) return (Date) object; + return null; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); + if (object instanceof OffsetDateTime) return (OffsetDateTime) object; + return null; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof Color) return (Color) object; + if (object instanceof String) return Color.decode((String) object); + return null; + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Map || value instanceof Document; + } + + @Override + public boolean contains(@Nonnull String path) { + return values.containsKey(path); + } + + @Override + public int size() { + return values.size(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(values); + } + + @Nonnull + @Override + public Collection keys() { + return values.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values.forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java new file mode 100644 index 000000000..58fa7b100 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -0,0 +1,285 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.collection.Colors; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.PropertiesUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; + +/** + * This document only supports basic objects like {@link Number numbers}, {@link String strings}, {@link Character characters} and {@link Boolean booleans}. + * You may use more advanced documents which are fully supported like {@link GsonDocument} + */ +public class PropertiesDocument extends AbstractDocument { + + protected final Properties properties; + + public PropertiesDocument(@Nullable Properties properties) { + this.properties = properties == null ? new Properties() : properties; + } + + public PropertiesDocument(@Nonnull File file) throws IOException { + properties = new Properties(); + properties.load(FileUtils.newBufferedReader(file)); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return properties.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return properties.getProperty(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + if (!contains(path)) return def; + return Boolean.parseBoolean(getString(path)); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return PropertyHelper.parseDate(getString(path)); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + String string = getString(path); + return string == null ? null : Color.decode(string); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean contains(@Nonnull String path) { + return properties.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return true; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return properties.size(); + } + + @Nonnull + @Override + public Map values() { + Map map = new LinkedHashMap<>(); + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + return map; + } + + @Nonnull + @Override + public Collection keys() { + return properties.stringPropertyNames(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + final String asString; + if (value instanceof Color) { + asString = Colors.asHex((Color) value); + } else { + asString = String.valueOf(value); + } + + properties.setProperty(path, asString); + } + + @Override + public void clear0() { + properties.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + properties.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + properties.store(writer, null); + } + + @Nonnull + public Properties getProperties() { + return properties; + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Nonnull + @Override + public Document copyJson() { + Map map = new HashMap<>(); + PropertiesUtils.setProperties(properties, map); + return new GsonDocument(map); + } + + @Override + public boolean isReadonly() { + return false; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java new file mode 100644 index 000000000..03bdf14d3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -0,0 +1,355 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.file.YamlConstructor; +import org.bukkit.configuration.file.YamlRepresenter; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.representer.Representer; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class YamlDocument extends AbstractDocument { + + protected final ConfigurationSection config; + + public YamlDocument() { + this.config = new YamlConfiguration(); + } + + public YamlDocument(@Nonnull ConfigurationSection config) { + this.config = config; + } + + public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.config = config; + } + + public YamlDocument(@Nonnull File file) { + this(YamlConfiguration.loadConfiguration(file)); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return config.getString(path); + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + String string = config.getString(path, def); + return string == null ? def : string; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return config.get(path); + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = config.get(path, def); + return value == null ? def : value; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + ConfigurationSection section = config.getConfigurationSection(path); + if (section == null) section = config.createSection(path); + return new YamlDocument(section, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List> maps = config.getMapList(path); + List documents = new ArrayList<>(maps.size()); + for (Map map : maps) { + documents.add(new MapDocument((Map) map, root, this)); + } + return documents; + } + + @Override + public long getLong(@Nonnull String path) { + return config.getLong(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return config.getLong(path, def); + } + + @Override + public int getInt(@Nonnull String path) { + return config.getInt(path); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return config.getInt(path, def); + } + + @Override + public short getShort(@Nonnull String path) { + return (short) config.getInt(path); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return (short) config.getInt(path, def); + } + + @Override + public byte getByte(@Nonnull String path) { + return (byte) config.getInt(path); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return (byte) config.getInt(path, def); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | StringIndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return config.getDouble(path); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return config.getDouble(path, def); + } + + @Override + public float getFloat(@Nonnull String path) { + return (float) config.getDouble(path); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return (float) config.getDouble(path, def); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return config.getBoolean(path); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return config.getBoolean(path, def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return config.getStringList(path); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + try { + return DateFormat.getDateTimeInstance().parse(path); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + try { + return Color.decode(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean isList(@Nonnull String path) { + return config.isList(path); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return config.get(path) instanceof ConfigurationSection; + } + + @Override + public boolean contains(@Nonnull String path) { + return config.contains(path, true); + } + + @Override + public int size() { + return config.getValues(false).size(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + if (value instanceof Enum) { + Enum enun = (Enum) value; + value = enun.name(); + } + config.set(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + config.set(path, null); + } + + @Override + public void clear0() { + for (String key : config.getKeys(true)) { + config.set(key, null); + } + } + + @Nonnull + @Override + public Map values() { + return config.getValues(true); + } + + @Nonnull + @Override + public Collection keys() { + return config.getKeys(false); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public String toString() { + + DumperOptions yamlOptions = new DumperOptions(); + LoaderOptions loaderOptions = new LoaderOptions(); + Representer yamlRepresenter = new YamlRepresenter(); + Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions, loaderOptions); + + yamlOptions.setIndent(2); + yamlOptions.setDefaultFlowStyle(FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(FlowStyle.BLOCK); + String dump = yaml.dump(config.getValues(false)); + if (dump.equals("{}\n")) { + dump = ""; + } + + return dump; + + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + writer.write(toString()); + } + + @Nonnull + @Override + public Document copyJson() { + return new GsonDocument(values()); + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java new file mode 100644 index 000000000..ed36fd787 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -0,0 +1,60 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.Map; +import java.util.Optional; + +public class BukkitReflectionSerializableTypeAdapter implements GsonTypeAdapter { + + public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { + + Map map = BukkitReflectionSerializationUtils.serializeObject(object); + if (map == null) return; + + JsonObject json = new JsonObject(); + json.addProperty(KEY, BukkitReflectionSerializationUtils.getSerializationName(object.getClass())); + GsonUtils.setDocumentProperties(gson, json, map); + TypeAdapters.JSON_ELEMENT.write(writer, json); + + } + + @Override + public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + + JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); + if (element == null || !element.isJsonObject()) return null; + + JsonObject json = element.getAsJsonObject(); + String classOfType = Optional.ofNullable(findClassContainer(json)).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString).orElse(null); + + Class clazz = null; + try { + clazz = Class.forName(classOfType); + } catch (ClassNotFoundException | NullPointerException ex) { + } + + Map map = GsonUtils.convertJsonObjectToMap(json); + return BukkitReflectionSerializationUtils.deserializeObject(map, clazz); + + } + + private JsonElement findClassContainer(@Nonnull JsonObject json) { + if (json.has(ALTERNATE_KEY)) + return json.get(ALTERNATE_KEY); + return json.get(KEY); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java new file mode 100644 index 000000000..3b85bbd16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class ClassTypeAdapter implements GsonTypeAdapter> { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { + TypeAdapters.STRING.write(writer, object.getName()); + } + + @Override + public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + try { + + String value = reader.nextString(); + if (value == null) return null; + + return Class.forName(value); + + } catch (ClassNotFoundException ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java new file mode 100644 index 000000000..6a172a83f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.Colors; + +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.IOException; + +public class ColorTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { + TypeAdapters.STRING.write(writer, Colors.asHex(color)); + } + + @Override + public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + String value = TypeAdapters.STRING.read(reader); + if (value == null) return null; + return Color.decode(value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java new file mode 100644 index 000000000..fffa43204 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java @@ -0,0 +1,46 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class DocumentTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { + if (document instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) document; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + Document copiedDocument = document.copyJson(); + if (copiedDocument instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) copiedDocument; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + GsonDocument gsonDocument = new GsonDocument(document.values()); + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + + } + + @Override + public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); + if (jsonElement != null && jsonElement.isJsonObject()) { + return new GsonDocument(jsonElement.getAsJsonObject()); + } else { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java new file mode 100644 index 000000000..e8f72f78b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.function.Predicate; + +@SuppressWarnings("unchecked") +public interface GsonTypeAdapter { + + void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; + + T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; + + default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { + return new TypeAdapter() { + @Override + public void write(JsonWriter writer, T object) throws IOException { + if (object == null) { + writer.nullValue(); + return; + } + GsonTypeAdapter.this.write(gson, writer, object); + } + + @Override + public T read(JsonReader reader) throws IOException { + return GsonTypeAdapter.this.read(gson, reader); + } + }; + } + + @Nonnull + static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken token) { + Class requestedType = token.getRawType(); + if (!clazz.isAssignableFrom(requestedType)) return null; + + return (TypeAdapter) adapter.toTypeAdapter(gson); + } + }; + } + + @Nonnull + static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + return predicate.test(type.getRawType()) ? (TypeAdapter) adapter.toTypeAdapter(gson) : null; + } + }; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java new file mode 100644 index 000000000..6b4b393d0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.collection.pair.Quadro; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.collection.pair.Tuple; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class PairTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { + Object[] values = object.values(); + JsonArray array = new JsonArray(values.length); + for (Object value : values) { + array.add(gson.toJsonTree(value)); + } + } + + @Override + public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonArray array = gson.fromJson(reader, JsonArray.class); + int size = array.size(); + switch (size) { + case 2: return Tuple.of(array.get(0), array.get(1)); + case 3: return Triple.of(array.get(0), array.get(1), array.get(2)); + case 4: return Quadro.of(array.get(0), array.get(1), array.get(2), array.get(3)); + default:throw new IllegalStateException("No Pair known for amount of " + size); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java new file mode 100644 index 000000000..4267a567c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.common.config.document.readonly; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.wrapper.WrappedDocument; + +import javax.annotation.Nonnull; + +public final class ReadOnlyDocumentWrapper implements WrappedDocument { + + private final Document document; + + public ReadOnlyDocumentWrapper(@Nonnull Document document) { + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java new file mode 100644 index 000000000..4cbb0a0f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.wrapper; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.nio.file.Path; + +public class FileDocumentWrapper implements WrappedDocument, FileDocument { + + protected final Document document; + protected final File file; + + public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { + this.file = file; + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Nonnull + @Override + public File getFile() { + return file; + } + + @Nonnull + @Override + public Path getPath() { + return file.toPath(); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull String path, @Nullable Object value) { + return WrappedDocument.super.set(path, value); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull Object value) { + return WrappedDocument.super.set(value); + } + + @Nonnull + @Override + public FileDocument clear() { + return WrappedDocument.super.clear(); + } + + @Nonnull + @Override + public FileDocument remove(@Nonnull String path) { + return WrappedDocument.super.remove(path); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java new file mode 100644 index 000000000..989c393e4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java @@ -0,0 +1,510 @@ +package net.codingarea.commons.common.config.document.wrapper; + + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public interface WrappedDocument extends Document { + + Document getWrappedDocument(); + + @Override + default boolean isReadonly() { + return getWrappedDocument().isReadonly(); + } + + @Nonnull + @Override + default Document getDocument(@Nonnull String path) { + return getWrappedDocument().getDocument(path); + } + + @Nonnull + @Override + default List getDocumentList(@Nonnull String path) { + return getWrappedDocument().getDocumentList(path); + } + + @Nonnull + @Override + default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializableList(path, classOfT); + } + + @Nonnull + @Override + default D set(@Nonnull String path, @Nullable Object value) { + getWrappedDocument().set(path, value); + return self(); + } + + @Nonnull + @Override + default D set(@Nonnull Object value) { + getWrappedDocument().set(value); + return self(); + } + + @Nonnull + @Override + default D clear() { + getWrappedDocument().clear(); + return self(); + } + + @Nonnull + @Override + default D remove(@Nonnull String path) { + getWrappedDocument().remove(path); + return self(); + } + + @Override + default void write(@Nonnull Writer writer) throws IOException { + getWrappedDocument().write(writer); + } + + @Override + default void saveToFile(@Nonnull File file) throws IOException { + getWrappedDocument().saveToFile(file); + } + + @Nonnull + @Override + default String toJson() { + return getWrappedDocument().toJson(); + } + + @Nonnull + @Override + default String toPrettyJson() { + return getWrappedDocument().toPrettyJson(); + } + + @Override + default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getInstance(path, classOfT); + } + + @Override + default T toInstanceOf(@Nonnull Class classOfT) { + return getWrappedDocument().toInstanceOf(classOfT); + } + + @Nullable + @Override + default Object getObject(@Nonnull String path) { + return getWrappedDocument().getObject(path); + } + + @Nonnull + @Override + default Object getObject(@Nonnull String path, @Nonnull Object def) { + return getWrappedDocument().getObject(path, def); + } + + @Nonnull + @Override + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return getWrappedDocument().getOptional(key, extractor); + } + + @Nullable + @Override + default String getString(@Nonnull String path) { + return getWrappedDocument().getString(path); + } + + @Nonnull + @Override + default String getString(@Nonnull String path, @Nonnull String def) { + return getWrappedDocument().getString(path, def); + } + + @Override + default char getChar(@Nonnull String path) { + return getWrappedDocument().getChar(path); + } + + @Override + default char getChar(@Nonnull String path, char def) { + return getWrappedDocument().getChar(path, def); + } + + @Override + default long getLong(@Nonnull String path) { + return getWrappedDocument().getLong(path); + } + + @Override + default long getLong(@Nonnull String path, long def) { + return getWrappedDocument().getLong(path, def); + } + + @Override + default int getInt(@Nonnull String path) { + return getWrappedDocument().getInt(path); + } + + @Override + default int getInt(@Nonnull String path, int def) { + return getWrappedDocument().getInt(path, def); + } + + @Override + default short getShort(@Nonnull String path) { + return getWrappedDocument().getShort(path); + } + + @Override + default short getShort(@Nonnull String path, short def) { + return getWrappedDocument().getShort(path, def); + } + + @Override + default byte getByte(@Nonnull String path) { + return getWrappedDocument().getByte(path); + } + + @Override + default byte getByte(@Nonnull String path, byte def) { + return getWrappedDocument().getByte(path, def); + } + + @Override + default float getFloat(@Nonnull String path) { + return getWrappedDocument().getFloat(path); + } + + @Override + default float getFloat(@Nonnull String path, float def) { + return getWrappedDocument().getFloat(path, def); + } + + @Override + default double getDouble(@Nonnull String path) { + return getWrappedDocument().getDouble(path); + } + + @Override + default double getDouble(@Nonnull String path, double def) { + return getWrappedDocument().getDouble(path, def); + } + + @Override + default boolean getBoolean(@Nonnull String path) { + return getWrappedDocument().getBoolean(path); + } + + @Override + default boolean getBoolean(@Nonnull String path, boolean def) { + return getWrappedDocument().getBoolean(path, def); + } + + @Nonnull + @Override + default List getStringList(@Nonnull String path) { + return getWrappedDocument().getStringList(path); + } + + @Nonnull + @Override + default String[] getStringArray(@Nonnull String path) { + return getWrappedDocument().getStringArray(path); + } + + @Nonnull + @Override + default List mapList(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapList(path, mapper); + } + + @Nonnull + @Override + default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnumList(path, classOfEnum); + } + + @Nonnull + @Override + default List getUUIDList(@Nonnull String path) { + return getWrappedDocument().getUUIDList(path); + } + + @Nonnull + @Override + default List getCharacterList(@Nonnull String path) { + return getWrappedDocument().getCharacterList(path); + } + + @Nonnull + @Override + default List getByteList(@Nonnull String path) { + return getWrappedDocument().getByteList(path); + } + + @Nonnull + @Override + default List getShortList(@Nonnull String path) { + return getWrappedDocument().getShortList(path); + } + + @Nonnull + @Override + default List getIntegerList(@Nonnull String path) { + return getWrappedDocument().getIntegerList(path); + } + + @Nonnull + @Override + default List getLongList(@Nonnull String path) { + return getWrappedDocument().getLongList(path); + } + + @Nonnull + @Override + default List getFloatList(@Nonnull String path) { + return getWrappedDocument().getFloatList(path); + } + + @Nonnull + @Override + default List getDoubleList(@Nonnull String path) { + return getWrappedDocument().getDoubleList(path); + } + + @Nullable + @Override + default UUID getUUID(@Nonnull String path) { + return getWrappedDocument().getUUID(path); + } + + @Nonnull + @Override + default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getWrappedDocument().getUUID(path, def); + } + + @Nullable + @Override + default Date getDate(@Nonnull String path) { + return getWrappedDocument().getDate(path); + } + + @Nonnull + @Override + default Date getDate(@Nonnull String path, @Nonnull Date def) { + return getWrappedDocument().getDate(path, def); + } + + @Nullable + @Override + default OffsetDateTime getDateTime(@Nonnull String path) { + return getWrappedDocument().getDateTime(path); + } + + @Nonnull + @Override + default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getWrappedDocument().getDateTime(path, def); + } + + @Nullable + @Override + default Color getColor(@Nonnull String path) { + return getWrappedDocument().getColor(path); + } + + @Nonnull + @Override + default Color getColor(@Nonnull String path, @Nonnull Color def) { + return getWrappedDocument().getColor(path, def); + } + + @Nullable + @Override + default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnum(path, classOfEnum); + } + + @Nonnull + @Override + default > E getEnum(@Nonnull String path, @Nonnull E def) { + return getWrappedDocument().getEnum(path, def); + } + + @Nullable + @Override + default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializable(path, classOfT); + } + + @Nonnull + @Override + default T getSerializable(@Nonnull String path, @Nonnull T def) { + return getWrappedDocument().getSerializable(path, def); + } + + @Nullable + @Override + default Class getClass(@Nonnull String path) { + return getWrappedDocument().getClass(path); + } + + @Nonnull + @Override + default Class getClass(@Nonnull String path, @Nonnull Class def) { + return getWrappedDocument().getClass(path, def); + } + + @Nullable + @Override + default Version getVersion(@Nonnull String path) { + return getWrappedDocument().getVersion(path); + } + + @Nonnull + @Override + default Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getWrappedDocument().getVersion(path, def); + } + + @Nullable + @Override + default byte[] getBinary(@Nonnull String path) { + return getWrappedDocument().getBinary(path); + } + + @Override + default boolean contains(@Nonnull String path) { + return getWrappedDocument().contains(path); + } + + @Override + default boolean hasChildren(@Nonnull String path) { + return getWrappedDocument().hasChildren(path); + } + + @Override + default boolean isObject(@Nonnull String path) { + return getWrappedDocument().isObject(path); + } + + @Override + default boolean isList(@Nonnull String path) { + return getWrappedDocument().isList(path); + } + + @Override + default boolean isDocument(@Nonnull String path) { + return getWrappedDocument().isDocument(path); + } + + @Override + default boolean isEmpty() { + return getWrappedDocument().isEmpty(); + } + + @Override + default int size() { + return getWrappedDocument().size(); + } + + @Nonnull + @Override + default Map values() { + return getWrappedDocument().values(); + } + + @Nonnull + @Override + default Map valuesAsStrings() { + return getWrappedDocument().valuesAsStrings(); + } + + @Nonnull + @Override + default Map children() { + return getWrappedDocument().children(); + } + + @Nonnull + @Override + default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapValues(keyMapper, valueMapper); + } + + @Nonnull + @Override + default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapDocuments(keyMapper, valueMapper); + } + + @Nonnull + @Override + default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocument(path, mapper); + } + + @Nullable + @Override + default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocumentNullable(path, mapper); + } + + @Nonnull + @Override + default Collection keys() { + return getWrappedDocument().keys(); + } + + @Nonnull + @Override + default Set> entrySet() { + return getWrappedDocument().entrySet(); + } + + @Override + default void forEach(@Nonnull BiConsumer action) { + getWrappedDocument().forEach(action); + } + + @Nonnull + @Override + default Document readonly() { + return getWrappedDocument().readonly(); + } + + @Nullable + @Override + default Document getParent() { + return getWrappedDocument().getParent(); + } + + @Nonnull + @Override + default Document getRoot() { + return getWrappedDocument().getRoot(); + } + + @SuppressWarnings("unchecked") + default D self() { + return (D) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java new file mode 100644 index 000000000..7fa62c991 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.common.config.exceptions; + +import javax.annotation.Nonnull; + +public final class ConfigReadOnlyException extends IllegalStateException { + + public ConfigReadOnlyException(@Nonnull String action) { + super("Config." + action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java new file mode 100644 index 000000000..2af90f2c1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.common.debug; + +import net.codingarea.commons.common.collection.NumberFormatter; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class TimingsHelper { + + public static final ILogger LOGGER = ILogger.forThisClass(); + private static final Map timings = new ConcurrentHashMap<>(); + + private TimingsHelper() {} + + public static void start(@Nonnull String id) { + timings.put(id, System.currentTimeMillis()); + } + + public static void stop(@Nonnull String id) { + Long start = timings.remove(id); + if (start == null) { + LOGGER.warn("Stopped timing {} which was not started before", id); + return; + } + + long time = System.currentTimeMillis() - start; + LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); + } + + public static void restart(@Nonnull String id) { + stop(id); + start(id); + } + + public static void start() { + start(ReflectionUtils.getCallerName()); + } + + public static void stop() { + stop(ReflectionUtils.getCallerName()); + } + + public static void restart() { + restart(ReflectionUtils.getCallerName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java new file mode 100644 index 000000000..49eeec955 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -0,0 +1,498 @@ +package net.codingarea.commons.common.discord; + +import net.codingarea.commons.common.config.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.HttpsURLConnection; +import java.awt.*; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +public class DiscordWebhook { + + protected String url; + protected String content; + protected String username; + protected String avatarUrl; + protected boolean tts; + protected List embeds = new ArrayList<>(); + + private DiscordWebhook() { + } + + /** + * Constructs a new DiscordWebhook instance + * + * @param url The webhook URL obtained in Discord + */ + public DiscordWebhook(@Nonnull String url) { + this.url = url; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username) { + this.url = url; + this.username = username; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + this.content = content; + this.embeds = embeds; + this.tts = tts; + } + + @Nonnull + public DiscordWebhook setUrl(@Nonnull String url) { + this.url = url; + return this; + } + + @Nonnull + public DiscordWebhook setContent(@Nullable String content) { + this.content = content; + return this; + } + + @Nonnull + public DiscordWebhook setUsername(@Nullable String username) { + this.username = username; + return this; + } + + @Nonnull + public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { + this.avatarUrl = avatarUrl; + return this; + } + + @Nonnull + public DiscordWebhook setTts(boolean tts) { + this.tts = tts; + return this; + } + + @Nonnull + public DiscordWebhook addEmbed(EmbedObject embed) { + this.embeds.add(embed); + return this; + } + + public void execute() throws IOException { + if (content == null && embeds.isEmpty()) + throw new IllegalArgumentException("Set content or add at least one EmbedObject"); + + Document json = Document.create(); + + json.set("content", content); + json.set("username", username); + json.set("avatar_url", avatarUrl); + json.set("tts", tts); + + if (!embeds.isEmpty()) { + List embedObjects = new ArrayList<>(); + + for (EmbedObject embed : embeds) { + Document jsonEmbed = Document.create(); + + jsonEmbed.set("title", embed.getTitle()); + jsonEmbed.set("description", embed.getDescription()); + jsonEmbed.set("url", embed.getUrl()); + + if (embed.getColor() != null) { + Color color = embed.getColor(); + int rgb = color.getRed(); + rgb = (rgb << 8) + color.getGreen(); + rgb = (rgb << 8) + color.getBlue(); + + jsonEmbed.set("color", rgb); + } + + EmbedObject.Footer footer = embed.getFooter(); + EmbedObject.Image image = embed.getImage(); + EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); + EmbedObject.Author author = embed.getAuthor(); + List fields = embed.getFields(); + + if (footer != null) { + Document jsonFooter =Document.create(); + + jsonFooter.set("text", footer.getText()); + jsonFooter.set("icon_url", footer.getIconUrl()); + jsonEmbed.set("footer", jsonFooter); + } + + if (image != null) { + Document jsonImage = Document.create(); + + jsonImage.set("url", image.getUrl()); + jsonEmbed.set("image", jsonImage); + } + + if (thumbnail != null) { + Document jsonThumbnail = Document.create(); + + jsonThumbnail.set("url", thumbnail.getUrl()); + jsonEmbed.set("thumbnail", jsonThumbnail); + } + + if (author != null) { + Document jsonAuthor = Document.create(); + + jsonAuthor.set("name", author.getName()); + jsonAuthor.set("url", author.getUrl()); + jsonAuthor.set("icon_url", author.getIconUrl()); + jsonEmbed.set("author", jsonAuthor); + } + + List jsonFields = new ArrayList<>(); + for (EmbedObject.Field field : fields) { + Document jsonField = Document.create(); + + jsonField.set("name", field.getName()); + jsonField.set("value", field.getValue()); + jsonField.set("inline", field.isInline()); + + jsonFields.add(jsonField); + } + + jsonEmbed.set("fields", jsonFields.toArray()); + embedObjects.add(jsonEmbed); + } + + json.set("embeds", embedObjects.toArray()); + } + + URL url = new URL(this.url); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setConnectTimeout(2500); + connection.setReadTimeout(1000); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + connection.setRequestProperty("Accept", "*/*"); + connection.setRequestProperty("Content-Type", "application/json"); + + OutputStream output = connection.getOutputStream(); + output.write(json.toString().getBytes(StandardCharsets.UTF_8)); + output.flush(); + output.close(); + + connection.getInputStream().close(); + connection.disconnect(); + } + + @Nonnull + public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { + if (content != null) content = content.replace(trigger, replacement); + if (username != null) username = username.replace(trigger, replacement); + for (EmbedObject embed : embeds) { + if (embed.author.name != null) embed.author.name = embed.author.name.replace(trigger, replacement); + if (embed.description != null) embed.description = embed.description.replace(trigger, replacement); + if (embed.title != null) embed.title = embed.title.replace(trigger, replacement); + if (embed.footer.text != null) embed.footer.text = embed.footer.text.replace(trigger, replacement); + for (EmbedObject.Field field : embed.fields) { + if (field.name != null) field.name = field.name.replace(trigger, replacement); + if (field.value != null) field.value = field.value.replace(trigger, replacement); + } + } + return this; + } + + public static class EmbedObject { + + protected String title; + protected String description; + protected String url; + protected Color color; + + protected Footer footer; + protected Thumbnail thumbnail; + protected Image image; + protected Author author; + protected List fields = new ArrayList<>(); + + public EmbedObject() { + } + + public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, + @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, + @Nonnull List fields) { + this.title = title; + this.description = description; + this.url = url; + this.color = color; + this.footer = footer; + this.thumbnail = thumbnail; + this.image = image; + this.author = author; + this.fields = fields; + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull + public EmbedObject setTitle(String title) { + this.title = title; + return this; + } + + @Nonnull + public EmbedObject setDescription(String description) { + this.description = description; + return this; + } + + @Nonnull + public EmbedObject setUrl(String url) { + this.url = url; + return this; + } + + @Nonnull + public EmbedObject setColor(Color color) { + this.color = color; + return this; + } + + @Nonnull + public EmbedObject setFooter(String text, String icon) { + this.footer = new Footer(text, icon); + return this; + } + + @Nonnull + public EmbedObject setThumbnail(String url) { + this.thumbnail = new Thumbnail(url); + return this; + } + + @Nonnull + public EmbedObject setImage(String url) { + this.image = new Image(url); + return this; + } + + @Nonnull + public EmbedObject setAuthor(String name, String url, String icon) { + this.author = new Author(name, url, icon); + return this; + } + + @Nonnull + public EmbedObject addField(String name, String value, boolean inline) { + this.fields.add(new Field(name, value, inline)); + return this; + } + + @Override + public EmbedObject clone() { + return new EmbedObject( + title, description, url, color, + footer == null ? null : footer.clone(), + thumbnail == null ? null : thumbnail.clone(), + image == null ? null : image.clone(), + author == null ? null : author.clone(), + DiscordWebhook.clone(fields, Field::clone) + ); + } + + public static class Footer { + + protected String text; + protected String iconUrl; + + private Footer() { + } + + public Footer(String text, String iconUrl) { + this.text = text; + this.iconUrl = iconUrl; + } + + private String getText() { + return text; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Footer clone() { + return new Footer(text, iconUrl); + } + } + + public static class Thumbnail { + + private String url; + + private Thumbnail() { + } + + public Thumbnail(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + protected Thumbnail clone() { + return new Thumbnail(url); + } + } + + public static class Image { + + private String url; + + private Image() { + } + + public Image(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + public Image clone() { + return new Image(url); + } + } + + public static class Author { + + private String name; + private String url; + private String iconUrl; + + private Author() { + } + + public Author(String name, String url, String iconUrl) { + this.name = name; + this.url = url; + this.iconUrl = iconUrl; + } + + private String getName() { + return name; + } + + private String getUrl() { + return url; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Author clone() { + return new Author(name, url, iconUrl); + } + } + + public static class Field { + + private String name; + private String value; + private boolean inline; + + private Field() { + } + + private Field(String name, String value, boolean inline) { + this.name = name; + this.value = value; + this.inline = inline; + } + + private String getName() { + return name; + } + + private String getValue() { + return value; + } + + private boolean isInline() { + return inline; + } + + @Override + protected Field clone() { + return new Field(name, value, inline); + } + } + } + + @Override + public DiscordWebhook clone() { + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + } + + @Nonnull + protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { + List list = new ArrayList<>(collection.size()); + for (T current : collection) { + list.add(cloner.apply(current)); + } + return list; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java new file mode 100644 index 000000000..5bca8f733 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiConsumer; + +@FunctionalInterface +public interface ExceptionallyBiConsumer extends BiConsumer { + + @Override + default void accept(T t, U u) { + try { + acceptExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java new file mode 100644 index 000000000..6977e1ea6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiFunction; + +@FunctionalInterface +public interface ExceptionallyBiFunction extends BiFunction { + + @Override + default R apply(T t, U u) { + try { + return applyExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java new file mode 100644 index 000000000..99f90b68d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.Consumer; + +@FunctionalInterface +public interface ExceptionallyConsumer extends Consumer { + + @Override + default void accept(T t) { + try { + acceptExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java new file mode 100644 index 000000000..007c6d3e7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.DoubleFunction; + +@FunctionalInterface +public interface ExceptionallyDoubleFunction extends DoubleFunction { + + @Override + default R apply(double value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(double value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java new file mode 100644 index 000000000..182afce47 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Function; + +@FunctionalInterface +public interface ExceptionallyFunction extends Function { + + @Override + default R apply(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t) throws Exception; + + @Nonnull + @CheckReturnValue + static ExceptionallyFunction identity() { + return t -> t; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java new file mode 100644 index 000000000..c15637c63 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.IntFunction; + +@FunctionalInterface +public interface ExceptionallyIntFunction extends IntFunction { + + @Override + default R apply(int value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(int value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java new file mode 100644 index 000000000..e3cd46a66 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.LongFunction; + +@FunctionalInterface +public interface ExceptionallyLongFunction extends LongFunction { + + @Override + default R apply(long value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(long value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java new file mode 100644 index 000000000..b15ce02c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; + +@FunctionalInterface +public interface ExceptionallyRunnable extends Runnable, Callable { + + @Override + default void run() { + try { + runExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default Void call() throws Exception { + runExceptionally(); + return null; + } + + void runExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java new file mode 100644 index 000000000..5aab4b750 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +@FunctionalInterface +public interface ExceptionallySupplier extends Supplier, Callable { + + @Override + default T get() { + try { + return getExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default T call() throws Exception { + return getExceptionally(); + } + + T getExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java new file mode 100644 index 000000000..759fd6f38 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToDoubleFunction; + +@FunctionalInterface +public interface ExceptionallyToDoubleFunction extends ToDoubleFunction { + + @Override + default double applyAsDouble(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + double applyExceptionally(T T) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java new file mode 100644 index 000000000..98e5520e9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToIntFunction; + +@FunctionalInterface +public interface ExceptionallyToIntFunction extends ToIntFunction { + + @Override + default int applyAsInt(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + int applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java new file mode 100644 index 000000000..6ace6ef31 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToLongFunction; + +@FunctionalInterface +public interface ExceptionallyToLongFunction extends ToLongFunction { + + @Override + default long applyAsLong(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + long applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java new file mode 100644 index 000000000..02ec550a7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -0,0 +1,282 @@ +package net.codingarea.commons.common.logging; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.internal.FallbackLogger; +import net.codingarea.commons.common.logging.internal.JavaLoggerWrapper; +import net.codingarea.commons.common.logging.internal.SimpleLogger; +import net.codingarea.commons.common.logging.internal.Slf4jLoggerWrapper; +import net.codingarea.commons.common.logging.internal.factory.ConstantLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.DefaultLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.Slf4jLoggerFactory; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.slf4j.LoggerFactory; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ServiceLoader; + +public interface ILogger { + + final class Holder { + + private static ILoggerFactory factory; + private static Data data; + + private static class Data { + private boolean slf4j, slf4jApi; + } + + @Nonnull + private static Data getData() { + if (data == null) + createData(); + + return data; + } + + private static synchronized void createData() { + boolean slf4j = false; + boolean slf4jApi = true; + + try { + Class.forName("org.slf4j.impl.StaticLoggerBinder"); + slf4j = true; + } catch (ClassNotFoundException eStatic) { // there was no static logger binder (SLF4J pre-1.8.x) + try { + Class serviceProviderInterface = Class.forName("org.slf4j.spi.SLF4JServiceProvider"); + // check if there is a service implementation for the service, indicating a provider for SLF4J 1.8.x+ is installed + slf4j = ServiceLoader.load(serviceProviderInterface).iterator().hasNext(); + } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) + try { + // prints warning of missing implementation + LoggerFactory.getLogger(ILogger.class); + } catch (NoClassDefFoundError eApi) { + slf4jApi = false; + } + } + } + + data = new Data(); + data.slf4j = slf4j; + data.slf4jApi = slf4jApi; + } + + @Nonnull + public static ILoggerFactory getFactory() { + if (factory == null) + factory = getFallbackFactory(); + + return factory; + } + + @Nonnull + private static ILoggerFactory getFallbackFactory() { + return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : + isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : + new DefaultLoggerFactory(FallbackLogger::new); + } + + private Holder() {} + + } + + static boolean isSlf4jImplAvailable() { + return Holder.getData().slf4j; + } + + static boolean isSlf4jApiAvailable() { + return Holder.getData().slf4jApi; + } + + @Nonnull + @CheckReturnValue + static ILogger forName(@Nullable String name) { + return getFactory().forName(name); + } + + @Nonnull + @CheckReturnValue + static ILogger forClass(@Nullable Class clazz) { + return forName(clazz == null ? null : clazz.getSimpleName()); + } + + @Nonnull + @CheckReturnValue + static ILogger forClassOf(@Nonnull Object object) { + return forClass(object.getClass()); + } + + @Nonnull + @CheckReturnValue + static ILogger forThisClass() { + return forClass(ReflectionUtils.getCaller()); + } + + @Nonnull + @CheckReturnValue + static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { + return new JavaLoggerWrapper(logger); + } + + @Nonnull + @CheckReturnValue + static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { + return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); + } + + static void setFactory(@Nonnull ILoggerFactory factory) { + Preconditions.checkNotNull(factory); + Holder.factory = factory; + } + + static void setConstantFactory(@Nonnull ILogger logger) { + setFactory(new ConstantLoggerFactory(logger)); + } + + @Nonnull + static ILoggerFactory getFactory() { + return Holder.getFactory(); + } + + void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); + + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + default void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void extended(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void trace(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return level.isShownAtLoggerLevel(getMinLevel()); + } + + default boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + default boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + default boolean isExtendedEnabled() { + return isLevelEnabled(LogLevel.EXTENDED); + } + + default boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + default boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + default boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Nonnull + LogLevel getMinLevel(); + + @Nonnull + ILogger setMinLevel(@Nonnull LogLevel level); + + @Nonnull + @CheckReturnValue + default Slf4jILogger slf4j() { + if (this instanceof Slf4jILogger) + return (Slf4jILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); + } + + @Nonnull + @CheckReturnValue + default JavaILogger java() { + if (this instanceof JavaILogger) + return (JavaILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); + } + + @Nonnull + @CheckReturnValue + default PrintStream asPrintStream(@Nonnull LogLevel level) { + try { + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { + StringBuilder message = new StringBuilder(String.valueOf(messageObject)); + for (Object arg : args) { + if (arg instanceof Throwable) continue; + int index = message.indexOf("{}"); + if (index == -1) break; + message.replace(index, index+2, String.valueOf(arg)); + } + return message.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java new file mode 100644 index 000000000..fed7742e6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java @@ -0,0 +1,15 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface ILoggerFactory { + + @Nonnull + @CheckReturnValue + ILogger forName(@Nullable String name); + + void setDefaultLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java new file mode 100644 index 000000000..ddf6d01c8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.util.logging.Level; + +public enum LogLevel { + + TRACE (0, "TRACE", "trace", Level.FINEST, false), + DEBUG (2, "DEBUG", "debug", Level.FINER, false), + EXTENDED(5, "EXTENDED", "extended", Level.FINE, false), + STATUS (7, "STATUS", "status", Level.CONFIG, false), + INFO (10, "INFO", "info", Level.INFO, false), + WARN (15, "WARN", "warn", Level.WARNING, true), + ERROR (25, "ERROR", "error", Level.SEVERE, true); + + private final String uppercaseName, lowercaseName; + private final Level javaLevel; + private final int value; + private final boolean highlighted; + + LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { + this.uppercaseName = uppercaseName; + this.lowercaseName = lowercaseName; + this.javaLevel = javaLevel; + this.value = value; + this.highlighted = highlighted; + } + + @Nonnull + public Level getJavaUtilLevel() { + return javaLevel; + } + + public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { + return this.getValue() >= loggerLevel.getValue(); + } + + public int getValue() { + return value; + } + + @Nonnull + public String getLowerCaseName() { + return lowercaseName; + } + + @Nonnull + public String getUpperCaseName() { + return uppercaseName; + } + + public boolean isHighlighted() { + return highlighted; + } + + @Nonnull + public static LogLevel fromJavaLevel(@Nonnull Level level) { + for (LogLevel logLevel : values()) { + if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) + return logLevel; + } + return INFO; + } + + @Nonnull + public static LogLevel fromValue(int value) { + for (LogLevel level : values()) { + if (level.getValue() == value) + return level; + } + return INFO; + } + + @Nonnull + public static LogLevel fromName(@Nonnull String name) { + for (LogLevel level : values()) { + if (level.getUpperCaseName().equalsIgnoreCase(name)) + return level; + } + return INFO; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java new file mode 100644 index 000000000..7095492ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public class LogOutputStream extends ByteArrayOutputStream { + + private final ILogger logger; + private final LogLevel level; + + public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { + this.logger = logger; + this.level = level; + } + + @Override + public void flush() throws IOException { + String input = this.toString(StandardCharsets.UTF_8.name()); + this.reset(); + + if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { + logger.log(level, input); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java new file mode 100644 index 000000000..06deb942a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface LoggingApiUser { + + @Nonnull + ILogger getTargetLogger(); + + default void error(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().error(message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().warn(message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().info(message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().status(message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().extended(message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().debug(message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().trace(message, args); + } + + default boolean isTraceEnabled() { + return getTargetLogger().isTraceEnabled(); + } + + default boolean isDebugEnabled() { + return getTargetLogger().isDebugEnabled(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java new file mode 100644 index 000000000..c4731eead --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java @@ -0,0 +1,159 @@ +package net.codingarea.commons.common.logging; + +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; + +public interface WrappedILogger extends ILogger { + + @Nonnull + ILogger getWrappedLogger(); + + @Override + default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void error(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void error(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void warn(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void warn(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void info(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void info(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void status(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void status(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void extended(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void extended(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void debug(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void debug(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void trace(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default void trace(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return getWrappedLogger().isLevelEnabled(level); + } + + @Override + default boolean isTraceEnabled() { + return getWrappedLogger().isTraceEnabled(); + } + + @Override + default boolean isDebugEnabled() { + return getWrappedLogger().isDebugEnabled(); + } + + @Override + default boolean isExtendedEnabled() { + return getWrappedLogger().isExtendedEnabled(); + } + + @Override + default boolean isInfoEnabled() { + return getWrappedLogger().isInfoEnabled(); + } + + @Override + default boolean isWarnEnabled() { + return getWrappedLogger().isWarnEnabled(); + } + + @Override + default boolean isErrorEnabled() { + return getWrappedLogger().isErrorEnabled(); + } + + @Nonnull + @Override + default LogLevel getMinLevel() { + return getWrappedLogger().getMinLevel(); + } + + @Nonnull + @Override + default ILogger setMinLevel(@Nonnull LogLevel level) { + return getWrappedLogger().setMinLevel(level); + } + + @Nonnull + @Override + default Slf4jILogger slf4j() { + return getWrappedLogger().slf4j(); + } + + @Nonnull + @Override + default JavaILogger java() { + return getWrappedLogger().java(); + } + + @Nonnull + @Override + default PrintStream asPrintStream(@Nonnull LogLevel level) { + return getWrappedLogger().asPrintStream(level); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java new file mode 100644 index 000000000..e19b07015 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java @@ -0,0 +1,23 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public class HandledAsyncLogger extends HandledLogger { + + protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); + + public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + executor.execute(() -> logNow(entry)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java new file mode 100644 index 000000000..cde16aac4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CopyOnWriteArrayList; + +public abstract class HandledLogger implements ILogger { + + protected final Collection handlers = new CopyOnWriteArrayList<>(); + protected LogLevel level; + + public HandledLogger(@Nonnull LogLevel initialLevel) { + this.level = initialLevel; + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!level.isShownAtLoggerLevel(this.level)) return; + Throwable exception = null; + for (Object arg : args) { + if (arg instanceof Throwable) + exception = (Throwable) arg; + } + log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); + } + + public void log(@Nonnull LogEntry entry) { + if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; + log0(entry); + } + + protected abstract void log0(@Nonnull LogEntry entry); + + protected void logNow(@Nonnull LogEntry entry) { + for (LogHandler handler : handlers) { + try { + handler.handle(entry); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @Nonnull + public HandledLogger addHandler(@Nonnull LogHandler... handler) { + handlers.addAll(Arrays.asList(handler)); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java new file mode 100644 index 000000000..0a62ac68b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; + +public class HandledSyncLogger extends HandledLogger { + + public HandledSyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + logNow(entry); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java new file mode 100644 index 000000000..5068d301b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; + +public class LogEntry { + + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; + + public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { + this.timestamp = timestamp; + this.threadName = threadName; + this.message = message; + this.level = level; + this.exception = exception; + } + + @Nonnull + public Instant getTimestamp() { + return timestamp; + } + + @Nonnull + public String getThreadName() { + return threadName; + } + + @Nonnull + public String getMessage() { + return message; + } + + @Nonnull + public LogLevel getLevel() { + return level; + } + + @Nullable + public Throwable getException() { + return exception; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java new file mode 100644 index 000000000..36141fed5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.logging.handler; + +import javax.annotation.Nonnull; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +public interface LogHandler { + + DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); + + void handle(@Nonnull LogEntry entry) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java new file mode 100644 index 000000000..711a8ab54 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal; + +import javax.annotation.Nonnull; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Because you can't change the level of a plugin logger properly, we create a wrapper for the plugin logger + * and map all levels below {@link Level#INFO} to {@link Level#INFO}, if they are loggable. + */ +public class BukkitLoggerWrapper extends JavaLoggerWrapper { + + public BukkitLoggerWrapper(@Nonnull Logger logger) { + super(logger); + } + + @Nonnull + @Override + protected Level mapLevel(@Nonnull Level level) { + if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) + return Level.INFO; + return level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java new file mode 100644 index 000000000..4a5e83e9c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +public class FallbackLogger implements ILogger { + + protected final PrintStream stream = System.err; + protected final String name; + + protected LogLevel level = LogLevel.INFO; + + public FallbackLogger(@Nullable String name) { + this.name = name; + } + + public FallbackLogger() { + this(null); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!isLevelEnabled(level)) return; + stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); + for (Object arg : args) { + if (!(arg instanceof Throwable)) continue; + ((Throwable)arg).printStackTrace(stream); + } + } + + @Nonnull + @Override + public FallbackLogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @CheckReturnValue + public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { + Thread thread = Thread.currentThread(); + String threadName = thread.getName(); + String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + return name == null ? + String.format("[%s: %s/%s]: %s", time, threadName, level.getUpperCaseName(), message) : + String.format("[%s: %s/%s] %s: %s", time, threadName, level.getUpperCaseName(), name, message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java new file mode 100644 index 000000000..f0c64bf8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -0,0 +1,666 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.JavaILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ResourceBundle; +import java.util.function.Supplier; +import java.util.logging.*; + +public class JavaLoggerWrapper extends JavaILogger { + + protected final Logger logger; + + public JavaLoggerWrapper(@Nonnull Logger logger) { + super(null, null); + this.logger = logger; + } + + @Override + public boolean getUseParentHandlers() { + return logger.getUseParentHandlers(); + } + + @Override + public Filter getFilter() { + return logger.getFilter(); + } + + @Override + public Handler[] getHandlers() { + return logger.getHandlers(); + } + + @Override + public Level getLevel() { + return logger.getLevel(); + } + + @Override + public Logger getParent() { + return logger.getParent(); + } + + @Override + public ResourceBundle getResourceBundle() { + return logger.getResourceBundle(); + } + + @Override + public String getResourceBundleName() { + return logger.getResourceBundleName(); + } + + @Override + public void log(LogRecord record) { + mapLevel(record); + logger.log(record); + } + + @Override + public void log(Level level, String msg, Object[] params) { + logger.log(mapLevel(level), msg, params); + } + + @Override + public void log(Level level, String msg, Object param1) { + logger.log(mapLevel(level), msg, param1); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + logger.log(mapLevel(level), msgSupplier); + } + + @Override + public void log(Level level, String msg) { + logger.log(mapLevel(level), msg); + } + + @Override + public void log(Level level, String msg, Throwable thrown) { + logger.log(mapLevel(level), msg, thrown); + } + + @Override + public void log(Level level, Throwable thrown, Supplier msgSupplier) { + logger.log(mapLevel(level), thrown, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, param1); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, params); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, thrown); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, thrown, msgSupplier); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Object... params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, thrown); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, param1); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, thrown); + } + + @Override + public boolean isLoggable(Level level) { + return logger.isLoggable(level); + } + + @Override + public void setLevel(Level newLevel) throws SecurityException { + logger.setLevel(newLevel); + } + + @Override + public void setFilter(Filter newFilter) throws SecurityException { + logger.setFilter(newFilter); + } + + @Override + public void setParent(Logger parent) { + logger.setParent(parent); + } + + @Override + public void setResourceBundle(ResourceBundle bundle) { + logger.setResourceBundle(bundle); + } + + @Override + public void setUseParentHandlers(boolean useParentHandlers) { + logger.setUseParentHandlers(useParentHandlers); + } + + @Override + public void severe(String msg) { + logger.severe(msg); + } + + @Override + public void severe(Supplier msgSupplier) { + logger.severe(msgSupplier); + } + + @Override + public void entering(String sourceClass, String sourceMethod) { + logger.entering(sourceClass, sourceMethod); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object param1) { + logger.entering(sourceClass, sourceMethod, param1); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object[] params) { + logger.entering(sourceClass, sourceMethod, params); + } + + @Override + public void exiting(String sourceClass, String sourceMethod) { + logger.exiting(sourceClass, sourceMethod); + } + + @Override + public void exiting(String sourceClass, String sourceMethod, Object result) { + logger.exiting(sourceClass, sourceMethod, result); + } + + @Override + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { + logger.throwing(sourceClass, sourceMethod, thrown); + } + + @Override + public void warning(String msg) { + logger.warning(msg); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void config(String msg) { + logger.config(msg); + } + + @Override + public void fine(String msg) { + logger.fine(msg); + } + + @Override + public void finer(String msg) { + logger.finer(msg); + } + + @Override + public void finest(String msg) { + logger.finest(msg); + } + + @Override + public void warning(Supplier msgSupplier) { + logger.warning(msgSupplier); + } + + @Override + public void info(Supplier msgSupplier) { + logger.info(msgSupplier); + } + + @Override + public void config(Supplier msgSupplier) { + logger.config(msgSupplier); + } + + @Override + public void fine(Supplier msgSupplier) { + logger.fine(msgSupplier); + } + + @Override + public void finer(Supplier msgSupplier) { + logger.finer(msgSupplier); + } + + @Override + public void finest(Supplier msgSupplier) { + logger.finest(msgSupplier); + } + + @Override + public void addHandler(Handler handler) throws SecurityException { + logger.addHandler(handler); + } + + @Override + public void removeHandler(Handler handler) throws SecurityException { + logger.removeHandler(handler); + } + + @Override + public int hashCode() { + return logger.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return logger.equals(obj); + } + + @Override + public String toString() { + return logger.toString(); + } + + protected void mapLevel(@Nonnull LogRecord record) { + record.setLevel(mapLevel(record.getLevel())); + } + + @Nonnull + protected Level mapLevel(@Nonnull Level level) { + return level; + } + + @Nonnull + @Override + public JavaILogger setMinLevel(@Nonnull LogLevel level) { + setLevel(level.getJavaUtilLevel()); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return LogLevel.fromJavaLevel(logger.getLevel()); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + Throwable thrown = null; + for (Object arg : args) { + if (arg instanceof Throwable) + thrown = (Throwable) arg; + } + log(level.getJavaUtilLevel(), ILogger.formatMessage(message, args), thrown); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + +// @Override +// public void trace(String msg) { +// trace(msg, new Object[0]); +// } +// +// @Override +// public void trace(String format, Object arg) { +// trace(format, new Object[] { arg }); +// } +// +// @Override +// public void trace(String format, Object arg1, Object arg2) { +// trace(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void trace(String msg, Throwable t) { +// trace(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isTraceEnabled(Marker marker) { +// return isTraceEnabled(); +// } +// +// @Override +// public void trace(Marker marker, String msg) { +// trace(msg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg) { +// trace(format, arg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg1, Object arg2) { +// trace(format, arg1, arg2); +// } +// +// @Override +// public void trace(Marker marker, String format, Object... argArray) { +// trace(format, argArray); +// } +// +// @Override +// public void trace(Marker marker, String msg, Throwable t) { +// trace(msg, t); +// } +// +// @Override +// public boolean isDebugEnabled() { +// return isLevelEnabled(LogLevel.DEBUG); +// } +// +// @Override +// public void debug(String msg) { +// debug(msg, new Object[0]); +// } +// +// @Override +// public void debug(String format, Object arg) { +// debug(format, new Object[] { arg }); +// } +// +// @Override +// public void debug(String format, Object arg1, Object arg2) { +// debug(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void debug(String msg, Throwable t) { +// debug(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isDebugEnabled(Marker marker) { +// return isDebugEnabled(); +// } +// +// @Override +// public void debug(Marker marker, String msg) { +// debug(msg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg) { +// debug(format, arg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg1, Object arg2) { +// debug(format, arg1, arg2); +// } +// +// @Override +// public void debug(Marker marker, String format, Object... arguments) { +// debug(format, arguments); +// } +// +// @Override +// public void debug(Marker marker, String msg, Throwable t) { +// debug(msg, t); +// } +// +// @Override +// public boolean isInfoEnabled() { +// return isLevelEnabled(LogLevel.INFO); +// } +// +// @Override +// public void info(String format, Object arg) { +// info(format, new Object[] { arg }); +// } +// +// @Override +// public void info(String format, Object arg1, Object arg2) { +// info(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void info(String msg, Throwable t) { +// info(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isInfoEnabled(Marker marker) { +// return isInfoEnabled(); +// } +// +// @Override +// public void info(Marker marker, String msg) { +// info(msg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg) { +// info(format, arg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg1, Object arg2) { +// info(format, arg1, arg2); +// } +// +// @Override +// public void info(Marker marker, String format, Object... arguments) { +// info(format, arguments); +// } +// +// @Override +// public void info(Marker marker, String msg, Throwable t) { +// info(msg, t); +// } +// +// @Override +// public boolean isWarnEnabled() { +// return isLevelEnabled(LogLevel.WARN); +// } +// +// @Override +// public void warn(String msg) { +// warn(msg, new Object[0]); +// } +// +// @Override +// public void warn(String format, Object arg) { +// warn(format, new Object[] { arg }); +// } +// +// @Override +// public void warn(String format, Object arg1, Object arg2) { +// warn(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void warn(String msg, Throwable t) { +// warn(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isWarnEnabled(Marker marker) { +// return isWarnEnabled(); +// } +// +// @Override +// public void warn(Marker marker, String msg) { +// warn(marker); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg) { +// warn(format, arg); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg1, Object arg2) { +// warn(format, arg1, arg2); +// } +// +// @Override +// public void warn(Marker marker, String format, Object... arguments) { +// warn(format, arguments); +// } +// +// @Override +// public void warn(Marker marker, String msg, Throwable t) { +// warn(msg, t); +// } +// +// @Override +// public boolean isErrorEnabled() { +// return isLevelEnabled(LogLevel.ERROR); +// } +// +// @Override +// public void error(String msg) { +// error(msg, new Object[0]); +// } +// +// @Override +// public void error(String format, Object arg) { +// error(format, new Object[] { arg }); +// } +// +// @Override +// public void error(String format, Object arg1, Object arg2) { +// error(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void error(String msg, Throwable t) { +// error(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isErrorEnabled(Marker marker) { +// return isErrorEnabled(); +// } +// +// @Override +// public void error(Marker marker, String msg) { +// error(msg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg) { +// error(format, arg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg1, Object arg2) { +// error(format, arg1, arg2); +// } +// +// @Override +// public void error(Marker marker, String format, Object... arguments) { +// error(format, arguments); +// } +// +// @Override +// public void error(Marker marker, String msg, Throwable t) { +// error(msg, t); +// } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java new file mode 100644 index 000000000..d99ca1fa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java @@ -0,0 +1,365 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class SimpleLogger extends FallbackLogger implements Slf4jILogger { + + public SimpleLogger(@Nullable String name) { + super(name); + } + + public SimpleLogger() { + super(); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + super.log(level, message, args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void trace(@Nullable String message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public void trace(@Nullable Object message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + @Override + public void trace(String msg) { + trace(msg, new Object[0]); + } + + @Override + public void trace(String format, Object arg) { + trace(format, new Object[] { arg }); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + trace(format, new Object[] { arg1, arg2 }); + } + + @Override + public void trace(String msg, Throwable t) { + trace(msg, new Object[] { t }); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + @Override + public void debug(String msg) { + debug(msg, new Object[0]); + } + + @Override + public void debug(String format, Object arg) { + debug(format, new Object[] { arg }); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + debug(format, new Object[] { arg1, arg2 }); + } + + @Override + public void debug(String msg, Throwable t) { + debug(msg, new Object[] { t }); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + @Override + public void info(String msg) { + info(msg, new Object[0]); + } + + @Override + public void info(String format, Object arg) { + info(format, new Object[] { arg }); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + info(format, new Object[] { arg1, arg2 }); + } + + @Override + public void info(String msg, Throwable t) { + info(msg, new Object[] { t }); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } + + @Override + public boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + @Override + public void warn(String msg) { + warn(msg, new Object[0]); + } + + @Override + public void warn(String format, Object arg) { + warn(format, new Object[] { arg }); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + warn(format, new Object[] { arg1, arg2 }); + } + + @Override + public void warn(String msg, Throwable t) { + warn(msg, new Object[] { t }); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } + + @Override + public void warn(Marker marker, String msg) { + warn(marker); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } + + @Override + public boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Override + public void error(String msg) { + error(msg, new Object[0]); + } + + @Override + public void error(String format, Object arg) { + error(format, new Object[] { arg }); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + error(format, new Object[] { arg1, arg2 }); + } + + @Override + public void error(String msg, Throwable t) { + error(msg, new Object[] { t }); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + error(msg, t); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java new file mode 100644 index 000000000..cc1b66a52 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java @@ -0,0 +1,173 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.WrappedILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.helpers.MarkerIgnoringBase; + +import javax.annotation.Nonnull; + +public class Slf4jILoggerWrapper extends MarkerIgnoringBase implements WrappedILogger, Slf4jILogger { + + private final ILogger logger; + + public Slf4jILoggerWrapper(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger getWrappedLogger() { + return logger; + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String message) { + logger.trace(message); + } + + @Override + public void trace(String message, Object arg) { + logger.trace(message, arg); + } + + @Override + public void trace(String message, Object arg1, Object arg2) { + logger.trace(message, arg1, arg2); + } + + @Override + public void trace(String message, Object... args) { + logger.trace(message, args); + } + + @Override + public void trace(String message, Throwable ex) { + logger.trace(message, ex); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String message) { + logger.debug(message); + } + + @Override + public void debug(String message, Object arg) { + logger.debug(message, arg); + } + + @Override + public void debug(String message, Object arg1, Object arg2) { + logger.debug(message, arg1, arg2); + } + + @Override + public void debug(String message, Object... args) { + logger.debug(message, args); + } + + @Override + public void debug(String message, Throwable ex) { + logger.debug(message, ex); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String message) { + logger.info(message); + } + + @Override + public void info(String message, Object arg) { + logger.info(message, arg); + } + + @Override + public void info(String message, Object arg1, Object arg2) { + logger.info(message, arg1, arg2); + } + + @Override + public void info(String message, Object... args) { + logger.info(message, args); + } + + @Override + public void info(String message, Throwable ex) { + logger.info(message, ex); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String message) { + logger.warn(message); + } + + @Override + public void warn(String message, Object arg) { + logger.warn(message, arg); + } + + @Override + public void warn(String message, Object... args) { + logger.warn(message, args); + } + + @Override + public void warn(String message, Object arg1, Object arg2) { + logger.warn(message, arg1, arg2); + } + + @Override + public void warn(String message, Throwable ex) { + logger.warn(message, ex); + } + + @Override + public boolean isErrorEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void error(String message) { + logger.error(message); + } + + @Override + public void error(String message, Object arg) { + logger.error(message, arg); + } + + @Override + public void error(String message, Object arg1, Object arg2) { + logger.error(message, arg1, arg2); + } + + @Override + public void error(String message, Object... args) { + logger.error(message, args); + } + + @Override + public void error(String message, Throwable ex) { + logger.error(message, ex); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java new file mode 100644 index 000000000..079877479 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java @@ -0,0 +1,369 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Logger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerWrapper implements Slf4jILogger { + + protected final Logger logger; + + public Slf4jLoggerWrapper(@Nonnull Logger logger) { + this.logger = logger; + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.trace(msg); + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + } + + @Override + public void trace(String msg, Throwable t) { + logger.trace(msg, t); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + @Override + public void trace(Marker marker, String msg) { + logger.trace(marker, msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + logger.trace(marker, format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + logger.trace(marker, format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + logger.trace(marker, format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + logger.trace(marker, msg, t); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.debug(msg); + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + } + + @Override + public void debug(String msg, Throwable t) { + logger.debug(msg, t); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + @Override + public void debug(Marker marker, String msg) { + logger.debug(marker, msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + logger.debug(marker, format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + logger.debug(marker, format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + logger.debug(marker, format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + logger.debug(marker, msg, t); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + } + + @Override + public void info(String msg, Throwable t) { + logger.info(msg, t); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + @Override + public void info(Marker marker, String msg) { + logger.info(marker, msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + logger.info(marker, format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + logger.info(marker, format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + logger.info(marker, format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + logger.info(marker, msg, t); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.warn(msg); + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + } + + @Override + public void warn(String msg, Throwable t) { + logger.warn(msg, t); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + @Override + public void warn(Marker marker, String msg) { + logger.warn(marker, msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + logger.warn(marker, format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + logger.warn(marker, format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + logger.warn(marker, format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + logger.warn(marker, msg, t); + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.error(msg); + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + switch (level) { + case TRACE: + trace(message, args); + return; + case DEBUG: + case EXTENDED: + debug(message, args); + return; + case STATUS: + case INFO: + info(message, args); + return; + case WARN: + warn(message, args); + return; + case ERROR: + error(message, args); + } + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + } + + @Override + public void error(String msg, Throwable t) { + logger.error(msg, t); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + @Override + public void error(Marker marker, String msg) { + logger.error(marker, msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + logger.error(marker, format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + logger.error(marker, format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + logger.error(marker, format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + logger.error(marker, msg, t); + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + if (logger.isTraceEnabled()) { + return LogLevel.TRACE; + } else if (logger.isDebugEnabled()) { + return LogLevel.DEBUG; + } else if (logger.isInfoEnabled()) { + return LogLevel.INFO; + } else if (logger.isWarnEnabled()) { + return LogLevel.WARN; + } else { + return LogLevel.ERROR; + } + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java new file mode 100644 index 000000000..2f4a6067d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class ConstantLoggerFactory implements ILoggerFactory { + + protected final ILogger logger; + + public ConstantLoggerFactory(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return logger; + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + logger.setMinLevel(level); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java new file mode 100644 index 000000000..7825389f4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +public class DefaultLoggerFactory implements ILoggerFactory { + + protected final Map loggers = new ConcurrentHashMap<>(); + protected final Function creator; + protected LogLevel level = LogLevel.DEBUG; + + public DefaultLoggerFactory(@Nonnull Function creator) { + this.creator = creator; + } + + @Nonnull + @Override + @CheckReturnValue + public synchronized ILogger forName(@Nullable String name) { + return loggers.computeIfAbsent(name == null ? "anonymous" : name, unused -> creator.apply(name).setMinLevel(level)); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + this.level = level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java new file mode 100644 index 000000000..e3948466a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerFactory implements ILoggerFactory { + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return ILogger.forSlf4jLogger( + LoggerFactory.getLogger(name == null ? "Logger" : name) + ); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java new file mode 100644 index 000000000..fde8ffb8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.logging.Logger; + +public abstract class JavaILogger extends Logger implements ILogger { + + protected JavaILogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } + + @Nonnull + @Override + public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java new file mode 100644 index 000000000..05afb6c81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import org.slf4j.Logger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface Slf4jILogger extends ILogger, Logger { + + @Override + boolean isTraceEnabled(); + + @Override + boolean isDebugEnabled(); + + @Override + boolean isInfoEnabled(); + + @Override + boolean isWarnEnabled(); + + @Override + boolean isErrorEnabled(); + + @Override + void trace(@Nullable String message, @Nonnull Object... args); + + @Override + void debug(@Nullable String message, @Nonnull Object... args); + + @Override + void info(@Nullable String message, @Nonnull Object... args); + + @Override + void warn(@Nullable String message, @Nonnull Object... args); + + @Override + void error(@Nullable String message, @Nonnull Object... args); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java new file mode 100644 index 000000000..fc9a86c16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -0,0 +1,101 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Map; + +public final class BukkitReflectionSerializationUtils { + + private BukkitReflectionSerializationUtils() {} + + protected static final ILogger logger = ILogger.forThisClass(); + + public static boolean isSerializable(@Nonnull Class clazz) { + try { + clazz.getMethod("serialize"); + return true; + } catch (Throwable ex) { + return false; + } + } + + @Nullable + public static Map serializeObject(@Nonnull Object object) { + Class classOfObject = object.getClass(); + try { + + Method method = classOfObject.getMethod("serialize"); + method.setAccessible(true); + Object serialized = method.invoke(object); + + if (!(serialized instanceof Map)) throw new IllegalArgumentException(method + " does not return a Map"); + + @SuppressWarnings("unchecked") + Map map = (Map) serialized; + return map; + + } catch (Throwable ex) { + logger.error("Could not serialize object of type {}", classOfObject, ex); + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { + try { + + Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); + Method method = configurationSerializationClass.getMethod("deserializeObject", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + return (T) object; + + } catch (Throwable ex) { + } + + if (classOfT == null) + return null; + + try { + + Method method = classOfT.getMethod("deserialize", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + if (!classOfT.isInstance(object)) throw new IllegalStateException("Deserialization of " + classOfT.getName() + " failed: returned " + (object == null ? null : object.getClass().getName())); + return classOfT.cast(object); + + } catch (Throwable ex) { + logger.error("Could not deserialize object of type {}", classOfT, ex); + return null; + } + } + + @Nonnull + public static String getSerializationName(@Nonnull Class clazz) { + for (Annotation annotation : clazz.getAnnotations()) { + Class annotationType = annotation.annotationType(); + Object value = ReflectionUtils.getAnnotationValue(annotation); + switch (annotationType.getSimpleName()) { + case "DelegateDeserialization": + case "DelegateSerialization": + case "SerializableAs": + if (value instanceof Class) { + return getSerializationName((Class) value); + } else if (value instanceof String) { + return (String) value; + } + break; + } + } + + return clazz.getName(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java new file mode 100644 index 000000000..b8733488f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -0,0 +1,565 @@ +package net.codingarea.commons.common.misc; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyConsumer; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.nio.file.FileSystem; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +public final class FileUtils { + + public static final InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]); + private static final Map ZIP_FILE_SYSTEM_PROPERTIES = ImmutableMap + .of("create", "false", "encoding", "UTF-8"); + private static Path tempDirectory; + + private FileUtils() {} + + @Nullable + public static Path getTempDirectory() { + return tempDirectory; + } + + public static void setTempDirectory(@Nullable Path tempDirectory) { + FileUtils.tempDirectory = tempDirectory; + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { + return newBufferedWriter(file.toPath()); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { + return newBufferedReader(file.toPath()); + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { + return Files.newBufferedWriter(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { + return Files.newBufferedReader(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static String getFileExtension(@Nonnull File file) { + return getFileExtension(file.getName()); + } + + @Nonnull + public static String getFileExtension(@Nonnull Path file) { + return getFileExtension(file.toString()); + } + + @Nonnull + public static String getFileExtension(@Nonnull String filename) { + return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); + } + + @Nonnull + public static String getFileName(@Nonnull File file) { + return getFileName(file.getName()); + } + + @Nonnull + public static String getFileName(@Nonnull Path file) { + return getFileName(file.toString()); + } + + @Nonnull + public static String getFileName(@Nonnull String filename) { + filename = stripFolders(filename); + int index = filename.lastIndexOf('.'); + if (index == -1) return filename; + return filename.substring(0, index); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull File file) { + return getRealFileName(file.getName()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull Path file) { + return getRealFileName(file.toString()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull String filename) { + return stripFolders(filename); + } + + @Nonnull + @CheckReturnValue + private static String stripFolders(@Nonnull String filename) { + int index = filename.lastIndexOf(File.pathSeparator); + if (index == -1) return filename; + return filename.substring(index + 1); + } + + public static void createFilesIfNecessary(@Nonnull File file) throws IOException { + if (file.exists()) return; + + if (file.isDirectory()) { + file.mkdirs(); + } else if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + + file.createNewFile(); + } + + public static void deleteWorldFolder(@Nonnull File path) { + if (path.exists()) { + File[] files = path.listFiles(); + if (files == null) return; + for (File currentFile : files) { + if (currentFile.isDirectory()) { + // Don't delete directories or we'Ll minecraft won't create them again + deleteWorldFolder(currentFile); + } else { + if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions + currentFile.delete(); + } + } + } + } + + public static byte[] toByteArray(@Nullable InputStream inputStream) { + return toByteArray(inputStream, new byte[8192]); + } + + public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffer) { + if (inputStream == null) { + return null; + } + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + copy(inputStream, byteArrayOutputStream, buffer); + return byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return null; + } + + public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { + try (FileSystem fileSystem = FileSystems + .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { + consumer.accept(fileSystem); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + + public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { + copy(inputStream, outputStream, new byte[8192]); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { + copy(inputStream, outputStream, buffer, null); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer, + Consumer lengthInputListener) throws IOException { + int len; + while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { + if (lengthInputListener != null) { + lengthInputListener.accept(len); + } + + outputStream.write(buffer, 0, len); + outputStream.flush(); + } + } + + public static void copy(Path from, Path to) throws IOException { + copy(from, to, new byte[8192]); + } + + public static void copy(Path from, Path to, byte[] buffer) throws IOException { + if (from == null || to == null || !Files.exists(from)) { + return; + } + + if (Files.notExists(to)) { + createDirectory(to.getParent()); + } + + try (InputStream stream = Files.newInputStream(from); OutputStream target = Files.newOutputStream(to)) { + copy(stream, target, buffer); + } + } + + public static void copyFilesToDirectory(Path from, Path to) { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }); + } + + public static void copyFilesToDirectory(Path from, Path to, DirectoryStream.Filter filter) { + if (filter == null) { + copyFilesToDirectory(from, to); + } else { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }, true, filter); + } + } + + public static void delete(Path file) { + if (file == null || Files.notExists(file)) { + return; + } + + if (Files.isDirectory(file)) { + walkFileTree(file, (root, current) -> FileUtils.deleteFile(current)); + } + + FileUtils.deleteFile(file); + } + + public static long size(@Nonnull Path path) { + try { + return Files.size(path); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + /** + * Converts a bunch of directories to a byte array + * + * @param directories The directories which should get converted + * @return A byte array of a zip file created from the provided directories + * @deprecated May cause a heap space (over)load + */ + @Deprecated + public static byte[] convert(Path... directories) { + if (directories == null) { + return emptyZipByteArray(); + } + + try (ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteBuffer, StandardCharsets.UTF_8)) { + for (Path directory : directories) { + zipDir(zipOutputStream, directory, null); + } + } + + return byteBuffer.toByteArray(); + + } catch (IOException ex) { + ex.printStackTrace(); + } + + return emptyZipByteArray(); + } + + @Nonnull + public static Path createTempFile() { + if (tempDirectory != null) + return createTempFile(UUID.randomUUID()); + + try { + File file = File.createTempFile(UUID.randomUUID().toString(), null); + file.deleteOnExit(); + return file.toPath(); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + public static Path createTempFile(@Nonnull UUID uuid) { + Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); + Path file = tempDirectory.resolve(uuid.toString()); + createFile(file); + return file; + } + + public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { + try { + Files.setAttribute(path, attribute, value, options); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { + setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory) throws IOException { + return zipToStream(directory, null); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { + Path target = createTempFile(); + zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); + return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); + } + + @Nullable + public static Path zipToFile(Path directory, Path target) { + return zipToFile(directory, target, null); + } + + @Nullable + public static Path zipToFile(Path directory, Path target, Predicate fileFilter) { + if (directory == null || !Files.exists(directory)) { + return null; + } + + delete(target); + try (OutputStream outputStream = Files.newOutputStream(target, StandardOpenOption.CREATE)) { + zipStream(directory, outputStream, fileFilter); + return target; + } catch (IOException ex) { + ex.printStackTrace(); + } + + return null; + } + + private static void zipStream(Path source, OutputStream buffer, Predicate fileFilter) throws IOException { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) { + if (Files.exists(source)) { + zipDir(zipOutputStream, source, fileFilter); + } + } + } + + private static void zipDir(ZipOutputStream zipOutputStream, Path directory, Predicate fileFilter) throws IOException { + Files.walkFileTree( + directory, + new SimpleFileVisitor() { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (fileFilter != null && !fileFilter.test(file)) { + return FileVisitResult.CONTINUE; + } + + try { + zipOutputStream.putNextEntry(new ZipEntry(directory.relativize(file).toString().replace("\\", "/"))); + Files.copy(file, zipOutputStream); + zipOutputStream.closeEntry(); + } catch (IOException ex) { + zipOutputStream.closeEntry(); + throw ex; + } + return FileVisitResult.CONTINUE; + } + } + ); + } + + public static Path extract(Path zipPath, Path targetDirectory) throws IOException { + if (zipPath == null || targetDirectory == null || !Files.exists(zipPath)) { + return targetDirectory; + } + + try (InputStream input = Files.newInputStream(zipPath)) { + return extract(input, targetDirectory); + } + } + + public static Path extract(InputStream input, Path targetDirectory) throws IOException { + if (input == null || targetDirectory == null) { + return targetDirectory; + } + + extract0(new ZipInputStream(input, StandardCharsets.UTF_8), targetDirectory); + + return targetDirectory; + } + + public static Path extract(byte[] zipData, Path targetDirectory) throws IOException { + if (zipData == null || zipData.length == 0 || targetDirectory == null) { + return targetDirectory; + } + + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(zipData)) { + extract0(new ZipInputStream(byteArrayInputStream, StandardCharsets.UTF_8), targetDirectory); + } + + return targetDirectory; + } + + public static void extract0(ZipInputStream zipInputStream, Path targetDirectory) throws IOException { + ZipEntry zipEntry; + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + extractEntry(zipInputStream, zipEntry, targetDirectory); + zipInputStream.closeEntry(); + } + } + + public static byte[] emptyZipByteArray() { + byte[] bytes = null; + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8); + zipOutputStream.close(); + + bytes = byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return bytes; + } + + private static void extractEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, Path targetDirectory) + throws IOException { + Path file = targetDirectory.resolve(zipEntry.getName()); + ensureChild(targetDirectory, file); + + if (zipEntry.isDirectory()) { + if (!Files.exists(file)) { + Files.createDirectories(file); + } + } else { + Path parent = file.getParent(); + if (!Files.exists(parent)) { + Files.createDirectories(parent); + } + + if (Files.exists(file)) { + Files.delete(file); + } + + Files.createFile(file); + try (OutputStream outputStream = Files.newOutputStream(file)) { + copy(zipInputStream, outputStream); + } + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer) { + walkFileTree(rootDirectoryPath, consumer, true); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories) { + walkFileTree(rootDirectoryPath, consumer, visitDirectories, "*"); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + String glob) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, glob)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, glob); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + DirectoryStream.Filter filter) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, filter)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, filter); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void createDirectory(@Nullable Path directoryPath) { + if (directoryPath != null && Files.notExists(directoryPath)) { + try { + Files.createDirectories(directoryPath); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + public static void createFile(@Nullable Path filePath) { + if (filePath != null && Files.notExists(filePath)) { + try { + if (filePath.getParent() != null) + Files.createDirectories(filePath.getParent()); + Files.createFile(filePath); + } catch (IOException ex) { + } + } + } + + public static void deleteFile(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private static void ensureChild(Path root, Path child) { + Path rootNormal = root.normalize().toAbsolutePath(); + Path childNormal = child.normalize().toAbsolutePath(); + + if (childNormal.getNameCount() <= rootNormal.getNameCount() || !childNormal.startsWith(rootNormal)) { + throw new IllegalStateException("Child " + childNormal + " is not in root path " + rootNormal); + } + } + + @Nonnull + public static Stream list(@Nonnull Path directory) { + try { + return Files.list(directory); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java new file mode 100644 index 000000000..ce3988f94 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -0,0 +1,127 @@ +package net.codingarea.commons.common.misc; + +import com.google.gson.*; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +@SuppressWarnings("unchecked") +public final class GsonUtils { + + private GsonUtils() {} + + @Nullable + public static Object unpackJsonElement(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonObject()) + return convertJsonObjectToMap(element.getAsJsonObject()); + if (element.isJsonArray()) + return convertJsonArrayToStringList(element.getAsJsonArray()); + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isNumber()) return primitive.getAsNumber(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isBoolean()) return primitive.getAsBoolean(); + } + return element; + } + + @Nullable + public static String convertJsonElementToString(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isNumber()) return primitive.getAsNumber() + ""; + if (primitive.isBoolean()) return primitive.getAsBoolean() + ""; + } + return element.toString(); + } + + @Nonnull + public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { + Map map = new LinkedHashMap<>(); + convertJsonObjectToMap(object, map); + return map; + } + + public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { + for (Entry entry : object.entrySet()) { + map.put(entry.getKey(), unpackJsonElement(entry.getValue())); + } + } + + + @Nonnull + public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + list.add(convertJsonElementToString(element)); + } + return list; + } + + @Nonnull + public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { + String[] list = new String[array.size()]; + for (int i = 0; i < array.size(); i++) { + list[i] = convertJsonElementToString(array.get(i)); + } + return list; + } + + @Nonnull + public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { + JsonArray array = new JsonArray(); + iterable.forEach(object -> array.add(gson.toJsonTree(object))); + return array; + } + + @Nonnull + public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { + JsonArray jsonArray = new JsonArray(); + ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); + return jsonArray; + } + + public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + + if (value == null) { + object.add(entry.getKey(), null); + } else if (value instanceof JsonElement) { + object.add(entry.getKey(), (JsonElement) value); + } else if (value instanceof Iterable) { + Iterable iterable = (Iterable) value; + object.add(entry.getKey(), convertIterableToJsonArray(gson, iterable)); + } else if (value.getClass().isArray()) { + object.add(entry.getKey(), convertArrayToJsonArray(gson, value)); + } else if (value instanceof Map) { + Map map = (Map) value; + JsonObject newObject = new JsonObject(); + object.add(entry.getKey(), newObject); + setDocumentProperties(gson, newObject, map); + } else { + object.add(entry.getKey(), gson.toJsonTree(value)); + } + } + } + + public static int getSize(@Nonnull JsonObject object) { + try { + return object.size(); + } catch (NoSuchMethodError ex) { + } + + return object.entrySet().size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java new file mode 100644 index 000000000..6be9f8af1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -0,0 +1,109 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.IOUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.font.TextLayout; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLConnection; + +public final class ImageUtils { + + private ImageUtils() {} + + /** + * @param height The y-position of the text + * @return The width of the text added in pixels + */ + public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); + return lineWidth; + + } + + /** + * @return The ending position of the text + */ + public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { + TextLayout layout = getTextLayout(graphics, text); + graphics.drawString(text, x, height); + return (int) (x + layout.getBounds().getWidth()); + } + + /** + * @return Returns where the text has started + */ + public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { + TextLayout layout = getTextLayout(graphics, text); + int position = (int) (endX - layout.getBounds().getWidth()); + graphics.drawString(text, position, height); + return position; + } + + /** + * @param height The y-position of the text + */ + public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); + } + + /** + * Reads a image from url using {@link ImageIO#read(InputStream)} and returns it + * + * @param url The URL the image is stored to + * + * @throws IOException + * When something goes wrong while connecting or reading the image + */ + public static BufferedImage loadUrl(@Nonnull String url) throws IOException { + URLConnection connection = IOUtils.createConnection(url); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage loadResource(@Nonnull String path) throws IOException { + InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); + return ImageIO.read(stream); + } + + public static BufferedImage loadFile(@Nonnull File file) throws IOException { + return ImageIO.read(file); + } + + @Nonnull + public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { + return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); + } + + public static void darkenImage(@Nonnull BufferedImage image) { + for (int i = 0; i < image.getWidth(); i++) { + for (int j = 0; j < image.getHeight(); j++) { + image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); + } + } + } + + @Nonnull + @CheckReturnValue + public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { + if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); + BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = created.createGraphics(); + graphics.setColor(replacementColor); + graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); + graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); + graphics.dispose(); + return created; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java new file mode 100644 index 000000000..1663748b7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.misc; + +public final class MathHelper { + + private MathHelper() {} + + public static double percentage(double total, double proportion) { + if (proportion == 0) return 0; + return (proportion * 100) / total; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java new file mode 100644 index 000000000..8b84e8f64 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.common.misc; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +public final class PropertiesUtils { + + private PropertiesUtils() {} + + public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java new file mode 100644 index 000000000..2c4566199 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -0,0 +1,258 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.ArrayWalker; +import net.codingarea.commons.common.collection.ClassWalker; +import net.codingarea.commons.common.collection.PublicSecurityManager; +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; + +public final class ReflectionUtils { + + private ReflectionUtils() {} + + @Nonnull + public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Method method : clazz.getMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + return annotatedMethods; + } + + @Nonnull + public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Class currentClass : ClassWalker.walk(clazz)) { + for (Method method : currentClass.getDeclaredMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + } + return annotatedMethods; + } + + @Nonnull + public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredMethod(name, parameterTypes); + } catch (Throwable ex) { + } + } + + throw new NoSuchMethodException(name); + } + + @Nonnull + public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredField(name); + } catch (Throwable ex) { + } + } + + throw new NoSuchFieldException(name); + } + + /** + * @param classOfEnum The class containing the enum constants + * @return The first enum found by the given names + */ + @Nonnull + public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { + for (String name : names) { + try { + return Enum.valueOf(classOfEnum, name); + } catch (IllegalArgumentException | NoSuchFieldError ex) { } + } + throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); + } + + /** + * Iterates through an array which may contain primitive data types or non primitive data types and performs the given action on each element. + * Because we can't just cast such an array to {@code Object[]}, we have to use some reflections. + * + * @param array The target array, as {@link Object}; Can't use an array type here. + * @param The type of data we will cast the content to. Use {@link Object} if the it's unknown. + * + * @throws IllegalArgumentException + * If the {@code array} is not an actual array + * + * @see Array + * @see Array#getLength(Object) + * @see Array#get(Object, int) + */ + public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { + ReflectionUtils.iterableArray(array).forEach(action); + } + + @Nonnull + @CheckReturnValue + public static Iterable iterableArray(@Nonnull Object array) { + return ArrayWalker.walk(array); + } + + @CheckReturnValue + public static Class getCaller(int index) { + try { + return new PublicSecurityManager().getPublicClassContext()[index + 2]; + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @CheckReturnValue + public static Class getCaller() { + return getCaller(2); + } + + @Nonnull + public static String getCallerName() { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + StackTraceElement element = trace[3]; + + String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); + return className + "." + element.getMethodName(); + } + + /** + * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} + * + * @see Class#getField(String) + */ + @Nonnull + public static Field getEnumAsField(@Nonnull Enum enun) { + Class classOfEnum = enun.getClass(); + + try { + return classOfEnum.getField(enun.name()); + } catch (NoSuchFieldException ex) { + throw new WrappedException(ex); + } + } + + /** + * @see Field#getAnnotations() + */ + @Nonnull + public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { + Field field = getEnumAsField(enun); + return field.getAnnotations(); + } + + /** + * @return Returns {@code null} if no annotation of this class is present + * + * @see Field#getAnnotation(Class) + */ + public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { + Field field = getEnumAsField(enun); + return field.getAnnotation(classOfAnnotation); + } + + @Nullable + public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { + try { + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name) { + try { + if (name == null) return null; + return (Class) Class.forName(name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { + try { + if (name == null) return null; + return (Class) Class.forName(name, initialize, classLoader); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { + try { + if (!method.isAccessible()) method.setAccessible(true); + return (T) method.invoke(instance); + } catch (Throwable ex) { + return null; + } + } + + @Nullable + public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { + try { + return invokeMethodOrNull(null, clazz.getMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { + try { + return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T getAnnotationValue(@Nonnull Annotation annotation) { + return invokeMethodOrNull(annotation, "value"); + } + + @Nullable + public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { + E[] values = invokeStaticMethodOrNull(classOfE, "values"); + String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; + for (E value : values) { + for (String method : methodNames) { + if (check(input, invokeMethodOrNull(value, method))) + return value; + } + } + + return null; + } + + private static boolean check(@Nonnull String input, @Nullable Object value) { + if (value == null) return false; + if (value.getClass().isArray()) { + for (Object key : iterableArray(value)) { + if (input.equalsIgnoreCase(String.valueOf(key))) + return true; + } + } + return input.equalsIgnoreCase(String.valueOf(value)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java new file mode 100644 index 000000000..66faae82d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -0,0 +1,143 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; + +public final class SimpleCollectionUtils { + + @Deprecated + public static final String REGEX_1 = ",", + REGEX_2 = "="; + private static final ILogger logger = ILogger.forThisClass(); + private static boolean logMappingError = true; + + private SimpleCollectionUtils() {} + + public static void disableErrorLogging() { + logMappingError = false; + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { + StringBuilder builder = new StringBuilder(); + for (Entry entry : map.entrySet()) { + if (builder.length() != 0) builder.append(REGEX_1); + builder.append(key.apply(entry.getKey())); + builder.append(REGEX_2); + builder.append(value.apply(entry.getValue())); + } + return builder.toString(); + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { + + Map map = new HashMap<>(); + if (string == null) return map; + + String[] args = string.split(REGEX_1); + for (String arg : args) { + try { + + String[] elements = arg.split(REGEX_2); + K keyElement = key.apply(elements[0]); + V valueElement = value.apply(elements[1]); + + if (keyElement == null || valueElement == null) + throw new NullPointerException(); + + map.put(keyElement, valueElement); + + } catch (Exception ex) { + if (logMappingError) + logger.error("Cannot generate key/value: " + ex.getClass().getName() + ": " + ex.getMessage()); + } + } + + return map; + + } + + @Nonnull + @CheckReturnValue + public static Map convertMap(@Nonnull Map map, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + map.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable to map '{}'='{}'", key, value, ex); + } + }); + return result; + } + + @Nonnull + @CheckReturnValue + public static List convert(@Nonnull Collection collection, + @Nonnull Function mapper) { + List result = new ArrayList<>(collection.size()); + collection.forEach(value -> { + try { + result.add(mapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable map '{}'", value, ex); + } + }); + return result; + } + + public static V getMostFrequentValue(@Nonnull Map map) { + Collection values = map.values(); + List list = new ArrayList<>(values); + Set set = new HashSet<>(values); + + V valueMax = null; + int max = 0; + for (V value : set) { + int frequency = Collections.frequency(list, value); + if (frequency > max) { + max = frequency; + valueMax = value; + } + } + + return valueMax; + } + + @SafeVarargs + public static Set setOf(@Nonnull Collection... collections) { + Set set = new HashSet<>(); + for (Collection collection : collections) { + set.addAll(collection); + } + return set; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java new file mode 100644 index 000000000..fdae424a0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -0,0 +1,181 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Supplier; + +public final class StringUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private StringUtils() {} + + @Nonnull + public static String getEnumName(@Nonnull Enum enun) { + return getEnumName(enun.name()); + } + + @Nonnull + public static String getEnumName(@Nonnull String name) { + StringBuilder builder = new StringBuilder(); + boolean nextUpperCase = true; + for (char letter : name.toCharArray()) { + // Replace _ with space + if (letter == '_') { + builder.append(' '); + nextUpperCase = true; + continue; + } + builder.append(nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter)); + nextUpperCase = false; + } + return builder.toString(); + } + + @Nonnull + public static String format(@Nonnull String sequence, @Nonnull Object... args) { + char start = '{', end = '}'; + boolean inArgument = false; + StringBuilder argument = new StringBuilder(); + StringBuilder builder = new StringBuilder(); + for (char c : sequence.toCharArray()) { + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + Object replacement = + current instanceof Supplier ? ((Supplier)current).get() : + current instanceof Callable ? ((Callable)current).call() : + current; + builder.append(replacement); + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + logger.warn("Invalid argument index '{}'", argument); + builder.append(start).append(argument).append(end); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + builder.append(c); + } + if (argument.length() > 0) builder.append(start).append(argument); + return builder.toString(); + } + + @Nonnull + public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { + return Optional.of(input) + .filter(name -> name.contains(separator)) + .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) + .orElse(""); + } + + @Nonnull + public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = format(array[i], args); + } + return result; + } + + @Nonnull + public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { + StringBuilder builder = new StringBuilder(); + for (String string : array) { + if (builder.length() != 0) builder.append(separator); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String[] getStringAsArray(@Nonnull String string) { + return string.split("\n"); + } + + @Nonnull + public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { + StringBuilder builder = new StringBuilder(); + for (T t : iterable) { + if (builder.length() > 0) builder.append(separator); + String string = mapper.apply(t); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String repeat(@Nullable Object sequence, int amount) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < amount; i++) builder.append(sequence); + return builder.toString(); + } + + private static int getMultiplier(char c) { + switch (Character.toLowerCase(c)) { + default: return 1; + case 'm': return 60; + case 'h': return 60*60; + case 'd': return 24*60*60; + case 'w': return 7*24*60*60; + case 'y': return 365*24*60*60; + } + } + + public static long parseSeconds(@Nonnull String input) { + if (input.toLowerCase().startsWith("perm")) return -1; + long current = 0; + long seconds = 0; + for (char c : input.toCharArray()) { + try { + long i = Long.parseUnsignedLong(String.valueOf(c)); + current *= 10; + current += i; + } catch (Exception ignored) { + int multiplier = getMultiplier(c); + seconds += current * multiplier; + current = 0; + } + } + seconds += current; + return seconds; + } + + public static boolean isNumber(@Nonnull String sequence) { + try { + Double.parseDouble(sequence); + return true; + } catch (Exception ex) { + return false; + } + } + + private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { + int lastIndex = 0; + for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { + int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); + if (index == -1) return -1; + lastIndex = index + 1; + } + + return lastIndex; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java new file mode 100644 index 000000000..d9e31fedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.annotations.Since; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public interface Version { + + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = getRevision(); + return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) + : String.format("%s.%s", getMajor(), getMinor()); + } + + default int intValue() { + int major = getMajor(); + int minor = getMinor(); + int revision = getRevision(); + + if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); + if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); + if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); + + return revision + + minor * 100 + + major * 10000; + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); + return parse(object.getClass().getAnnotation(Since.class).value()); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + for (V version : versions) { + if (version.isNewerThan(target)) continue; + return version; + } + throw new IllegalArgumentException("No version found for '" + target + "'"); + } + + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java new file mode 100644 index 000000000..14a6a89c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.version; + +import javax.annotation.Nonnull; +import java.util.Comparator; + +public class VersionComparator implements Comparator { + + @Override + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java new file mode 100644 index 000000000..29dbac10b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -0,0 +1,80 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nullable; +import java.util.Objects; + +public class VersionInfo implements Version { + + protected static final ILogger logger = ILogger.forThisClass(); + + private final int major, minor, revision; + + public VersionInfo() { + this(1, 0, 0); + } + + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Version)) return false; + return this.equals((Version) other); + } + + @Override + public int hashCode() { + return Objects.hash(major, minor, revision); + } + + @Override + public String toString() { + return this.format(); + } + + /** + * @throws IllegalArgumentException + * If the version could not be parsed + */ + public static Version parseExceptionally(@Nullable String input) { + if (input == null) throw new IllegalArgumentException("Version cannot be null"); + String[] array = input.split("\\."); + if (array.length == 0) throw new IllegalArgumentException("Version cannot be empty"); + try { + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); + } catch (Exception ex) { + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", ex.getMessage()); + return def; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Database.java b/plugin/src/main/java/net/codingarea/commons/database/Database.java new file mode 100644 index 000000000..9092f3c1f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Database.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public interface Database { + + ILogger LOGGER = ILogger.forThisClass(); + + @Nonnull + @CheckReturnValue + static Database empty() { + return new EmptyDatabase(true); + } + + @Nonnull + @CheckReturnValue + static Database unsupported() { + return new EmptyDatabase(false); + } + + boolean isConnected(); + + /** + * Creates the connection to the database synchronously. + * + * @throws DatabaseException + * If the connection could not be established + * @throws DatabaseAlreadyConnectedException + * If this database is already {@link #isConnected() connected} + */ + void connect() throws DatabaseException; + + /** + * Creates the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was established successfully + */ + boolean connectSafely(); + + /** + * Closes the connection to the database synchronously. + * + * @throws DatabaseException + * If something went wrong while closing the connection to the database + * @throws DatabaseConnectionClosedException + * If this database is not {@link #isConnected() connected} + */ + void disconnect() throws DatabaseException; + + /** + * Closes the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was closed without errors + */ + boolean disconnectSafely(); + + void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; + void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); + + @Nonnull + default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { + return Task.asyncRunExceptionally(() -> createTable(name, columns)); + } + + @Nonnull + @CheckReturnValue + DatabaseListTables listTables(); + + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseQuery query(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseUpdate update(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(@Nonnull String table); + + @Nonnull + @CheckReturnValue + SpecificDatabase getSpecificDatabase(@Nonnull String name); + + @Nonnull + DatabaseConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java new file mode 100644 index 000000000..8c67b2b87 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.config.Propertyable; + +import javax.annotation.Nonnull; + +public final class DatabaseConfig { + + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; + private final boolean portIsSet; + + public DatabaseConfig(String host, String database, String password, String user, int port) { + this(host, database, null, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String password, String user) { + this(host, database, null, password, user, 0, false, null); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port) { + this(host, database, authDatabase, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String authDatabase, String password, String user) { + this(host, database, authDatabase, password, user, 0, false, null); + } + + public DatabaseConfig(String database, String file) { + this(null, database, null, null, null, 0, false, file); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port, boolean portIsSet, String file) { + this.host = host; + this.database = database; + this.authDatabase = authDatabase; + this.password = password; + this.user = user; + this.port = port; + this.portIsSet = portIsSet; + this.file = file; + } + + public DatabaseConfig(@Nonnull Propertyable config) { + this( + config.getString("host"), + config.getString("database"), + config.getString("auth-database"), + config.getString("password"), + config.getString("user"), + config.getInt("port"), + config.contains("port"), + config.getString("file") + ); + } + + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { + return portIsSet; + } + + public String getFile() { + return file; + } + + @Override + public String toString() { + return "DatabaseConfig{" + + "host='" + host + '\'' + + ", database='" + database + '\'' + + ", authDatabase='" + authDatabase + '\'' + + ", user='" + user + '\'' + + ", file='" + file + '\'' + + ", port=" + port + + ", portIsSet=" + portIsSet + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java new file mode 100644 index 000000000..0770c8b67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -0,0 +1,288 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.abstraction.DefaultSpecificDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; + +public class EmptyDatabase implements Database { + + private final boolean silent; + + public EmptyDatabase(boolean silent) { + this.silent = silent; + } + + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { + throw new UnsupportedOperationException(message); + } + + @Override + public boolean isConnected() { + return false; + } + + @Override + public void connect() throws DatabaseException { + if (!silent) + exception("Cannot connect with a NOP Database"); + } + + @Override + public boolean connectSafely() { + return false; + } + + @Override + public void disconnect() throws DatabaseException { + if (!silent) + exception("Cannot disconnect from a NOP Database"); + } + + @Override + public boolean disconnectSafely() { + return false; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + if (!silent) + exception("Cannot create tables from a NOP Database"); + } + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + if (!silent) + exception("Cannot list tables of a NOP Database"); + + return new EmptyListTables(); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + if (!silent) + exception("Cannot count entries of a NOP Database"); + + return new EmptyCountEntries(); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + if (!silent) + exception("Cannot query in a NOP Database"); + + return new EmptyDatabaseQuery(); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + if (!silent) + exception("Cannot update in a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + if (!silent) + exception("Cannot insert into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + if (!silent) + exception("Cannot inset or update into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + if (!silent) + exception("Cannot delete from a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "EmptyDatabase[silent=" + silent + "]"; + } + + public static class EmptyDatabaseQuery implements DatabaseQuery { + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + return new DefaultExecutedQuery(Collections.emptyList()); + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.syncCall(this::execute); + } + + } + + public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Override + public Void execute() throws DatabaseException { + return null; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completedVoid(); + } + + } + + public static class EmptyCountEntries implements DatabaseCountEntries { + + @Nonnull + @Override + public Long execute() throws DatabaseException { + return 0L; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completed(0L); + } + + } + + public static class EmptyListTables implements DatabaseListTables { + + @Nonnull + @Override + public List execute() throws DatabaseException { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Task> executeAsync() { + return Task.completed(Collections.emptyList()); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Order.java b/plugin/src/main/java/net/codingarea/commons/database/Order.java new file mode 100644 index 000000000..8165ecb8e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Order.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.hierarchy.OrderedAction; + +/** + * @see OrderedAction#orderBy(String, Order) + */ +public enum Order { + + HIGHEST, + LOWEST + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java new file mode 100644 index 000000000..f58d9d0aa --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public final class SQLColumn { + + public enum Type { + /** A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 */ + CHAR, + /** A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 */ + VARCHAR, + /** Equal to {@link #CHAR}, but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 */ + BINARY, + /** Equal to {@link #VARCHAR}, but stores binary byte strings. The size parameter specifies the maximum column length in bytes. */ + VARBINARY, + /** For BLOBs (Binary Large OBjects). Max length: 255 bytes */ + TINYBLOB, + /** Holds a string with a maximum length of 255 characters */ + TINYTEXT, + /** Holds a string with a maximum length of 65,535 bytes */ + TEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + BLOB, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + MEDIUMTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data */ + MEDIUMBLOB, + /** Holds a string with a maximum length of 4,294,967,295 characters */ + LONGTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data */ + LONGBLOB, + /** A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them */ + ENUM, + /** A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list */ + SET, + /** A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1. */ + BIT, + /** A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255) */ + TINYINT, + /** Zero is considered as false, nonzero values are considered as true. */ + BOOLEAN, + /** A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255) */ + SMALLINT, + /** A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255) */ + MEDIUMINT, + /** A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255) */ + INT, + /** A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255) */ + BIGINT, + /** A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE() */ + FLOAT, + /** A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter */ + DOUBLE, + /** An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.*/ + DECIMAL + } + + private final String name; + private final String type; + private final String param; + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { + if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); + if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); + + this.name = name; + this.type = type; + this.param = param; + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { + this(name, type, String.valueOf(size)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { + this(name, type, String.valueOf(size), String.valueOf(d)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { + this(name, type, StringUtils.getArrayAsString(params, ", ")); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { + this(name, type.name(), param); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { + this(name, type.name(), size); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { + this(name, type.name(), size, d); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { + this(name, type.name(), params); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { + this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getType() { + return type; + } + + @Nullable + public Type findType() { + return ReflectionUtils.getEnumOrNull(type.toUpperCase(), Type.class); + } + + @Nullable + public String getParam() { + return param; + } + + @Override + public String toString() { + return name + " " + type + (param == null ? "" : "(" + param + ")"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java new file mode 100644 index 000000000..56ae16184 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +public final class SimpleDatabaseTypeResolver { + + private SimpleDatabaseTypeResolver() {} + + private static final Map registry = new HashMap<>(); + static { + registerType("mongodb", "net.codingarea.commons.database.mongodb.MongoDBDatabase"); + registerType("mysql", "net.codingarea.commons.database.sql.mysql.MySQLDatabase"); + registerType("sqlite", "net.codingarea.commons.database.sql.sqlite.SQLiteDatabase"); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name) { + return ReflectionUtils.getClassOrNull(registry.get(name)); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { + return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); + } + + public static void registerType(@Nonnull String name, @Nonnull String className) { + registry.put(name, className); + } + + public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { + registerType(name, databaseClass.getName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java new file mode 100644 index 000000000..3ef75df74 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.*; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +/** + * Represents a table/collection of a database + * + * @see Database + * @see Database#getSpecificDatabase(String) + */ +public interface SpecificDatabase { + + boolean isConnected(); + + @Nonnull + String getName(); + + /** + * @see Database#countEntries(String) + */ + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(); + + /** + * @see Database#query(String) + */ + @Nonnull + @CheckReturnValue + DatabaseQuery query(); + + /** + * @see Database#update(String) + */ + @Nonnull + @CheckReturnValue + DatabaseUpdate update(); + + /** + * @see Database#insert(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(); + + /** + * @see Database#insertOrUpdate(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(); + + /** + * @see Database#delete(String) + */ + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(); + + @Nonnull + Database getParent(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java new file mode 100644 index 000000000..755ddeedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -0,0 +1,100 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; + +public abstract class AbstractDatabase implements Database { + + protected final DatabaseConfig config; + + public AbstractDatabase(@Nonnull DatabaseConfig config) { + this.config = config; + } + + @Override + public boolean disconnectSafely() { + try { + disconnect(); + LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not disconnect from database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void disconnect() throws DatabaseException { + checkConnection(); + try { + disconnect0(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + protected abstract void disconnect0() throws Exception; + + @Override + public boolean connectSafely() { + try { + connect(); + LOGGER.status("Successfully created connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not connect to database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void connect() throws DatabaseException { + if (isConnected()) throw new DatabaseAlreadyConnectedException(); + try { + connect0(); + } catch (Exception ex) { + if (ex instanceof DatabaseException) throw (DatabaseException) ex; + throw new DatabaseException(ex); + } + } + + protected abstract void connect0() throws Exception; + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + try { + createTable(name, columns); + } catch (DatabaseException ex) { + LOGGER.error("Could not create table (" + this.getClass().getSimpleName() + ")", ex); + } + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + return config; + } + + protected final void checkConnection() throws DatabaseConnectionClosedException { + if (!isConnected()) + throw new DatabaseConnectionClosedException(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "[connected=" + isConnected() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java new file mode 100644 index 000000000..dd437cfb5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java @@ -0,0 +1,124 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.action.ExecutedQuery; + +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +public class DefaultExecutedQuery implements ExecutedQuery { + + protected final List results; + + public DefaultExecutedQuery(@Nonnull List results) { + this.results = results; + } + + @Nonnull + @Override + public Optional first() { + if (results.isEmpty()) return Optional.empty(); + return Optional.ofNullable(results.get(0)); + } + + @Nonnull + @Override + public Optional get(int index) { + if (index >= results.size()) return Optional.empty(); + return Optional.ofNullable(results.get(index)); + } + + @Nonnull + @Override + public Stream all() { + return results.stream(); + } + + @Nonnull + @Override + public > C toCollection(@Nonnull C collection) { + collection.addAll(results); + return collection; + } + + @Nonnull + @Override + public Document[] toArray(@Nonnull IntFunction arraySupplier) { + Document[] array = arraySupplier.apply(size()); + for (int i = 0; i < size(); i++) { + array[i] = results.get(i); + } + return array; + } + + @Override + public int index(@Nonnull Predicate filter) { + int index = 0; + for (Document result : results) { + if (filter.test(result)) + return index; + index++; + } + return -1; + } + + @Override + public boolean isEmpty() { + return results.isEmpty(); + } + + @Override + public boolean isSet() { + return !results.isEmpty(); + } + + @Override + public int size() { + return results.size(); + } + + @Override + public void print(@Nonnull PrintStream out) { + if (results.isEmpty()) { + out.println(""); + return; + } + + int index = 0; + for (Document result : results) { + out.print(index + " | "); + result.forEach((key, value) -> { + out.print(key + " = '" + value + "' "); + }); + out.println(); + index++; + } + } + + @Override + public Iterator iterator() { + return Collections.unmodifiableCollection(results).iterator(); + } + + @Override + public String toString() { + return "ExecutedQuery[size=" + size() + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultExecutedQuery documents = (DefaultExecutedQuery) o; + return Objects.equals(results, documents.results); + } + + @Override + public int hashCode() { + return Objects.hash(results); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java new file mode 100644 index 000000000..52496f6c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java @@ -0,0 +1,90 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.*; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class DefaultSpecificDatabase implements SpecificDatabase { + + protected final Database parent; + protected final String name; + + public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { + this.parent = parent; + this.name = name; + } + + @Override + public boolean isConnected() { + return parent.isConnected(); + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries() { + return parent.countEntries(name); + } + + @Nonnull + @Override + public DatabaseQuery query() { + return parent.query(name); + } + + @Nonnull + @Override + public DatabaseUpdate update() { + return parent.update(name); + } + + @Nonnull + @Override + public DatabaseInsertion insert() { + return parent.insert(name); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate() { + return parent.insertOrUpdate(name); + } + + @Nonnull + @Override + public DatabaseDeletion delete() { + return parent.delete(name); + } + + @Nonnull + @Override + public Database getParent() { + return parent; + } + + @Override + public String toString() { + return "SpecificDatabase[" + name + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultSpecificDatabase that = (DefaultSpecificDatabase) o; + return Objects.equals(parent, that.parent) && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(parent, name); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java new file mode 100644 index 000000000..118141f4e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; + +public class CachedDatabaseAccess extends DirectDatabaseAccess { + + protected final Map cache = new ConcurrentHashMap<>(); + + public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + super(database, config, mapper); + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key, def); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + V cached = cache.get(key); + if (cached != null) return Optional.of(cached); + + return super.getValueOptional(key); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + cache.put(key, value); + super.setValue(key, value); + } + + @Nonnull + public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getString); + } + + @Nonnull + public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); + } + + @Nonnull + public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); + } + + @Nonnull + public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); + } + + @Nonnull + public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Document::getDocument); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java new file mode 100644 index 000000000..9215c50cd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; + +public interface DatabaseAccess { + + @Nullable + V getValue(@Nonnull String key) throws DatabaseException; + + @Nonnull + V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; + + @Nonnull + Optional getValueOptional(@Nonnull String key) throws DatabaseException; + + void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; + + default boolean hasValue(@Nonnull String key) throws DatabaseException { + return getValueOptional(key).isPresent(); + } + + @Nonnull + Database getDatabase(); + + @Nonnull + DatabaseAccessConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java new file mode 100644 index 000000000..824b8bbdd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.database.access; + +import javax.annotation.Nonnull; + +public final class DatabaseAccessConfig { + + private final String table; + private final String keyField; + private final String valueField; + + public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { + this.table = table; + this.keyField = keyField; + this.valueField = valueField; + } + + @Nonnull + public String getTable() { + return table; + } + + @Nonnull + public String getKeyField() { + return keyField; + } + + @Nonnull + public String getValueField() { + return valueField; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java new file mode 100644 index 000000000..e2213d1bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.function.BiFunction; + +public class DirectDatabaseAccess implements DatabaseAccess { + + protected final Database database; + protected final DatabaseAccessConfig config; + protected final BiFunction mapper; + + public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + this.database = database; + this.config = config; + this.mapper = mapper; + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + return getValue0(key).orElse(null); + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + return getValue0(key).orElse(def); + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + return getValue0(key); + } + + @Nonnull + protected Optional getValue0(@Nonnull String key) throws DatabaseException { + return database.query(config.getTable()) + .where(config.getKeyField(), key) + .execute().first() + .map(document -> mapper.apply(document, config.getValueField())); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + database.insertOrUpdate(config.getTable()) + .set(config.getValueField(), value) + .where(config.getKeyField(), key) + .execute(); + } + + @Nonnull + @Override + public Database getDatabase() { + return database; + } + + @Nonnull + @Override + public DatabaseAccessConfig getConfig() { + return config; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java new file mode 100644 index 000000000..da7a8ee61 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.exceptions.UnsignedDatabaseException; + +import javax.annotation.Nonnull; + +/** + * Some action which will be executed on a database. + * + * This action is only prepared. + * + * It will be executed synchronously by calling {@link #execute()}, + * a {@link DatabaseException} will be thrown when something goes from or + * a {@link DatabaseConnectionClosedException} will be thrown + * when the connection to the database is already closed. + * + * It will also be executed synchronously by calling {@link #executeUnsigned()} but this method has no signed exceptions ({@code throws} declaration), + * so when an exception occurs it will be rethrown as a {@link UnsignedDatabaseException}. + * + * Calling {@link #executeAsync()} will return a new {@link Task} which will complete when the action is done or fail if something went wrong (a {@link DatabaseException} was thrown). + * + * @param The type of the result this action will return + * + * @see WhereAction + * @see SetAction + * @see OrderedAction + * + * @see DatabaseListTables + * @see DatabaseCountEntries + * @see DatabaseDeletion + * @see DatabaseUpdate + * @see DatabaseInsertion + * @see DatabaseInsertionOrUpdate + * @see DatabaseQuery + */ +public interface DatabaseAction { + + /** + * Executes this action synchronously + * + * @return the result of type {@link R} returned by the database + * + * @throws DatabaseException + * If a database error occurs + * @throws DatabaseConnectionClosedException + * If the database is no longer connected + */ + R execute() throws DatabaseException; + + /** + * Executes this action synchronously without any signed exceptions + * + * @return the result of type {@link R} returned by the database + * + * @throws UnsignedDatabaseException + * If a database error occurs + */ + default R executeUnsigned() { + try { + return execute(); + } catch (DatabaseException ex) { + throw new UnsignedDatabaseException(ex); + } + } + + /** + * Executes this action asynchronous + * + * @return a new {@link Task} which will be completed when the action was executed + */ + @Nonnull + default Task executeAsync() { + return Task.asyncCall(this::execute); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java new file mode 100644 index 000000000..70bedb389 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Database#countEntries(String) + * @see SpecificDatabase#countEntries() + */ +public interface DatabaseCountEntries extends DatabaseAction { + + @Nonnull + @Override + @Nonnegative + Long execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java new file mode 100644 index 000000000..3c3b20fe1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#delete(String) + * @see SpecificDatabase#delete() + */ +public interface DatabaseDeletion extends DatabaseAction, WhereAction { + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java new file mode 100644 index 000000000..ef0d7b8ca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insert(String) + * @see SpecificDatabase#insert() + */ +public interface DatabaseInsertion extends DatabaseAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseInsertion set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java new file mode 100644 index 000000000..000f76a09 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java @@ -0,0 +1,45 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insertOrUpdate(String) + * @see SpecificDatabase#insertOrUpdate() + */ +public interface DatabaseInsertionOrUpdate extends DatabaseUpdate, DatabaseInsertion { + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java new file mode 100644 index 000000000..be7173659 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import java.util.List; + +/** + * @see Database#listTables() + */ +public interface DatabaseListTables extends DatabaseAction> { + + @Nonnull + @Override + List execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java new file mode 100644 index 000000000..770b8b542 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#query(String) + * @see SpecificDatabase#query() + */ +public interface DatabaseQuery extends DatabaseAction, WhereAction, OrderedAction { + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Object object); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseQuery select(@Nonnull String... selection); + + @Nonnull + @CheckReturnValue + DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); + + @Nonnull + @Override + @CheckReturnValue + ExecutedQuery execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java new file mode 100644 index 000000000..83073b113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#update(String) + * @see SpecificDatabase#update() + */ +public interface DatabaseUpdate extends DatabaseAction, WhereAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java new file mode 100644 index 000000000..37cf98630 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java @@ -0,0 +1,86 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * @see DatabaseQuery#execute() + */ +public interface ExecutedQuery extends Iterable { + + @Nonnull + @CheckReturnValue + Optional first(); + + @Nonnull + @CheckReturnValue + default Document firstOrEmpty() { + return first().orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Optional get(int index); + + @Nonnull + @CheckReturnValue + default Document getOrEmpty(int index) { + return get(index).orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Stream all(); + + @Nonnull + @CheckReturnValue + default List toList() { + return toCollection((IntFunction>) ArrayList::new); + } + + @Nonnull + @CheckReturnValue + default Set toSet() { + return toCollection((IntFunction>) HashSet::new); + } + + @Nonnull + > C toCollection(@Nonnull C collection); + + @Nonnull + @CheckReturnValue + default > C toCollection(@Nonnull IntFunction collectionSupplier) { + return toCollection(collectionSupplier.apply(size())); + } + + @Nonnull + Document[] toArray(@Nonnull IntFunction arraySupplier); + + int index(@Nonnull Predicate filter); + + boolean isEmpty(); + + boolean isSet(); + + int size(); + + void print(@Nonnull PrintStream out); + + default void print(@Nonnull ILogger logger) { + print(logger.asPrintStream(LogLevel.INFO)); + } + + default void print() { + print(System.out); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java new file mode 100644 index 000000000..edfdc29b1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.action.hierarchy; + +import net.codingarea.commons.database.Order; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface OrderedAction { + + @Nullable + OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java new file mode 100644 index 000000000..cb395773b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface SetAction { + + @Nonnull + SetAction set(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java new file mode 100644 index 000000000..5e5d69c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface WhereAction { + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + WhereAction whereNot(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java new file mode 100644 index 000000000..192f891f6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception in thrown, when a database tries to connect but is already connected. + */ +public class DatabaseAlreadyConnectedException extends DatabaseException { + + public DatabaseAlreadyConnectedException() { + super("Database already connected"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java new file mode 100644 index 000000000..f3563f241 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception is thrown, when a database operation is tried which requires a active connection, but the database is not connected. + */ +public class DatabaseConnectionClosedException extends DatabaseException { + + public DatabaseConnectionClosedException() { + super("Database connection closed"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java new file mode 100644 index 000000000..d42805661 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseAlreadyConnectedException + * @see DatabaseConnectionClosedException + * @see DatabaseUnsupportedFeatureException + * + * @see DatabaseAction#execute() + */ +public class DatabaseException extends Exception { + + protected DatabaseException() { + super(); + } + + public DatabaseException(@Nonnull String message) { + super(message); + } + + public DatabaseException(@Nonnull Throwable cause) { + super(cause); + } + + public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { + super(message, cause); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java new file mode 100644 index 000000000..0f57f6827 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.database.exceptions; + +import javax.annotation.Nonnull; + +public class DatabaseUnsupportedFeatureException extends DatabaseException { + + public DatabaseUnsupportedFeatureException() { + } + + public DatabaseUnsupportedFeatureException(@Nonnull String message) { + super(message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java new file mode 100644 index 000000000..a5f96d5f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java @@ -0,0 +1,24 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseException + * + * @see DatabaseAction#executeUnsigned() + */ +public class UnsignedDatabaseException extends WrappedException { + + public UnsignedDatabaseException(@Nonnull DatabaseException cause) { + super(cause); + } + + @Nonnull + @Override + public DatabaseException getCause() { + return (DatabaseException) super.getCause(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java new file mode 100644 index 000000000..10887b6c3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.sql.abstraction.count.SQLCountEntries; +import net.codingarea.commons.database.sql.abstraction.deletion.SQLDeletion; +import net.codingarea.commons.database.sql.abstraction.insertion.SQLInsertion; +import net.codingarea.commons.database.sql.abstraction.insertorupdate.SQLInsertionOrUpdate; +import net.codingarea.commons.database.sql.abstraction.query.SQLQuery; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public abstract class AbstractSQLDatabase extends AbstractDatabase { + + protected Connection connection; + + public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void disconnect0() throws Exception { + connection.close(); + connection = null; + } + + @Override + public void connect0() throws Exception { + connection = DriverManager.getConnection(createUrl(), config.getUser(), config.getPassword()); + } + + protected abstract String createUrl(); + + @Override + public boolean isConnected() { + try { + if (connection == null) return false; + connection.isClosed(); + return true; + } catch (SQLException ex) { + LOGGER.error("Could not check connection state: " + ex.getMessage()); + return false; + } + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + try { + StringBuilder command = new StringBuilder(); + command.append("CREATE TABLE IF NOT EXISTS `"); + command.append(name); + command.append("` ("); + { + int index = 0; + for (SQLColumn column : columns) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(")"); + + PreparedStatement statement = prepare(command.toString()); + statement.execute(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new SQLCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new SQLQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new SQLQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new SQLUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new SQLInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new SQLInsertion(this, table, values); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new SQLInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new SQLDeletion(this, table); + } + + @Nonnull + public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { + checkConnection(); + PreparedStatement statement = connection.prepareStatement(command.toString()); + SQLHelper.fillParams(statement, args); + return statement; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java new file mode 100644 index 000000000..9fdf86b6c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public final class SQLHelper { + + private SQLHelper() {} + + public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + Object param = serializeObject(params[i]); + statement.setObject(i + 1 /* in sql we count from 1 */, param); + } + } + + @Nullable + public static Object serializeObject(@Nullable Object object) { + if (object == null) return null; + if (object instanceof Number) return object; + if (object instanceof Boolean) return object; + if (object instanceof Enum) return ((Enum)object).name(); + if (object instanceof Json) return ((Json)object).toJson(); + if (object instanceof Map) return new GsonDocument((Map) object).toJson(); + if (object instanceof Iterable) return GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, (Iterable) object).toString(); + if (object.getClass().isArray()) return GsonUtils.convertArrayToJsonArray(GsonDocument.GSON, object).toString(); + return object.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java new file mode 100644 index 000000000..dbf6aa821 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java @@ -0,0 +1,54 @@ +package net.codingarea.commons.database.sql.abstraction.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Objects; + +public class SQLCountEntries implements DatabaseCountEntries { + + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT COUNT(*) FROM `" + table + "`"); + ResultSet result = statement.executeQuery(); + + if (!result.next()) { + result.close(); + return 0L; + } + + long count = result.getLong(1); + result.close(); + return count; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLCountEntries that = (SQLCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java new file mode 100644 index 000000000..d1dfeaf9b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database.sql.abstraction.deletion; + +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLDeletion implements DatabaseDeletion { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where = new HashMap<>(); + + public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("DELETE FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(),args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLDeletion that = (SQLDeletion) o; + return database.equals(that.database) && table.equals(that.table) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java new file mode 100644 index 000000000..6af25eaa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java @@ -0,0 +1,95 @@ +package net.codingarea.commons.database.sql.abstraction.insertion; + +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; + +public class SQLInsertion implements DatabaseInsertion { + + protected final Map values; + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.values = new HashMap<>(); + } + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { + this.database = database; + this.table = table; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(values.size()); + + command.append("INSERT INTO "); + command.append(table); + command.append(" ("); + { + int index = 0; + for (String column : values.keySet()) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(") VALUES ("); + { + int index = 0; + for (Object value : values.values()) { + if (index > 0) command.append(", "); + command.append("?"); + args.add(value); + index++; + } + } + command.append(")"); + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLInsertion that = (SQLInsertion) o; + return values.equals(that.values) && database.equals(that.database) && table.equals(that.table); + } + + @Override + public int hashCode() { + return Objects.hash(values, database, table); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java new file mode 100644 index 000000000..f89cbc135 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.sql.abstraction.insertorupdate; + +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class SQLInsertionOrUpdate extends SQLUpdate implements DatabaseInsertionOrUpdate { + + public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + super(database, table); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { + super.whereNot(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { + super.set(column, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(table, where).execute().isSet()) { + return super.execute(); + } else { + Map insert = new HashMap<>(values); + for (Entry entry : where.entrySet()) { + Object[] args = entry.getValue().getArgs(); + if (args.length == 0) continue; + insert.put(entry.getKey(), args[0]); + } + + database.insert(table, insert).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java new file mode 100644 index 000000000..75536fe81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -0,0 +1,176 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLQuery implements DatabaseQuery { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected String[] selection = { "*" }; + protected String orderBy; + protected Order order; + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + } + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { + this.database = database; + this.table = table; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); + this.selection = selection; + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new LinkedList<>(); + + command.append("SELECT "); + for (int i = 0; i < selection.length; i++) { + if (i > 0) command.append(", "); + command.append(selection[i]); + } + command.append(" FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + if (orderBy != null) { + command.append(" ORDER BY "); + command.append(orderBy); + if (order != null) + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" "); + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + ResultSet result = statement.executeQuery(); + return createExecutedQuery(result); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { + List results = new ArrayList<>(); + ResultSetMetaData data = result.getMetaData(); + while (result.next()) { + Map map = new HashMap<>(); + for (int i = 1; i <= data.getColumnCount(); i++) { + Object value = result.getObject(i); + map.put(data.getColumnLabel(i), value); + } + Document row = new SQLResult(map); + results.add(row); + } + result.close(); + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLQuery sqlQuery = (SQLQuery) o; + return database.equals(sqlQuery.database) && table.equals(sqlQuery.table) && where.equals(sqlQuery.where) && Arrays.equals(selection, sqlQuery.selection) && Objects.equals(orderBy, sqlQuery.orderBy) && order == sqlQuery.order; + } + + @Override + public int hashCode() { + int result = Objects.hash(database, table, where, orderBy, order); + result = 31 * result + Arrays.hashCode(selection); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java new file mode 100644 index 000000000..2d6536855 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.MapDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; + +public final class SQLResult extends MapDocument { + + public SQLResult(@Nonnull Map values) { + super(values); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + try { + return new GsonDocument(getString(path), this, this).readonly(); + } catch (Exception ex) { + return new EmptyDocument(this, null); + } + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java new file mode 100644 index 000000000..d3b4cd844 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -0,0 +1,140 @@ +package net.codingarea.commons.database.sql.abstraction.update; + +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLUpdate implements DatabaseUpdate { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected final Map values; + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.table = table; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { + values.put(column, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("UPDATE "); + command.append(table); + command.append(" SET "); + + { + int index = 0; + for (Entry entry : values.entrySet()) { + if (index > 0) command.append(", "); + command.append("`" + entry.getKey() + "` = ?"); + args.add(entry.getValue()); + index++; + } + } + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.executeUpdate(); + return null; + } catch (SQLException ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLUpdate sqlUpdate = (SQLUpdate) o; + return database.equals(sqlUpdate.database) && table.equals(sqlUpdate.table) && where.equals(sqlUpdate.where) && values.equals(sqlUpdate.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where, values); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java new file mode 100644 index 000000000..f398190fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class ObjectWhere implements SQLWhere { + + protected final String column; + protected final Object value; + protected final String comparator; + + public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { + this.column = column; + this.value = value; + this.comparator = comparator; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("`%s` %s ?", column, comparator); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return column.equals(that.column) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java new file mode 100644 index 000000000..a16075f93 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; + +public interface SQLWhere { + + @Nonnull + Object[] getArgs(); + + @Nonnull + String getAsSQLString(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..7a3fe07b6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements SQLWhere { + + protected final String column; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { + this.column = column; + this.value = value; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("LOWER(%s) = LOWER(?)", column); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return column.equals(that.column) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java new file mode 100644 index 000000000..627b39e20 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.database.sql.mysql; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.list.MySQLListTables; + +import javax.annotation.Nonnull; + +public class MySQLDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load mysql driver"); + } + } + + public MySQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Nonnull + @Override + protected String createUrl() { + return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MySQLListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java new file mode 100644 index 000000000..2d60ee58b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.mysql.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class MySQLListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public MySQLListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SHOW TABLES"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java new file mode 100644 index 000000000..70fbe6953 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.sql.sqlite; + +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.sqlite.list.SQLiteListTables; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.IOException; + +public class SQLiteDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load sqlite driver"); + } + } + + protected final File file; + + public SQLiteDatabase(@Nonnull DatabaseConfig config) { + super(config); + file = new File(config.getFile()); + } + + @Override + public void connect() throws DatabaseException { + try { + FileUtils.createFilesIfNecessary(file); + } catch (IOException ex) { + throw new DatabaseException(ex); + } + + super.connect(); + } + + @Override + protected String createUrl() { + return "jdbc:sqlite:" + file; + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new SQLiteListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java new file mode 100644 index 000000000..f7a4c48d6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.sqlite.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class SQLiteListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index e8148167a..02be209b6 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -22,21 +22,9 @@ # The config-version is even with the version of the default config. # You will be notified, when this version is older than the of the default in the plugin jar. # We recommend regenerating the config to get access to new features / settings. -config-version: "2.2.0" - -# Currently supported by default -# - en (English) -# - de (German / Deutsch) -language: "de" - -# Makes text from the plugin appear in the 'small caps' font -# Example: ᴛʜɪs ɪs sᴍᴀʟʟ ᴄᴀᴘs -small-caps: false +config-version: "2.4" timer: - stopped-message: "§8• §7Timer §c§lpaused §8•" - count-up-message: "§8• §7Time: §a§l{time} §8•" - count-down-message: "§8• §7Time: §c§l{time} §8•" format: seconds: "{mm}:{ss}" minutes: "{mm}:{ss}" @@ -162,10 +150,6 @@ no-stats-after-cheating: false # - Will download languages from github development branch (https://github.com/anweisen/Challenges/tree/development). dev-mode: false -# Set a path to a json language file on your computer to use the translations out of this file. -# Useful when developing with the plugin -# direct-language-file: C:\PathToWorkDic\Challenges\language\files\de.json - database: # Available database types: # - mysql diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 4d1e61547..c331983af 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: Challenges -version: 2.3.2 +version: 2.3.3 author: CodingArea authors: - anweisen @@ -224,4 +224,11 @@ commands: description: "Disable damage for a player" permission: "challenges.godmode" aliases: - - "god" \ No newline at end of file + - "god" + setlanguage: + usage: "/setlanguage [language]" + description: "Changes the language" + permission: "challenges.setlanguage" + aliases: + - "setlang" + - "language" \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7ebbd174f..810fb27fb 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 pom root https://github.com/anweisen/Challenges @@ -17,8 +17,7 @@ - 1.3.15 - 1.21-R0.1-SNAPSHOT + 1.21.4-R0.1-SNAPSHOT diff --git a/qodana.yml b/qodana.yml index 31e254679..d017ce4c4 100644 --- a/qodana.yml +++ b/qodana.yml @@ -1,4 +1,5 @@ version: "1.0" -failThreshold: 999 +#linter: jetbrains/qodana-jvm-community:2024.3 +fixesStrategy: apply profile: - name: qodana.starter + name: qodana.recommended