This commit is contained in:
Lautaro Mancini 2018-05-27 14:01:53 +00:00 committed by GitHub
commit 1acc8efe2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 2763 additions and 2799 deletions

View File

@ -1,6 +1,6 @@
name: BSkyBlock-Challenges name: BSkyBlock-Challenges
main: bskyblock.addon.challenges.ChallengesAddon main: bskyblock.addon.challenges.ChallengesAddon
version: 0.1 version: ${version}
authors: tastybento authors: tastybento

23
pom.xml
View File

@ -2,12 +2,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>bskyblock.addon</groupId>
<artifactId>Challenges</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<powermock.version>1.7.1</powermock.version> <powermock.version>1.7.1</powermock.version>
</properties> </properties>
<build> <build>
<defaultGoal>clean package install</defaultGoal> <defaultGoal>clean package install</defaultGoal>
<resources> <resources>
@ -28,7 +32,6 @@
</includes> </includes>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
@ -40,6 +43,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
@ -50,12 +54,13 @@
<dependency> <dependency>
<groupId>us.tastybento</groupId> <groupId>us.tastybento</groupId>
<artifactId>bskyblock</artifactId> <artifactId>bskyblock</artifactId>
<version>LATEST</version> <version>0.0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>bskyblock.addon</groupId> <groupId>bskyblock.addon</groupId>
<artifactId>Level</artifactId> <artifactId>Level</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -76,23 +81,13 @@
<version>${powermock.version}</version> <version>${powermock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository> </repository>
</repositories> </repositories>
<artifactId>Challenges</artifactId>
<groupId>bskyblock.addons</groupId>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>bskyblock.addon</groupId>
<artifactId>Level</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</dependencyManagement>
</project> </project>

View File

@ -13,37 +13,37 @@ import us.tastybento.bskyblock.api.addons.Addon;
*/ */
public class ChallengesAddon extends Addon { public class ChallengesAddon extends Addon {
private ChallengesManager challengesManager; private ChallengesManager challengesManager;
@Override @Override
public void onEnable() { public void onEnable() {
// Check if it is enabled - it might be loaded, but not enabled. // Check if it is enabled - it might be loaded, but not enabled.
if (getBSkyBlock() == null || !getBSkyBlock().isEnabled()) { if (getBSkyBlock() == null || !getBSkyBlock().isEnabled()) {
Bukkit.getLogger().severe("BSkyBlock is not available or disabled!"); Bukkit.getLogger().severe("BSkyBlock is not available or disabled!");
this.setEnabled(false); this.setEnabled(false);
return; return;
} }
// Challenges Manager // Challenges Manager
challengesManager = new ChallengesManager(this); challengesManager = new ChallengesManager(this);
// First time challenges creation // First time challenges creation
new FreshSqueezedChallenges(this); new FreshSqueezedChallenges(this);
// Register commands // Register commands
new ChallengesCommand(this); new ChallengesCommand(this);
new ChallengesAdminCommand(this); new ChallengesAdminCommand(this);
// Done // Done
} }
@Override @Override
public void onDisable(){ public void onDisable(){
if (challengesManager != null) { if (challengesManager != null) {
challengesManager.save(false); challengesManager.save(false);
} }
} }
public ChallengesManager getChallengesManager() { public ChallengesManager getChallengesManager() {
return challengesManager; return challengesManager;
} }
} }

View File

@ -32,400 +32,401 @@ import us.tastybento.bskyblock.util.Util;
public class ChallengesManager { public class ChallengesManager {
public static final String FREE = "Free"; public static final String FREE = "Free";
private Map<ChallengeLevels, Set<Challenges>> challengeMap; private Map<ChallengeLevels, Set<Challenges>> challengeMap;
private BSBConfig<Challenges> chConfig; private BSBConfig<Challenges> chConfig;
private BSBConfig<ChallengeLevels> lvConfig; private BSBConfig<ChallengeLevels> lvConfig;
private BSBDatabase<PlayerData> players; private BSBDatabase<PlayerData> players;
private ChallengesPanels challengesPanels; private ChallengesPanels challengesPanels;
private Map<UUID,PlayerData> playerData; private Map<UUID,PlayerData> playerData;
private ChallengesAddon addon; private ChallengesAddon addon;
public ChallengesManager(ChallengesAddon addon) { public ChallengesManager(ChallengesAddon addon) {
this.addon = addon; this.addon = addon;
// Set up the configs // Set up the configs
chConfig = new BSBConfig<>(addon, Challenges.class); chConfig = new BSBConfig<>(addon, Challenges.class);
lvConfig = new BSBConfig<>(addon, ChallengeLevels.class); lvConfig = new BSBConfig<>(addon, ChallengeLevels.class);
// Players is where all the player history will be stored // Players is where all the player history will be stored
players = new BSBDatabase<>(addon, PlayerData.class); players = new BSBDatabase<>(addon, PlayerData.class);
// Cache of challenges // Cache of challenges
challengeMap = new LinkedHashMap<>(); challengeMap = new LinkedHashMap<>();
// Start panels // Start panels
challengesPanels = new ChallengesPanels(addon, this); challengesPanels = new ChallengesPanels(addon, this);
// Cache of player data // Cache of player data
playerData = new HashMap<>(); playerData = new HashMap<>();
load(); load();
} }
/** /**
* Load player from database into the cache or create new player data * Load player from database into the cache or create new player data
* @param user - user to add * @param user - user to add
*/ */
private void addPlayer(User user) { private void addPlayer(User user) {
if (playerData.containsKey(user.getUniqueId())) { if (playerData.containsKey(user.getUniqueId())) {
return; return;
} }
// The player is not in the cache // The player is not in the cache
// Check if the player exists in the database // Check if the player exists in the database
if (players.objectExists(user.getUniqueId().toString())) { if (players.objectExists(user.getUniqueId().toString())) {
// Load player from database // Load player from database
PlayerData data = players.loadObject(user.getUniqueId().toString()); PlayerData data = players.loadObject(user.getUniqueId().toString());
// Store in cache // Store in cache
playerData.put(user.getUniqueId(), data); playerData.put(user.getUniqueId(), data);
} else { } else {
// Create the player data // Create the player data
PlayerData pd = new PlayerData(user.getUniqueId().toString()); PlayerData pd = new PlayerData(user.getUniqueId().toString());
players.saveObject(pd); players.saveObject(pd);
// Add to cache // Add to cache
playerData.put(user.getUniqueId(), pd); playerData.put(user.getUniqueId(), pd);
} }
} }
/** /**
* Check how many times a player has done a challenge before * Check how many times a player has done a challenge before
* @param user - user * @param user - user
* @param challenge - challenge * @param challenge - challenge
* @return - number of times * @return - number of times
*/ */
public long checkChallengeTimes(User user, Challenges challenge) { public long checkChallengeTimes(User user, Challenges challenge) {
addPlayer(user); addPlayer(user);
return playerData.get(user.getUniqueId()).getTimes(challenge.getUniqueId()); return playerData.get(user.getUniqueId()).getTimes(challenge.getUniqueId());
} }
/** /**
* Creates a simple example description of the requirements * Creates a simple example description of the requirements
* @param user - user of this command * @param user - user of this command
* @param requiredItems - list of items * @param requiredItems - list of items
* @return Description list * @return Description list
*/ */
private List<String> createDescription(User user, List<ItemStack> requiredItems) { private List<String> createDescription(User user, List<ItemStack> requiredItems) {
addPlayer(user); addPlayer(user);
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
result.add(user.getTranslation("challenges.admin.create.description")); result.add(user.getTranslation("challenges.admin.create.description"));
for (ItemStack item : requiredItems) { for (ItemStack item : requiredItems) {
result.add(user.getTranslation("challenges.admin.create.description-item-color") + item.getAmount() + " x " + Util.prettifyText(item.getType().toString())); result.add(user.getTranslation("challenges.admin.create.description-item-color") + item.getAmount() + " x " + Util.prettifyText(item.getType().toString()));
} }
return result; return result;
} }
/** /**
* Creates an inventory challenge * Creates an inventory challenge
* @param user - the user who is making the challenge * @param user - the user who is making the challenge
* @param inventory - the inventory that will be used to make the challenge * @param inventory - the inventory that will be used to make the challenge
*/ */
public boolean createInvChallenge(User user, Inventory inventory) { public boolean createInvChallenge(User user, Inventory inventory) {
addPlayer(user); addPlayer(user);
if (inventory.getContents().length == 0) { if (inventory.getContents().length == 0) {
return false; return false;
} }
Challenges newChallenge = new Challenges(); Challenges newChallenge = new Challenges();
newChallenge.setChallengeType(ChallengeType.INVENTORY); newChallenge.setChallengeType(ChallengeType.INVENTORY);
newChallenge.setFriendlyName(inventory.getTitle()); newChallenge.setFriendlyName(inventory.getTitle());
newChallenge.setDeployed(false); newChallenge.setDeployed(false);
List<ItemStack> requiredItems = new ArrayList<>(); List<ItemStack> requiredItems = new ArrayList<>();
inventory.forEach(item -> { inventory.forEach(item -> {
if (item != null && !item.getType().equals(Material.AIR)) { if (item != null && !item.getType().equals(Material.AIR)) {
requiredItems.add(item); requiredItems.add(item);
} }
}); });
newChallenge.setRequiredItems(requiredItems); newChallenge.setRequiredItems(requiredItems);
newChallenge.setTakeItems(true); newChallenge.setTakeItems(true);
newChallenge.setUniqueId(inventory.getTitle()); newChallenge.setUniqueId(inventory.getTitle());
newChallenge.setIcon(new ItemStack(Material.EMPTY_MAP)); newChallenge.setIcon(new ItemStack(Material.EMPTY_MAP));
newChallenge.setLevel(FREE); newChallenge.setLevel(FREE);
newChallenge.setDescription(createDescription(user, requiredItems)); newChallenge.setDescription(createDescription(user, requiredItems));
// Move all the items back to the player's inventory // Move all the items back to the player's inventory
inventory.forEach(item -> { inventory.forEach(item -> {
if (item != null) { if (item != null) {
Map<Integer, ItemStack> residual = user.getInventory().addItem(item); Map<Integer, ItemStack> residual = user.getInventory().addItem(item);
// Drop any residual items at the foot of the player // Drop any residual items at the foot of the player
residual.forEach((k, v) -> user.getWorld().dropItem(user.getLocation(), v)); residual.forEach((k, v) -> user.getWorld().dropItem(user.getLocation(), v));
} }
}); });
// Save the challenge // Save the challenge
if (!chConfig.saveConfigObject(newChallenge)) { if (!chConfig.saveConfigObject(newChallenge)) {
user.sendRawMessage(ChatColor.RED + "Challenge creation failed!"); user.sendRawMessage(ChatColor.RED + "Challenge creation failed!");
return false; return false;
} }
user.sendRawMessage("Success"); user.sendRawMessage("Success");
return true; return true;
} }
/** /**
* Create a surrounding challenge * Create a surrounding challenge
* @param challengeInfo - info on the challenge from the builder * @param challengeInfo - info on the challenge from the builder
* @return true if successful, false if not * @return true if successful, false if not
*/ */
public boolean createSurroundingChallenge(SurroundChallengeBuilder challengeInfo) { public boolean createSurroundingChallenge(SurroundChallengeBuilder challengeInfo) {
if (challengeInfo.getReqBlocks().isEmpty() && challengeInfo.getReqEntities().isEmpty()) { if (challengeInfo.getReqBlocks().isEmpty() && challengeInfo.getReqEntities().isEmpty()) {
challengeInfo.getOwner().sendMessage("challenges.error.no-items-clicked"); challengeInfo.getOwner().sendMessage("challenges.error.no-items-clicked");
return false; return false;
} }
Challenges newChallenge = new Challenges(); Challenges newChallenge = new Challenges();
newChallenge.setChallengeType(ChallengeType.ISLAND); newChallenge.setChallengeType(ChallengeType.ISLAND);
newChallenge.setFriendlyName(challengeInfo.getName()); newChallenge.setFriendlyName(challengeInfo.getName());
newChallenge.setDeployed(true); newChallenge.setDeployed(true);
newChallenge.setRequiredBlocks(challengeInfo.getReqBlocks()); newChallenge.setRequiredBlocks(challengeInfo.getReqBlocks());
newChallenge.setRequiredEntities(challengeInfo.getReqEntities()); newChallenge.setRequiredEntities(challengeInfo.getReqEntities());
newChallenge.setUniqueId(challengeInfo.getName()); newChallenge.setUniqueId(challengeInfo.getName());
newChallenge.setIcon(new ItemStack(Material.ARMOR_STAND)); newChallenge.setIcon(new ItemStack(Material.ARMOR_STAND));
newChallenge.setLevel(FREE); newChallenge.setLevel(FREE);
// Save the challenge // Save the challenge
if (!chConfig.saveConfigObject(newChallenge)) { if (!chConfig.saveConfigObject(newChallenge)) {
challengeInfo.getOwner().sendMessage("challenges.error.could-not-save"); challengeInfo.getOwner().sendMessage("challenges.error.could-not-save");
return false; return false;
} }
return true; return true;
} }
/** /**
* Get the list of all challenge unique names. * Get the list of all challenge unique names.
* Used for checking admin commands and tab complete * Used for checking admin commands and tab complete
* @return List of challenge names * @return List of challenge names
*/ */
public List<String> getAllChallengesList() { public List<String> getAllChallengesList() {
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
challengeMap.values().forEach(ch -> ch.forEach(c -> result.add(c.getUniqueId()))); challengeMap.values().forEach(ch -> ch.forEach(c -> result.add(c.getUniqueId())));
return result; return result;
} }
/** /**
* Get challenge by name * Get challenge by name
* @param name - unique name of challenge * @param name - unique name of challenge
* @return - challenge or null if it does not exist * @return - challenge or null if it does not exist
*/ */
public Challenges getChallenge(String name) { public Challenges getChallenge(String name) {
for (Set<Challenges> ch : challengeMap.values()) { for (Set<Challenges> ch : challengeMap.values()) {
Optional<Challenges> challenge = ch.stream().filter(c -> c.getUniqueId().equalsIgnoreCase(name)).findFirst(); Optional<Challenges> challenge = ch.stream().filter(c -> c.getUniqueId().equalsIgnoreCase(name)).findFirst();
if (challenge.isPresent()) { if (challenge.isPresent()) {
return challenge.get(); return challenge.get();
} }
} }
return null; return null;
} }
/** /**
* Get the status on every level * Get the status on every level
* @param user - user * @param user - user
* @return Level status - how many challenges still to do on which level * @return Level status - how many challenges still to do on which level
*/ */
public List<LevelStatus> getChallengeLevelStatus(User user) { public List<LevelStatus> getChallengeLevelStatus(User user) {
addPlayer(user); addPlayer(user);
PlayerData pd = playerData.get(user.getUniqueId()); PlayerData pd = playerData.get(user.getUniqueId());
List<LevelStatus> result = new ArrayList<>(); List<LevelStatus> result = new ArrayList<>();
ChallengeLevels previousLevel = null; ChallengeLevels previousLevel = null;
// The first level is always unlocked // The first level is always unlocked
boolean isUnlocked = true; boolean isUnlocked = true;
// For each challenge level, check how many the user has done // For each challenge level, check how many the user has done
for (Entry<ChallengeLevels, Set<Challenges>> en : challengeMap.entrySet()) { for (Entry<ChallengeLevels, Set<Challenges>> en : challengeMap.entrySet()) {
int total = challengeMap.values().size(); int total = challengeMap.values().size();
int waiverAmount = en.getKey().getWaiveramount(); int waiverAmount = en.getKey().getWaiveramount();
int challengesDone = (int) en.getValue().stream().filter(ch -> pd.isChallengeDone(ch.getUniqueId())).count(); int challengesDone = (int) en.getValue().stream().filter(ch -> pd.isChallengeDone(ch.getUniqueId())).count();
int challsToDo = Math.max(0,total-challengesDone-waiverAmount); int challsToDo = Math.max(0,total-challengesDone-waiverAmount);
boolean complete = challsToDo > 0 ? false : true; boolean complete = challsToDo > 0 ? false : true;
// Create result class with the data // Create result class with the data
result.add(new LevelStatus(en.getKey(), previousLevel, challsToDo, complete, isUnlocked)); result.add(new LevelStatus(en.getKey(), previousLevel, challsToDo, complete, isUnlocked));
// Set up the next level for the next loop // Set up the next level for the next loop
previousLevel = en.getKey(); previousLevel = en.getKey();
isUnlocked = complete; isUnlocked = complete;
} }
return result; return result;
} }
/** /**
* @return the challengeList * @return the challengeList
*/ */
public Map<ChallengeLevels, Set<Challenges>> getChallengeList() { public Map<ChallengeLevels, Set<Challenges>> getChallengeList() {
return challengeMap; return challengeMap;
} }
/** /**
* Get the set of challenges for this level * Get the set of challenges for this level
* @param level - the level required * @param level - the level required
* @return the set of challenges for this level, or the first set of challenges if level is blank, or a blank list if there are no challenges * @return the set of challenges for this level, or the first set of challenges if level is blank, or a blank list if there are no challenges
*/ */
public Set<Challenges> getChallenges(String level) { public Set<Challenges> getChallenges(String level) {
Optional<ChallengeLevels> lv = challengeMap.keySet().stream().filter(l -> l.getUniqueId().equalsIgnoreCase(level)).findFirst(); Optional<ChallengeLevels> lv = challengeMap.keySet().stream().filter(l -> l.getUniqueId().equalsIgnoreCase(level)).findFirst();
return lv.isPresent() ? challengeMap.get(lv.get()) : new HashSet<>(); return lv.isPresent() ? challengeMap.get(lv.get()) : new HashSet<>();
} }
/** /**
* @return the challengesPanels * @return the challengesPanels
*/ */
public ChallengesPanels getChallengesPanels() { public ChallengesPanels getChallengesPanels() {
return challengesPanels; return challengesPanels;
} }
/** /**
* Get the previous level to the one supplied * Get the previous level to the one supplied
* @param currentLevel - the current level * @param currentLevel - the current level
* @return the previous level, or null if there is none * @return the previous level, or null if there is none
*/ */
public ChallengeLevels getPreviousLevel(ChallengeLevels currentLevel) { public ChallengeLevels getPreviousLevel(ChallengeLevels currentLevel) {
ChallengeLevels result = null; ChallengeLevels result = null;
for (ChallengeLevels level : challengeMap.keySet()) { for (ChallengeLevels level : challengeMap.keySet()) {
if (level.equals(currentLevel)) { if (level.equals(currentLevel)) {
return result; return result;
} }
result = level; result = level;
} }
return result; return result;
} }
/** /**
* Check if a challenge exists - case insensitive * Check if a challenge exists - case insensitive
* @param name - name of challenge * @param name - name of challenge
* @return true if it exists, otherwise false * @return true if it exists, otherwise false
*/ */
public boolean isChallenge(String name) { public boolean isChallenge(String name) {
for (Set<Challenges> ch : challengeMap.values()) { for (Set<Challenges> ch : challengeMap.values()) {
if (ch.stream().anyMatch(c -> c.getUniqueId().equalsIgnoreCase(name))) { if (ch.stream().anyMatch(c -> c.getUniqueId().equalsIgnoreCase(name))) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Checks if a challenge is complete or not * Checks if a challenge is complete or not
* @param uniqueId - unique ID - player's UUID * @param uniqueId - unique ID - player's UUID
* @param challengeName - Challenge uniqueId * @param challengeName - Challenge uniqueId
* @return - true if completed * @return - true if completed
*/ */
public boolean isChallengeComplete(User user, String challengeName) { public boolean isChallengeComplete(User user, String challengeName) {
addPlayer(user); addPlayer(user);
return playerData.get(user.getUniqueId()).isChallengeDone(challengeName); return playerData.get(user.getUniqueId()).isChallengeDone(challengeName);
} }
/** /**
* Check is user can see level * Check is user can see level
* @param user - user * @param user - user
* @param level - level unique id * @param level - level unique id
* @return true if level is unlocked * @return true if level is unlocked
*/ */
public boolean isLevelUnlocked(User user, String level) { public boolean isLevelUnlocked(User user, String level) {
addPlayer(user); addPlayer(user);
return getChallengeLevelStatus(user).stream().filter(LevelStatus::isUnlocked).anyMatch(lv -> lv.getLevel().getUniqueId().equalsIgnoreCase(level)); return getChallengeLevelStatus(user).stream().filter(LevelStatus::isUnlocked).anyMatch(lv -> lv.getLevel().getUniqueId().equalsIgnoreCase(level));
} }
/** /**
* Clear and reload all challenges * Clear and reload all challenges
*/ */
public void load() { public void load() {
// Load the challenges // Load the challenges
challengeMap.clear(); challengeMap.clear();
addon.getLogger().info("Loading challenges..."); addon.getLogger().info("Loading challenges...");
chConfig.loadConfigObjects().forEach(this::storeChallenge); chConfig.loadConfigObjects().forEach(this::storeChallenge);
sortChallenges(); sortChallenges();
players.loadObjects().forEach(pd -> { players.loadObjects().forEach(pd -> {
try { try {
UUID uuid = UUID.fromString(pd.getUniqueId()); UUID uuid = UUID.fromString(pd.getUniqueId());
playerData.put(uuid,pd); playerData.put(uuid,pd);
} catch (Exception e) { } catch (Exception e) {
addon.getLogger().severe("UUID for player in challenge data file is invalid!"); addon.getLogger().severe("UUID for player in challenge data file is invalid!");
} }
}); });
} }
/** /**
* Save configs and player data * Save configs and player data
*/ */
private void save() { private void save() {
challengeMap.entrySet().forEach(en -> { challengeMap.entrySet().forEach(en -> {
lvConfig.saveConfigObject(en.getKey()); lvConfig.saveConfigObject(en.getKey());
en.getValue().forEach(chConfig::saveConfigObject); en.getValue().forEach(chConfig::saveConfigObject);
}); });
playerData.values().forEach(players :: saveObject); playerData.values().forEach(players :: saveObject);
} }
/** /**
* Save to the database * Save to the database
* @param async - if true, saving will be done async * @param async - if true, saving will be done async
*/ */
public void save(boolean async) { public void save(boolean async) {
if (async) { if (async) {
addon.getServer().getScheduler().runTaskAsynchronously(addon.getBSkyBlock(), this::save); addon.getServer().getScheduler().runTaskAsynchronously(addon.getBSkyBlock(), this::save);
} else { } else {
save(); save();
} }
} }
/** /**
* Sets the challenge as complete and increments the number of times it has been completed * Sets the challenge as complete and increments the number of times it has been completed
* @param user * @param user
* @param uniqueId * @param uniqueId
*/ */
public void setChallengeComplete(User user, String challengeUniqueId) { public void setChallengeComplete(User user, String challengeUniqueId) {
addPlayer(user); addPlayer(user);
playerData.get(user.getUniqueId()).setChallengeDone(challengeUniqueId); playerData.get(user.getUniqueId()).setChallengeDone(challengeUniqueId);
} }
/** /**
* @param challengeList the challengeList to set * @param challengeList the challengeList to set
*/ */
public void setChallengeList(Map<ChallengeLevels, Set<Challenges>> challengeList) { public void setChallengeList(Map<ChallengeLevels, Set<Challenges>> challengeList) {
this.challengeMap = challengeList; this.challengeMap = challengeList;
} }
public void sortChallenges() { public void sortChallenges() {
// Sort the challenge list into level order // Sort the challenge list into level order
challengeMap = challengeMap.entrySet().stream() challengeMap = challengeMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey()) .sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new)); (oldValue, newValue) -> oldValue, LinkedHashMap::new));
} }
/** /**
* Stores the challenge. If a challenge already exists with the same name, it is overwritten. * Stores the challenge. If a challenge already exists with the same name, it is overwritten.
* @param challenge * @param challenge
*/ */
public void storeChallenge(Challenges challenge) { public void storeChallenge(Challenges challenge) {
// See if we have this level already // See if we have this level already
ChallengeLevels level; ChallengeLevels level;
if (lvConfig.configObjectExists(challenge.getLevel())) { if (lvConfig.configObjectExists(challenge.getLevel())) {
// Get it from the database // Get it from the database
level = lvConfig.loadConfigObject(challenge.getLevel()); level = lvConfig.loadConfigObject(challenge.getLevel());
} else { } else {
// Make it // Make it
level = new ChallengeLevels(); level = new ChallengeLevels();
level.setUniqueId(challenge.getLevel()); level.setUniqueId(challenge.getLevel());
lvConfig.saveConfigObject(level); lvConfig.saveConfigObject(level);
} }
if (challengeMap.containsKey(level)) { if (challengeMap.containsKey(level)) {
// Replace if this challenge uniqueId already exists // Replace if this challenge uniqueId already exists
if (challengeMap.get(level).contains(challenge)) { if (challengeMap.get(level).contains(challenge)) {
challengeMap.get(level).remove(challenge); challengeMap.get(level).remove(challenge);
} }
challengeMap.get(level).add(challenge); challengeMap.get(level).add(challenge);
} else { } else {
// First challenge of this level type // First challenge of this level type
Set<Challenges> challenges = new HashSet<>(); Set<Challenges> challenges = new HashSet<>();
challenges.add(challenge); challenges.add(challenge);
challengeMap.put(level, challenges); challengeMap.put(level, challenges);
} }
} }
/** /**
* Store a challenge level * Store a challenge level
* @param level the challenge level * @param level the challenge level
*/ */
public void storeLevel(ChallengeLevels level) { public void storeLevel(ChallengeLevels level) {
lvConfig.saveConfigObject(level); lvConfig.saveConfigObject(level);
} }
/** /**
* Simple splitter * Simple splitter
* @param string - string to be split * @param string - string to be split
* @return list of split strings * @return list of split strings
*/ */
public List<String> stringSplit(String string) { public List<String> stringSplit(String string) {
string = ChatColor.translateAlternateColorCodes('&', string); string = ChatColor.translateAlternateColorCodes('&', string);
// Check length of lines // Check length of lines
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
Arrays.asList(string.split("\\|")).forEach(line -> result.addAll(Arrays.asList(WordUtils.wrap(line,25).split("\\n")))); Arrays.asList(string.split("\\|")).forEach(line -> result.addAll(Arrays.asList(WordUtils.wrap(line,25).split("\\n"))));
return result; return result;
} }
}
}

View File

@ -20,134 +20,132 @@ import bskyblock.addon.challenges.database.object.Challenges;
public class FreshSqueezedChallenges { public class FreshSqueezedChallenges {
ChallengesAddon addon; ChallengesAddon addon;
YamlConfiguration chal; YamlConfiguration chal;
public FreshSqueezedChallenges(ChallengesAddon challengesAddon) { public FreshSqueezedChallenges(ChallengesAddon challengesAddon) {
this.addon = challengesAddon; this.addon = challengesAddon;
File challengeFile = new File(addon.getDataFolder(), "challenges.yml"); File challengeFile = new File(addon.getDataFolder(), "challenges.yml");
if (!challengeFile.exists()) { if (!challengeFile.exists()) {
addon.saveResource("challenges.yml",false); addon.saveResource("challenges.yml",false);
} }
chal = new YamlConfiguration(); chal = new YamlConfiguration();
try { try {
chal.load(challengeFile); chal.load(challengeFile);
} catch (IOException | InvalidConfigurationException e) { } catch (IOException | InvalidConfigurationException e) {
addon.getLogger().severe("Could not set up initial challenges"); addon.getLogger().severe("Could not set up initial challenges");
} }
makeLevels(); makeLevels();
makeChallenges(); makeChallenges();
addon.getChallengesManager().save(true); addon.getChallengesManager().save(true);
} }
private void makeLevels() { private void makeLevels() {
// Parse the levels // Parse the levels
String levels = chal.getString("challenges.levels", ""); String levels = chal.getString("challenges.levels", "");
if (!levels.isEmpty()) { if (!levels.isEmpty()) {
String[] lvs = levels.split(" "); String[] lvs = levels.split(" ");
int order = 0; int order = 0;
for (String level : lvs) { for (String level : lvs) {
ChallengeLevels challengeLevel = new ChallengeLevels(); ChallengeLevels challengeLevel = new ChallengeLevels();
challengeLevel.setFriendlyName(level); challengeLevel.setFriendlyName(level);
challengeLevel.setUniqueId(level); challengeLevel.setUniqueId(level);
challengeLevel.setOrder(order++); challengeLevel.setOrder(order++);
challengeLevel.setWaiveramount(chal.getInt("challenges.waiveramount")); challengeLevel.setWaiveramount(chal.getInt("challenges.waiveramount"));
// Check if there is a level reward // Check if there is a level reward
ConfigurationSection unlock = chal.getConfigurationSection("challenges.levelUnlock." + level); ConfigurationSection unlock = chal.getConfigurationSection("challenges.levelUnlock." + level);
if (unlock != null) { if (unlock != null) {
challengeLevel.setUnlockMessage(unlock.getString("message")); challengeLevel.setUnlockMessage(unlock.getString("message"));
challengeLevel.setRewardDescription(unlock.getString("rewardDesc","")); challengeLevel.setRewardDescription(unlock.getString("rewardDesc",""));
challengeLevel.setRewardItems(parseItems(unlock.getString("itemReward",""))); challengeLevel.setRewardItems(parseItems(unlock.getString("itemReward","")));
challengeLevel.setMoneyReward(unlock.getInt("moneyReward")); challengeLevel.setMoneyReward(unlock.getInt("moneyReward"));
challengeLevel.setExpReward(unlock.getInt("expReward")); challengeLevel.setExpReward(unlock.getInt("expReward"));
challengeLevel.setRewardCommands(unlock.getStringList("commands")); challengeLevel.setRewardCommands(unlock.getStringList("commands"));
} }
addon.getChallengesManager().storeLevel(challengeLevel); addon.getChallengesManager().storeLevel(challengeLevel);
} }
} }
} }
/** /**
* Imports challenges * Imports challenges
*/ */
private void makeChallenges() { private void makeChallenges() {
// Parse the challenge file // Parse the challenge file
ConfigurationSection chals = chal.getConfigurationSection("challenges.challengeList"); ConfigurationSection chals = chal.getConfigurationSection("challenges.challengeList");
for (String challenge : chals.getKeys(false)) { for (String challenge : chals.getKeys(false)) {
Challenges newChallenge = new Challenges(); Challenges newChallenge = new Challenges();
newChallenge.setUniqueId(challenge); newChallenge.setUniqueId(challenge);
ConfigurationSection details = chals.getConfigurationSection(challenge); ConfigurationSection details = chals.getConfigurationSection(challenge);
newChallenge.setFriendlyName(details.getString("friendlyname", challenge)); newChallenge.setFriendlyName(details.getString("friendlyname", challenge));
newChallenge.setDescription(addon.getChallengesManager().stringSplit(details.getString("description", ""))); newChallenge.setDescription(addon.getChallengesManager().stringSplit(details.getString("description", "")));
newChallenge.setIcon(new ParseItem(addon, details.getString("icon") + ":1").getItem()); newChallenge.setIcon(new ParseItem(addon, details.getString("icon") + ":1").getItem());
newChallenge.setLevel(details.getString("level", ChallengesManager.FREE)); newChallenge.setLevel(details.getString("level", ChallengesManager.FREE));
newChallenge.setChallengeType(Challenges.ChallengeType.valueOf(details.getString("type","INVENTORY").toUpperCase())); newChallenge.setChallengeType(Challenges.ChallengeType.valueOf(details.getString("type","INVENTORY").toUpperCase()));
newChallenge.setTakeItems(details.getBoolean("takeItems",true)); newChallenge.setTakeItems(details.getBoolean("takeItems",true));
newChallenge.setRewardText(details.getString("rewardText", "")); newChallenge.setRewardText(details.getString("rewardText", ""));
newChallenge.setRewardCommands(details.getStringList("rewardcommands")); newChallenge.setRewardCommands(details.getStringList("rewardcommands"));
newChallenge.setMoneyReward(details.getInt("moneyReward",0)); newChallenge.setMoneyReward(details.getInt("moneyReward",0));
newChallenge.setExpReward(details.getInt("expReward")); newChallenge.setExpReward(details.getInt("expReward"));
newChallenge.setRepeatable(details.getBoolean("repeatable")); newChallenge.setRepeatable(details.getBoolean("repeatable"));
newChallenge.setRepeatRewardText(details.getString("repeatRewardText","")); newChallenge.setRepeatRewardText(details.getString("repeatRewardText",""));
newChallenge.setRepeatMoneyReward(details.getInt("repearMoneyReward")); newChallenge.setRepeatMoneyReward(details.getInt("repearMoneyReward"));
newChallenge.setRepeatExpReward(details.getInt("repeatExpReward")); newChallenge.setRepeatExpReward(details.getInt("repeatExpReward"));
newChallenge.setRepeatRewardCommands(details.getStringList("repeatrewardcommands")); newChallenge.setRepeatRewardCommands(details.getStringList("repeatrewardcommands"));
newChallenge.setMaxTimes(details.getInt("maxtimes")); newChallenge.setMaxTimes(details.getInt("maxtimes"));
// TODO reset allowed // TODO reset allowed
newChallenge.setReqMoney(details.getInt("requiredMoney")); newChallenge.setReqMoney(details.getInt("requiredMoney"));
newChallenge.setReqExp(details.getInt("requiredExp")); newChallenge.setReqExp(details.getInt("requiredExp"));
String reqItems = details.getString("requiredItems",""); String reqItems = details.getString("requiredItems","");
if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.INVENTORY)) { if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.INVENTORY)) {
newChallenge.setRequiredItems(parseItems(reqItems)); newChallenge.setRequiredItems(parseItems(reqItems));
} else if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.LEVEL)) { } else if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.LEVEL)) {
newChallenge.setReqIslandlevel(Long.parseLong(reqItems)); newChallenge.setReqIslandlevel(Long.parseLong(reqItems));
} else if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.ISLAND)) { } else if (newChallenge.getChallengeType().equals(Challenges.ChallengeType.ISLAND)) {
parseEntities(newChallenge, reqItems); parseEntities(newChallenge, reqItems);
} }
newChallenge.setItemReward(parseItems(details.getString("itemReward"))); newChallenge.setItemReward(parseItems(details.getString("itemReward")));
newChallenge.setRepeatItemReward(parseItems(details.getString("repeatItemReward"))); newChallenge.setRepeatItemReward(parseItems(details.getString("repeatItemReward")));
// Save // Save
addon.getChallengesManager().storeChallenge(newChallenge); addon.getChallengesManager().storeChallenge(newChallenge);
} }
addon.getChallengesManager().sortChallenges(); addon.getChallengesManager().sortChallenges();
} }
/** /**
* Run through entity types and materials and try to match to the string given * Run through entity types and materials and try to match to the string given
* @param challenge - challenge to be adjusted * @param challenge - challenge to be adjusted
* @param string - string from YAML file * @param string - string from YAML file
*/ */
private void parseEntities(Challenges challenge, String string) { private void parseEntities(Challenges challenge, String string) {
Map<EntityType, Integer> req = new EnumMap<>(EntityType.class); Map<EntityType, Integer> req = new EnumMap<>(EntityType.class);
Map<Material, Integer> blocks = new EnumMap<>(Material.class); Map<Material, Integer> blocks = new EnumMap<>(Material.class);
if (!string.isEmpty()) { if (!string.isEmpty()) {
for (String s : string.split(" ")) { for (String s : string.split(" ")) {
String[] part = s.split(":"); String[] part = s.split(":");
try { try {
Arrays.asList(EntityType.values()).stream().filter(t -> t.name().equalsIgnoreCase(part[0])).forEach(t -> req.put(t, Integer.valueOf(part[1]))); Arrays.asList(EntityType.values()).stream().filter(t -> t.name().equalsIgnoreCase(part[0])).forEach(t -> req.put(t, Integer.valueOf(part[1])));
Arrays.asList(Material.values()).stream().filter(t -> t.name().equalsIgnoreCase(part[0])).forEach(t -> blocks.put(t, Integer.valueOf(part[1]))); Arrays.asList(Material.values()).stream().filter(t -> t.name().equalsIgnoreCase(part[0])).forEach(t -> blocks.put(t, Integer.valueOf(part[1])));
} catch (Exception e) { } catch (Exception e) {
addon.getLogger().severe("Cannot parse '" + s + "'. Skipping..."); addon.getLogger().severe("Cannot parse '" + s + "'. Skipping...");
} }
} }
} }
challenge.setRequiredEntities(req); challenge.setRequiredEntities(req);
challenge.setRequiredBlocks(blocks); challenge.setRequiredBlocks(blocks);
} }
private List<ItemStack> parseItems(String reqList) { private List<ItemStack> parseItems(String reqList) {
List<ItemStack> result = new ArrayList<>(); List<ItemStack> result = new ArrayList<>();
if (!reqList.isEmpty()) { if (!reqList.isEmpty()) {
for (String s : reqList.split(" ")) { for (String s : reqList.split(" ")) {
ItemStack item = new ParseItem(addon,s).getItem(); ItemStack item = new ParseItem(addon,s).getItem();
if (item != null) { if (item != null) {
result.add(item); result.add(item);
} }
} }
} }
return result; return result;
} }
}
}

