Compare commits

..

No commits in common. "develop" and "1.0.0" have entirely different histories.

44 changed files with 5422 additions and 11728 deletions

View File

@ -11,22 +11,21 @@ jobs:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 17
uses: actions/setup-java@v3
- name: Set up JDK 16
uses: actions/setup-java@v1
with:
distribution: 'adopt'
java-version: 17
java-version: 16
- name: Cache SonarCloud packages
uses: actions/cache@v3
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v3
uses: actions/cache@v1
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
@ -35,4 +34,4 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar

6
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,6 @@
Contributions are welcome but acceptance is completely up to tastybento. Do not be offended if your contribution is rejected.
I will not accept any contributions that are formatting only, or mostly formatting.
Automated code cleanup is also not a valid contribution as a first Pull Request. If a tool is doing your job,
the submit an issue that recommends we use a specific tool.
Contributions are accepted under the license terms and conditions. Note that this means we may use them elsewhere.
Thank you!

5
PULL_REQUEST_TEMPLATE.md Normal file
View File

@ -0,0 +1,5 @@
Thanks for submitting a pull request. Do not use this form for bug reports!
Your submission must meet the minimum requirements of a contribution, i.e., add code, refactor code or fix code.
It takes time and effort to review submissions, so please do not waste our time.
Note: formatting/spacing-only submissions will be rejected!
For submissions, we want you to use spaces, not tabs (4 spaces) - thank you.

View File

@ -2,9 +2,24 @@
[![Discord](https://img.shields.io/discord/272499714048524288.svg?logo=discord)](https://discord.bentobox.world)
[![Build Status](https://ci.codemc.org/buildStatus/icon?job=BentoBoxWorld/Challenges)](https://ci.codemc.org/job/BentoBoxWorld/job/Challenges/)
Add-on for BentoBox to provide challenges for any BentoBox GameMode. Challenges can be to collect items, to have items or blocks nearby, to amass an amount of money or island levels, or to have accomplished some player statistic. Each challenge can reward the player with money, experience points, blocks, items, or other things, like permissions, Pre-built challenges are available and there is also a Web Library of pre-built ones. Customize them to fit your needs!
Add-on for BentoBox to provide challenges for any BentoBox GameMode.
![Challenges](https://github.com/BentoBoxWorld/Challenges/assets/4407265/9b3c5278-3a9d-45f2-9ee1-2c1fc1199a8d)
## Where to find
Currently Challenges Addon is in **Beta stage**, so it may or may not contain bugs... a lot of bugs. Also it means, that some features are not working or implemented.
Latest official **Beta Release is 0.8.3**, and you can download it from [Release tab](https://github.com/BentoBoxWorld/Challenges/releases)
But it will work with BentoBox 1.14.
Latest development builds will be based on **Minecraft 1.16.1** and **BentoBox 1.14.0**.
**Nightly builds** are available in [Jenkins Server](https://ci.codemc.org/job/BentoBoxWorld/job/Challenges/lastStableBuild/).
If you like this addon but something is missing or is not working as you want, you can always submit an [Issue request](https://github.com/BentoBoxWorld/Challenges/issues) or get a support in Discord [BentoBox ![icon](https://avatars2.githubusercontent.com/u/41555324?s=15&v=4)](https://discord.bentobox.world)
## Translations
As most of BentoBox projects, Challenges Addon is translatable in any language. Everyone can contribute, and translate some parts of the addon in their language via [GitLocalize](https://gitlocalize.com/repo/2896).
If your language is not in the list, please contact to developers via Discord and it will be added there.
Unfortunately, default challenges come only in English translation. But with version 0.8.0 there will be access to different challenges libraries, where everyone could share their challenges with their translations. More information will come soon.
## How to use
@ -12,32 +27,21 @@ Add-on for BentoBox to provide challenges for any BentoBox GameMode. Challenges
2. Restart the server
3. Edit the config.yml how you want.
4. Restart the server
5. Run the Admin challenges command to set up challenges for your game mode.
#### Installation
#### Challenges
By default, challenges addon comes without any challenge or level. On first run time only Admin GUI will be accessible.
Admins can create their own challenges or import some default challenges. Default challenges contains 5 levels and 57 challenges.
There also exists a Web Library, where admins can download public challenges. It is accessible from the Admin GUI by clicking on the Web icon.
By default, challenges addon comes without any challenge or level. On first runtime only Admin GUI will be accessible.
Admins can create their own challenges or import some default challenges, which importing also are available via Admin GUI. Default challenges contains 5 levels and 57 challenges.
There exist also Web Library, where users can download public challenges. It is accessible with Admin GUI by clicking on Web icon.
## Compatibility
- [x] BentoBok
- [x] BentoBox - 1.14 versions
- [x] BSkyBlock
- [x] AcidIsland
- [x] SkyGrid
- [x] CaveBlock
## Translations
As with most of BentoBox projects, Challenges Addon is translatable into any language. Everyone can contribute, and translate some parts of the addon in their language via [GitLocalize](https://gitlocalize.com/repo/2896).
If your language is not in the list, please contact the developers via Discord and it will be added there.
Unfortunately, default challenges come only be in English, but there are different challenges libraries where everyone can share their challenges with their translations.
## Documentation
More information can be found in the docs: https://docs.bentobox.world/en/latest/addons/Challenges/
## Bugs or feature requests
If you like this addon but something is missing or is not working as you want, you can always submit an [Issue request](https://github.com/BentoBoxWorld/Challenges/issues) or get a support in Discord [BentoBox ![icon](https://avatars2.githubusercontent.com/u/41555324?s=15&v=4)](https://discord.bentobox.world)
## Information
More information can be found in [Wiki Pages](https://docs.bentobox.world/en/latest/addons/Challenges/).

106
pom.xml
View File

@ -32,19 +32,19 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>17</java.version>
<java.version>16</java.version>
<powermock.version>2.0.9</powermock.version>
<!-- More visible way how to change dependency versions -->
<spigot.version>1.20.4-R0.1-SNAPSHOT</spigot.version>
<spigot.version>1.17.1-R0.1-SNAPSHOT</spigot.version>
<spigot-annotations.version>1.2.3-SNAPSHOT</spigot-annotations.version>
<bentobox.version>2.1.0</bentobox.version>
<bentobox.version>1.20.0</bentobox.version>
<level.version>2.6.3</level.version>
<vault.version>1.7</vault.version>
<panelutils.version>1.2.0</panelutils.version>
<panelutils.version>1.0.0</panelutils.version>
<!-- Revision variable removes warning about dynamic version -->
<revision>${build.version}-SNAPSHOT</revision>
<!-- This allows to change between versions and snapshots. -->
<build.version>1.3.0</build.version>
<build.version>1.0.0</build.version>
<build.number>-LOCAL</build.number>
<!-- Sonar Cloud -->
<sonar.projectKey>BentoBoxWorld_Challenges</sonar.projectKey>
@ -120,12 +120,6 @@
</repositories>
<dependencies>
<!-- This is required for PowerMockito to work and must be placed before it -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.30.2-GA</version>
</dependency>
<!-- Spigot API -->
<dependency>
<groupId>org.spigotmc</groupId>
@ -133,6 +127,12 @@
<version>${spigot.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>plugin-annotations</artifactId>
<version>1.2.3-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Vault API -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
@ -193,11 +193,6 @@
<version>1.5.21</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
</dependencies>
<build>
@ -228,38 +223,6 @@
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.1-SNAPSHOT</version>
<configuration>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>lv.id.bonne:panelutils:*</include>
</includes>
</artifactSet>
<transformers>
<!-- Add a transformer to exclude any other manifest files (possibly from dependencies). -->
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>MANIFEST.MF</resource>
</transformer>
<!-- Add a transformer to include your custom manifest file. -->
<transformer implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer">
<resource>META-INF/MANIFEST.MF</resource>
<file>src/main/resources/META-INF/MANIFEST.MF</file>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
@ -286,7 +249,6 @@
<version>3.0.0-M5</version>
<configuration>
<argLine>
${argLine}
--add-opens java.base/java.lang=ALL-UNNAMED
--add-opens java.base/java.math=ALL-UNNAMED
--add-opens java.base/java.io=ALL-UNNAMED
@ -368,35 +330,59 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.10</version>
<version>0.8.4</version>
<configuration>
<append>true</append>
<excludes>
<!-- This is required to prevent Jacoco from adding
synthetic fields to a JavaBean class (causes errors in testing) -->
<exclude>**/*Names*</exclude>
<!-- Prevents the Material is too large to mock error -->
<exclude>org/bukkit/Material*</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>prepare-agent</id>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<id>post-unit-test</id>
<goals>
<goal>report</goal>
</goals>
<configuration>
<formats>
<format>XML</format>
</formats>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.1-SNAPSHOT</version>
<configuration>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>lv.id.bonne:panelutils:*</include>
</includes>
</artifactSet>
<transformers>
<!-- Add a transformer to exclude any other manifest files (possibly from dependencies). -->
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>MANIFEST.MF</resource>
</transformer>
<!-- Add a transformer to include your custom manifest file. -->
<transformer implementation="org.apache.maven.plugins.shade.resource.IncludeResourceTransformer">
<resource>META-INF/MANIFEST.MF</resource>
<file>src/main/resources/META-INF/MANIFEST.MF</file>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>

View File

@ -408,18 +408,8 @@ public class ChallengesAddon extends Addon {
addonName + "_latest_level_uncompleted_count",
user -> {
ChallengeLevel level = this.challengesManager.getLatestUnlockedLevel(user, world);
if (level == null)
{
return "0";
}
int challengeCount = this.getChallengesSettings().isIncludeUndeployed() ?
level.getChallenges().size() :
this.challengesManager.getLevelChallenges(level, false).size();
return String.valueOf(challengeCount -
this.challengesManager.getLevelCompletedChallengeCount(user, world, level));
return String.valueOf(level != null ?
level.getChallenges().size() - this.challengesManager.getLevelCompletedChallengeCount(user, world, level) : 0);
});
}

View File

@ -7,12 +7,19 @@
package world.bentobox.challenges;
import org.bukkit.plugin.java.annotation.dependency.Dependency;
import org.bukkit.plugin.java.annotation.plugin.ApiVersion;
import org.bukkit.plugin.java.annotation.plugin.Plugin;
import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.addons.Pladdon;
/**
* @author tastybento
*/
@Plugin(name="Pladdon", version="1.0")
@ApiVersion(ApiVersion.Target.v1_17)
@Dependency(value = "BentoBox")
public class ChallengesPladdon extends Pladdon
{
@Override
@ -20,4 +27,4 @@ public class ChallengesPladdon extends Pladdon
{
return new ChallengesAddon();
}
}
}

View File

@ -55,7 +55,7 @@ public class ChallengesGlobalPlayerCommand extends CompositeCommand
if (this.gameModeAddons.isEmpty())
{
Utils.sendMessage(user, user.getWorld(), Constants.ERRORS + "not-hooked");
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "not-hooked"));
return false;
}
else if (this.gameModeAddons.size() == 1)
@ -80,7 +80,7 @@ public class ChallengesGlobalPlayerCommand extends CompositeCommand
}
}
Utils.sendMessage(user, user.getWorld(), "general.errors.wrong-world");
Utils.sendMessage(user, user.getTranslation("general.errors.wrong-world"));
}
else if (this.<ChallengesAddon>getAddon().getChallengesSettings().getUserGuiMode() == GuiMode.GAMEMODE_LIST)
{

View File

@ -8,7 +8,6 @@ import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.util.Util;
import world.bentobox.challenges.ChallengesAddon;
import world.bentobox.challenges.panel.user.ChallengesPanel;
import world.bentobox.challenges.utils.Constants;
import world.bentobox.challenges.utils.Utils;
@ -32,7 +31,7 @@ public class ChallengesPlayerCommand extends CompositeCommand
if (!this.getIWM().inWorld(user.getWorld()) ||
!Util.sameWorld(this.getWorld(), user.getWorld())) {
// Not a GameMode world.
Utils.sendMessage(user, user.getWorld(), "general.errors.wrong-world");
Utils.sendMessage(user, user.getTranslation("general.errors.wrong-world"));
return false;
}
@ -48,13 +47,13 @@ public class ChallengesPlayerCommand extends CompositeCommand
map(GameModeAddon::getAdminCommand).
map(optionalAdminCommand -> optionalAdminCommand.map(CompositeCommand::getTopLabel).orElse(this.getTopLabel())).
orElse(this.getTopLabel());
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-challenges-admin",
Utils.sendMessage(user, user.getTranslation("challenges.errors.no-challenges-admin",
"[command]",
topLabel + " " + this.<ChallengesAddon>getAddon().getChallengesSettings().getAdminMainCommand().split(" ")[0]);
topLabel + " " + this.<ChallengesAddon>getAddon().getChallengesSettings().getAdminMainCommand().split(" ")[0]));
}
else
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-challenges");
Utils.sendMessage(user, user.getTranslation("challenges.errors.no-challenges"));
}
return false;
@ -63,14 +62,14 @@ public class ChallengesPlayerCommand extends CompositeCommand
if (this.getIslands().getIsland(this.getWorld(), user) == null)
{
// Do not open gui if there is no island for this player.
Utils.sendMessage(user, this.getWorld(), "general.errors.no-island");
Utils.sendMessage(user, user.getTranslation("general.errors.no-island"));
return false;
} else if (ChallengesAddon.CHALLENGES_WORLD_PROTECTION.isSetForWorld(this.getWorld()) &&
!this.getIslands().locationIsOnIsland(user.getPlayer(), user.getLocation()))
{
// Do not open gui if player is not on the island, but challenges requires island for
// completion.
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "not-on-island");
Utils.sendMessage(user, user.getTranslation("challenges.errors.not-on-island"));
return false;
}

View File

@ -11,7 +11,6 @@ import world.bentobox.bentobox.util.Util;
import world.bentobox.challenges.ChallengesAddon;
import world.bentobox.challenges.database.object.Challenge;
import world.bentobox.challenges.tasks.TryToComplete;
import world.bentobox.challenges.utils.Constants;
import world.bentobox.challenges.utils.Utils;
@ -55,7 +54,7 @@ public class CompleteChallengeCommand extends CompositeCommand
{
if (args.isEmpty())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-name");
Utils.sendMessage(user, user.getTranslation("challenges.errors.no-name"));
this.showHelp(this, user);
return false;
}
@ -74,7 +73,7 @@ public class CompleteChallengeCommand extends CompositeCommand
if (!canMultipleTimes && count > 1)
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-multiple-permission");
Utils.sendMessage(user, user.getTranslation("challenges.error.no-multiple-permission"));
count = 1;
}
@ -88,7 +87,7 @@ public class CompleteChallengeCommand extends CompositeCommand
}
else
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "unknown-challenge");
Utils.sendMessage(user, user.getTranslation("challenges.errors.unknown-challenge"));
this.showHelp(this, user);
return false;
}