View File

@ -8,57 +8,62 @@ import bskyblock.addon.challenges.database.object.ChallengeLevels;
* *
*/ */
public class LevelStatus { public class LevelStatus {
private final ChallengeLevels level;
private final ChallengeLevels previousLevel;
private final int numberOfChallengesStillToDo;
private final boolean complete;
private final boolean isUnlocked;
/** private final ChallengeLevels level;
* @param level - level private final ChallengeLevels previousLevel;
* @param previousLevel - previous level private final int numberOfChallengesStillToDo;
* @param numberOfChallengesStillToDo - number of challenges still to do on this level private final boolean complete;
* @param complete - whether complete or not private final boolean isUnlocked;
* @param isUnlocked
*/
public LevelStatus(ChallengeLevels level, ChallengeLevels previousLevel, int numberOfChallengesStillToDo, boolean complete, boolean isUnlocked) {
super();
this.level = level;
this.previousLevel = previousLevel;
this.numberOfChallengesStillToDo = numberOfChallengesStillToDo;
this.complete = complete;
this.isUnlocked = isUnlocked;
}
/**
* @return the level
*/
public ChallengeLevels getLevel() {
return level;
}
/**
* @return the numberOfChallengesStillToDo
*/
public int getNumberOfChallengesStillToDo() {
return numberOfChallengesStillToDo;
}
/**
* @return the previousLevel
*/
public ChallengeLevels getPreviousLevel() {
return previousLevel;
}
/**
* @return the complete
*/
public boolean isComplete() {
return complete;
}
/**
* @return the isUnlocked
*/
public boolean isUnlocked() {
return isUnlocked;
}
/**
* @param level - level
* @param previousLevel - previous level
* @param numberOfChallengesStillToDo - number of challenges still to do on this level
* @param complete - whether complete or not
* @param isUnlocked
*/
public LevelStatus(ChallengeLevels level, ChallengeLevels previousLevel, int numberOfChallengesStillToDo, boolean complete, boolean isUnlocked) {
super();
this.level = level;
this.previousLevel = previousLevel;
this.numberOfChallengesStillToDo = numberOfChallengesStillToDo;
this.complete = complete;
this.isUnlocked = isUnlocked;
}
} /**
* @return the level
*/
public ChallengeLevels getLevel() {
return level;
}
/**
* @return the numberOfChallengesStillToDo
*/
public int getNumberOfChallengesStillToDo() {
return numberOfChallengesStillToDo;
}
/**
* @return the previousLevel
*/
public ChallengeLevels getPreviousLevel() {
return previousLevel;
}
/**
* @return the complete
*/
public boolean isComplete() {
return complete;
}
/**
* @return the isUnlocked
*/
public boolean isUnlocked() {
return isUnlocked;
}
}

View File

@ -17,124 +17,126 @@ import org.bukkit.potion.PotionType;
*/ */
public class ParseItem { public class ParseItem {
private final ItemStack item; private final ItemStack item;
private ChallengesAddon addon;
public ParseItem(ChallengesAddon addon, String s) { private ChallengesAddon addon;
this.addon = addon;
item = parseItem(s);
}
/** public ParseItem(ChallengesAddon addon, String s) {
* Parse a string into an itemstack this.addon = addon;
* @param s - input string item = parseItem(s);
* @return ItemStack or null if parsing failed }
*/
private ItemStack parseItem(String s) {
String[] part = s.split(":");
// Material:Qty
if (part.length == 2) {
return two(s, part);
} else if (part.length == 3) {
return three(s, part);
} else if (part.length == 6 && (part[0].contains("POTION") || part[0].equalsIgnoreCase("TIPPED_ARROW"))) {
return potion(s, part);
}
return null;
} /**
* Parse a string into an itemstack
* @param s - input string
* @return ItemStack or null if parsing failed
*/
private ItemStack parseItem(String s) {
String[] part = s.split(":");
// Material:Qty
if (part.length == 2) {
return two(s, part);
} else if (part.length == 3) {
return three(s, part);
} else if (part.length == 6 && (part[0].contains("POTION") || part[0].equalsIgnoreCase("TIPPED_ARROW"))) {
return potion(s, part);
}
return null;
private ItemStack potion(String s, String[] part) { }
int reqAmount = 0;
try {
reqAmount = Integer.parseInt(part[5]);
} catch (Exception e) {
addon.getLogger().severe(() -> "Could not parse the quantity of the potion or tipped arrow " + s);
return null;
}
/*
* # Format POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
# LEVEL, EXTENDED, SPLASH, LINGER are optional.
# LEVEL is a number, 1 or 2
# LINGER is for V1.9 servers and later
# Examples:
# POTION:STRENGTH:1:EXTENDED:SPLASH:1
# POTION:INSTANT_DAMAGE:2::LINGER:2
# POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1
# POTION:WEAKNESS::::1 - any weakness potion
*/
ItemStack result = new ItemStack(Material.POTION);
if (part[4].equalsIgnoreCase("SPLASH")) {
result = new ItemStack(Material.SPLASH_POTION);
} else if (part[4].equalsIgnoreCase("LINGER")) {
result = new ItemStack(Material.LINGERING_POTION);
}
if (part[0].equalsIgnoreCase("TIPPED_ARROW")) {
result = new ItemStack(Material.TIPPED_ARROW);
}
result.setAmount(reqAmount);
PotionMeta potionMeta = (PotionMeta)(result.getItemMeta());
PotionType type = PotionType.valueOf(part[1].toUpperCase());
boolean isUpgraded = (part[2].isEmpty() || part[2].equalsIgnoreCase("1")) ? false: true;
boolean isExtended = part[3].equalsIgnoreCase("EXTENDED") ? true : false;
PotionData data = new PotionData(type, isExtended, isUpgraded);
potionMeta.setBasePotionData(data);
result.setAmount(reqAmount); private ItemStack potion(String s, String[] part) {
return result; int reqAmount = 0;
} try {
reqAmount = Integer.parseInt(part[5]);
} catch (Exception e) {
addon.getLogger().severe(() -> "Could not parse the quantity of the potion or tipped arrow " + s);
return null;
}
/*
* # Format POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
# LEVEL, EXTENDED, SPLASH, LINGER are optional.
# LEVEL is a number, 1 or 2
# LINGER is for V1.9 servers and later
# Examples:
# POTION:STRENGTH:1:EXTENDED:SPLASH:1
# POTION:INSTANT_DAMAGE:2::LINGER:2
# POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1
# POTION:WEAKNESS::::1 - any weakness potion
*/
ItemStack result = new ItemStack(Material.POTION);
if (part[4].equalsIgnoreCase("SPLASH")) {
result = new ItemStack(Material.SPLASH_POTION);
} else if (part[4].equalsIgnoreCase("LINGER")) {
result = new ItemStack(Material.LINGERING_POTION);
}
if (part[0].equalsIgnoreCase("TIPPED_ARROW")) {
result = new ItemStack(Material.TIPPED_ARROW);
}
result.setAmount(reqAmount);
PotionMeta potionMeta = (PotionMeta)(result.getItemMeta());
PotionType type = PotionType.valueOf(part[1].toUpperCase());
boolean isUpgraded = (part[2].isEmpty() || part[2].equalsIgnoreCase("1")) ? false: true;
boolean isExtended = part[3].equalsIgnoreCase("EXTENDED") ? true : false;
PotionData data = new PotionData(type, isExtended, isUpgraded);
potionMeta.setBasePotionData(data);
private ItemStack three(String s, String[] part) { result.setAmount(reqAmount);
// Rearrange return result;
String[] twoer = {part[0], part[2]}; }
ItemStack result = two(s, twoer);
if (result == null) {
return null;
}
if (StringUtils.isNumeric(part[1])) {
result.setDurability((short) Integer.parseInt(part[1]));
} else if (result.getType().equals(Material.MONSTER_EGG)) {
// Check if this is a string
EntityType entityType = EntityType.valueOf(part[1]);
SpawnEggMeta meta = ((SpawnEggMeta)result.getItemMeta());
meta.setSpawnedType(entityType);
result.setItemMeta(meta);
}
return result;
} private ItemStack three(String s, String[] part) {
// Rearrange
String[] twoer = {part[0], part[2]};
ItemStack result = two(s, twoer);
if (result == null) {
return null;
}
if (StringUtils.isNumeric(part[1])) {
result.setDurability((short) Integer.parseInt(part[1]));
} else if (result.getType().equals(Material.MONSTER_EGG)) {
// Check if this is a string
EntityType entityType = EntityType.valueOf(part[1]);
SpawnEggMeta meta = ((SpawnEggMeta)result.getItemMeta());
meta.setSpawnedType(entityType);
result.setItemMeta(meta);
}
return result;
private void showError(String s) { }
addon.getLogger().severe(() -> "Problem with " + s + " in challenges.yml!");
}
private ItemStack two(String s, String[] part) { private void showError(String s) {
int reqAmount = 0; addon.getLogger().severe(() -> "Problem with " + s + " in challenges.yml!");
try { }
reqAmount = Integer.parseInt(part[1]);
} catch (Exception e) {
addon.getLogger().severe(() -> "Could not parse the quantity of the item " + s);
return null;
}
Material reqItem = Material.getMaterial(part[0].toUpperCase() + "_ITEM"); private ItemStack two(String s, String[] part) {
if (reqItem == null) { int reqAmount = 0;
// Try the item try {
reqItem = Material.getMaterial(part[0].toUpperCase()); reqAmount = Integer.parseInt(part[1]);
} } catch (Exception e) {
addon.getLogger().severe(() -> "Could not parse the quantity of the item " + s);
return null;
}
if (reqItem == null) { Material reqItem = Material.getMaterial(part[0].toUpperCase() + "_ITEM");
showError(s); if (reqItem == null) {
return null; // Try the item
} reqItem = Material.getMaterial(part[0].toUpperCase());
return new ItemStack(reqItem, reqAmount); }
} if (reqItem == null) {
showError(s);
return null;
}
return new ItemStack(reqItem, reqAmount);
/** }
* @return the item
*/ /**
public ItemStack getItem() { * @return the item
return item; */
} public ItemStack getItem() {
} return item;
}
}