View File

@ -37,7 +37,7 @@ public class ChallengesGlobalAdminCommand extends CompositeCommand
@Override
public void setup()
{
this.setPermission("admin.challenges");
this.setPermission("addon.admin.challenges");
this.setParametersHelp("challenges.commands.admin.main.parameters");
this.setDescription("challenges.commands.admin.main.description");
}
@ -53,7 +53,7 @@ public class ChallengesGlobalAdminCommand extends CompositeCommand
if (this.gameModeAddons.isEmpty())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "not-hooked");
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "not-hooked"));
return false;
}
else if (this.gameModeAddons.size() == 1)

View File

@ -56,7 +56,7 @@ public class CompleteCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-name");
Utils.sendMessage(user, user.getTranslation("challenges.errors.no-name"));
}
else
{
@ -67,7 +67,7 @@ public class CompleteCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "missing-arguments");
Utils.sendMessage(user, user.getTranslation("challenges.errors.missing-arguments"));
}
else
{
@ -82,11 +82,9 @@ public class CompleteCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
"general.errors.unknown-player",
Utils.sendMessage(user, user.getTranslation("general.errors.unknown-player",
TextVariables.NAME,
args.get(0));
args.get(0)));
}
else
{
@ -111,11 +109,9 @@ public class CompleteCommand extends CompositeCommand
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.MESSAGES + "completed",
Utils.sendMessage(user, user.getTranslation("challenges.messages.completed",
Constants.PARAMETER_NAME, challenge.getFriendlyName(),
Constants.PARAMETER_PLAYER, target.getName());
Constants.PARAMETER_PLAYER, target.getName()));
}
else
{
@ -127,9 +123,7 @@ public class CompleteCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.MESSAGES + "already-completed");
Utils.sendMessage(user, user.getTranslation("challenges.messages.already-completed"));
}
else
{
@ -143,9 +137,7 @@ public class CompleteCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.ERRORS + "unknown-challenge");
Utils.sendMessage(user, user.getTranslation("challenges.errors.unknown-challenge"));
}
else
{

View File

@ -49,13 +49,13 @@ public class ReloadChallenges extends CompositeCommand
if (args.isEmpty())
{
this.manager.load();
Utils.sendMessage(user, this.getWorld(), "general.success");
Utils.sendMessage(user, user.getTranslation("general.success"));
return true;
}
else if (args.get(0).equalsIgnoreCase("hard"))
{
this.manager.reload();
Utils.sendMessage(user, this.getWorld(), "general.success");
Utils.sendMessage(user, user.getTranslation("general.success"));
return true;
}
else

View File

@ -56,7 +56,7 @@ public class ResetCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "no-name");
Utils.sendMessage(user, user.getTranslation("challenges.errors.no-name"));
}
else
{
@ -67,7 +67,7 @@ public class ResetCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user, this.getWorld(), Constants.ERRORS + "missing-arguments");
Utils.sendMessage(user, user.getTranslation("challenges.errors.missing-arguments"));
}
else
{
@ -82,11 +82,8 @@ public class ResetCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.ERRORS + "unknown-player",
TextVariables.NAME,
args.get(0));
Utils.sendMessage(user, user.getTranslation("general.errors.unknown-player",
TextVariables.NAME, args.get(0)));
}
else
{
@ -105,11 +102,8 @@ public class ResetCommand extends CompositeCommand
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.MESSAGES + "reset-all",
Constants.PARAMETER_PLAYER,
target.getName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.reset-all",
Constants.PARAMETER_PLAYER, target.getName()));
}
else
{
@ -131,11 +125,9 @@ public class ResetCommand extends CompositeCommand
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.MESSAGES + "reset",
Utils.sendMessage(user, user.getTranslation("challenges.messages.reset",
Constants.PARAMETER_NAME, challenge.getFriendlyName(),
Constants.PARAMETER_PLAYER, target.getName());
Constants.PARAMETER_PLAYER, target.getName()));
}
else
{
@ -147,9 +139,7 @@ public class ResetCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.MESSAGES + "not-completed");
Utils.sendMessage(user, user.getTranslation("challenges.messages.not-completed"));
}
else
{
@ -163,9 +153,7 @@ public class ResetCommand extends CompositeCommand
{
if (user.isPlayer())
{
Utils.sendMessage(user,
this.getWorld(),
Constants.ERRORS + "unknown-challenge");
Utils.sendMessage(user, user.getTranslation("challenges.errors.unknown-challenge"));
}
else
{

View File

@ -106,10 +106,11 @@ public class Settings implements ConfigObject
@ConfigComment("Valid values are:")
@ConfigComment(" 'VISIBLE' - there will be no hidden challenges. All challenges will be viewable in GUI.")
@ConfigComment(" 'HIDDEN' - shows only deployed challenges.")
@ConfigComment(" 'TOGGLEABLE' - there will be button in GUI that allows users to switch from ALL modes.")
@ConfigComment("TOGGLEABLE - Currently not implemented.")
@ConfigEntry(path = "gui-settings.undeployed-view-mode")
private VisibilityMode visibilityMode = VisibilityMode.VISIBLE;
@ConfigComment("")
@ConfigComment("This allows to change default locked level icon. This option may be")
@ConfigComment("overwritten by each challenge level. If challenge level has specified")
@ -129,13 +130,6 @@ public class Settings implements ConfigObject
@ConfigEntry(path = "reset-challenges")
private boolean resetChallenges = true;
@ConfigComment("")
@ConfigComment("This option indicates if undepolyed challenges should be counted to level completion.")
@ConfigComment("Disabling this option will make it so that only deployed challenges will be counted.")
@ConfigComment("Default: true")
@ConfigEntry(path = "include-undeployed")
private boolean includeUndeployed = true;
@ConfigComment("")
@ConfigComment("Broadcast 1st time challenge completion messages to all players.")
@ConfigComment("Change to false if the spam becomes too much.")
@ -171,7 +165,7 @@ public class Settings implements ConfigObject
* Configuration version
*/
@ConfigComment("")
private String configVersion = "v4";
private String configVersion = "v3";
// ---------------------------------------------------------------------
@ -603,26 +597,4 @@ public class Settings implements ConfigObject
{
this.visibilityMode = visibilityMode;
}
/**
* Is count undeployed to completion boolean.
*
* @return the boolean
*/
public boolean isIncludeUndeployed()
{
return includeUndeployed;
}
/**
* Sets count undeployed to completion.
*
* @param includeUndeployed the count undeployed to completion
*/
public void setIncludeUndeployed(boolean includeUndeployed)
{
this.includeUndeployed = includeUndeployed;
}
}

View File

@ -82,11 +82,7 @@ public class ChallengesImportManager
{
if (user != null)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "no-file",
Constants.PARAMETER_FILE,
file);
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-file", Constants.PARAMETER_FILE, file));
}
return;
@ -102,14 +98,13 @@ public class ChallengesImportManager
{
if (user != null)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "no-load",
Constants.PARAMETER_FILE, file,
TextVariables.DESCRIPTION, e.getMessage());
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-load",
Constants.PARAMETER_FILE, file, TextVariables.DESCRIPTION, e.getMessage()));
}
else
{
this.addon.logError("Exception when loading file. " + e.getMessage());
}
this.addon.logError("Exception when loading file. " + e.getMessage());
return;
}
@ -121,12 +116,13 @@ public class ChallengesImportManager
if (user != null)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "not-a-gamemode-world",
Constants.PARAMETER_WORLD, world.getName());
user.getTranslation(Constants.ERRORS + "not-a-gamemode-world",
Constants.PARAMETER_WORLD, world.getName()));
}
else
{
this.addon.logWarning("Given world is not a gamemode world.");
}
this.addon.logWarning("Given world is not a gamemode world.");
return;
}
@ -159,7 +155,6 @@ public class ChallengesImportManager
challengeCount = reader.getKeys(false).stream().
mapToInt(challengeId -> this.createChallenge(challengeId,
prefix,
world,
reader.getConfigurationSection(challengeId))).
sum();
}
@ -183,10 +178,9 @@ public class ChallengesImportManager
if (user != null)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "import-count",
"[levels]", String.valueOf(levelCount),
"[challenges]", String.valueOf(challengeCount));
user.getTranslation(Constants.MESSAGES + "import-count",
"[levels]", String.valueOf(levelCount),
"[challenges]", String.valueOf(challengeCount)));
}
this.addon.log("Imported " + challengeCount + " challenges and " +
@ -198,13 +192,11 @@ public class ChallengesImportManager
* This method creates challenge from given config section.
* @param challengeId Challenge ID.
* @param prefix GameMode prefix.
* @param world world where challenge is created.
* @param section Configuration Section that contains information.
* @return 1 if challenge is created, otherwise 0.
*/
private int createChallenge(String challengeId,
String prefix,
World world,
@Nullable ConfigurationSection section)
{
if (section == null)
@ -278,7 +270,7 @@ public class ChallengesImportManager
}
this.addon.getChallengesManager().saveChallenge(challenge);
this.addon.getChallengesManager().loadChallenge(challenge, world, true, null, true);
this.addon.getChallengesManager().loadChallenge(challenge, true, null, true);
}
catch (Exception e)
{
@ -644,7 +636,7 @@ public class ChallengesImportManager
}
this.addon.getChallengesManager().saveLevel(level);
this.addon.getChallengesManager().loadLevel(level, world,true, null, true);
this.addon.getChallengesManager().loadLevel(level, true, null, true);
}
catch (Exception ignored)
{
@ -708,7 +700,7 @@ public class ChallengesImportManager
challenge.setLevel(uniqueIDPrefix + challenge.getLevel());
}
// Load challenge in memory
manager.loadChallenge(challenge, world, false, user, user == null);
manager.loadChallenge(challenge, false, user, user == null);
});
downloadedChallenges.getLevelList().forEach(challengeLevel -> {
@ -721,7 +713,7 @@ public class ChallengesImportManager
map(challenge -> uniqueIDPrefix + challenge).
collect(Collectors.toSet()));
// Load level in memory
manager.loadLevel(challengeLevel, world, false, user, user == null);
manager.loadLevel(challengeLevel, false, user, user == null);
});
}
catch (Exception e)
@ -758,7 +750,7 @@ public class ChallengesImportManager
{
if (user.isPlayer())
{
Utils.sendMessage(user, world, Constants.ERRORS + "exist-challenges-or-levels");
Utils.sendMessage(user, user.getTranslation("challenges.errors.exist-challenges-or-levels"));
}
else
{
@ -785,7 +777,7 @@ public class ChallengesImportManager
challenge.setLevel(uniqueIDPrefix + challenge.getLevel());
}
// Load challenge in memory
manager.loadChallenge(challenge, world, false, user, user == null);
manager.loadChallenge(challenge, false, user, user == null);
});
downloadedChallenges.getLevelList().forEach(challengeLevel -> {
@ -798,7 +790,7 @@ public class ChallengesImportManager
map(challenge -> uniqueIDPrefix + challenge).
collect(Collectors.toSet()));
// Load level in memory
manager.loadLevel(challengeLevel, world, false, user, user == null);
manager.loadLevel(challengeLevel, false, user, user == null);
});
}
catch (Exception e)
@ -827,9 +819,8 @@ public class ChallengesImportManager
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "file-exist",
Constants.PARAMETER_FILE, fileName);
user.getTranslation(Constants.ERRORS + "file-exist",
Constants.PARAMETER_FILE, fileName));
}
else
{
@ -895,10 +886,9 @@ public class ChallengesImportManager
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "no-load",
Constants.PARAMETER_FILE, fileName,
TextVariables.DESCRIPTION, e.getMessage());
user.getTranslation(Constants.ERRORS + "no-load",
Constants.PARAMETER_FILE, fileName,
TextVariables.DESCRIPTION, e.getMessage()));
}
this.addon.logError("Could not save json file: " + e.getMessage());
@ -908,10 +898,9 @@ public class ChallengesImportManager
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.CONVERSATIONS + "database-export-completed",
Constants.PARAMETER_WORLD, world.getName(),
Constants.PARAMETER_FILE, fileName);
user.getTranslation(Constants.CONVERSATIONS + "database-export-completed",
Constants.PARAMETER_WORLD, world.getName(),
Constants.PARAMETER_FILE, fileName));
}
else
{

View File

@ -28,7 +28,6 @@ import world.bentobox.challenges.events.ChallengeCompletedEvent;
import world.bentobox.challenges.events.ChallengeResetAllEvent;
import world.bentobox.challenges.events.ChallengeResetEvent;
import world.bentobox.challenges.events.LevelCompletedEvent;
import world.bentobox.challenges.utils.Constants;
import world.bentobox.challenges.utils.LevelStatus;
import world.bentobox.challenges.utils.Utils;
@ -98,6 +97,7 @@ public class ChallengesManager
* String for free Challenge Level.
*/
public static final String FREE = "";
public static final String VALUE = "[value]";
public static final String USER_ID = "user-id";
public static final String CHALLENGE_ID = "challenge-id";
public static final String ADMIN_ID = "admin-id";
@ -113,28 +113,41 @@ public class ChallengesManager
* This comparator orders challenges by their level, order and name.
*/
private final Comparator<Challenge> challengeComparator = (o1, o2) -> {
ChallengeLevel o1Level = this.getLevel(o1.getLevel());
ChallengeLevel o2Level = this.getLevel(o2.getLevel());
if (o1Level == null && o2Level == null)
if (o1.getLevel().equals(o2.getLevel()))
{
return Integer.compare(o1.getOrder(), o2.getOrder());
}
else if (o1Level == null)
{
return -1;
}
else if (o2Level == null)
{
return 1;
}
else if (o1Level.equals(o2Level))
{
return Integer.compare(o1.getOrder(), o2.getOrder());
if (o1.getOrder() == o2.getOrder())
{
// If orders are equal, sort by unique id
return o1.getUniqueId().compareToIgnoreCase(o2.getUniqueId());
}
else
{
// If levels are equal, sort them by order numbers.
return Integer.compare(o1.getOrder(), o2.getOrder());
}
}
else
{
return Integer.compare(o1Level.getOrder(), o2Level.getOrder());
if (o1.getLevel().isEmpty() || o2.getLevel().isEmpty())
{
// If exist free level challenge, then it should be at the start.
return Boolean.compare(o2.getLevel().isEmpty(), o1.getLevel().isEmpty());
}
else
{
ChallengeLevel o1Level = this.getLevel(o1.getLevel());
ChallengeLevel o2Level = this.getLevel(o2.getLevel());
if (o1Level == null || o2Level == null)
{
return Boolean.compare(o1Level == null, o2Level == null);
}
else
{
// Sort by challenges level order numbers
return Integer.compare(o1Level.getOrder(), o2Level.getOrder());
}
}
}
};
@ -230,7 +243,7 @@ public class ChallengesManager
*/
private void loadChallenge(@NonNull Challenge challenge)
{
this.loadChallenge(challenge, null, true, null, true);
this.loadChallenge(challenge, true, null, true);
}
@ -244,10 +257,9 @@ public class ChallengesManager
* @return - true if imported
*/
public boolean loadChallenge(@Nullable Challenge challenge,
World world,
boolean overwrite,
User user,
boolean silent)
boolean overwrite,
User user,
boolean silent)
{
// This may happen if database somehow failed to load challenge and return
// null as input.
@ -255,10 +267,7 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "load-error",
Constants.PARAMETER_VALUE, "NULL");
Utils.sendMessage(user, user.getTranslation("load-error", "[value]", "NULL"));
}
return false;
@ -268,10 +277,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "invalid-challenge",
Constants.PARAMETER_CHALLENGE, challenge.getUniqueId());
Utils.sendMessage(user, user.getTranslation("challenges.errors.invalid-challenge",
"[challenge]", challenge.getUniqueId()));
}
this.addon.logWarning("Data for challenge `" + challenge.getUniqueId() + "` is not valid. It could be NULL element in item-stack!");
@ -286,10 +293,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-skipping",
Constants.PARAMETER_VALUE, challenge.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-skipping",
VALUE, challenge.getFriendlyName()));
}
return false;
@ -298,10 +303,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-overwriting",
Constants.PARAMETER_VALUE, challenge.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-overwriting",
VALUE, challenge.getFriendlyName()));
}
}
}
@ -309,10 +312,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-add",
Constants.PARAMETER_VALUE, challenge.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-add",
VALUE, challenge.getFriendlyName()));
}
}
@ -328,7 +329,7 @@ public class ChallengesManager
*/
private void loadLevel(@NonNull ChallengeLevel level)
{
this.loadLevel(level, null, true, null, true);
this.loadLevel(level, true, null, true);
}
@ -343,7 +344,6 @@ public class ChallengesManager
* @return boolean that indicate about load status.
*/
public boolean loadLevel(@Nullable ChallengeLevel level,
World world,
boolean overwrite,
User user,
boolean silent)
@ -354,10 +354,7 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "load-error",
Constants.PARAMETER_VALUE, "NULL");
Utils.sendMessage(user, user.getTranslation("load-error", "[value]", "NULL"));
}
return false;
@ -367,10 +364,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "invalid-level",
"[level]", level.getUniqueId());
Utils.sendMessage(user, user.getTranslation("challenges.errors.invalid-level",
"[level]", level.getUniqueId()));
}
this.addon.logWarning("Data for level `" + level.getUniqueId() + "` is not valid. It could be NULL element in item-stack!");
@ -381,10 +376,8 @@ public class ChallengesManager
{
if (user != null)
{
Utils.sendMessage(user,
world,
Constants.ERRORS + "load-error",
Constants.PARAMETER_VALUE, level.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.errors.load-error",
VALUE, level.getFriendlyName()));
}
else
{
@ -400,10 +393,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-skipping",
Constants.PARAMETER_VALUE, level.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-skipping",
VALUE, level.getFriendlyName()));
}
return false;
@ -412,10 +403,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-overwriting",
Constants.PARAMETER_VALUE, level.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-overwriting",
VALUE, level.getFriendlyName()));
}
}
}
@ -423,10 +412,8 @@ public class ChallengesManager
{
if (!silent)
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "load-add",
Constants.PARAMETER_VALUE, level.getFriendlyName());
Utils.sendMessage(user, user.getTranslation("challenges.messages.load-add",
VALUE, level.getFriendlyName()));
}
}
@ -512,7 +499,7 @@ public class ChallengesManager
if (!this.challengeCacheData.containsKey(uniqueID))
{
if (!this.challengeDatabase.objectExists(uniqueID) ||
!this.loadChallenge(this.challengeDatabase.loadObject(uniqueID), Bukkit.getWorld(level.getWorld()), false, null, true))
!this.loadChallenge(this.challengeDatabase.loadObject(uniqueID), false, null, true))
{
this.addon.logError("Cannot find " + uniqueID + " challenge for " + level.getUniqueId());
return false;
@ -666,9 +653,7 @@ public class ChallengesManager
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "migrate-start");
Utils.sendMessage(user, user.getTranslation("challenges.messages.migrate-start"));
}
else
{
@ -684,9 +669,7 @@ public class ChallengesManager
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "migrate-end");
Utils.sendMessage(user, user.getTranslation("challenges.messages.migrate-end"));
}
else
{
@ -697,9 +680,7 @@ public class ChallengesManager
{
if (user.isPlayer())
{
Utils.sendMessage(user,
world,
Constants.MESSAGES + "migrate-not");
Utils.sendMessage(user, user.getTranslation("challenges.messages.migrate-not"));
}
else
{
@ -1126,20 +1107,11 @@ public class ChallengesManager
// know how many challenges there were and how many has been done. Then
// remove waiver amount to get count of challenges that still necessary to do.
List<Challenge> previousChallengeList = previousLevel == null ?
Collections.emptyList() :
this.getLevelChallenges(previousLevel);
int challengesToDo = previousLevel == null ? 0 :
(previousChallengeList.size() - doneChallengeCount - previousLevel.getWaiverAmount());
List<Challenge> challengeList = this.getLevelChallenges(level);
(previousLevel.getChallenges().size() - doneChallengeCount - previousLevel.getWaiverAmount());
// As level already contains unique ids of challenges, just iterate through them.
doneChallengeCount = (int) challengeList.stream().
map(Challenge::getUniqueId).
filter(playerData::isChallengeDone).
count();
doneChallengeCount = (int) level.getChallenges().stream().filter(playerData::isChallengeDone).count();
// Mark if level is unlocked
boolean unlocked = previousUnlocked && challengesToDo <= 0;
@ -1148,7 +1120,7 @@ public class ChallengesManager
level,
previousLevel,
challengesToDo,
challengeList.size() == doneChallengeCount,
level.getChallenges().size() == doneChallengeCount,
unlocked));
previousLevel = level;
@ -1184,27 +1156,18 @@ public class ChallengesManager
{
ChallengeLevel previousLevel = levelIndex < 1 ? null : challengeLevelList.get(levelIndex - 1);
List<Challenge> previousChallengeList = previousLevel == null ? Collections.emptyList() :
this.getLevelChallenges(previousLevel);
int challengesToDo = previousLevel == null ? 0 :
(previousChallengeList.size() - previousLevel.getWaiverAmount()) -
(int) previousChallengeList.stream().map(Challenge::getUniqueId).
filter(playerData::isChallengeDone).count();
List<Challenge> challengeList = this.getLevelChallenges(level);
(previousLevel.getChallenges().size() - previousLevel.getWaiverAmount()) -
(int) previousLevel.getChallenges().stream().filter(playerData::isChallengeDone).count();
// As level already contains unique ids of challenges, just iterate through them.
int doneChallengeCount = (int) challengeList.stream().
map(Challenge::getUniqueId).
filter(playerData::isChallengeDone).
count();
int doneChallengeCount = (int) level.getChallenges().stream().filter(playerData::isChallengeDone).count();
return new LevelStatus(
level,
previousLevel,
challengesToDo,
challengeList.size() == doneChallengeCount,
level.getChallenges().size() == doneChallengeCount,
challengesToDo <= 0);
}
}
@ -1232,15 +1195,9 @@ public class ChallengesManager
{
this.addPlayerData(storageDataID);
ChallengesPlayerData playerData = this.playerCacheData.get(storageDataID);
long doneChallengeCount = level.getChallenges().stream().filter(playerData::isChallengeDone).count();
List<Challenge> challengeList = this.getLevelChallenges(level);
long doneChallengeCount = challengeList.stream().
map(Challenge::getUniqueId).
filter(playerData::isChallengeDone).
count();
return challengeList.size() == doneChallengeCount;
return level.getChallenges().size() == doneChallengeCount;
}
@ -1799,11 +1756,11 @@ public class ChallengesManager
{
// Free Challenges hides under FREE level.
return this.islandWorldManager.getAddon(world).map(gameMode ->
this.challengeCacheData.values().stream().
filter(challenge -> challenge.getLevel().equals(FREE) &&
challenge.matchGameMode(gameMode.getDescription().getName())).
sorted(Comparator.comparing(Challenge::getOrder)).
collect(Collectors.toList())).
this.challengeCacheData.values().stream().
filter(challenge -> challenge.getLevel().equals(FREE) &&
challenge.matchGameMode(gameMode.getDescription().getName())).
sorted(Comparator.comparing(Challenge::getOrder)).
collect(Collectors.toList())).
orElse(Collections.emptyList());
}
@ -1814,24 +1771,10 @@ public class ChallengesManager
* @return List with challenges in given level.
*/
public List<Challenge> getLevelChallenges(ChallengeLevel level)
{
return this.getLevelChallenges(level,
this.addon.getChallengesSettings().isIncludeUndeployed());
}
/**
* Level which challenges must be received
* @param level Challenge level.
* @param includeUndeployed if true, then include challenges that are not deployed.
* @return List with challenges in given level.
*/
public List<Challenge> getLevelChallenges(ChallengeLevel level, boolean includeUndeployed)
{
return level.getChallenges().stream().
map(this::getChallenge).
filter(Objects::nonNull).
filter(challenge -> includeUndeployed || challenge.isDeployed()).
sorted(Comparator.comparing(Challenge::getOrder)).
collect(Collectors.toList());
}
@ -1950,9 +1893,7 @@ public class ChallengesManager
*/
public int getChallengeCount(World world)
{
return (int) this.getAllChallenges(world).stream().
filter(challenge -> this.settings.isIncludeUndeployed() || challenge.isDeployed()).
count();
return this.getAllChallenges(world).size();
}