View File

@ -3,38 +3,38 @@ package bskyblock.addon.challenges.commands;
import java.util.List; import java.util.List;
import bskyblock.addon.challenges.ChallengesAddon; import bskyblock.addon.challenges.ChallengesAddon;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
public class ChallengesCommand extends CompositeCommand { public class ChallengesCommand extends CompositeCommand {
public static final String CHALLENGE_COMMAND = "challenges";
private ChallengesAddon addon;
public ChallengesCommand(ChallengesAddon addon) { public static final String CHALLENGE_COMMAND = "challenges";
super(CHALLENGE_COMMAND, "c", "challenge");
this.addon = addon;
// Set up commands
}
@Override private ChallengesAddon addon;
public boolean execute(User user, List<String> args) {
// Open up the challenges GUI
if (user.isPlayer()) {
addon.getChallengesManager().getChallengesPanels().getChallenges(user, args.isEmpty() ? "" : args.get(0));
return true;
}
return false;
}
@Override public ChallengesCommand(ChallengesAddon addon) {
public void setup() { super(CHALLENGE_COMMAND, "c", "challenge");
this.setOnlyPlayer(true); this.addon = addon;
this.setPermission(Constants.PERMPREFIX + CHALLENGE_COMMAND); // Set up commands
this.setParameters(CHALLENGE_COMMAND + ".parameters"); }
this.setDescription(CHALLENGE_COMMAND + ".description");
this.setOnlyPlayer(true);
}
@Override
public boolean execute(User user, List<String> args) {
// Open up the challenges GUI
if (user.isPlayer()) {
addon.getChallengesManager().getChallengesPanels().getChallenges(user, args.isEmpty() ? "" : args.get(0));
return true;
}
return false;
}
} @Override
public void setup() {
this.setOnlyPlayer(true);
this.setPermission("bskyblock." + CHALLENGE_COMMAND);
this.setParameters(CHALLENGE_COMMAND + ".parameters");
this.setDescription(CHALLENGE_COMMAND + ".description");
this.setOnlyPlayer(true);
}
}

View File

@ -3,39 +3,40 @@ package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
import bskyblock.addon.challenges.ChallengesAddon; import bskyblock.addon.challenges.ChallengesAddon;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
public class ChallengesAdminCommand extends CompositeCommand { public class ChallengesAdminCommand extends CompositeCommand {
private static final String CHALLENGE_ADMIN_COMMAND = "cadmin";
private ChallengesAddon addon;
public ChallengesAdminCommand(ChallengesAddon addon) { private static final String CHALLENGE_ADMIN_COMMAND = "cadmin";
super(CHALLENGE_ADMIN_COMMAND);
this.addon = addon;
// Set up create command
new CreateChallenge(addon, this);
new SetIcon(addon, this);
}
@Override private ChallengesAddon addon;
public boolean execute(User user, List<String> args) {
// Open up the challenges GUI
if (user.isPlayer()) {
addon.getChallengesManager().getChallengesPanels().getChallenges(user);
return true;
}
return false;
}
@Override public ChallengesAdminCommand(ChallengesAddon addon) {
public void setup() { super(CHALLENGE_ADMIN_COMMAND);
this.setOnlyPlayer(true); this.addon = addon;
this.setPermission(Constants.PERMPREFIX + "challenges.admin"); // Set up create command
this.setParameters("challaneges.admin.parameters"); new CreateChallenge(addon, this);
this.setDescription("challenges.admin.description"); new SetIcon(addon, this);
this.setOnlyPlayer(true); }
}
} @Override
public boolean execute(User user, List<String> args) {
// Open up the challenges GUI
if (user.isPlayer()) {
addon.getChallengesManager().getChallengesPanels().getChallenges(user);
return true;
}
return false;
}
@Override
public void setup() {
this.setOnlyPlayer(true);
this.setPermission("bskyblock.challenges.admin");
this.setParameters("challenges.admin.parameters");
this.setDescription("challenges.admin.description");
this.setOnlyPlayer(true);
}
}

View File

@ -4,49 +4,46 @@ import java.util.List;
import bskyblock.addon.challenges.ChallengesAddon; import bskyblock.addon.challenges.ChallengesAddon;
import bskyblock.addon.challenges.panel.CreateChallengeListener; import bskyblock.addon.challenges.panel.CreateChallengeListener;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.panels.builders.PanelBuilder; import us.tastybento.bskyblock.api.panels.builders.PanelBuilder;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
public class CreateChallenge extends CompositeCommand { public class CreateChallenge extends CompositeCommand {
private ChallengesAddon addon;
private ChallengesAddon addon; /**
* Admin command to make challenges
* @param parent
*/
public CreateChallenge(ChallengesAddon addon, CompositeCommand parent) {
super(parent, "create");
this.addon = addon;
new CreateSurrounding(addon, this);
}
/** @Override
* Admin command to make challenges public void setup() {
* @param parent this.setOnlyPlayer(true);
*/ this.setPermission("bskyblock.admin.challenges");
public CreateChallenge(ChallengesAddon addon, CompositeCommand parent) { this.setParameters("challenges.admin.create.parameters");
super(parent, "create"); this.setDescription("challenges.admin.create.description");
this.addon = addon;
new CreateSurrounding(addon, this);
} }
@Override @Override
public void setup() { public boolean execute(User user, List<String> args) {
this.setOnlyPlayer(true); if (args.isEmpty()) {
this.setPermission(Constants.PERMPREFIX + "admin.challenges"); user.sendRawMessage("not enough args");
this.setParameters("challaneges.admin.create.parameters"); return false;
this.setDescription("challenges.admin.create.description"); }
new PanelBuilder()
.name(args.get(0))
.size(49)
.listener(new CreateChallengeListener(addon, user))
.user(user)
.build();
return true;
}
} }
@Override
public boolean execute(User user, List<String> args) {
if (args.isEmpty()) {
user.sendRawMessage("not enough args");
return false;
}
new PanelBuilder()
.name(args.get(0))
.size(49)
.listener(new CreateChallengeListener(addon, user))
.user(user)
.build();
return true;
}
}

View File