View File

@ -7,12 +7,12 @@
package world.bentobox.challenges.panel;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.conversations.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
@ -65,7 +65,7 @@ public class ConversationUtils
// Split and check if they exist in valid entries.
String[] accepted = validEntry.toLowerCase().replaceAll("\\s", "").split(",");
return Arrays.asList(accepted).contains(input.toLowerCase());
return ArrayUtils.contains(accepted, input.toLowerCase());
}
@ -81,7 +81,7 @@ public class ConversationUtils
{
String validEntry = user.getTranslation(Constants.CONVERSATIONS + "confirm-string").toLowerCase();
if (Arrays.asList(validEntry.replaceAll("\\s", "").split(",")).contains(input.toLowerCase()))
if (ArrayUtils.contains(validEntry.replaceAll("\\s", "").split(","), input.toLowerCase()))
{
// Add answer to consumer.
consumer.accept(true);
@ -432,7 +432,7 @@ public class ConversationUtils
toLowerCase().replaceAll("\\s", "").
split(",");
if (input != null && Arrays.asList(exit).contains(input.toLowerCase()))
if (input != null && ArrayUtils.contains(exit, input.toLowerCase()))
{
return messagePrompt;
}

View File

@ -212,7 +212,7 @@ public class EditLevelPanel extends CommonPagedPanel<Challenge>
private void buildChallengesPanel(PanelBuilder panelBuilder)
{
List<Challenge> challengeList = this.addon.getChallengesManager().
getLevelChallenges(this.challengeLevel, true).stream().
getLevelChallenges(this.challengeLevel).stream().
filter(challenge -> this.searchString.isBlank() ||
challenge.getFriendlyName().toLowerCase().contains(this.searchString.toLowerCase()) ||
challenge.getUniqueId().toLowerCase().contains(this.searchString.toLowerCase()) ||
@ -784,7 +784,7 @@ public class EditLevelPanel extends CommonPagedPanel<Challenge>
// Get all challenge that is not in current level.
List<Challenge> challengeList = manager.getAllChallenges(this.world);
challengeList.removeAll(manager.getLevelChallenges(this.challengeLevel, true));
challengeList.removeAll(manager.getLevelChallenges(this.challengeLevel));
// Generate descriptions for these challenges
Map<Challenge, List<String>> challengeDescriptionMap = challengeList.stream().
@ -820,7 +820,7 @@ public class EditLevelPanel extends CommonPagedPanel<Challenge>
ChallengesManager manager = this.addon.getChallengesManager();
// Get all challenge that is in current level.
List<Challenge> challengeList = manager.getLevelChallenges(this.challengeLevel, true);
List<Challenge> challengeList = manager.getLevelChallenges(this.challengeLevel);
// Generate descriptions for these challenges
Map<Challenge, List<String>> challengeDescriptionMap = challengeList.stream().

View File

@ -119,7 +119,6 @@ public class EditSettingsPanel extends CommonPanel
panelBuilder.item(11, this.getSettingsButton(Button.GLOW_COMPLETED));
panelBuilder.item(20, this.getSettingsButton(Button.REMOVE_COMPLETED));
panelBuilder.item(29, this.getSettingsButton(Button.VISIBILITY_MODE));
panelBuilder.item(30, this.getSettingsButton(Button.INCLUDE_UNDEPLOYED));
panelBuilder.item(21, this.getSettingsButton(Button.LOCKED_LEVEL_ICON));
@ -415,6 +414,9 @@ public class EditSettingsPanel extends CommonPanel
description.add(this.user.getTranslation(reference +
(this.settings.getVisibilityMode().equals(VisibilityMode.HIDDEN) ? "enabled" : "disabled")) +
this.user.getTranslation(reference + "hidden"));
description.add(this.user.getTranslation(reference +
(this.settings.getVisibilityMode().equals(VisibilityMode.TOGGLEABLE) ? "enabled" : "disabled")) +
this.user.getTranslation(reference + "toggleable"));
if (this.settings.getVisibilityMode().equals(VisibilityMode.VISIBLE))
{
@ -452,22 +454,6 @@ public class EditSettingsPanel extends CommonPanel
description.add(this.user.getTranslation(Constants.TIPS + "left-click-to-cycle"));
description.add(this.user.getTranslation(Constants.TIPS + "right-click-to-cycle"));
}
case INCLUDE_UNDEPLOYED -> {
description.add(this.user.getTranslation(reference +
(this.settings.isIncludeUndeployed() ? "enabled" : "disabled")));
icon = new ItemStack(Material.BARREL);
clickHandler = (panel, user1, clickType, i) -> {
this.settings.setIncludeUndeployed(!this.settings.isIncludeUndeployed());
panel.getInventory().setItem(i, this.getSettingsButton(button).getItem());
this.addon.saveSettings();
return true;
};
glow = this.settings.isIncludeUndeployed();
description.add("");
description.add(this.user.getTranslation(Constants.TIPS + "click-to-toggle"));
}
default -> {
icon = new ItemStack(Material.PAPER);
clickHandler = null;
@ -571,10 +557,6 @@ public class EditSettingsPanel extends CommonPanel
LOCKED_LEVEL_ICON,
SHOW_TITLE,
TITLE_SHOWTIME,
/**
* This allows to switch between counting/not couting undeployed challenges.
*/
INCLUDE_UNDEPLOYED,
/**
* This allows to switch between different challenges visibility modes.
*/

View File

@ -166,9 +166,8 @@ public class LibraryPanel extends CommonPagedPanel<LibraryEntry>
{
if (this.libraryEntries.isEmpty())
{
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "no-library-entries");
Utils.sendMessage(this.user, this.user.getTranslation(
Constants.ERRORS + "no-library-entries"));
return;
}
@ -312,9 +311,8 @@ public class LibraryPanel extends CommonPagedPanel<LibraryEntry>
{
this.blockedForDownland = true;
Utils.sendMessage(this.user,
this.world,
Constants.MESSAGES + "start-downloading");
Utils.sendMessage(this.user, this.user.getTranslation(
Constants.MESSAGES + "start-downloading"));
// Run download task after 5 ticks.
this.updateTask = this.addon.getPlugin().getServer().getScheduler().

View File

@ -8,7 +8,6 @@ package world.bentobox.challenges.panel.user;
import org.bukkit.World;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
@ -77,7 +76,7 @@ public class ChallengesPanel extends CommonPanel
if (!this.containsChallenges)
{
this.addon.logError("There are no challenges set up!");
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "no-challenges");
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-challenges"));
return;
}
@ -130,7 +129,7 @@ public class ChallengesPanel extends CommonPanel
{
if (this.lastSelectedLevel != null)
{
this.challengeList = this.manager.getLevelChallenges(this.lastSelectedLevel.getLevel(), true);
this.challengeList = this.manager.getLevelChallenges(this.lastSelectedLevel.getLevel());
if (this.addon.getChallengesSettings().isRemoveCompleteOneTimeChallenges())
{
@ -275,43 +274,11 @@ public class ChallengesPanel extends CommonPanel
builder.description(this.generateChallengeDescription(challenge, this.user));
}
// If challenge is not repeatable, remove all other actions beside "COMPLETE".
// If challenge is completed all possible times, remove action.
List<ItemTemplateRecord.ActionRecords> actions = template.actions().stream().
filter(action -> challenge.isRepeatable() || "COMPLETE".equalsIgnoreCase(action.actionType())).
filter(action ->
{
boolean isCompletedOnce =
this.manager.isChallengeComplete(this.user.getUniqueId(), this.world, challenge);
if (!isCompletedOnce)
{
// Is not completed once, then it must appear.
return true;
}
else if (challenge.isRepeatable() && challenge.getMaxTimes() <= 0)
{
// Challenge is unlimited. Must appear in the list.
return true;
}
else
{
// Challenge still have some opened slots.
long doneTimes = challenge.isRepeatable() ?
this.manager.getChallengeTimes(this.user, this.world, challenge) : 1;
return challenge.isRepeatable() && doneTimes < challenge.getMaxTimes();
}
}).
toList();
// Add Click handler
builder.clickHandler((panel, user, clickType, i) -> {
for (ItemTemplateRecord.ActionRecords action : actions)
for (ItemTemplateRecord.ActionRecords action : template.actions())
{
if (clickType == action.clickType() || clickType.equals(ClickType.UNKNOWN))
if (clickType == action.clickType())
{
switch (action.actionType().toUpperCase())
{
@ -401,8 +368,9 @@ public class ChallengesPanel extends CommonPanel
});
// Collect tooltips.
List<String> tooltips = actions.stream().
List<String> tooltips = template.actions().stream().
filter(action -> action.tooltip() != null).
filter(action -> challenge.isRepeatable() || "COMPLETE".equalsIgnoreCase(action.actionType())).
map(action -> this.user.getTranslation(this.world, action.tooltip())).
filter(text -> !text.isBlank()).
collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size())));

View File

@ -265,21 +265,18 @@ public class TryToComplete
// Send message about first completion only if it is completed only once.
if (result.getFactor() == 1)
{
Utils.sendMessage(this.user,
this.world,
Constants.MESSAGES + "you-completed-challenge",
Constants.PARAMETER_VALUE, this.challenge.getFriendlyName());
Utils.sendMessage(this.user, this.user.getTranslation("challenges.messages.you-completed-challenge",
"[value]", this.challenge.getFriendlyName()));
}
if (this.addon.getChallengesSettings().isBroadcastMessages())
{
Bukkit.getOnlinePlayers().stream().
map(User::getInstance).
forEach(user -> Utils.sendMessage(user,
this.world,
Constants.MESSAGES + "name-has-completed-challenge",
forEach(user -> Utils.sendMessage(user, user.getTranslation(
"challenges.messages.name-has-completed-challenge",
Constants.PARAMETER_NAME, this.user.getName(),
Constants.PARAMETER_VALUE, this.challenge.getFriendlyName()));
"[value]", this.challenge.getFriendlyName())));
}
// sends title to player on challenge completion
@ -330,18 +327,14 @@ public class TryToComplete
if (result.getFactor() > 1)
{
Utils.sendMessage(this.user,
this.world,
Constants.MESSAGES + "you-repeated-challenge-multiple",
Constants.PARAMETER_VALUE, this.challenge.getFriendlyName(),
"[count]", Integer.toString(result.getFactor()));
Utils.sendMessage(this.user, this.user.getTranslation("challenges.messages.you-repeated-challenge-multiple",
"[value]", this.challenge.getFriendlyName(),
"[count]", Integer.toString(result.getFactor())));
}
else
{
Utils.sendMessage(this.user,
this.world,
Constants.MESSAGES + "you-repeated-challenge",
Constants.PARAMETER_VALUE, this.challenge.getFriendlyName());
Utils.sendMessage(this.user, this.user.getTranslation("challenges.messages.you-repeated-challenge",
"[value]", this.challenge.getFriendlyName()));
}
}
@ -379,20 +372,17 @@ public class TryToComplete
// Run commands
this.runCommands(level.getRewardCommands());
Utils.sendMessage(this.user,
this.world,
Constants.MESSAGES + "you-completed-level",
Constants.PARAMETER_VALUE, level.getFriendlyName());
Utils.sendMessage(this.user, this.user.getTranslation("challenges.messages.you-completed-level",
"[value]", level.getFriendlyName()));
if (this.addon.getChallengesSettings().isBroadcastMessages())
{
Bukkit.getOnlinePlayers().stream().
map(User::getInstance).
forEach(user -> Utils.sendMessage(user,
this.world,
Constants.MESSAGES + "name-has-completed-level",
forEach(user -> Utils.sendMessage(user, user.getTranslation(
"challenges.messages.name-has-completed-level",
Constants.PARAMETER_NAME, this.user.getName(),
Constants.PARAMETER_VALUE, level.getFriendlyName()));
"[value]", level.getFriendlyName())));
}
this.manager.setLevelComplete(this.user, this.world, level);
@ -457,8 +447,7 @@ public class TryToComplete
if (sumEverything != removedAmount)
{
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "cannot-remove-items");
this.user.getTranslation("challenges.errors.cannot-remove-items"));
result.removedItems = removedItems;
result.meetsRequirements = false;
@ -506,54 +495,45 @@ public class TryToComplete
}
}
case ITEM, BLOCK -> {
int statistic = this.user.getPlayer().getStatistic(requirements.getStatistic());
if (requirements.getMaterial() == null)
{
// Just a sanity check. Material cannot be null at this point of code.
removeAmount = 0;
}
else if (removeAmount >= statistic)
{
this.user.getPlayer().setStatistic(requirements.getStatistic(), requirements.getMaterial(), 0);
removeAmount -= statistic;
}
else
{
int statistic = this.user.getPlayer().getStatistic(requirements.getStatistic(),
requirements.getMaterial());
if (removeAmount >= statistic)
{
this.user.getPlayer()
.setStatistic(requirements.getStatistic(), requirements.getMaterial(), 0);
removeAmount -= statistic;
}
else
{
this.user.getPlayer().setStatistic(requirements.getStatistic(),
requirements.getMaterial(),
statistic - removeAmount);
removeAmount = 0;
}
this.user.getPlayer().setStatistic(requirements.getStatistic(),
requirements.getMaterial(),
statistic - removeAmount);
removeAmount = 0;
}
}
case ENTITY -> {
int statistic = this.user.getPlayer().getStatistic(requirements.getStatistic());
if (requirements.getEntity() == null)
{
// Just a sanity check. Entity cannot be null at this point of code.
removeAmount = 0;
}
else if (removeAmount >= statistic)
{
this.user.getPlayer().setStatistic(requirements.getStatistic(), requirements.getEntity(), 0);
removeAmount -= statistic;
}
else
{
int statistic = this.user.getPlayer().getStatistic(requirements.getStatistic(),
requirements.getEntity());
if (removeAmount >= statistic)
{
this.user.getPlayer().setStatistic(requirements.getStatistic(), requirements.getEntity(), 0);
removeAmount -= statistic;
}
else
{
this.user.getPlayer().setStatistic(requirements.getStatistic(),
requirements.getEntity(),
statistic - removeAmount);
removeAmount = 0;
}
this.user.getPlayer().setStatistic(requirements.getStatistic(),
requirements.getEntity(),
statistic - removeAmount);
removeAmount = 0;
}
}
}
@ -597,57 +577,45 @@ public class TryToComplete
}
}
case ITEM, BLOCK -> {
int statistic = player.getStatistic(requirements.getStatistic());
if (requirements.getMaterial() == null)
{
// Just a sanity check. Entity cannot be null at this point of code.
removeAmount = 0;
}
else if (removeAmount >= statistic)
{
removeAmount -= statistic;
player.setStatistic(requirements.getStatistic(), requirements.getMaterial(), 0);
}
else
{
int statistic = player.getStatistic(requirements.getStatistic(),
requirements.getMaterial());
if (removeAmount >= statistic)
{
removeAmount -= statistic;
player.setStatistic(requirements.getStatistic(),
requirements.getMaterial(),
0);
}
else
{
player.setStatistic(requirements.getStatistic(),
requirements.getMaterial(),
statistic - removeAmount);
removeAmount = 0;
}
player.setStatistic(requirements.getStatistic(),
requirements.getMaterial(),
statistic - removeAmount);
removeAmount = 0;
}
}
case ENTITY -> {
int statistic = player.getStatistic(requirements.getStatistic());
if (requirements.getEntity() == null)
{
// Just a sanity check. Entity cannot be null at this point of code.
removeAmount = 0;
}
else if (removeAmount >= statistic)
{
removeAmount -= statistic;
player.setStatistic(requirements.getStatistic(), requirements.getEntity(), 0);
}
else
{
int statistic = player.getStatistic(requirements.getStatistic(),
requirements.getEntity());
if (removeAmount >= statistic)
{
removeAmount -= statistic;
player.setStatistic(requirements.getStatistic(),
requirements.getEntity(),
0);
}
else
{
player.setStatistic(requirements.getStatistic(),
requirements.getEntity(),
statistic - removeAmount);
removeAmount = 0;
}
player.setStatistic(requirements.getStatistic(),
requirements.getEntity(),
statistic - removeAmount);
removeAmount = 0;
}
}
}
@ -672,18 +640,18 @@ public class TryToComplete
// Check the world
if (!this.challenge.isDeployed())
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "not-deployed");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-deployed"));
result = EMPTY_RESULT;
}
else if (maxTimes < 1)
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "not-valid-integer");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-valid-integer"));
result = EMPTY_RESULT;
}
else if (Util.getWorld(this.world) != Util.getWorld(this.user.getWorld()) ||
!this.challenge.matchGameMode(Utils.getGameMode(this.world)))
{
Utils.sendMessage(this.user, this.world, "general.errors.wrong-world");
Utils.sendMessage(this.user, this.user.getTranslation("general.errors.wrong-world"));
result = EMPTY_RESULT;
}
// Player is not on island
@ -691,7 +659,7 @@ public class TryToComplete
ChallengesAddon.CHALLENGES_WORLD_PROTECTION.isSetForWorld(this.world) &&
!this.addon.getIslands().locationIsOnIsland(this.user.getPlayer(), this.user.getLocation()))
{
Utils.sendMessage(this.user, this.world, Constants.MESSAGES + "not-on-island");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-on-island"));
result = EMPTY_RESULT;
}
// Check player permission
@ -699,27 +667,27 @@ public class TryToComplete
map(i -> i.isAllowed(this.user, ChallengesAddon.CHALLENGES_ISLAND_PROTECTION)).
orElse(false))
{
Utils.sendMessage(this.user, this.world, Constants.MESSAGES + "no-rank");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.no-rank"));
result = EMPTY_RESULT;
}
// Check if user has unlocked challenges level.
else if (!this.challenge.getLevel().equals(ChallengesManager.FREE) &&
!this.manager.isLevelUnlocked(this.user, this.world, this.manager.getLevel(this.challenge.getLevel())))
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "challenge-level-not-available");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.challenge-level-not-available"));
result = EMPTY_RESULT;
}
// Check max times
else if (this.challenge.isRepeatable() && this.challenge.getMaxTimes() > 0 &&
this.manager.getChallengeTimes(this.user, this.world, this.challenge) >= this.challenge.getMaxTimes())
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "not-repeatable");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-repeatable"));
result = EMPTY_RESULT;
}
// Check repeatability
else if (!this.challenge.isRepeatable() && this.manager.isChallengeComplete(this.user, this.world, this.challenge))
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "not-repeatable");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-repeatable"));
result = EMPTY_RESULT;
}
// Check if timeout is not broken
@ -728,22 +696,22 @@ public class TryToComplete
long missing = this.manager.getLastCompletionDate(this.user, this.world, challenge) +
this.challenge.getTimeout() - System.currentTimeMillis();
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "timeout",
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.timeout",
"[timeout]", Utils.parseDuration(Duration.ofMillis(this.challenge.getTimeout()), this.user),
"[wait-time]", Utils.parseDuration(Duration.ofMillis(missing), this.user));
"[wait-time]", Utils.parseDuration(Duration.ofMillis(missing), this.user)));
result = EMPTY_RESULT;
}
// Check environment
else if (!this.challenge.getEnvironment().isEmpty() &&
!this.challenge.getEnvironment().contains(this.user.getWorld().getEnvironment()))
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "wrong-environment");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.wrong-environment"));
result = EMPTY_RESULT;
}
// Check permission
else if (!this.checkPermissions())
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "no-permission");
Utils.sendMessage(this.user, this.user.getTranslation("general.errors.no-permission"));
result = EMPTY_RESULT;
}
else if (type.equals(ChallengeType.INVENTORY_TYPE))
@ -823,25 +791,17 @@ public class TryToComplete
private void runCommands(List<String> commands)
{
// Ignore commands with this perm
if (this.user.hasPermission(this.permissionPrefix + "command.challengeexempt") && !this.user.isOp())
if (user.hasPermission(this.permissionPrefix + "command.challengeexempt") && !user.isOp())
{
return;
}
final Island island = this.addon.getIslandsManager().getIsland(this.world, this.user);
final String owner = island == null ? "" : this.addon.getPlayers().getName(island.getOwner());
for (String cmd : commands)
{
if (cmd.startsWith("[SELF]"))
{
String alert = "Running command '" + cmd + "' as " + this.user.getName();
this.addon.getLogger().info(alert);
cmd = cmd.substring(6).
replaceAll(Constants.ESC + Constants.PARAMETER_PLAYER, this.user.getName()).
replaceAll(Constants.ESC + Constants.PARAMETER_OWNER, owner).
replaceAll(Constants.ESC + Constants.PARAMETER_NAME, island == null || island.getName() == null ? "" : island.getName()).
trim();
cmd = cmd.substring(6).replace(Constants.PARAMETER_PLAYER, this.user.getName()).trim();
try
{
if (!user.performCommand(cmd))
@ -856,17 +816,11 @@ public class TryToComplete
continue;
}
// Substitute in any references to player
try
{
cmd = cmd.replaceAll(Constants.ESC + Constants.PARAMETER_PLAYER, this.user.getName()).
replaceAll(Constants.ESC + Constants.PARAMETER_OWNER, owner).
replaceAll(Constants.ESC + Constants.PARAMETER_NAME, island == null || island.getName() == null ? "" : island.getName()).
trim();
if (!this.addon.getServer().dispatchCommand(this.addon.getServer().getConsoleSender(), cmd))
if (!this.addon.getServer().dispatchCommand(this.addon.getServer().getConsoleSender(),
cmd.replace(Constants.PARAMETER_PLAYER, this.user.getName())))
{
this.showError(cmd);
}
@ -940,9 +894,9 @@ public class TryToComplete
if (numInInventory < required.getAmount())
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "not-enough-items",
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-enough-items",
"[items]",
Utils.prettifyObject(required, this.user));
Utils.prettifyObject(required, this.user)));
return EMPTY_RESULT;
}
@ -952,8 +906,6 @@ public class TryToComplete
else
{
requiredItems = Collections.emptyList();
// Set maxTime to 2, to not crash client when completing 2147483647 times.
maxTimes = 2;
}
// Return the result
@ -1207,16 +1159,13 @@ public class TryToComplete
return new ChallengeResult().setMeetsRequirements().setCompleteFactor(factor).setBlockQueue(blockFromWorld);
}
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "not-close-enough",
Constants.PARAMETER_NUMBER, String.valueOf(this.getIslandRequirements().getSearchRadius()));
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-close-enough",
"[number]", String.valueOf(this.getIslandRequirements().getSearchRadius())));
blocks.forEach((k, v) -> Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "you-still-need",
"[amount]", String.valueOf(v),
"[item]", Utils.prettifyObject(k, this.user)));
this.user.getTranslation("challenges.errors.you-still-need",
"[amount]", String.valueOf(v),
"[item]", Utils.prettifyObject(k, this.user))));
// kick garbage collector
@ -1296,11 +1245,9 @@ public class TryToComplete
}
minimalRequirements.forEach((reqEnt, amount) ->
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "you-still-need",
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.you-still-need",
"[amount]", String.valueOf(amount),
"[item]", Utils.prettifyObject(reqEnt, this.user)));
"[item]", Utils.prettifyObject(reqEnt, this.user))));
// Kick garbage collector
entitiesFound.clear();
@ -1381,47 +1328,42 @@ public class TryToComplete
if (!this.addon.isLevelProvided() && requirements.getRequiredIslandLevel() != 0)
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "missing-addon");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.missing-addon"));
}
else if (!this.addon.isEconomyProvided() &&
requirements.getRequiredMoney() != 0)
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "missing-addon");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.missing-addon"));
}
else if (this.addon.isEconomyProvided() && requirements.getRequiredMoney() < 0)
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "incorrect");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.incorrect"));
}
else if (this.addon.isEconomyProvided() &&
!this.addon.getEconomyProvider().has(this.user, requirements.getRequiredMoney()))
{
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "not-enough-money",
Constants.PARAMETER_VALUE, Double.toString(requirements.getRequiredMoney()));
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-enough-money",
"[value]",
Double.toString(requirements.getRequiredMoney())));
}
else if (requirements.getRequiredExperience() < 0)
{
Utils.sendMessage(this.user, this.world, Constants.ERRORS + "incorrect");
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.incorrect"));
}
else if (this.user.getPlayer().getTotalExperience() < requirements.getRequiredExperience() &&
this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
{
// Players in creative gamemode has infinite amount of EXP.
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "not-enough-experience",
Constants.PARAMETER_VALUE,
Integer.toString(requirements.getRequiredExperience()));
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.not-enough-experience",
"[value]",
Integer.toString(requirements.getRequiredExperience())));
}
else if (this.addon.isLevelProvided() &&
this.addon.getLevelAddon().getIslandLevel(this.world, this.user.getUniqueId()) < requirements.getRequiredIslandLevel())
{
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "island-level",
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.island-level",
TextVariables.NUMBER,
String.valueOf(requirements.getRequiredIslandLevel()));
String.valueOf(requirements.getRequiredIslandLevel())));
}
else
{
@ -1484,35 +1426,9 @@ public class TryToComplete
if (currentValue < requirements.getAmount())
{
switch (Objects.requireNonNull(requirements.getStatistic()).getType())
{
case ITEM, BLOCK -> {
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "requirement-not-met-material",
TextVariables.NUMBER, String.valueOf(requirements.getAmount()),
"[statistic]", Utils.prettifyObject(requirements.getStatistic(), this.user),
"[material]", Utils.prettifyObject(requirements.getMaterial(), this.user),
Constants.PARAMETER_VALUE, String.valueOf(currentValue));
}
case ENTITY -> {
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "requirement-not-met-entity",
TextVariables.NUMBER, String.valueOf(requirements.getAmount()),
"[statistic]", Utils.prettifyObject(requirements.getStatistic(), this.user),
"[entity]", Utils.prettifyObject(requirements.getEntity(), this.user),
Constants.PARAMETER_VALUE, String.valueOf(currentValue));
}
default -> {
Utils.sendMessage(this.user,
this.world,
Constants.ERRORS + "requirement-not-met",
TextVariables.NUMBER, String.valueOf(requirements.getAmount()),
"[statistic]", Utils.prettifyObject(requirements.getStatistic(), this.user),
Constants.PARAMETER_VALUE, String.valueOf(currentValue));
}
}
Utils.sendMessage(this.user, this.user.getTranslation("challenges.errors.requirement-not-met",
TextVariables.NUMBER, String.valueOf(requirements.getAmount()),
"[value]", String.valueOf(currentValue)));
}
else
{

View File

@ -223,9 +223,4 @@ public class Constants
* Reference string to challenge parameter in translations.
*/
public static final String PARAMETER_CHALLENGE = "[challenge]";
/**
* Regex escape chars.
*/
public static final String ESC = "\\";
}

View File

@ -7,19 +7,11 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import org.eclipse.jdt.annotation.Nullable;
@ -194,14 +186,11 @@ public class Utils
* Send given message to user and add prefix to the start of the message.
*
* @param user User who need to receive message.
* @param world Reference to world where message must be send.
* @param translation String of message that must be send.
* @param parameters Parameters that must be added to translation.
* @param message String of message that must be send.
*/
public static void sendMessage(User user, World world, String translation, String... parameters)
public static void sendMessage(User user, String message)
{
user.sendMessage(user.getTranslation(world, Constants.CONVERSATIONS + "prefix") +
user.getTranslation(world, translation, parameters));
user.sendMessage(user.getTranslation(Constants.CONVERSATIONS + "prefix") + message);
}
@ -566,13 +555,6 @@ public class Utils
{
return "";
}
// Return the display name if it already has one
if (object.hasItemMeta()) {
ItemMeta im = object.getItemMeta();
if (im.hasDisplayName()) {
return im.getDisplayName();
}
}
// Find addon structure with:
// [addon]:
@ -838,7 +820,7 @@ public class Utils
StringBuilder builder = new StringBuilder();
enchantmentMeta.getStoredEnchants().forEach((enchantment, level) -> {
enchantmentMeta.getEnchants().forEach((enchantment, level) -> {
builder.append("\n");
builder.append(user.getTranslationOrNothing(Constants.ITEM_STACKS + "meta.enchant-meta",
"[type]", prettifyObject(enchantment, user),
@ -883,8 +865,8 @@ public class Utils
final String metaReference = Constants.ITEM_STACKS + "meta.";
String meta = user.getTranslationOrNothing(metaReference + "book-meta",
"[title]", bookMeta.hasTitle() ? bookMeta.getTitle() : "",
"[author]", bookMeta.hasAuthor() ? bookMeta.getAuthor() : "");
"[title]", bookMeta.getTitle(),
"[author]", bookMeta.getAuthor());
return user.getTranslationOrNothing(Constants.ITEM_STACKS + "generic",
"[type]", prettifyObject(itemType, user),

View File

@ -683,15 +683,6 @@ challenges:
visible: "Show visible challenges"
hidden: "Show all challenges"
toggleable: "Allow toggling"
include_undeployed:
name: "&f&l Include Undeployed Challenges"
description: |-
&7 Indicates if undeployed
&7 challenges should be
&7 counted towards level
&7 completion.
enabled: "&2 Enabled"
disabled: "&c Disabled"
download:
name: "&f&l Download Libraries"
description: |-
@ -907,7 +898,7 @@ challenges:
# Message that will be added after environment-title-multiple.
environment-list: " &7 - &e [environment]"
# Message that will replace [permissions] placeholder if there is just a single permission.
permission-single: "&c Requires [permission] permission"
permission-single: "&c Requires [permissions] permission"
# Message that will replace [permissions] placeholder if there are multiple permissions.
permissions-title: "&c Requires permissions: "
# Message that will be added after permissions-title-multiple.
@ -1198,7 +1189,7 @@ challenges:
not-enough-money: '&c It is necessary to have [value] on your account to complete the challenge.'
not-enough-experience: '&c It is necessary to have [value] EXP to complete this challenge.'
island-level: '&c Your island must be level [number] or greater to complete this challenge!'
no-load: '&c Error: Could not load [file]. Error [message]'
no-load: '&c Error: Could not load file. [message]'
load-error: '&c Error: Cannot load [value].'
no-rank: "&c You do not have rank that is high enough to do that."
cannot-remove-items: '&c Some items cannot be removed from your inventory!'
@ -1212,9 +1203,6 @@ challenges:
no-library-entries: "&c Cannot find any library entries. Nothing to show."
not-hooked: "&c Challenges Addon could not find any GameMode."
timeout: "&c This challenge requires to wait [timeout] between completions. You must wait [wait-time] till complete it again."
requirement-not-met: "&c This challenge requires [statistic] to have [number]. You have only [value]. "
requirement-not-met-entity: "&c This challenge requires [statistic] [entity] to have [number]. You have only [value]. "
requirement-not-met-material: "&c This challenge requires [statistic] [material] to have [number]. You have only [value]. "
# # Showcase for manual material translation
# materials:
# # Names should be lowercase.
@ -1250,27 +1238,7 @@ challenges:
# # This will overwrite generic translation.
# name: "[type] [upgraded] [extended]"
# # Type is either specific translation or potion effect.
# uncraftable: "Uncraftable"
# water: "Water"
# mundane: "Mundane"
# thick: "Thick"
# awkward: "Awkward"
# night_vision: "Potion of Night Vision"
# invisibility: "Potion of Invisibility"
# jump: "Potion of Leaping"
# fire_resistance: "Potion of Fire Resistance"
# speed: "Potion of Swiftness"
# slowness: "Potion of Slowness"
# water_breathing: "Potion of Water Breathing"
# instant_heal: "Potion of Healing"
# instant_damage: "Potion of Harming"
# poison: "Potion of Poison"
# regen: "Potion of Regeneration"
# strength: "Potion of Strength"
# weakness: "Potion of Weakness"
# luck: "Potion of Luck"
# turtle_master: "Potion of Turtle Master"
# slow_falling: "Potion of Slow Falling"
# stone_shovel:
# # This will mean that only stone shovels will not show
# # meta information.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,7 @@ gamemode_panel:
content:
2:
1:
icon: tipped_arrow{CustomPotionColor:11546150}
icon: TIPPED_ARROW:INSTANT_HEAL::::1
title: challenges.gui.buttons.previous.name
description: challenges.gui.buttons.previous.description
data:
@ -33,7 +33,7 @@ gamemode_panel:
7: gamemode
8: gamemode
9:
icon: tipped_arrow{CustomPotionColor:8439583}
icon: TIPPED_ARROW:JUMP::::1
title: challenges.gui.buttons.next.name
description: challenges.gui.buttons.next.description
data:

View File

@ -23,7 +23,7 @@ main_panel:
8: challenge_button
3:
1:
icon: tipped_arrow{CustomPotionColor:11546150}
icon: TIPPED_ARROW:INSTANT_HEAL::::1
title: challenges.gui.buttons.previous.name
description: challenges.gui.buttons.previous.description
data:
@ -41,7 +41,7 @@ main_panel:
7: challenge_button
8: challenge_button
9:
icon: tipped_arrow{CustomPotionColor:8439583}
icon: TIPPED_ARROW:JUMP::::1
title: challenges.gui.buttons.next.name
description: challenges.gui.buttons.next.description
data:
@ -53,7 +53,7 @@ main_panel:
tooltip: challenges.gui.tips.click-to-next
5:
1:
icon: tipped_arrow{CustomPotionColor:11546150}
icon: TIPPED_ARROW:INSTANT_HEAL::::1
title: challenges.gui.buttons.previous.name
description: challenges.gui.buttons.previous.description
data:
@ -71,7 +71,7 @@ main_panel:
7: level_button
8: level_button
9:
icon: tipped_arrow{CustomPotionColor:8439583}
icon: TIPPED_ARROW:JUMP::::1
title: challenges.gui.buttons.next.name
description: challenges.gui.buttons.next.description
data:

View File

@ -1,9 +0,0 @@
name: BentoBox-Challenges
main: world.bentobox.challenges.ChallengesPladdon
version: ${project.version}${build.number}
api-version: "1.17"
authors: [tastybento, BONNe]
contributors: ["The BentoBoxWorld Community"]
website: https://bentobox.world
description: ${project.description}

View File

@ -88,10 +88,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -126,10 +122,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -228,10 +220,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -266,10 +254,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -355,10 +339,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -393,10 +373,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -488,10 +464,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -526,10 +498,6 @@ challenges:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]
@ -583,10 +551,6 @@ levels:
# It is not necessary to writhe `/`.
# This examples first command will force player to execute `/island` command,
# While second command will run `/kill [player]` from the server console.
# There are 3 available parameters for commands:
# - [player] - player who completed the challenge
# - [owner] - the island owner
# - [name] - the name of the island.
commands:
- island
- kill [player]

View File

@ -82,7 +82,7 @@ public class ChallengesManagerTest {
// Mocks
@Mock
private ChallengesAddon addon;
@Mock
private Settings settings;
@Mock
private IslandWorldManager iwm;
@ -134,11 +134,9 @@ public class ChallengesManagerTest {
when(s.getDatabaseType()).thenReturn(DatabaseType.JSON);
// Addon Settings
settings = new Settings();
when(addon.getChallengesSettings()).thenReturn(settings);
settings.setStoreAsIslandData(false);
settings.setStoreHistory(true);
settings.setLifeSpan(10);
when(settings.isStoreHistory()).thenReturn(true);
when(settings.getLifeSpan()).thenReturn(10);
// Database
database = new File("database");
@ -247,97 +245,97 @@ public class ChallengesManagerTest {
}
/**
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadChallengeNoOverwriteSilent() {
// load once
assertTrue(cm.loadChallenge(challenge, world, false, user, true));
assertTrue(cm.loadChallenge(challenge, false, user, true));
// load twice - no overwrite
assertFalse(cm.loadChallenge(challenge, world, false, user, true));
assertFalse(cm.loadChallenge(challenge, false, user, true));
}
/**
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadChallengeNoOverwriteNotSilent() {
// load once
assertTrue(cm.loadChallenge(challenge, world, false, user, true));
assertTrue(cm.loadChallenge(challenge, false, user, true));
// load twice - no overwrite, not silent
assertFalse(cm.loadChallenge(challenge, world, false, user, false));
verify(user).getTranslation(world, "challenges.messages.load-skipping", "[value]", "name");
assertFalse(cm.loadChallenge(challenge, false, user, false));
verify(user).getTranslation("challenges.messages.load-skipping", "[value]", "name");
}
/**
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadChallengeOverwriteSilent() {
// load once
assertTrue(cm.loadChallenge(challenge, world, false, user, true));
assertTrue(cm.loadChallenge(challenge, false, user, true));
// overwrite
assertTrue(cm.loadChallenge(challenge, world, true, user, true));
verify(user, never()).getTranslation(any(World.class), anyString(), anyString(), anyString());
assertTrue(cm.loadChallenge(challenge, true, user, true));
verify(user, never()).getTranslation(anyString(), anyString(), anyString());
}
/**
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadChallenge(world.bentobox.challenges.database.object.Challenge, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadChallengeOverwriteNotSilent() {
// load once
assertTrue(cm.loadChallenge(challenge, world, false, user, true));
assertTrue(cm.loadChallenge(challenge, false, user, true));
// overwrite not silent
assertTrue(cm.loadChallenge(challenge, world, true, user, false));
verify(user).getTranslation(world, "challenges.messages.load-overwriting", "[value]", "name");
assertTrue(cm.loadChallenge(challenge, true, user, false));
verify(user).getTranslation("challenges.messages.load-overwriting", "[value]", "name");
}
/**
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadLevelNoOverwriteSilent() {
// load once
assertTrue(cm.loadLevel(level, world, false, user, true));
assertTrue(cm.loadLevel(level, false, user, true));
// load twice - no overwrite
assertFalse(cm.loadLevel(level, world, false, user, true));
assertFalse(cm.loadLevel(level, false, user, true));
}
/**
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadLevelNoOverwriteNotSilent() {
// load once
assertTrue(cm.loadLevel(level, world, false, user, true));
assertTrue(cm.loadLevel(level, false, user, true));
// load twice - no overwrite, not silent
assertFalse(cm.loadLevel(level, world, false, user, false));
verify(user).getTranslation(world, "challenges.messages.load-skipping", "[value]", "Novice");
assertFalse(cm.loadLevel(level, false, user, false));
verify(user).getTranslation("challenges.messages.load-skipping", "[value]", "Novice");
}
/**
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadLevelOverwriteSilent() {
// load once
assertTrue(cm.loadLevel(level, world, false, user, true));
assertTrue(cm.loadLevel(level, false, user, true));
// overwrite
assertTrue(cm.loadLevel(level, world, true, user, true));
verify(user, never()).getTranslation(any(World.class), anyString(), anyString(), anyString());
assertTrue(cm.loadLevel(level, true, user, true));
verify(user, never()).getTranslation(anyString(), anyString(), anyString());
}
/**
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, World, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
* Test method for {@link ChallengesManager#loadLevel(world.bentobox.challenges.database.object.ChallengeLevel, boolean, world.bentobox.bentobox.api.user.User, boolean)}.
*/
@Test
public void testLoadLevelOverwriteNotSilent() {
// load once
assertTrue(cm.loadLevel(level, world, false, user, true));
assertTrue(cm.loadLevel(level, false, user, true));
// overwrite not silent
assertTrue(cm.loadLevel(level, world, true, user, false));
verify(user).getTranslation(world, "challenges.messages.load-overwriting", "[value]", "Novice");
assertTrue(cm.loadLevel(level, true, user, false));
verify(user).getTranslation("challenges.messages.load-overwriting", "[value]", "Novice");
}
/**
@ -662,7 +660,7 @@ public class ChallengesManagerTest {
public void testGetAllChallengesNames() {
assertTrue(cm.getAllChallengesNames(world).isEmpty());
cm.saveChallenge(challenge);
cm.loadChallenge(challenge, world, false, user, true);
cm.loadChallenge(challenge, false, user, true);
List<String> list = cm.getAllChallengesNames(world);
assertFalse(list.isEmpty());
assertEquals(cName, list.get(0));
@ -675,7 +673,7 @@ public class ChallengesManagerTest {
public void testGetAllChallenges() {
assertTrue(cm.getAllChallenges(world).isEmpty());
cm.saveChallenge(challenge);
cm.loadChallenge(challenge, world, false, user, true);
cm.loadChallenge(challenge, false, user, true);
List<Challenge> list = cm.getAllChallenges(world);
assertFalse(list.isEmpty());
assertEquals(challenge, list.get(0));
@ -690,12 +688,12 @@ public class ChallengesManagerTest {
assertTrue(cm.getFreeChallenges(world).isEmpty());
// One normal
cm.saveChallenge(challenge);
cm.loadChallenge(challenge, world, false, user, true);
cm.loadChallenge(challenge, false, user, true);
assertTrue(cm.getFreeChallenges(world).isEmpty());
// One free
challenge.setLevel("");
cm.saveChallenge(challenge);
cm.loadChallenge(challenge, world, false, user, true);
cm.loadChallenge(challenge, false, user, true);
List<Challenge> list = cm.getFreeChallenges(world);
assertFalse(list.isEmpty());
assertEquals(challenge, list.get(0));
@ -794,7 +792,7 @@ public class ChallengesManagerTest {
public void testGetLevelString() {
assertNull(cm.getLevel("dss"));
cm.saveLevel(level);
cm.loadLevel(level, world, false, user, true);
cm.loadLevel(level, false, user, true);
assertEquals(level, cm.getLevel(levelName));
}

View File

@ -6,6 +6,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@ -16,6 +17,7 @@ import java.util.Optional;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFactory;
@ -36,6 +38,7 @@ import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.configuration.WorldSettings;
import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.managers.CommandsManager;
@ -43,16 +46,16 @@ import world.bentobox.bentobox.managers.IslandWorldManager;
import world.bentobox.bentobox.managers.IslandsManager;
import world.bentobox.bentobox.util.Util;
import world.bentobox.challenges.ChallengesAddon;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.config.Settings;
import world.bentobox.challenges.config.SettingsUtils.VisibilityMode;
import world.bentobox.challenges.managers.ChallengesManager;
/**
* @author tastybento
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Bukkit.class, BentoBox.class, Util.class })
@PrepareForTest({Bukkit.class, BentoBox.class, ChatColor.class, Util.class})
public class ChallengesCommandTest {
@Mock
@ -101,7 +104,7 @@ public class ChallengesCommandTest {
Optional<GameModeAddon> optionalAddon = Optional.of(gameModeAddon);
when(iwm.getAddon(any())).thenReturn(optionalAddon);
when(plugin.getIWM()).thenReturn(iwm);
@NonNull
WorldSettings ws = new TestWorldSetting();
when(iwm.getWorldSettings(any())).thenReturn(ws);
@ -140,6 +143,10 @@ public class ChallengesCommandTest {
// Challenges exist
when(chm.hasAnyChallengeData(any(World.class))).thenReturn(true);
// ChatColor
PowerMockito.mockStatic(ChatColor.class);
when(ChatColor.translateAlternateColorCodes(any(char.class), anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
// Settings
Settings settings = new Settings();
when(addon.getChallengesSettings()).thenReturn(settings);
@ -154,9 +161,6 @@ public class ChallengesCommandTest {
// Util
PowerMockito.mockStatic(Util.class, Mockito.RETURNS_MOCKS);
when(Util.sameWorld(any(), any())).thenReturn(true);
when(Util.translateColorCodes(anyString()))
.thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
// Command under test
cc = new ChallengesPlayerCommand(addon, ic);
}
@ -168,7 +172,7 @@ public class ChallengesCommandTest {
public void testCanExecuteWrongWorld() {
when(iwm.inWorld(any(World.class))).thenReturn(false);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(user).getTranslation(world, "general.errors.wrong-world");
verify(user).getTranslation("general.errors.wrong-world");
}
/**
@ -180,7 +184,7 @@ public class ChallengesCommandTest {
when(chm.hasAnyChallengeData(any(World.class))).thenReturn(false);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(addon).logError("There are no challenges set up in world!");
verify(user).getTranslation(world, "challenges.errors.no-challenges");
verify(user).getTranslation("challenges.errors.no-challenges");
}
/**
@ -192,8 +196,8 @@ public class ChallengesCommandTest {
when(chm.hasAnyChallengeData(any(World.class))).thenReturn(false);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(addon).logError("There are no challenges set up in world!");
verify(user).getTranslation(world, "challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation(world, "challenges.errors.no-challenges");
verify(user).getTranslation("challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation("challenges.errors.no-challenges");
}
/**
@ -205,8 +209,8 @@ public class ChallengesCommandTest {
when(chm.hasAnyChallengeData(any(World.class))).thenReturn(false);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(addon).logError("There are no challenges set up in world!");
verify(user).getTranslation(world, "challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation(world, "challenges.errors.no-challenges");
verify(user).getTranslation("challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation("challenges.errors.no-challenges");
}
/**
@ -219,8 +223,8 @@ public class ChallengesCommandTest {
when(chm.hasAnyChallengeData(any(World.class))).thenReturn(false);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(addon).logError("There are no challenges set up in world!");
verify(user).getTranslation(world, "challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation(world, "challenges.errors.no-challenges");
verify(user).getTranslation("challenges.errors.no-challenges-admin", "[command]", "bsb challenges");
verify(user, never()).getTranslation("challenges.errors.no-challenges");
}
/**
@ -230,7 +234,7 @@ public class ChallengesCommandTest {
public void testCanExecuteNoIsland() {
when(im.getIsland(any(), any(User.class))).thenReturn(null);
assertFalse(cc.canExecute(user, "challenges", Collections.emptyList()));
verify(user).getTranslation(world, "general.errors.no-island");
verify(user).getTranslation("general.errors.no-island");
}
/**
@ -242,6 +246,16 @@ public class ChallengesCommandTest {
verify(user, never()).sendMessage(anyString());
}
/**
* Test method for {@link ChallengesPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
public void testExecuteUserStringListOfStringConsole() {
User console = mock(User.class);
assertFalse(cc.execute(console, "challenges", Collections.emptyList()));
verify(console).sendMessage(eq("commands.help.header"), eq(TextVariables.LABEL), eq("BSkyBlock"));
}
/**
* Test method for {@link ChallengesPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/

View File

@ -19,6 +19,7 @@ import java.util.Optional;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFactory;
@ -45,12 +46,11 @@ import world.bentobox.bentobox.managers.IslandWorldManager;
import world.bentobox.bentobox.managers.IslandsManager;
import world.bentobox.bentobox.util.Util;
import world.bentobox.challenges.ChallengesAddon;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.config.Settings;
import world.bentobox.challenges.config.SettingsUtils.VisibilityMode;
import world.bentobox.challenges.database.object.Challenge;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete;
import world.bentobox.challenges.utils.Constants;
import world.bentobox.challenges.utils.Utils;
/**
@ -58,7 +58,7 @@ import world.bentobox.challenges.utils.Utils;
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Bukkit.class, BentoBox.class, Utils.class, TryToComplete.class, Util.class })
@PrepareForTest({Bukkit.class, BentoBox.class, ChatColor.class, Utils.class, TryToComplete.class, Util.class})
public class CompleteChallengeCommandTest {
@Mock
@ -149,6 +149,11 @@ public class CompleteChallengeCommandTest {
List<String> nameList = Arrays.asList("world_maker", "world_placer", "bad_challenge_name", "world_breaker");
when(chm.getAllChallengesNames(any())).thenReturn(nameList);
// ChatColor
PowerMockito.mockStatic(ChatColor.class);
when(ChatColor.translateAlternateColorCodes(any(char.class), anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
// Settings
Settings settings = new Settings();
when(addon.getChallengesSettings()).thenReturn(settings);
@ -170,8 +175,6 @@ public class CompleteChallengeCommandTest {
// Util
PowerMockito.mockStatic(Util.class);
when(Util.tabLimit(any(), any())).thenAnswer((Answer<List<String>>) invocation -> (List<String>)invocation.getArgument(0, List.class));
when(Util.translateColorCodes(anyString()))
.thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
// Command under test
cc = new CompleteChallengeCommand(addon, ic);
@ -204,8 +207,7 @@ public class CompleteChallengeCommandTest {
@Test
public void testExecuteUserStringListOfStringNoArgs() {
assertFalse(cc.execute(user, "complete", Collections.emptyList()));
PowerMockito.verifyStatic(Utils.class);
Utils.sendMessage(user, world, Constants.ERRORS + "no-name");
verify(user).getTranslation(eq("challenges.errors.no-name"));
verify(user).sendMessage(eq("commands.help.header"), eq(TextVariables.LABEL), eq("BSkyBlock"));
}
@ -216,8 +218,7 @@ public class CompleteChallengeCommandTest {
public void testExecuteUserStringListOfStringUnknownChallenge() {
when(chm.getChallenge(anyString())).thenReturn(null);
assertFalse(cc.execute(user, "complete", Collections.singletonList("mychal")));
PowerMockito.verifyStatic(Utils.class);
Utils.sendMessage(user, world, Constants.ERRORS + "unknown-challenge");
verify(user).getTranslation(eq("challenges.errors.unknown-challenge"));
verify(user).sendMessage(eq("commands.help.header"), eq(TextVariables.LABEL), eq("BSkyBlock"));
}
@ -246,8 +247,7 @@ public class CompleteChallengeCommandTest {
@Test
public void testExecuteUserStringListOfStringKnownChallengeSuccessMultipleTimesNoPerm() {
assertTrue(cc.execute(user, "complete", Arrays.asList("mychal", "5")));
PowerMockito.verifyStatic(Utils.class);
Utils.sendMessage(user, world, Constants.ERRORS + "no-multiple-permission");
verify(user).getTranslation(eq("challenges.error.no-multiple-permission"));
}
/**