@ -17,7 +17,6 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import bskyblock.addon.challenges.ChallengesAddon; import bskyblock.addon.challenges.ChallengesAddon;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand; import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
import us.tastybento.bskyblock.util.Util; import us.tastybento.bskyblock.util.Util;
@ -29,99 +28,98 @@ import us.tastybento.bskyblock.util.Util;
*/ */
public class CreateSurrounding extends CompositeCommand implements Listener { public class CreateSurrounding extends CompositeCommand implements Listener {
private ChallengesAddon addon;
private ChallengesAddon addon; HashMap<UUID,SurroundChallengeBuilder> inProgress = new HashMap<>();
HashMap<UUID,SurroundChallengeBuilder> inProgress = new HashMap<>();
/** /**
* Admin command to make surrounding challenges * Admin command to make surrounding challenges
* @param parent * @param parent
*/ */
public CreateSurrounding(ChallengesAddon addon, CompositeCommand parent) { public CreateSurrounding(ChallengesAddon addon, CompositeCommand parent) {
super(parent, "surrounding"); super(parent, "surrounding");
this.addon = addon; this.addon = addon;
addon.getServer().getPluginManager().registerEvents(this, addon.getBSkyBlock()); addon.getServer().getPluginManager().registerEvents(this, addon.getBSkyBlock());
} }
@Override @Override
public void setup() { public void setup() {
this.setOnlyPlayer(true); this.setOnlyPlayer(true);
this.setPermission(Constants.PERMPREFIX + "admin.challenges"); this.setPermission("bskyblock.admin.challenges");
this.setParameters("challaneges.admin.create.surrounding.parameters"); this.setParameters("challenges.admin.create.surrounding.parameters");
this.setDescription("challenges.admin.create.surrounding.description"); this.setDescription("challenges.admin.create.surrounding.description");
} }
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
if (args.isEmpty()) { if (args.isEmpty()) {
user.sendMessage("challenges.admin.error.no-name"); user.sendMessage("challenges.admin.error.no-name");
return false; return false;
} }
// Tell user to hit objects to add to the surrounding object requirements // Tell user to hit objects to add to the surrounding object requirements
user.sendMessage("challenges.admin.create.surrounding.hit-things"); user.sendMessage("challenges.admin.create.surrounding.hit-things");
inProgress.put(user.getUniqueId(), new SurroundChallengeBuilder(addon).owner(user).name(args.get(0))); inProgress.put(user.getUniqueId(), new SurroundChallengeBuilder(addon).owner(user).name(args.get(0)));
return true; return true;
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) { public void onBlockBreak(BlockBreakEvent e) {
e.setCancelled(inProgress.containsKey(e.getPlayer().getUniqueId()) ? true : false); e.setCancelled(inProgress.containsKey(e.getPlayer().getUniqueId()) ? true : false);
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent e) { public void onPlayerQuit(PlayerQuitEvent e) {
inProgress.remove(e.getPlayer().getUniqueId()); inProgress.remove(e.getPlayer().getUniqueId());
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerInteract(PlayerInteractEvent e) { public boolean onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK) && inProgress.containsKey(e.getPlayer().getUniqueId())) { if (e.getAction().equals(Action.LEFT_CLICK_BLOCK) && inProgress.containsKey(e.getPlayer().getUniqueId())) {
// Prevent damage // Prevent damage
e.setCancelled(true); e.setCancelled(true);
inProgress.get(e.getPlayer().getUniqueId()).addBlock(e.getClickedBlock().getType()); inProgress.get(e.getPlayer().getUniqueId()).addBlock(e.getClickedBlock().getType());
User.getInstance(e.getPlayer()).sendMessage("challenges.admin.you-added", "[thing]", Util.prettifyText(e.getClickedBlock().getType().toString())); User.getInstance(e.getPlayer()).sendMessage("challenges.admin.you-added", "[thing]", Util.prettifyText(e.getClickedBlock().getType().toString()));
return true; return true;
} }
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return finished(e, e.getPlayer().getUniqueId()); return finished(e, e.getPlayer().getUniqueId());
} }
return false; return false;
} }
private boolean finished(Cancellable e, UUID uuid) { private boolean finished(Cancellable e, UUID uuid) {
if (inProgress.containsKey(uuid)) { if (inProgress.containsKey(uuid)) {
e.setCancelled(true); e.setCancelled(true);
boolean status = inProgress.get(uuid).build(); boolean status = inProgress.get(uuid).build();
if (status) { if (status) {
inProgress.get(uuid).getOwner().sendMessage("challenges.admin.challenge-created", "[challenge]", inProgress.get(uuid).getName()); inProgress.get(uuid).getOwner().sendMessage("challenges.admin.challenge-created", "[challenge]", inProgress.get(uuid).getName());
} }
inProgress.remove(uuid); inProgress.remove(uuid);
return status; return status;
} }
return false; return false;
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerInteract(PlayerInteractAtEntityEvent e) { public boolean onPlayerInteract(PlayerInteractAtEntityEvent e) {
return finished(e, e.getPlayer().getUniqueId()); return finished(e, e.getPlayer().getUniqueId());
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onLeft(EntityDamageByEntityEvent e) { public boolean onLeft(EntityDamageByEntityEvent e) {
if (!(e.getDamager() instanceof Player)) { if (!(e.getDamager() instanceof Player)) {
return false; return false;
} }
Player player = (Player)e.getDamager(); Player player = (Player)e.getDamager();
if (inProgress.containsKey(player.getUniqueId())) { if (inProgress.containsKey(player.getUniqueId())) {
// Prevent damage // Prevent damage
e.setCancelled(true); e.setCancelled(true);
inProgress.get(player.getUniqueId()).addEntity(e.getEntityType()); inProgress.get(player.getUniqueId()).addEntity(e.getEntityType());
User.getInstance(player).sendMessage("challenges.admin.you-added", "[thing]", Util.prettifyText(e.getEntityType().toString())); User.getInstance(player).sendMessage("challenges.admin.you-added", "[thing]", Util.prettifyText(e.getEntityType().toString()));
return true; return true;
} }
return false; return false;
} }
}
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class MakeLevel extends CompositeCommand { public class MakeLevel extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public MakeLevel(BSkyBlock plugin, String label, String... string) { public MakeLevel(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public MakeLevel(CompositeCommand parent, String label, String... aliases) { public MakeLevel(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public MakeLevel(String label, String... aliases) { public MakeLevel(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetDeployed extends CompositeCommand { public class SetDeployed extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetDeployed(BSkyBlock plugin, String label, String... string) { public SetDeployed(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetDeployed(CompositeCommand parent, String label, String... aliases) { public SetDeployed(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetDeployed(String label, String... aliases) { public SetDeployed(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetDescription extends CompositeCommand { public class SetDescription extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetDescription(BSkyBlock plugin, String label, String... string) { public SetDescription(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetDescription(CompositeCommand parent, String label, String... aliases) { public SetDescription(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetDescription(String label, String... aliases) { public SetDescription(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetExp extends CompositeCommand { public class SetExp extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetExp(BSkyBlock plugin, String label, String... string) { public SetExp(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetExp(CompositeCommand parent, String label, String... aliases) { public SetExp(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetExp(String label, String... aliases) { public SetExp(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetFriendlyName extends CompositeCommand { public class SetFriendlyName extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetFriendlyName(BSkyBlock plugin, String label, String... string) { public SetFriendlyName(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetFriendlyName(CompositeCommand parent, String label, String... aliases) { public SetFriendlyName(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetFriendlyName(String label, String... aliases) { public SetFriendlyName(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -18,46 +15,46 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetIcon extends CompositeCommand { public class SetIcon extends CompositeCommand {
private ChallengesAddon addon; private ChallengesAddon addon;
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetIcon(ChallengesAddon addon, CompositeCommand parent) { public SetIcon(ChallengesAddon addon, CompositeCommand parent) {
super(parent, "seticon"); super(parent, "seticon");
this.addon = addon; this.addon = addon;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
setParameters("challenges.admin.seticon.parameters"); setParameters("challenges.admin.seticon.parameters");
setDescription("challenges.admin.seticon.description"); setDescription("challenges.admin.seticon.description");
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
ItemStack icon = user.getInventory().getItemInMainHand(); ItemStack icon = user.getInventory().getItemInMainHand();
if (args.isEmpty() || icon == null) { if (args.isEmpty() || icon == null) {
user.sendMessage("challenges.admin.seticon.description"); user.sendMessage("challenges.admin.seticon.description");
return false; return false;
} }
Challenges challenge = addon.getChallengesManager().getChallenge(args.get(0)); Challenges challenge = addon.getChallengesManager().getChallenge(args.get(0));
// Check if this challenge name exists // Check if this challenge name exists
if (challenge == null) { if (challenge == null) {
user.sendMessage("challenges.admin.seticon.error.no-such-challenge"); user.sendMessage("challenges.admin.seticon.error.no-such-challenge");
return false; return false;
} }
challenge.setIcon(icon); challenge.setIcon(icon);
user.sendMessage("general.success"); user.sendMessage("general.success");
return true; return true;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetLevel extends CompositeCommand { public class SetLevel extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetLevel(BSkyBlock plugin, String label, String... string) { public SetLevel(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetLevel(CompositeCommand parent, String label, String... aliases) { public SetLevel(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetLevel(String label, String... aliases) { public SetLevel(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetMaxTimes extends CompositeCommand { public class SetMaxTimes extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetMaxTimes(BSkyBlock plugin, String label, String... string) { public SetMaxTimes(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetMaxTimes(CompositeCommand parent, String label, String... aliases) { public SetMaxTimes(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetMaxTimes(String label, String... aliases) { public SetMaxTimes(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetPerm extends CompositeCommand { public class SetPerm extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetPerm(BSkyBlock plugin, String label, String... string) { public SetPerm(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetPerm(CompositeCommand parent, String label, String... aliases) { public SetPerm(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetPerm(String label, String... aliases) { public SetPerm(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetRepeatable extends CompositeCommand { public class SetRepeatable extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetRepeatable(BSkyBlock plugin, String label, String... string) { public SetRepeatable(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetRepeatable(CompositeCommand parent, String label, String... aliases) { public SetRepeatable(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetRepeatable(String label, String... aliases) { public SetRepeatable(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetReward extends CompositeCommand { public class SetReward extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetReward(BSkyBlock plugin, String label, String... string) { public SetReward(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetReward(CompositeCommand parent, String label, String... aliases) { public SetReward(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetReward(String label, String... aliases) { public SetReward(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -15,51 +12,51 @@ import us.tastybento.bskyblock.api.user.User;
*/ */
public class SetType extends CompositeCommand { public class SetType extends CompositeCommand {
/** /**
* @param plugin * @param plugin
* @param label * @param label
* @param string * @param string
*/ */
public SetType(BSkyBlock plugin, String label, String... string) { public SetType(BSkyBlock plugin, String label, String... string) {
super(plugin, label, string); super(plugin, label, string);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param parent * @param parent
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetType(CompositeCommand parent, String label, String... aliases) { public SetType(CompositeCommand parent, String label, String... aliases) {
super(parent, label, aliases); super(parent, label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param label * @param label
* @param aliases * @param aliases
*/ */
public SetType(String label, String... aliases) { public SetType(String label, String... aliases) {
super(label, aliases); super(label, aliases);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup() * @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/ */
@Override @Override
public void setup() { public void setup() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List) * @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/ */
@Override @Override
public boolean execute(User user, List<String> args) { public boolean execute(User user, List<String> args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -15,69 +15,70 @@ import us.tastybento.bskyblock.api.user.User;
* *
*/ */
public class SurroundChallengeBuilder { public class SurroundChallengeBuilder {
private ChallengesAddon addon;
private String name;
private User owner;
private Map<Material, Integer> reqBlocks = new EnumMap<>(Material.class);
private Map<EntityType, Integer> reqEntities = new EnumMap<>(EntityType.class);
public SurroundChallengeBuilder(ChallengesAddon addon) { private ChallengesAddon addon;
this.addon = addon; private String name;
} private User owner;
private Map<Material, Integer> reqBlocks = new EnumMap<>(Material.class);
private Map<EntityType, Integer> reqEntities = new EnumMap<>(EntityType.class);
SurroundChallengeBuilder name(String name) { public SurroundChallengeBuilder(ChallengesAddon addon) {
this.name = name; this.addon = addon;
return this; }
}
SurroundChallengeBuilder owner(User user) { SurroundChallengeBuilder name(String name) {
this.owner = user; this.name = name;
return this; return this;
} }
SurroundChallengeBuilder addBlock(Material mat) { SurroundChallengeBuilder owner(User user) {
reqBlocks.computeIfPresent(mat, (material, amount) -> amount + 1); this.owner = user;
reqBlocks.putIfAbsent(mat, 1); return this;
return this; }
}
SurroundChallengeBuilder addEntity(EntityType ent) { SurroundChallengeBuilder addBlock(Material mat) {
reqEntities.computeIfPresent(ent, (type, amount) -> amount + 1); reqBlocks.computeIfPresent(mat, (material, amount) -> amount + 1);
reqEntities.putIfAbsent(ent, 1); reqBlocks.putIfAbsent(mat, 1);
return this; return this;
} }
/** SurroundChallengeBuilder addEntity(EntityType ent) {
* @return the name reqEntities.computeIfPresent(ent, (type, amount) -> amount + 1);
*/ reqEntities.putIfAbsent(ent, 1);
public String getName() { return this;
return name; }
}
/** /**
* @return the owner * @return the name
*/ */
public User getOwner() { public String getName() {
return owner; return name;
} }
/** /**
* @return the reqBlocks * @return the owner
*/ */
public Map<Material, Integer> getReqBlocks() { public User getOwner() {
return reqBlocks; return owner;
} }
/** /**
* @return the reqEntities * @return the reqBlocks
*/ */
public Map<EntityType, Integer> getReqEntities() { public Map<Material, Integer> getReqBlocks() {
return reqEntities; return reqBlocks;
} }
public boolean build() { /**
return addon.getChallengesManager().createSurroundingChallenge(this); * @return the reqEntities
*/
} public Map<EntityType, Integer> getReqEntities() {
return reqEntities;
}
public boolean build() {
return addon.getChallengesManager().createSurroundingChallenge(this);
}
} }

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.commands.admin; package bskyblock.addon.challenges.commands.admin;
import java.util.List; import java.util.List;
@ -62,4 +59,4 @@ public class TakeItems extends CompositeCommand {
return false; return false;
} }
} }

View File

@ -16,192 +16,191 @@ import us.tastybento.bskyblock.database.objects.DataObject;
*/ */
public class ChallengeLevels implements DataObject, Comparable<ChallengeLevels> { public class ChallengeLevels implements DataObject, Comparable<ChallengeLevels> {
@ConfigComment("A friendly name for the level. If blank, level name is used.")
private String friendlyName = "";
@ConfigComment("A friendly name for the level. If blank, level name is used.") @ConfigComment("Commands to run when this level is completed")
private String friendlyName = ""; private List<String> rewardCommands = new ArrayList<>();
@ConfigComment("Level name")
private String uniqueId = ChallengesManager.FREE;
@ConfigComment("The number of undone challenges that can be left on this level before unlocking next level")
private int waiveramount = 1;
@ConfigComment("The ordering of the levels, lowest to highest")
private int order = 0;
@ConfigComment("The message shown when unlocking this level")
private String unlockMessage = "";
@ConfigComment("Unlock reward description")
private String rewardDescription = "";
@ConfigComment("List of reward itemstacks")
private List<ItemStack> rewardItems;
@ConfigComment("Unlock experience reward")
private int expReward;
@ConfigComment("Unlock money reward")
private int moneyReward;
public String getFriendlyName() {
return friendlyName;
}
@ConfigComment("Commands to run when this level is completed") public List<String> getRewardCommands() {
private List<String> rewardCommands = new ArrayList<>(); return rewardCommands;
}
@ConfigComment("Level name")
private String uniqueId = ChallengesManager.FREE;
@ConfigComment("The number of undone challenges that can be left on this level before unlocking next level")
private int waiveramount = 1;
@ConfigComment("The ordering of the levels, lowest to highest")
private int order = 0;
@ConfigComment("The message shown when unlocking this level")
private String unlockMessage = "";
@ConfigComment("Unlock reward description")
private String rewardDescription = "";
@ConfigComment("List of reward itemstacks")
private List<ItemStack> rewardItems;
@ConfigComment("Unlock experience reward")
private int expReward;
@ConfigComment("Unlock money reward")
private int moneyReward;
public String getFriendlyName() {
return friendlyName;
}
public List<String> getRewardCommands() { @Override
return rewardCommands; public String getUniqueId() {
} return uniqueId;
}
@Override /**
public String getUniqueId() { * Get the number of undone tasks that can be left on a level before unlocking next level
return uniqueId; * @return
} */
public int getWaiveramount() {
return waiveramount;
}
/** public void setFriendlyName(String friendlyName) {
* Get the number of undone tasks that can be left on a level before unlocking next level this.friendlyName = friendlyName;
* @return }
*/
public int getWaiveramount() {
return waiveramount;
}
public void setFriendlyName(String friendlyName) { public void setRewardCommands(List<String> rewardCommands) {
this.friendlyName = friendlyName; this.rewardCommands = rewardCommands;
} }
public void setRewardCommands(List<String> rewardCommands) { @Override
this.rewardCommands = rewardCommands; public void setUniqueId(String uniqueId) {
} this.uniqueId = uniqueId;
}
@Override public void setWaiveramount(int waiveramount) {
public void setUniqueId(String uniqueId) { this.waiveramount = waiveramount;
this.uniqueId = uniqueId; }
}
public void setWaiveramount(int waiveramount) { public int getOrder() {
this.waiveramount = waiveramount; return order;
} }
public int getOrder() { public void setOrder(int order) {
return order; this.order = order;
} }
public void setOrder(int order) { @Override
this.order = order; public int compareTo(ChallengeLevels o) {
} return Integer.compare(this.order, o.order);
}
/**
* @return the rewardDescription
*/
public String getRewardDescription() {
return rewardDescription;
}
@Override /**
public int compareTo(ChallengeLevels o) { * @param rewardDescription the rewardDescription to set
return Integer.compare(this.order, o.order); */
} public void setRewardDescription(String rewardDescription) {
this.rewardDescription = rewardDescription;
/** }
* @return the rewardDescription
*/
public String getRewardDescription() {
return rewardDescription;
}
/** /**
* @param rewardDescription the rewardDescription to set * @return the rewardItems
*/ */
public void setRewardDescription(String rewardDescription) { public List<ItemStack> getRewardItems() {
this.rewardDescription = rewardDescription; return rewardItems;
} }
/** /**
* @return the rewardItems * @param rewardItems the rewardItems to set
*/ */
public List<ItemStack> getRewardItems() { public void setRewardItems(List<ItemStack> rewardItems) {
return rewardItems; this.rewardItems = rewardItems;
} }
/** /**
* @param rewardItems the rewardItems to set * @return the expReward
*/ */
public void setRewardItems(List<ItemStack> rewardItems) { public int getExpReward() {
this.rewardItems = rewardItems; return expReward;
} }
/** /**
* @return the expReward * @param expReward the expReward to set
*/ */
public int getExpReward() { public void setExpReward(int expReward) {
return expReward; this.expReward = expReward;
} }
/** /**
* @param expReward the expReward to set * @return the moneyReward
*/ */
public void setExpReward(int expReward) { public int getMoneyReward() {
this.expReward = expReward; return moneyReward;
} }
/** /**
* @return the moneyReward * @param moneyReward the moneyReward to set
*/ */
public int getMoneyReward() { public void setMoneyReward(int moneyReward) {
return moneyReward; this.moneyReward = moneyReward;
} }
/** /**
* @param moneyReward the moneyReward to set * @return the unlockMessage
*/ */
public void setMoneyReward(int moneyReward) { public String getUnlockMessage() {
this.moneyReward = moneyReward; return unlockMessage;
} }
/** /**
* @return the unlockMessage * @param unlockMessage the unlockMessage to set
*/ */
public String getUnlockMessage() { public void setUnlockMessage(String unlockMessage) {
return unlockMessage; this.unlockMessage = unlockMessage;
} }
/** /* (non-Javadoc)
* @param unlockMessage the unlockMessage to set * @see java.lang.Object#hashCode()
*/ */
public void setUnlockMessage(String unlockMessage) { @Override
this.unlockMessage = unlockMessage; public int hashCode() {
} final int prime = 31;
int result = 1;
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
return result;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#hashCode() * @see java.lang.Object#equals(java.lang.Object)
*/ */
@Override @Override
public int hashCode() { public boolean equals(Object obj) {
final int prime = 31; if (this == obj) {
int result = 1; return true;
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); }
return result; if (obj == null) {
} return false;
}
if (!(obj instanceof ChallengeLevels)) {
return false;
}
ChallengeLevels other = (ChallengeLevels) obj;
if (uniqueId == null) {
if (other.uniqueId != null) {
return false;
}
} else if (!uniqueId.equals(other.uniqueId)) {
return false;
}
return true;
}
/* (non-Javadoc) }
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ChallengeLevels)) {
return false;
}
ChallengeLevels other = (ChallengeLevels) obj;
if (uniqueId == null) {
if (other.uniqueId != null) {
return false;
}
} else if (!uniqueId.equals(other.uniqueId)) {
return false;
}
return true;
}
}

View File

@ -1,6 +1,3 @@
/**
*
*/
package bskyblock.addon.challenges.database.object; package bskyblock.addon.challenges.database.object;
import java.util.HashMap; import java.util.HashMap;
@ -19,147 +16,151 @@ import us.tastybento.bskyblock.database.objects.DataObject;
*/ */
public class PlayerData implements DataObject { public class PlayerData implements DataObject {
@Expose @Expose
private String uniqueId = ""; private String uniqueId = "";
/** /**
* Challenge map, where key = unique challenge name and Value = number of times completed * Challenge map, where key = unique challenge name and Value = number of times completed
*/ */
@Expose @Expose
private Map<String, Integer> challengeStatus = new HashMap<>(); private Map<String, Integer> challengeStatus = new HashMap<>();
@Expose @Expose
private Map<String, Long> challengesTimestamp = new HashMap<>(); private Map<String, Long> challengesTimestamp = new HashMap<>();
@Expose @Expose
private Set<String> levelsDone = new HashSet<>(); private Set<String> levelsDone = new HashSet<>();
// Required for bean instantiation // Required for bean instantiation
public PlayerData() {} public PlayerData() {}
/**
* Mark a challenge as having been completed. Will increment the number of times and timestamp
* @param challengeName - unique challenge name
*/
public void setChallengeDone(String challengeName) {
int times = challengeStatus.getOrDefault(challengeName, 0) + 1;
challengeStatus.put(challengeName, times);
challengesTimestamp.put(challengeName, System.currentTimeMillis());
}
/**
* Check if a challenge has been done
* @param challengeName - unique challenge name
* @return true if done at least once
*/
public boolean isChallengeDone(String challengeName) {
return getTimes(challengeName) > 0 ? true : false;
}
/**
* Check how many times a challenge has been done
* @param challengeName - unique challenge name
* @return - number of times
*/
public int getTimes(String challengeName) {
return challengeStatus.getOrDefault(challengeName, 0);
}
/**
* Creates a player data entry
* @param uniqueId - the player's UUID in string format
*/
public PlayerData(String uniqueId) {
this.uniqueId = uniqueId;
}
/* (non-Javadoc) /**
* @see us.tastybento.bskyblock.database.objects.DataObject#getUniqueId() * Mark a challenge as having been completed. Will increment the number of times and timestamp
*/ * @param challengeName - unique challenge name
@Override */
public String getUniqueId() { public void setChallengeDone(String challengeName) {
// TODO Auto-generated method stub int times = challengeStatus.getOrDefault(challengeName, 0) + 1;
return uniqueId; challengeStatus.put(challengeName, times);
} challengesTimestamp.put(challengeName, System.currentTimeMillis());
}
/* (non-Javadoc) /**
* @see us.tastybento.bskyblock.database.objects.DataObject#setUniqueId(java.lang.String) * Check if a challenge has been done
*/ * @param challengeName - unique challenge name
@Override * @return true if done at least once
public void setUniqueId(String uniqueId) { */
this.uniqueId = uniqueId; public boolean isChallengeDone(String challengeName) {
return getTimes(challengeName) > 0 ? true : false;
}
} /**
* Check how many times a challenge has been done
* @param challengeName - unique challenge name
* @return - number of times
*/
public int getTimes(String challengeName) {
return challengeStatus.getOrDefault(challengeName, 0);
}
/** /**
* @return the challengeStatus * Creates a player data entry
*/ * @param uniqueId - the player's UUID in string format
public Map<String, Integer> getChallengeStatus() { */
return challengeStatus; public PlayerData(String uniqueId) {
} this.uniqueId = uniqueId;
/** }
* @param challengeStatus the challengeStatus to set
*/
public void setChallengeStatus(Map<String, Integer> challengeStatus) {
this.challengeStatus = challengeStatus;
}
/**
* @return the challengesTimestamp
*/
public Map<String, Long> getChallengesTimestamp() {
return challengesTimestamp;
}
/**
* @param challengesTimestamp the challengesTimestamp to set
*/
public void setChallengesTimestamp(Map<String, Long> challengesTimestamp) {
this.challengesTimestamp = challengesTimestamp;
}
/**
* @return the levelsDone
*/
public Set<String> getLevelsDone() {
return levelsDone;
}
/** /* (non-Javadoc)
* @param levelsDone the levelsDone to set * @see us.tastybento.bskyblock.database.objects.DataObject#getUniqueId()
*/ */
public void setLevelsDone(Set<String> levelsDone) { @Override
this.levelsDone = levelsDone; public String getUniqueId() {
} // TODO Auto-generated method stub
return uniqueId;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#hashCode() * @see us.tastybento.bskyblock.database.objects.DataObject#setUniqueId(java.lang.String)
*/ */
@Override @Override
public int hashCode() { public void setUniqueId(String uniqueId) {
final int prime = 31; this.uniqueId = uniqueId;
int result = 1;
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
return result;
}
/* (non-Javadoc) }
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof PlayerData)) {
return false;
}
PlayerData other = (PlayerData) obj;
if (uniqueId == null) {
if (other.uniqueId != null) {
return false;
}
} else if (!uniqueId.equals(other.uniqueId)) {
return false;
}
return true;
}
} /**
* @return the challengeStatus
*/
public Map<String, Integer> getChallengeStatus() {
return challengeStatus;
}
/**
* @param challengeStatus the challengeStatus to set
*/
public void setChallengeStatus(Map<String, Integer> challengeStatus) {
this.challengeStatus = challengeStatus;
}
/**
* @return the challengesTimestamp
*/
public Map<String, Long> getChallengesTimestamp() {
return challengesTimestamp;
}
/**
* @param challengesTimestamp the challengesTimestamp to set
*/
public void setChallengesTimestamp(Map<String, Long> challengesTimestamp) {
this.challengesTimestamp = challengesTimestamp;
}
/**
* @return the levelsDone
*/
public Set<String> getLevelsDone() {
return levelsDone;
}
/**
* @param levelsDone the levelsDone to set
*/
public void setLevelsDone(Set<String> levelsDone) {
this.levelsDone = levelsDone;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof PlayerData)) {
return false;
}
PlayerData other = (PlayerData) obj;
if (uniqueId == null) {
if (other.uniqueId != null) {
return false;
}
} else if (!uniqueId.equals(other.uniqueId)) {
return false;
}
return true;
}
}

View File

@ -14,224 +14,224 @@ import bskyblock.addon.challenges.LevelStatus;
import bskyblock.addon.challenges.commands.ChallengesCommand; import bskyblock.addon.challenges.commands.ChallengesCommand;
import bskyblock.addon.challenges.database.object.Challenges; import bskyblock.addon.challenges.database.object.Challenges;
import bskyblock.addon.challenges.database.object.Challenges.ChallengeType; import bskyblock.addon.challenges.database.object.Challenges.ChallengeType;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.panels.Panel; import us.tastybento.bskyblock.api.panels.Panel;
import us.tastybento.bskyblock.api.panels.PanelItem; import us.tastybento.bskyblock.api.panels.PanelItem;
import us.tastybento.bskyblock.api.panels.builders.PanelBuilder; import us.tastybento.bskyblock.api.panels.builders.PanelBuilder;
import us.tastybento.bskyblock.api.panels.builders.PanelItemBuilder; import us.tastybento.bskyblock.api.panels.builders.PanelItemBuilder;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
public class ChallengesPanels { public class ChallengesPanels {
private ChallengesAddon addon;
private ChallengesManager manager;
public ChallengesPanels(ChallengesAddon plugin, ChallengesManager manager){ private ChallengesAddon addon;
this.addon = plugin;
this.manager = manager;
}
/** private ChallengesManager manager;
* @param user
* @return
*/
public void getChallenges(User user) {
// Get the challenge level this player is on
getChallenges(user, "");
}
/** public ChallengesPanels(ChallengesAddon plugin, ChallengesManager manager){
* Dynamically creates an inventory of challenges for the player showing the this.addon = plugin;
* level this.manager = manager;
*/ }
public void getChallenges(User user, String level) {
if (manager.getChallengeList().isEmpty()) {
addon.getLogger().severe("There are no challenges set up!");
user.sendMessage("general.errors.general");
return;
}
if (level.isEmpty()) {
level = manager.getChallengeList().keySet().iterator().next().getUniqueId();
}
// Check if level is valid
if (!manager.isLevelUnlocked(user, level)) {
return;
}
PanelBuilder panelBuilder = new PanelBuilder()
.name(user.getTranslation("challenges.gui-title"));
addChallengeItems(panelBuilder, user, level); /**
addNavigation(panelBuilder, user, level); * @param user
addFreeChallanges(panelBuilder, user); * @return
*/
public void getChallenges(User user) {
// Get the challenge level this player is on
getChallenges(user, "");
}
// Create the panel /**
Panel panel = panelBuilder.build(); * Dynamically creates an inventory of challenges for the player showing the
panel.open(user); * level
} */
public void getChallenges(User user, String level) {
if (manager.getChallengeList().isEmpty()) {
addon.getLogger().severe("There are no challenges set up!");
user.sendMessage("general.errors.general");
return;
}
if (level.isEmpty()) {
level = manager.getChallengeList().keySet().iterator().next().getUniqueId();
}
// Check if level is valid
if (!manager.isLevelUnlocked(user, level)) {
return;
}
PanelBuilder panelBuilder = new PanelBuilder()
.name(user.getTranslation("challenges.gui-title"));
private void addFreeChallanges(PanelBuilder panelBuilder, User user) { addChallengeItems(panelBuilder, user, level);
manager.getChallenges(ChallengesManager.FREE).forEach(challenge -> createItem(panelBuilder, challenge, user)); addNavigation(panelBuilder, user, level);
} addFreeChallanges(panelBuilder, user);
// Create the panel
Panel panel = panelBuilder.build();
panel.open(user);
}
private void addFreeChallanges(PanelBuilder panelBuilder, User user) {
manager.getChallenges(ChallengesManager.FREE).forEach(challenge -> createItem(panelBuilder, challenge, user));
}
/** /**
* Creates a panel item for challenge if appropriate and adds it to panelBuilder * Creates a panel item for challenge if appropriate and adds it to panelBuilder
* @param panelBuilder * @param panelBuilder
* @param challenge * @param challenge
* @param user * @param user
*/ */
private void createItem(PanelBuilder panelBuilder, Challenges challenge, User user) { private void createItem(PanelBuilder panelBuilder, Challenges challenge, User user) {
// Check completion // Check completion
boolean completed = manager.isChallengeComplete(user, challenge.getUniqueId()); boolean completed = manager.isChallengeComplete(user, challenge.getUniqueId());
// If challenge is removed after completion, remove it // If challenge is removed after completion, remove it
if (completed && challenge.isRemoveWhenCompleted()) { if (completed && challenge.isRemoveWhenCompleted()) {
return; return;
} }
PanelItem item = new PanelItemBuilder() PanelItem item = new PanelItemBuilder()
.icon(challenge.getIcon()) .icon(challenge.getIcon())
.name(challenge.getFriendlyName().isEmpty() ? challenge.getUniqueId() : challenge.getFriendlyName()) .name(challenge.getFriendlyName().isEmpty() ? challenge.getUniqueId() : challenge.getFriendlyName())
.description(challengeDescription(challenge, user)) .description(challengeDescription(challenge, user))
.glow(completed) .glow(completed)
.clickHandler((panel, player, c, s) -> { .clickHandler((panel, player, c, s) -> {
if (!challenge.getChallengeType().equals(ChallengeType.ICON)) { if (!challenge.getChallengeType().equals(ChallengeType.ICON)) {
new TryToComplete(addon, player, manager, challenge); new TryToComplete(addon, player, manager, challenge);
} }
return true; return true;
}) })
.build(); .build();
if (challenge.getSlot() >= 0) { if (challenge.getSlot() >= 0) {
panelBuilder.item(challenge.getSlot(),item); panelBuilder.item(challenge.getSlot(),item);
} else { } else {
panelBuilder.item(item); panelBuilder.item(item);
} }
} }
private void addChallengeItems(PanelBuilder panelBuilder, User user, String level) { private void addChallengeItems(PanelBuilder panelBuilder, User user, String level) {
Set<Challenges> levelChallenges = manager.getChallenges(level); Set<Challenges> levelChallenges = manager.getChallenges(level);
// Only show a control panel for the level requested. // Only show a control panel for the level requested.
for (Challenges challenge : levelChallenges) { for (Challenges challenge : levelChallenges) {
createItem(panelBuilder, challenge, user); createItem(panelBuilder, challenge, user);
} }
} }
private void addNavigation(PanelBuilder panelBuilder, User user, String level) { private void addNavigation(PanelBuilder panelBuilder, User user, String level) {
// Add navigation to other levels // Add navigation to other levels
for (LevelStatus status: manager.getChallengeLevelStatus(user)) { for (LevelStatus status: manager.getChallengeLevelStatus(user)) {
if (status.getLevel().getUniqueId().equals(level)) { if (status.getLevel().getUniqueId().equals(level)) {
// Skip if this is the current level // Skip if this is the current level
continue; continue;
} }
// Create a nice name for the level // Create a nice name for the level
String name = status.getLevel().getFriendlyName().isEmpty() ? status.getLevel().getUniqueId() : status.getLevel().getFriendlyName(); String name = status.getLevel().getFriendlyName().isEmpty() ? status.getLevel().getUniqueId() : status.getLevel().getFriendlyName();
if (status.isUnlocked()) { if (status.isUnlocked()) {
// Clicking on this icon will open up this level's challenges // Clicking on this icon will open up this level's challenges
PanelItem item = new PanelItemBuilder() PanelItem item = new PanelItemBuilder()
.icon(new ItemStack(Material.BOOK_AND_QUILL)) .icon(new ItemStack(Material.BOOK_AND_QUILL))
.name(name) .name(name)
.description(manager.stringSplit(user.getTranslation("challenges.navigation","[level]",name))) .description(manager.stringSplit(user.getTranslation("challenges.navigation","[level]",name)))
.clickHandler((p, u, c, s) -> { .clickHandler((p, u, c, s) -> {
u.closeInventory(); u.closeInventory();
u.performCommand(ChallengesCommand.CHALLENGE_COMMAND + " " + status.getLevel().getUniqueId()); u.performCommand(ChallengesCommand.CHALLENGE_COMMAND + " " + status.getLevel().getUniqueId());
return true; return true;
}) })
.build(); .build();
panelBuilder.item(item); panelBuilder.item(item);
} else { } else {
// Clicking on this icon will do nothing because the challenge is not unlocked yet // Clicking on this icon will do nothing because the challenge is not unlocked yet
String previousLevelName = status.getPreviousLevel().getFriendlyName().isEmpty() ? status.getPreviousLevel().getUniqueId() : status.getPreviousLevel().getFriendlyName(); String previousLevelName = status.getPreviousLevel().getFriendlyName().isEmpty() ? status.getPreviousLevel().getUniqueId() : status.getPreviousLevel().getFriendlyName();
PanelItem item = new PanelItemBuilder() PanelItem item = new PanelItemBuilder()
.icon(new ItemStack(Material.BOOK)) .icon(new ItemStack(Material.BOOK))
.name(name) .name(name)
.description(manager.stringSplit(user.getTranslation("challenges.to-complete", "[challengesToDo]",String.valueOf(status.getNumberOfChallengesStillToDo()), "[thisLevel]", previousLevelName))) .description(manager.stringSplit(user.getTranslation("challenges.to-complete", "[challengesToDo]",String.valueOf(status.getNumberOfChallengesStillToDo()), "[thisLevel]", previousLevelName)))
.build(); .build();
panelBuilder.item(item); panelBuilder.item(item);
} }
} }
} }
/** /**
* Creates the challenge description for the "item" in the inventory * Creates the challenge description for the "item" in the inventory
* *
* @param challenge * @param challenge
* @param player * @param player
* @return List of strings splitting challenge string into 25 chars long * @return List of strings splitting challenge string into 25 chars long
*/ */
private List<String> challengeDescription(Challenges challenge, User user) { private List<String> challengeDescription(Challenges challenge, User user) {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
String level = challenge.getLevel(); String level = challenge.getLevel();
if (!level.isEmpty()) { if (!level.isEmpty()) {
result.addAll(splitTrans(user, "challenges.level", "[level]", level)); result.addAll(splitTrans(user, "challenges.level", "[level]", level));
} }
// Check if completed or not
boolean complete = addon.getChallengesManager().isChallengeComplete(user, challenge.getUniqueId()); // Check if completed or not
int maxTimes = challenge.getMaxTimes(); boolean complete = addon.getChallengesManager().isChallengeComplete(user, challenge.getUniqueId());
long doneTimes = addon.getChallengesManager().checkChallengeTimes(user, challenge); int maxTimes = challenge.getMaxTimes();
if (complete) { long doneTimes = addon.getChallengesManager().checkChallengeTimes(user, challenge);
result.add(user.getTranslation("challenges.complete")); if (complete) {
} result.add(user.getTranslation("challenges.complete"));
if (challenge.isRepeatable()) { }
if (maxTimes == 0) { if (challenge.isRepeatable()) {
if (maxTimes == 0) {
// Check if the player has maxed out the challenge // Check if the player has maxed out the challenge
if (doneTimes < maxTimes) { if (doneTimes < maxTimes) {
result.addAll(splitTrans(user, "challenges.completed-times","[donetimes]", String.valueOf(doneTimes),"[maxtimes]", String.valueOf(maxTimes))); result.addAll(splitTrans(user, "challenges.completed-times","[donetimes]", String.valueOf(doneTimes),"[maxtimes]", String.valueOf(maxTimes)));
} else { } else {
result.addAll(splitTrans(user, "challenges.maxed-reached","[donetimes]", String.valueOf(doneTimes),"[maxtimes]", String.valueOf(maxTimes))); result.addAll(splitTrans(user, "challenges.maxed-reached","[donetimes]", String.valueOf(doneTimes),"[maxtimes]", String.valueOf(maxTimes)));
} }
} }
} }
if (!complete || (complete && challenge.isRepeatable())) { if (!complete || (complete && challenge.isRepeatable())) {
result.addAll(challenge.getDescription()); result.addAll(challenge.getDescription());
if (challenge.getChallengeType().equals(ChallengeType.INVENTORY)) { if (challenge.getChallengeType().equals(ChallengeType.INVENTORY)) {
if (challenge.isTakeItems()) { if (challenge.isTakeItems()) {
result.addAll(splitTrans(user, "challenges.item-take-warning")); result.addAll(splitTrans(user, "challenges.item-take-warning"));
} }
} else if (challenge.getChallengeType().equals(ChallengeType.ISLAND)) { } else if (challenge.getChallengeType().equals(ChallengeType.ISLAND)) {
result.addAll(splitTrans(user, "challenges.items-closeby")); result.addAll(splitTrans(user, "challenges.items-closeby"));
} }
} }
if (complete && (!challenge.getChallengeType().equals(ChallengeType.INVENTORY) || !challenge.isRepeatable())) { if (complete && (!challenge.getChallengeType().equals(ChallengeType.INVENTORY) || !challenge.isRepeatable())) {
result.addAll(splitTrans(user, "challenges.not-repeatable")); result.addAll(splitTrans(user, "challenges.not-repeatable"));
return result; return result;
} }
double moneyReward = 0; double moneyReward = 0;
int expReward = 0; int expReward = 0;
String rewardText = ""; String rewardText = "";
if (!complete) { if (!complete) {
// First time // First time
moneyReward = challenge.getMoneyReward(); moneyReward = challenge.getMoneyReward();
rewardText = challenge.getRewardText(); rewardText = challenge.getRewardText();
expReward = challenge.getExpReward(); expReward = challenge.getExpReward();
if (!rewardText.isEmpty()) { if (!rewardText.isEmpty()) {
result.addAll(splitTrans(user, "challenges.first-time-rewards")); result.addAll(splitTrans(user, "challenges.first-time-rewards"));
} }
} else { } else {
// Repeat challenge // Repeat challenge
moneyReward = challenge.getRepeatMoneyReward(); moneyReward = challenge.getRepeatMoneyReward();
rewardText = challenge.getRepeatRewardText(); rewardText = challenge.getRepeatRewardText();
expReward = challenge.getRepeatExpReward(); expReward = challenge.getRepeatExpReward();
if (!rewardText.isEmpty()) { if (!rewardText.isEmpty()) {
result.addAll(splitTrans(user, "challenges.repeat-rewards")); result.addAll(splitTrans(user, "challenges.repeat-rewards"));
} }
}
if (!rewardText.isEmpty()) {
result.addAll(splitTrans(user,rewardText));
}
if (expReward > 0) {
result.addAll(splitTrans(user,"challenges.exp-reward", "[reward]", String.valueOf(expReward)));
}
if (addon.getBSkyBlock().getSettings().isUseEconomy() && moneyReward > 0) {
result.addAll(splitTrans(user,"challenges.money-reward", "[reward]", String.valueOf(moneyReward)));
}
// Final placeholder change for [label]
result.replaceAll(x -> x.replace("[label]", "island"));
return result;
}
} private Collection<? extends String> splitTrans(User user, String string, String...strings) {
if (!rewardText.isEmpty()) { return addon.getChallengesManager().stringSplit(user.getTranslation(string, strings));
result.addAll(splitTrans(user,rewardText)); }
}
if (expReward > 0) {
result.addAll(splitTrans(user,"challenges.exp-reward", "[reward]", String.valueOf(expReward)));
}
if (addon.getBSkyBlock().getSettings().isUseEconomy() && moneyReward > 0) {
result.addAll(splitTrans(user,"challenges.money-reward", "[reward]", String.valueOf(moneyReward)));
}
// Final placeholder change for [label]
result.replaceAll(x -> x.replace("[label]", Constants.ISLANDCOMMAND));
return result;
}
private Collection<? extends String> splitTrans(User user, String string, String...strings) { }
return addon.getChallengesManager().stringSplit(user.getTranslation(string, strings));
}
}

View File

@ -8,28 +8,30 @@ import us.tastybento.bskyblock.api.panels.PanelListener;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
public class CreateChallengeListener implements PanelListener { public class CreateChallengeListener implements PanelListener {
private ChallengesAddon addon;
private ChallengesAddon addon; private User user;
private User user;
public CreateChallengeListener(ChallengesAddon addon, User user) { public CreateChallengeListener(ChallengesAddon addon, User user) {
this.addon = addon; this.addon = addon;
this.user = user; this.user = user;
} }
@Override @Override
public void setup() { public void setup() {
// Nothing to setup // Nothing to setup
} }
@Override @Override
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
addon.getChallengesManager().createInvChallenge(user, event.getInventory()); addon.getChallengesManager().createInvChallenge(user, event.getInventory());
} }
@Override @Override
public void onInventoryClick(User user, InventoryClickEvent event) { public void onInventoryClick(User user, InventoryClickEvent event) {
// Allow drag and drop // Allow drag and drop
event.setCancelled(false); event.setCancelled(false);
} }
}
}

View File

@ -6,8 +6,8 @@ import us.tastybento.bskyblock.api.user.User;
public class CreateChallengePanel { public class CreateChallengePanel {
public CreateChallengePanel(ChallengesAddon addon, User user) { public CreateChallengePanel(ChallengesAddon addon, User user) {
new PanelBuilder().size(49).listener(new CreateChallengeListener(addon, user)).user(user).build(); new PanelBuilder().size(49).listener(new CreateChallengeListener(addon, user)).user(user).build();
} }
} }

View File

@ -19,7 +19,7 @@ import bskyblock.addon.challenges.commands.ChallengesCommand;
import bskyblock.addon.challenges.database.object.Challenges; import bskyblock.addon.challenges.database.object.Challenges;
import bskyblock.addon.challenges.database.object.Challenges.ChallengeType; import bskyblock.addon.challenges.database.object.Challenges.ChallengeType;
import bskyblock.addon.level.Level; import bskyblock.addon.level.Level;
import us.tastybento.bskyblock.Constants; import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.user.User; import us.tastybento.bskyblock.api.user.User;
import us.tastybento.bskyblock.util.Util; import us.tastybento.bskyblock.util.Util;
@ -30,231 +30,233 @@ import us.tastybento.bskyblock.util.Util;
*/ */
public class TryToComplete { public class TryToComplete {
private ChallengesAddon addon; private BSkyBlock bSkyBlock;
/** private ChallengesAddon addon;
* @param addon
* @param user
* @param manager
* @param challenge
*/
public TryToComplete(ChallengesAddon addon, User user, ChallengesManager manager, Challenges challenge) {
this.addon = addon;
// Check if user is in the worlds
if (!Util.inWorld(user.getLocation())) {
user.sendMessage("general.errors.wrong-world");
return;
}
// Check if can complete challenge
ChallengeResult result = checkIfCanCompleteChallenge(user, manager, challenge);
if (!result.meetsRequirements) {
return;
}
if (!result.repeat) {
// Give rewards
for (ItemStack reward : challenge.getItemReward()) {
user.getInventory().addItem(reward).forEach((k,v) -> user.getWorld().dropItem(user.getLocation(), v));
}
// Give money
challenge.getMoneyReward();
// Give exp
user.getPlayer().giveExp(challenge.getExpReward());
// Run commands
runCommands(user, challenge.getRewardCommands());
user.sendMessage("challenges.you-completed", "[challenge]", challenge.getFriendlyName());
} else {
// Give rewards
for (ItemStack reward : challenge.getRepeatItemReward()) {
user.getInventory().addItem(reward).forEach((k,v) -> user.getWorld().dropItem(user.getLocation(), v));
}
// Give money
challenge.getRepeatMoneyReward();
// Give exp
user.getPlayer().giveExp(challenge.getRepeatExpReward());
// Run commands
runCommands(user, challenge.getRepeatRewardCommands());
user.sendMessage("challenges.you-repeated", "[challenge]", challenge.getFriendlyName());
}
// Mark as complete
manager.setChallengeComplete(user, challenge.getUniqueId());
user.closeInventory();
user.getPlayer().performCommand(ChallengesCommand.CHALLENGE_COMMAND + " " + challenge.getLevel());
}
/** /**
* Checks if a challenge can be completed or not * @param addon
*/ * @param user
private ChallengeResult checkIfCanCompleteChallenge(User user, ChallengesManager manager, Challenges challenge) { * @param manager
// Check if user has the * @param challenge
if (!challenge.getLevel().equals(ChallengesManager.FREE) && !manager.isLevelUnlocked(user, challenge.getLevel())) { */
user.sendMessage("challenges.errors.challenge-level-not-available"); public TryToComplete(ChallengesAddon addon, User user, ChallengesManager manager, Challenges challenge) {
return new ChallengeResult(); this.addon = addon;
} // Check if user is in the worlds
// Check max times if (!Util.sameWorld(bSkyBlock.getIWM().getIslandWorld(), user.getLocation().getWorld())) {
if (challenge.isRepeatable() && challenge.getMaxTimes() > 0 && manager.checkChallengeTimes(user, challenge) >= challenge.getMaxTimes()) { user.sendMessage("general.errors.wrong-world");
user.sendMessage("challenges.not-repeatable"); return;
return new ChallengeResult(); }
} // Check if can complete challenge
// Check repeatability ChallengeResult result = checkIfCanCompleteChallenge(user, manager, challenge);
if (manager.isChallengeComplete(user, challenge.getUniqueId()) if (!result.meetsRequirements) {
&& (!challenge.isRepeatable() || challenge.getChallengeType().equals(ChallengeType.LEVEL) return;
|| challenge.getChallengeType().equals(ChallengeType.ISLAND))) { }
user.sendMessage("challenges.not-repeatable"); if (!result.repeat) {
return new ChallengeResult(); // Give rewards
} for (ItemStack reward : challenge.getItemReward()) {
switch (challenge.getChallengeType()) { user.getInventory().addItem(reward).forEach((k,v) -> user.getWorld().dropItem(user.getLocation(), v));
case INVENTORY: }
return checkInventory(user, manager, challenge); // Give money
case LEVEL: challenge.getMoneyReward();
return checkLevel(user, challenge); // Give exp
case ISLAND: user.getPlayer().giveExp(challenge.getExpReward());
return checkSurrounding(user, challenge); // Run commands
default: runCommands(user, challenge.getRewardCommands());
return new ChallengeResult(); user.sendMessage("challenges.you-completed", "[challenge]", challenge.getFriendlyName());
} } else {
} // Give rewards
for (ItemStack reward : challenge.getRepeatItemReward()) {
user.getInventory().addItem(reward).forEach((k,v) -> user.getWorld().dropItem(user.getLocation(), v));
}
// Give money
challenge.getRepeatMoneyReward();
// Give exp
user.getPlayer().giveExp(challenge.getRepeatExpReward());
// Run commands
runCommands(user, challenge.getRepeatRewardCommands());
user.sendMessage("challenges.you-repeated", "[challenge]", challenge.getFriendlyName());
}
// Mark as complete
manager.setChallengeComplete(user, challenge.getUniqueId());
user.closeInventory();
user.getPlayer().performCommand(ChallengesCommand.CHALLENGE_COMMAND + " " + challenge.getLevel());
}
private ChallengeResult checkInventory(User user, ChallengesManager manager, Challenges challenge) { /**
// Run through inventory * Checks if a challenge can be completed or not
List<ItemStack> required = new ArrayList<>(challenge.getRequiredItems()); */
for (ItemStack req : required) { private ChallengeResult checkIfCanCompleteChallenge(User user, ChallengesManager manager, Challenges challenge) {
// I wonder how well this works // Check if user has the
if (!user.getInventory().containsAtLeast(req, req.getAmount())) { if (!challenge.getLevel().equals(ChallengesManager.FREE) && !manager.isLevelUnlocked(user, challenge.getLevel())) {
user.sendMessage("challenges.error.not-enough-items", "[items]", Util.prettifyText(req.getType().toString())); user.sendMessage("challenges.errors.challenge-level-not-available");
return new ChallengeResult(); return new ChallengeResult();
} }
} // Check max times
// If remove items, then remove them if (challenge.isRepeatable() && challenge.getMaxTimes() > 0 && manager.checkChallengeTimes(user, challenge) >= challenge.getMaxTimes()) {
if (challenge.isTakeItems()) { user.sendMessage("challenges.not-repeatable");
for (ItemStack items : required) { return new ChallengeResult();
user.getInventory().removeItem(items); }
} // Check repeatability
} if (manager.isChallengeComplete(user, challenge.getUniqueId())
return new ChallengeResult().setMeetsRequirements().setRepeat(manager.isChallengeComplete(user, challenge.getUniqueId())); && (!challenge.isRepeatable() || challenge.getChallengeType().equals(ChallengeType.LEVEL)
} || challenge.getChallengeType().equals(ChallengeType.ISLAND))) {
user.sendMessage("challenges.not-repeatable");
return new ChallengeResult();
}
switch (challenge.getChallengeType()) {
case INVENTORY:
return checkInventory(user, manager, challenge);
case LEVEL:
return checkLevel(user, challenge);
case ISLAND:
return checkSurrounding(user, challenge);
default:
return new ChallengeResult();
}
}
private ChallengeResult checkLevel(User user, Challenges challenge) { private ChallengeResult checkInventory(User user, ChallengesManager manager, Challenges challenge) {
// Check if the level addon is installed or not // Run through inventory
return addon.getAddonByName("BSkyBlock-Level") List<ItemStack> required = new ArrayList<>(challenge.getRequiredItems());
.map(l -> ((Level)l).getIslandLevel(user.getUniqueId()) >= challenge.getReqIslandlevel() ? new ChallengeResult().setMeetsRequirements() : new ChallengeResult() for (ItemStack req : required) {
).orElse(new ChallengeResult()); // I wonder how well this works
} if (!user.getInventory().containsAtLeast(req, req.getAmount())) {
user.sendMessage("challenges.error.not-enough-items", "[items]", Util.prettifyText(req.getType().toString()));
return new ChallengeResult();
}
}
// If remove items, then remove them
if (challenge.isTakeItems()) {
for (ItemStack items : required) {
user.getInventory().removeItem(items);
}
}
return new ChallengeResult().setMeetsRequirements().setRepeat(manager.isChallengeComplete(user, challenge.getUniqueId()));
}
private ChallengeResult checkSurrounding(User user, Challenges challenge) { private ChallengeResult checkLevel(User user, Challenges challenge) {
if (!addon.getIslands().userIsOnIsland(user)) { // Check if the level addon is installed or not
// Player is not on island return addon.getAddonByName("BSkyBlock-Level")
user.sendMessage("challenges.error.not-on-island"); .map(l -> ((Level)l).getIslandLevel(bSkyBlock.getIWM().getIslandWorld(), user.getUniqueId()) >= challenge.getReqIslandlevel() ? new ChallengeResult().setMeetsRequirements() : new ChallengeResult()
return new ChallengeResult(); ).orElse(new ChallengeResult());
} }
// Check for items or entities in the area
ChallengeResult result = searchForEntities(user, challenge.getRequiredEntities(), challenge.getSearchRadius());
if (result.meetsRequirements) {
// Search for items only if entities found
result = searchForBlocks(user, challenge.getRequiredBlocks(), challenge.getSearchRadius());
}
return result;
}
private ChallengeResult searchForBlocks(User user, Map<Material, Integer> map, int searchRadius) { private ChallengeResult checkSurrounding(User user, Challenges challenge) {
Map<Material, Integer> blocks = new EnumMap<>(map); if (!addon.getIslands().userIsOnIsland(bSkyBlock.getIWM().getIslandWorld(), user)) {
for (int x = -searchRadius; x <= searchRadius; x++) { // Player is not on island
for (int y = -searchRadius; y <= searchRadius; y++) { user.sendMessage("challenges.error.not-on-island");
for (int z = -searchRadius; z <= searchRadius; z++) { return new ChallengeResult();
Material mat = user.getWorld().getBlockAt(user.getLocation().add(new Vector(x,y,z))).getType(); }
// Remove one // Check for items or entities in the area
blocks.computeIfPresent(mat, (b, amount) -> amount - 1); ChallengeResult result = searchForEntities(user, challenge.getRequiredEntities(), challenge.getSearchRadius());
// Remove any that have an amount of 0 if (result.meetsRequirements) {
blocks.entrySet().removeIf(en -> en.getValue() <= 0); // Search for items only if entities found
} result = searchForBlocks(user, challenge.getRequiredBlocks(), challenge.getSearchRadius());
} }
} return result;
if (blocks.isEmpty()) { }
return new ChallengeResult().setMeetsRequirements();
}
user.sendMessage("challenges.error.not-close-enough", "[number]", String.valueOf(searchRadius));
blocks.forEach((k,v) -> user.sendMessage("challenges.error.you-still-need",
"[amount]", String.valueOf(v),
"[item]", Util.prettifyText(k.toString())));
return new ChallengeResult(); private ChallengeResult searchForBlocks(User user, Map<Material, Integer> map, int searchRadius) {
} Map<Material, Integer> blocks = new EnumMap<>(map);
for (int x = -searchRadius; x <= searchRadius; x++) {
for (int y = -searchRadius; y <= searchRadius; y++) {
for (int z = -searchRadius; z <= searchRadius; z++) {
Material mat = user.getWorld().getBlockAt(user.getLocation().add(new Vector(x,y,z))).getType();
// Remove one
blocks.computeIfPresent(mat, (b, amount) -> amount - 1);
// Remove any that have an amount of 0
blocks.entrySet().removeIf(en -> en.getValue() <= 0);
}
}
}
if (blocks.isEmpty()) {
return new ChallengeResult().setMeetsRequirements();
}
user.sendMessage("challenges.error.not-close-enough", "[number]", String.valueOf(searchRadius));
blocks.forEach((k,v) -> user.sendMessage("challenges.error.you-still-need",
"[amount]", String.valueOf(v),
"[item]", Util.prettifyText(k.toString())));
private ChallengeResult searchForEntities(User user, Map<EntityType, Integer> map, int searchRadius) { return new ChallengeResult();
Map<EntityType, Integer> entities = new EnumMap<>(map); }
user.getPlayer().getNearbyEntities(searchRadius, searchRadius, searchRadius).forEach(entity -> {
// Look through all the nearby Entities, filtering by type private ChallengeResult searchForEntities(User user, Map<EntityType, Integer> map, int searchRadius) {
entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1); Map<EntityType, Integer> entities = new EnumMap<>(map);
entities.entrySet().removeIf(e -> e.getValue() == 0); user.getPlayer().getNearbyEntities(searchRadius, searchRadius, searchRadius).forEach(entity -> {
}); // Look through all the nearby Entities, filtering by type
if (entities.isEmpty()) { entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1);
return new ChallengeResult().setMeetsRequirements(); entities.entrySet().removeIf(e -> e.getValue() == 0);
} });
entities.forEach((reqEnt, amount) -> user.sendMessage("challenges.error.you-still-need", if (entities.isEmpty()) {
"[amount]", String.valueOf(amount), return new ChallengeResult().setMeetsRequirements();
"[item]", Util.prettifyText(reqEnt.toString()))); }
return new ChallengeResult(); entities.forEach((reqEnt, amount) -> user.sendMessage("challenges.error.you-still-need",
} "[amount]", String.valueOf(amount),
"[item]", Util.prettifyText(reqEnt.toString())));
return new ChallengeResult();
}
/** /**
* Contains flags on completion of challenge * Contains flags on completion of challenge
* @author tastybento * @author tastybento
* *
*/ */
public class ChallengeResult { public class ChallengeResult {
private boolean meetsRequirements; private boolean meetsRequirements;
private boolean repeat; private boolean repeat;
/** /**
* @param meetsRequirements the meetsRequirements to set * @param meetsRequirements the meetsRequirements to set
*/ */
public ChallengeResult setMeetsRequirements() { public ChallengeResult setMeetsRequirements() {
this.meetsRequirements = true; this.meetsRequirements = true;
return this; return this;
} }
/** /**
* @param repeat the repeat to set * @param repeat the repeat to set
*/ */
public ChallengeResult setRepeat(boolean repeat) { public ChallengeResult setRepeat(boolean repeat) {
this.repeat = repeat; this.repeat = repeat;
return this; return this;
} }
} }
private void runCommands(User player, List<String> commands) { private void runCommands(User player, List<String> commands) {
// Ignore commands with this perm // Ignore commands with this perm
if (player.hasPermission(Constants.PERMPREFIX + "command.challengeexempt") && !player.isOp()) { if (player.hasPermission("bskyblock.command.challengeexempt") && !player.isOp()) {
return; return;
} }
for (String cmd : commands) { for (String cmd : commands) {
if (cmd.startsWith("[SELF]")) { if (cmd.startsWith("[SELF]")) {
String alert = "Running command '" + cmd + "' as " + player.getName(); String alert = "Running command '" + cmd + "' as " + player.getName();
addon.getLogger().info(alert); addon.getLogger().info(alert);
cmd = cmd.substring(6,cmd.length()).replace("[player]", player.getName()).trim(); cmd = cmd.substring(6,cmd.length()).replace("[player]", player.getName()).trim();
try { try {
if (!player.performCommand(cmd)) { if (!player.performCommand(cmd)) {
showError(cmd); showError(cmd);
} }
} catch (Exception e) { } catch (Exception e) {
showError(cmd); showError(cmd);
} }
continue; continue;
} }
// Substitute in any references to player // Substitute in any references to player
try { try {
if (!addon.getServer().dispatchCommand(addon.getServer().getConsoleSender(), cmd.replace("[player]", player.getName()))) { if (!addon.getServer().dispatchCommand(addon.getServer().getConsoleSender(), cmd.replace("[player]", player.getName()))) {
showError(cmd); showError(cmd);
} }
} catch (Exception e) { } catch (Exception e) {
showError(cmd); showError(cmd);
} }
} }
} }
private void showError(final String cmd) { private void showError(final String cmd) {
addon.getLogger().severe("Problem executing command executed by player - skipping!"); addon.getLogger().severe("Problem executing command executed by player - skipping!");
addon.getLogger().severe(() -> "Command was : " + cmd); addon.getLogger().severe(() -> "Command was : " + cmd);
}
} }
}