1
0
mirror of https://github.com/mcMMO-Dev/mcMMO.git synced 2026-02-18 17:53:00 +01:00

Compare commits

..

16 Commits

Author SHA1 Message Date
T00thpick1
b700a99c52 NuclearW loves his spacing, also pinging him. 2013-03-11 00:12:31 -04:00
T00thpick1
7294175d9c Messages 2013-03-11 00:08:18 -04:00
NuclearW
1b17b90f32 Diff cleanup 2013-03-10 22:54:47 -04:00
NuclearW
d27f668a2e Fix rebase (see also: me) being dumb 2013-03-10 22:30:20 -04:00
T00thpick1
69dd5769e4 Correct format and comment 2013-03-10 22:30:20 -04:00
T00thpick1
7c9d09a878 Clean queuemanager on disable 2013-03-10 22:30:20 -04:00
T00thpick1
17c64251db Position right 2013-03-10 22:30:19 -04:00
T00thpick1
d728eba5c4 Change not addition 2013-03-10 22:30:19 -04:00
T00thpick1
429055bae2 Update changelog 2013-03-10 22:30:19 -04:00
T00thpick1
3f22a8f479 The sleep didn't actually do much of anything.... 2013-03-10 22:30:19 -04:00
T00thpick1
aeae60f968 check permissions earlier 2013-03-10 22:30:19 -04:00
T00thpick1
a97b889af5 Queue 2013-03-10 22:30:18 -04:00
T00thpick1
0e9953c25b Throttle 2013-03-10 22:30:18 -04:00
T00thpick1
869b30fcaa String wrapper 2013-03-10 22:30:18 -04:00
T00thpick1
44188396b4 One per player 2013-03-10 22:30:18 -04:00
T00thpick1
a7f146a835 queue concept, nowhere near final 2013-03-10 22:30:18 -04:00
225 changed files with 7281 additions and 13726 deletions

View File

@@ -7,118 +7,10 @@ Key:
! Change ! Change
- Removal - Removal
Version 1.4.06-dev Version 1.4.03-dev
+ Added "Ice Fishing" ability to Fishing
+ Added global scoreboards to track skill rankings (display using /mctop)
+ Added per-player scoreboard displays for the /inspect, /mcrank, /mcstats, and /<skillname> commands
+ Added tab-complete support for all commands
+ Added ability to configure drops from Shake in treasures.yml
+ Added "Master Angler" ability to Fishing.
+ Added health display for mobs during combat.
+ Added new API method to McMMOPlayerLevelUpEvent to set levels gained
+ Added new permission node for /ptp; mcmmo.commands.ptp.send (enabled by default)
+ Added configurable cooldown and warmup times when using /ptp
+ Added a new Party item share category "Misc" which contains a list of configurable items. (By default all tools and armor)
+ Added fishing exploit prevention
+ Added permission node to bypass the fishing exploit prevention
+ Added boosts to Fishing chance depending on conditions
+ Added McMMOAbilityActivateEvent and McMMOAbilityDeactivateEvent
+ Added config option to toggle the size of fireworks
+ Added config option to multiply xp gains from mob spawner mobs
+ Added multiplier to Archery XP based on bow force
+ Added information about /party itemshare and /party expshare to the party help page
+ Added option to use scoreboards for power level display instead of Spout.
+ Added permission node to prevent inspecting hidden players
+ Added SQL to Flatfile database conversion
+ Added ability to use custom database managers and convert to/from them
= Fixed bug which could cause the server to hang for a minute when checking for updates. (Thanks to Riking)
= Fixed bug where spawned arrows could throw ArrayIndexOutOfBoundsException
= Fixed bug where custom Spout titles were overwritten by mcMMO.
= Fixed bug where Nether Quartz wasn't included in Smelting or item sharing
= Fixed bug where players were able to join the same party multiple times
= Fixed displaying partial names when trying to use /ptp
= Fixed wolves from Call of the Wild only having 8 health
= Fixed bug where /party chat was not working
= Fixed bug where experience commands were adding levels to all skills when they shouldn't
= Fixed mcmmo.commands.ptp.send not being set by default
= Fixed NPE when trying to tab-complete /mctop
= Fixed Fishing treasures always having the same enchants
= Fixed Smelting returning ink sacs instead of Lapis when double-dropping
= Fixed bug where players could remain in party chat after leaving or being kicked from a party.
= Fixed bug where non-player arrows couldn't be deflected.
= Fixed experience being applied even when the permission for a skill was denied
= Fixed possible item duplication bug with infinity bows
= Fixed bug with removing players from mySQL database
= Fixed bug with empty metadata lists and Smelting
= Fixed bug where Blast Mining would drop wrong items
= Fixed bug with Blast Mining where the Ability refreshed message was being send too early
= Fixed bug where the chance of a successful Gracefull Roll was twice as high as displayed
= Fixed bug where lucky perks where not working
= Fixed bug with Ice Fishing on a single block of ice
= Fixed bug with Ice Fishing which allowed players to break ice in protected areas
= Fixed a small bug with mob healthbars and bosses, such as EnderDragons and Withers
! Changed Spout notification tiers to be stored in SpoutConfig instead of AdvancedConfig
! Changed Berserk to add items to inventory rather than denying pickup
! Changed Call of the Wild, newly summoned pet's will have a custom name. (added permission node to disable this)
! Changed Chimaera Wing's recipe result to use the ingredient Material
! Changed Repair to ask a confirmation of the player when he tries to repair an enchanted item
! Players will no longer pickup items to their hotbar while using Unarmed
! ExperienceAPI methods will now throw InvalidSkillException if the skill name passed in is invalid.
! Changed default value for recently-hurt cooldown between teleports, this is also fully configurable now
! Changed the amount of info messages in the console when enabling/disabling, enable Verbose_Logging to enable them again
! Items dropped by players are now being tracked and are not being shared with party members
! Optimized tracking of tool & ability cooldowns.
! Updated the localization files
Version 1.4.05
+ Added option to allow refreshing of chunks after block-breaking abilities. (Disabled by default)
+ Added fireworks effects when a player levels-up, for every 100 levels (configurable)
= Fixed bug where /addxp was setting instead of adding experience
= Fixed bug where /addxp was not processessing level-ups for online players
= Fixed bug which allowed players to share experience with nearby dead players
= Fixed bug with ChimaeraWings not taking Wings from a players inventory properly
= Fixed bug which caused a NPE when trying to use /mctop smelting
= Fixed Berserk misbehaving when /reload was used
= Fixed parties misbehaving when /reload was used
= Fixed Berserk getting "stuck" when /mcrefresh was used
= Fixed ClassCastException with Taming
= Fixed huge mushroom blocks not being properly tracked
= Fixed potion buff option not using the appropriate # of ticks
= Fixed Chimera Wing spamming console if Metrics was disabled
= Fixed Chimera Wing displaying warmup message if warmup was set to 0
= Fixed party & admin chat errors when not aysnc
! Updated localization files
Version 1.4.04
+ Added functions to ExperienceAPI for use with offline players
+ Added Nether Quartz Ore to Mining
+ Added Dropper, Hopper, and Trapped Chest to blocks that shouldn't activate abilities
+ Added partial name matching
= Fixed bug where trying to activate a Chimaera Wing would require one item too much
= Fixed bug where Treefeller would try to cut too many leaves and reach the threshold when it shouldn't
= Fixed bug where Mining wasn't awarding double drops
= Fixed bug where Shake wouldn't damage mobs whose max health was less than 4
= Fixed bug where the API would fail if the name of a player's current party is requested when the player isn't in one (Thanks @dualspiral!)
= Fixed bug with retrieving a player's party members
= Fixed bug which caused a NPE when trying to join the party of a non-existing player or when ptp to a non-existing player
= Fixed bug which causes a NPE when trying to use /mcrefresh from the console
= Fixed bug where Carrots and Potatoes weren't awarding Herbalism XP.
= Fixed bug where some herbalism drops weren't properly shared within parties.
= Fixed bug where players wouldn't be able to pick up items if they logged our while Berserk was still active.
! Changed config node name for the skill experience modifiers from "Experience.Formula.Multiplier.[Skill]" to "Experience.Formula.Modifier.[Skill]"
! Updated localization files
! mcMMO abilities can no longer be activated while in Creative mode
! Expanded ChatAPI to allow toggling of chat states for users
! Updated to EMetrics 0.0.4-SNAPSHOT
- Removed deprecated functions from API classes.
- Removed functions for getting the PlayerProfile - using API classes is preferred, but if not the McMMOPlayer should be used instead
- Removed Ender Dragon, Wither, and Witch from granting combat experience and related configuration options
Version 1.4.03
+ Added option to advanced.yml to determine the # of enchant levels used when buffing Super Breaker & Giga Drill Breaker + Added option to advanced.yml to determine the # of enchant levels used when buffing Super Breaker & Giga Drill Breaker
+ Improved stats display for child skills + Improved stats display for child skills
+ Added cooldown between using Chimaera Wings + Added cooldown between using Chimaera Wings
= Fixed bug with '/party chat (on|off)' and '/partychat (on|off)' not working
= Fixed bug with Repair not decreasing enchanting levels properly = Fixed bug with Repair not decreasing enchanting levels properly
= Fixed bug with Smelting not properly tracking furnaces = Fixed bug with Smelting not properly tracking furnaces
= Fixed bug with Blast Mining not dropping blocks correctly = Fixed bug with Blast Mining not dropping blocks correctly
@@ -136,10 +28,9 @@ Version 1.4.03
= Fixed bug where the 'mcmmo.commands.ptp.world.all' was registered twice = Fixed bug where the 'mcmmo.commands.ptp.world.all' was registered twice
= Fixed bug where Beast Lore wouldn't work on friendly pets = Fixed bug where Beast Lore wouldn't work on friendly pets
= Fixed bug where Deflect was calculated based on the attacker, not the defender. (We really did this time!) = Fixed bug where Deflect was calculated based on the attacker, not the defender. (We really did this time!)
= Fixed bug where Treefeller would not deal durability damage when the axe "splinters into dozens of pieces"
! Moved the Salvage unlock level from config.yml to advanced.yml ! Moved the Salvage unlock level from config.yml to advanced.yml
! Changed how Chimaera Wings are acquired, you need to craft them now. (By default, use 5 feathers in a shapeless recipe) ! Changed how Chimaera Wings are acquired, you need to craft them now. (By default, use 5 feathers in a shapeless recipe)
! Changed how Chimaera Wings teleport players to the spawnpoint, will now check if the location is safe ! Queue mctop and mcrank commands when using mySQL
- Removed option to disable Salvage via the config file. This should be handled via permissions instead. - Removed option to disable Salvage via the config file. This should be handled via permissions instead.
- Removed the option to use Woodcutting without an axe from the config file. - Removed the option to use Woodcutting without an axe from the config file.

View File

@@ -29,7 +29,7 @@ mcMMO is currently developed by a team of individuals from all over the world.
(https://github.com/shatteredbeam) (https://github.com/shatteredbeam)
[![TfT_02](http://www.gravatar.com/avatar/b8914f9970e1f6ffd5281ce4770e20a7.png)] [![TfT_02](http://www.gravatar.com/avatar/b8914f9970e1f6ffd5281ce4770e20a7.png)]
(https://github.com/TfT-02) (https://github.com/TfT-02)
[![t00thpick1](http://www.gravatar.com/avatar/ee23c7794a0c40120c3474287c7bce06.png)] [![t00thpick1](http://www.gravatar.com/avatar/??.png)]
(https://github.com/t00thpick1) (https://github.com/t00thpick1)
## Compiling ## Compiling

12
pom.xml
View File

@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.nossr50.mcMMO</groupId> <groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId> <artifactId>mcMMO</artifactId>
<version>1.4.06-dev6</version> <version>1.4.03-dev1</version>
<name>mcMMO</name> <name>mcMMO</name>
<url>https://github.com/mcMMO-Dev/mcMMO</url> <url>https://github.com/mcMMO-Dev/mcMMO</url>
<issueManagement> <issueManagement>
@@ -145,7 +145,7 @@
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.5.2-R1.0</version> <version>LATEST</version>
<type>jar</type> <type>jar</type>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -165,7 +165,9 @@
<dependency> <dependency>
<groupId>com.turt2live.metrics</groupId> <groupId>com.turt2live.metrics</groupId>
<artifactId>MetricsExtension</artifactId> <artifactId>MetricsExtension</artifactId>
<version>0.0.5-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<distributionManagement> <distributionManagement>
@@ -177,8 +179,4 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<ciManagement>
<system>Jenkins</system>
<url>ci.mcmmo.org</url>
</ciManagement>
</project> </project>

View File

@@ -48,36 +48,4 @@ public final class AbilityAPI {
return false; return false;
} }
public static void resetCooldowns(Player player) {
UserManager.getPlayer(player).getProfile().resetCooldowns();
}
public static void setBerserkCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.BERSERK, cooldown);
}
public static void setGigaDrillBreakerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.GIGA_DRILL_BREAKER, cooldown);
}
public static void setGreenTerraCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.GREEN_TERRA, cooldown);
}
public static void setSerratedStrikesCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.SERRATED_STRIKES, cooldown);
}
public static void setSkullSplitterCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.SKULL_SPLITTER, cooldown);
}
public static void setSuperBreakerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.SUPER_BREAKER, cooldown);
}
public static void setTreeFellerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).getProfile().setSkillDATS(AbilityType.TREE_FELLER, cooldown);
}
} }

View File

@@ -4,9 +4,6 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.chat.ChatManager; import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.chat.PartyChatManager;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@@ -25,7 +22,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) { public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) {
getPartyChatManager(plugin, party).handleChat(sender, displayName, message); ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, displayName, message);
} }
/** /**
@@ -39,7 +36,23 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendPartyChat(Plugin plugin, String sender, String party, String message) { public static void sendPartyChat(Plugin plugin, String sender, String party, String message) {
getPartyChatManager(plugin, party).handleChat(sender, message); ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, sender, message);
}
/**
* Send a message to all members of a party
* </br>
* This function is designed for API usage.
*
* @deprecated Replaced by sendPartyChat(Plugin, String, String, String)
*
* @param sender The name of the sender to display in the chat
* @param party The name of the party to send to
* @param message The message to send
*/
@Deprecated
public static void sendPartyChat(String sender, String party, String message) {
sendPartyChat(null, party, sender, sender, message);
} }
/** /**
@@ -53,7 +66,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) { public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) {
ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, displayName, message); ChatManager.handleAdminChat(plugin, sender, displayName, message);
} }
/** /**
@@ -66,7 +79,22 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendAdminChat(Plugin plugin, String sender, String message) { public static void sendAdminChat(Plugin plugin, String sender, String message) {
ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, message); ChatManager.handleAdminChat(plugin, sender, sender, message);
}
/**
* Send a message to administrators
* </br>
* This function is designed for API usage.
*
* @deprecated Replaced by sendAdminChat(Plugin, String, String)
*
* @param sender The name of the sender to display in the chat
* @param message The message to send
*/
@Deprecated
public static void sendAdminChat(String sender, String message) {
sendAdminChat(null, sender, sender, message);
} }
/** /**
@@ -108,47 +136,4 @@ public final class ChatAPI {
public static boolean isUsingAdminChat(String playerName) { public static boolean isUsingAdminChat(String playerName) {
return UserManager.getPlayer(playerName).getAdminChatMode(); return UserManager.getPlayer(playerName).getAdminChatMode();
} }
/**
* Toggle the party chat mode of a player.
*
* @param player The player to toggle party chat on.
*/
public static void togglePartyChat(Player player) {
UserManager.getPlayer(player).togglePartyChat();
}
/**
* Toggle the party chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void togglePartyChat(String playerName) {
UserManager.getPlayer(playerName).togglePartyChat();
}
/**
* Toggle the admin chat mode of a player.
*
* @param player The player to toggle admin chat on.
*/
public static void toggleAdminChat(Player player) {
UserManager.getPlayer(player).toggleAdminChat();
}
/**
* Toggle the admin chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void toggleAdminChat(String playerName) {
UserManager.getPlayer(playerName).toggleAdminChat();
}
private static ChatManager getPartyChatManager(Plugin plugin, String party) {
ChatManager chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.PARTY);
((PartyChatManager) chatManager).setParty(PartyManager.getParty(party));
return chatManager;
}
} }

View File

@@ -1,50 +1,28 @@
package com.gmail.nossr50.api; package com.gmail.nossr50.api;
import java.util.Set;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.api.exceptions.InvalidPlayerException;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class ExperienceAPI { public final class ExperienceAPI {
private ExperienceAPI() {} private ExperienceAPI() {}
/** /**
* Returns whether given string is a valid type of skill suitable for the * Adds raw XP to the player.
* other API calls in this class.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param skillType A string that may or may not be a skill * @param player The player to add XP to
* @return true if this is a valid mcMMO skill * @param skillType The skill to add XP to
* @param XP The amount of XP to add
* @deprecated Use {@link #addRawXP(Player, String, int)} instead
*/ */
public static boolean isValidSkillType(String skillType) { @Deprecated
return SkillType.getSkill(skillType) != null; public static void addRawXP(Player player, SkillType skillType, int XP) {
} UserManager.getPlayer(player).applyXpGain(skillType, XP);
/**
* Returns whether the given skill type string is both valid and not a
* child skill. (Child skills have no XP of their own, and their level is
* derived from the parent(s).)
* </br>
* This function is designed for API usage.
*
* @param skillType the skill to check
* @return true if this is a valid, non-child mcMMO skill
*/
public static boolean isNonChildSkill(String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) return false;
return !skill.isChildSkill();
} }
/** /**
@@ -55,27 +33,9 @@ public final class ExperienceAPI {
* @param player The player to add XP to * @param player The player to add XP to
* @param skillType The skill to add XP to * @param skillType The skill to add XP to
* @param XP The amount of XP to add * @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addRawXP(Player player, String skillType, int XP) { public static void addRawXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), XP); UserManager.getPlayer(player).applyXpGain(SkillType.getSkill(skillType), XP);
}
/**
* Adds raw XP to an offline player.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static void addRawXPOffline(String playerName, String skillType, int XP) {
addOfflineXP(playerName, getSkillType(skillType), XP);
} }
/** /**
@@ -86,78 +46,52 @@ public final class ExperienceAPI {
* @param player The player to add XP to * @param player The player to add XP to
* @param skillType The skill to add XP to * @param skillType The skill to add XP to
* @param XP The amount of XP to add * @param XP The amount of XP to add
* @deprecated Use {@link #addMultipliedXP(Player, String, int)} instead
*/
@Deprecated
public static void addMultipliedXP(Player player, SkillType skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(skillType, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
* Adds XP to the player, calculates for XP Rate only.
* </br>
* This function is designed for API usage.
* *
* @throws InvalidSkillException if the given skill is not valid * @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*/ */
public static void addMultipliedXP(Player player, String skillType, int XP) { public static void addMultipliedXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier())); UserManager.getPlayer(player).applyXpGain(SkillType.getSkill(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
* Adds XP to an offline player, calculates for XP Rate only. * Adds XP to the player, calculates for XP Rate, skill modifiers and perks. May be shared with the party.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static void addMultipliedXPOffline(String playerName, String skillType, int XP) {
addOfflineXP(playerName, getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
* Adds XP to the player, calculates for XP Rate and skill modifier.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to add XP to * @param player The player to add XP to
* @param skillType The skill to add XP to * @param skillType The skill to add XP to
* @param XP The amount of XP to add * @param XP The amount of XP to add
* * @deprecated Use {@link #addXP(Player, String, int)} instead
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addModifiedXP(Player player, String skillType, int XP) { @Deprecated
SkillType skill = getSkillType(skillType); public static void addXP(Player player, SkillType skillType, int XP) {
UserManager.getPlayer(player).beginXpGain(skillType, XP);
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
* Adds XP to an offline player, calculates for XP Rate and skill modifier. * Adds XP to the player, calculates for XP Rate, skill modifiers and perks. May be shared with the party.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static void addModifiedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = getSkillType(skillType);
addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
* Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills,
* and party sharing.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to add XP to * @param player The player to add XP to
* @param skillType The skill to add XP to * @param skillType The skill to add XP to
* @param XP The amount of XP to add * @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addXP(Player player, String skillType, int XP) { public static void addXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).beginXpGain(getSkillType(skillType), XP); UserManager.getPlayer(player).beginXpGain(SkillType.getSkill(skillType), XP);
} }
/** /**
@@ -168,136 +102,52 @@ public final class ExperienceAPI {
* @param player The player to get XP for * @param player The player to get XP for
* @param skillType The skill to get XP for * @param skillType The skill to get XP for
* @return the amount of XP in a given skill * @return the amount of XP in a given skill
* * @deprecated Use {@link #getXP(Player, String)} instead
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getXP(Player player, String skillType) { @Deprecated
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(getNonChildSkillType(skillType)); public static int getXP(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(skillType);
} }
/** /**
* Get the amount of XP an offline player has in a specific skill. * Get the amount of XP a player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getOfflineXP(String playerName, String skillType) {
return getOfflineProfile(playerName).getSkillXpLevel(getNonChildSkillType(skillType));
}
/**
* Get the raw amount of XP a player has in a specific skill.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to get XP for * @param player The player to get XP for
* @param skillType The skill to get XP for * @param skillType The skill to get XP for
* @return the amount of XP in a given skill * @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static float getXPRaw(Player player, String skillType) { public static int getXP(Player player, String skillType) {
return UserManager.getPlayer(player).getProfile().getSkillXpLevelRaw(getNonChildSkillType(skillType)); return UserManager.getPlayer(player).getProfile().getSkillXpLevel(SkillType.getSkill(skillType));
} }
/** /**
* Get the raw amount of XP an offline player has in a specific skill. * Get the amount of XP left before leveling up.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static float getOfflineXPRaw(String playerName, String skillType) {
return getOfflineProfile(playerName).getSkillXpLevelRaw(getNonChildSkillType(skillType));
}
/**
* Get the total amount of XP needed to reach the next level.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to get the XP amount for * @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for * @param skillType The skill to get the XP amount for
* @return the total amount of XP needed to reach the next level * @return the amount of XP left before leveling up a specifc skill
* @deprecated Use {@link #getXPToNextLevel(Player, String)} instead
*/
@Deprecated
public static int getXPToNextLevel(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getXpToLevel(skillType);
}
/**
* Get the amount of XP left before leveling up.
* </br>
* This function is designed for API usage.
* *
* @throws InvalidSkillException if the given skill is not valid * @param player The player to get the XP amount for
* @throws UnsupportedOperationException if the given skill is a child skill * @param skillType The skill to get the XP amount for
* @return the amount of XP left before leveling up a specifc skill
*/ */
public static int getXPToNextLevel(Player player, String skillType) { public static int getXPToNextLevel(Player player, String skillType) {
return UserManager.getPlayer(player).getProfile().getXpToLevel(getNonChildSkillType(skillType)); return UserManager.getPlayer(player).getProfile().getXpToLevel(SkillType.getSkill(skillType));
}
/**
* Get the total amount of XP an offline player needs to reach the next level.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the total amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getOfflineXPToNextLevel(String playerName, String skillType) {
return getOfflineProfile(playerName).getXpToLevel(getNonChildSkillType(skillType));
}
/**
* Get the amount of XP remaining until the next level.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for
* @return the amount of XP remaining until the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getXPRemaining(Player player, String skillType) {
SkillType skill = getNonChildSkillType(skillType);
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
}
/**
* Get the amount of XP an offline player has left before leveling up.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getOfflineXPRemaining(String playerName, String skillType) {
SkillType skill = getNonChildSkillType(skillType);
PlayerProfile profile = getOfflineProfile(playerName);
return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
} }
/** /**
@@ -308,42 +158,43 @@ public final class ExperienceAPI {
* @param player The player to add levels to * @param player The player to add levels to
* @param skillType Type of skill to add levels to * @param skillType Type of skill to add levels to
* @param levels Number of levels to add * @param levels Number of levels to add
* * @param notify Unused argument
* @throws InvalidSkillException if the given skill is not valid * @deprecated Use addLevel(Player, SKillType, int) instead
*/ */
public static void addLevel(Player player, String skillType, int levels) { public static void addLevel(Player player, SkillType skillType, int levels, boolean notify) {
UserManager.getPlayer(player).getProfile().addLevels(getSkillType(skillType), levels); UserManager.getProfile(player).addLevels(skillType, levels);
if (notify) {
checkXP(player, skillType);
}
} }
/** /**
* Add levels to a skill for an offline player. * Add levels to a skill.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param playerName The player to add levels to * @param player The player to add levels to
* @param skillType Type of skill to add levels to * @param skillType Type of skill to add levels to
* @param levels Number of levels to add * @param levels Number of levels to add
* * @deprecated Use {@link #addLevel(Player, String, int)} instead
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addLevelOffline(String playerName, String skillType, int levels) { @Deprecated
PlayerProfile profile = getOfflineProfile(playerName); public static void addLevel(Player player, SkillType skillType, int levels) {
SkillType skill = getSkillType(skillType); UserManager.getPlayer(player).getProfile().addLevels(skillType, levels);
}
if (skill.isChildSkill()) { /**
Set<SkillType> parentSkills = FamilyTree.getParents(skill); * Add levels to a skill.
* </br>
for (SkillType parentSkill : parentSkills) { * This function is designed for API usage.
profile.addLevels(parentSkill, (levels / parentSkills.size())); *
} * @param player The player to add levels to
* @param skillType Type of skill to add levels to
profile.save(); * @param levels Number of levels to add
return; */
} public static void addLevel(Player player, String skillType, int levels) {
UserManager.getPlayer(player).getProfile().addLevels(SkillType.getSkill(skillType), levels);
profile.addLevels(skill, levels);
profile.save();
} }
/** /**
@@ -354,27 +205,24 @@ public final class ExperienceAPI {
* @param player The player to get the level for * @param player The player to get the level for
* @param skillType The skill to get the level for * @param skillType The skill to get the level for
* @return the level of a given skill * @return the level of a given skill
* * @deprecated Use {@link #getLevel(Player, String)} instead
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevel(Player player, String skillType) { @Deprecated
return UserManager.getPlayer(player).getProfile().getSkillLevel(getSkillType(skillType)); public static int getLevel(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getSkillLevel(skillType);
} }
/** /**
* Get the level an offline player has in a specific skill. * Get the level a player has in a specific skill.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param playerName The player to get the level for * @param player The player to get the level for
* @param skillType The skill to get the level for * @param skillType The skill to get the level for
* @return the level of a given skill * @return the level of a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static int getLevelOffline(String playerName, String skillType) { public static int getLevel(Player player, String skillType) {
return getOfflineProfile(playerName).getSkillLevel(getSkillType(skillType)); return UserManager.getPlayer(player).getProfile().getSkillLevel(SkillType.getSkill(skillType));
} }
/** /**
@@ -389,27 +237,6 @@ public final class ExperienceAPI {
return UserManager.getPlayer(player).getPowerLevel(); return UserManager.getPlayer(player).getPowerLevel();
} }
/**
* Gets the power level of an offline player.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get the power level for
* @return the power level of the player
*
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static int getPowerLevelOffline(String playerName) {
int powerLevel = 0;
PlayerProfile profile = getOfflineProfile(playerName);
for (SkillType type : SkillType.nonChildSkills()) {
powerLevel += profile.getSkillLevel(type);
}
return powerLevel;
}
/** /**
* Get the level cap of a specific skill. * Get the level cap of a specific skill.
* </br> * </br>
@@ -417,11 +244,9 @@ public final class ExperienceAPI {
* *
* @param skillType The skill to get the level cap for * @param skillType The skill to get the level cap for
* @return the level cap of a given skill * @return the level cap of a given skill
*
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevelCap(String skillType) { public static int getLevelCap(String skillType) {
return Config.getInstance().getLevelCap(getSkillType(skillType)); return Config.getInstance().getLevelCap(SkillType.getSkill(skillType));
} }
/** /**
@@ -429,7 +254,7 @@ public final class ExperienceAPI {
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @return the overall power level cap * @return the power level cap of a given skill
*/ */
public static int getPowerLevelCap() { public static int getPowerLevelCap() {
return Config.getInstance().getPowerLevelCap(); return Config.getInstance().getPowerLevelCap();
@@ -443,27 +268,24 @@ public final class ExperienceAPI {
* @param player The player to set the level of * @param player The player to set the level of
* @param skillType The skill to set the level for * @param skillType The skill to set the level for
* @param skillLevel The value to set the level to * @param skillLevel The value to set the level to
* * @deprecated Use {@link #setLevel(Player, String, int)} instead
* @throws InvalidSkillException if the given skill is not valid
*/ */
public static void setLevel(Player player, String skillType, int skillLevel) { @Deprecated
UserManager.getPlayer(player).getProfile().modifySkill(getSkillType(skillType), skillLevel); public static void setLevel(Player player, SkillType skillType, int skillLevel) {
UserManager.getPlayer(player).getProfile().modifySkill(skillType, skillLevel);
} }
/** /**
* Sets the level of an offline player in a specific skill type. * Sets the level of a player in a specific skill type.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param playerName The player to set the level of * @param player The player to set the level of
* @param skillType The skill to set the level for * @param skillType The skill to set the level for
* @param skillLevel The value to set the level to * @param skillLevel The value to set the level to
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void setLevelOffline(String playerName, String skillType, int skillLevel) { public static void setLevel(Player player, String skillType, int skillLevel) {
getOfflineProfile(playerName).modifySkill(getSkillType(skillType), skillLevel); UserManager.getPlayer(player).getProfile().modifySkill(SkillType.getSkill(skillType), skillLevel);
} }
/** /**
@@ -474,29 +296,24 @@ public final class ExperienceAPI {
* @param player The player to set the XP of * @param player The player to set the XP of
* @param skillType The skill to set the XP for * @param skillType The skill to set the XP for
* @param newValue The value to set the XP to * @param newValue The value to set the XP to
* * @deprecated Use {@link #setXP(Player, String, int)} instead
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void setXP(Player player, String skillType, int newValue) { @Deprecated
UserManager.getPlayer(player).getProfile().setSkillXpLevel(getNonChildSkillType(skillType), newValue); public static void setXP(Player player, SkillType skillType, int newValue) {
UserManager.getPlayer(player).getProfile().setSkillXpLevel(skillType, newValue);
} }
/** /**
* Sets the XP of an offline player in a specific skill type. * Sets the XP of a player in a specific skill type.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param playerName The player to set the XP of * @param player The player to set the XP of
* @param skillType The skill to set the XP for * @param skillType The skill to set the XP for
* @param newValue The value to set the XP to * @param newValue The value to set the XP to
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void setXPOffline(String playerName, String skillType, int newValue) { public static void setXP(Player player, String skillType, int newValue) {
getOfflineProfile(playerName).setSkillXpLevel(getNonChildSkillType(skillType), newValue); UserManager.getPlayer(player).getProfile().setSkillXpLevel(SkillType.getSkill(skillType), newValue);
} }
/** /**
@@ -507,78 +324,35 @@ public final class ExperienceAPI {
* @param player The player to change the XP of * @param player The player to change the XP of
* @param skillType The skill to change the XP for * @param skillType The skill to change the XP for
* @param xp The amount of XP to remove * @param xp The amount of XP to remove
* * @deprecated Use {@link #removeXP(Player, String, int)} instead
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void removeXP(Player player, String skillType, int xp) { @Deprecated
UserManager.getPlayer(player).getProfile().removeXp(getNonChildSkillType(skillType), xp); public static void removeXP(Player player, SkillType skillType, int xp) {
UserManager.getPlayer(player).getProfile().removeXp(skillType, xp);
} }
/** /**
* Removes XP from an offline player in a specific skill type. * Removes XP from a player in a specific skill type.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param playerName The player to change the XP of * @param player The player to change the XP of
* @param skillType The skill to change the XP for * @param skillType The skill to change the XP for
* @param xp The amount of XP to remove * @param xp The amount of XP to remove
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void removeXPOffline(String playerName, String skillType, int xp) { public static void removeXP(Player player, String skillType, int xp) {
getOfflineProfile(playerName).removeXp(getNonChildSkillType(skillType), xp); UserManager.getPlayer(player).getProfile().removeXp(SkillType.getSkill(skillType), xp);
} }
// Utility methods follow. /**
* Check the XP of a player. This should be called after giving XP to process level-ups.
private static void addOfflineXP(String playerName, SkillType skill, int XP) { *
PlayerProfile profile = getOfflineProfile(playerName); * @param player The player to check
* @param skillType The skill to check
if (skill.isChildSkill()) { * @deprecated Calling this function is no longer needed and should be avoided
Set<SkillType> parentSkills = FamilyTree.getParents(skill); */
@Deprecated
for (SkillType parentSkill : parentSkills) { private static void checkXP(Player player, SkillType skillType) {
profile.setSkillXpLevel(parentSkill, profile.getSkillLevel(parentSkill) + (XP / parentSkills.size())); SkillUtils.xpCheckSkill(skillType, player, UserManager.getProfile(player));
}
profile.save();
return;
}
profile.setSkillXpLevel(skill, profile.getSkillXpLevel(skill) + XP);
profile.save();
}
private static PlayerProfile getOfflineProfile(String playerName) {
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false);
if (!profile.isLoaded()) {
throw new InvalidPlayerException();
}
return profile;
}
private static SkillType getSkillType(String skillType) throws InvalidSkillException {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
return skill;
}
private static SkillType getNonChildSkillType(String skillType) throws InvalidSkillException, UnsupportedOperationException {
SkillType skill = getSkillType(skillType);
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return skill;
} }
} }

View File

@@ -1,13 +1,11 @@
package com.gmail.nossr50.api; package com.gmail.nossr50.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@@ -21,13 +19,9 @@ public final class PartyAPI {
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to check the party name of * @param player The player to check the party name of
* @return the name of the player's party, or null if not in a party * @return the name of the player's party
*/ */
public static String getPartyName(Player player) { public static String getPartyName(Player player) {
if (!inParty(player)) {
return null;
}
return UserManager.getPlayer(player).getParty().getName(); return UserManager.getPlayer(player).getParty().getName();
} }
@@ -77,13 +71,14 @@ public final class PartyAPI {
*/ */
public static void addToParty(Player player, String partyName) { public static void addToParty(Player player, String partyName) {
Party party = PartyManager.getParty(partyName); Party party = PartyManager.getParty(partyName);
String playerName = player.getName();
if (party == null) { if (party == null) {
party = new Party(playerName, partyName); party = new Party();
party.setName(partyName);
party.setLeader(player.getName());
} }
PartyManager.addToParty(playerName, UserManager.getPlayer(player), party); PartyManager.addToParty(player, UserManager.getPlayer(player), party);
} }
/** /**
@@ -128,27 +123,28 @@ public final class PartyAPI {
* *
* @param player The player to check * @param player The player to check
* @return all the players in the player's party * @return all the players in the player's party
* @deprecated
*/ */
@Deprecated @Deprecated
public static List<OfflinePlayer> getOnlineAndOfflineMembers(Player player) { public static List<String> getAllMembers(Player player) {
List<OfflinePlayer> members = new ArrayList<OfflinePlayer>(); List<String> memberNames = new ArrayList<String>();
for (String memberName : PartyManager.getAllMembers(player)) { for (OfflinePlayer member : PartyManager.getAllMembers(player)) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName); memberNames.add(member.getName());
members.add(member);
} }
return members;
return memberNames;
} }
/** /**
* Get a list of all player names in this player's party. * Get a list of all players in this player's party.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to check * @param player The player to check
* @return all the player names in the player's party * @return all the players in the player's party
*/ */
public static LinkedHashSet<String> getMembers(Player player) { public static List<OfflinePlayer> getOnlineAndOfflineMembers(Player player) {
return PartyManager.getAllMembers(player); return PartyManager.getAllMembers(player);
} }

View File

@@ -1,9 +0,0 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidPlayerException extends RuntimeException {
private static final long serialVersionUID = 907213002618581385L;
public InvalidPlayerException() {
super("That player does not exist in the database.");
}
}

View File

@@ -1,9 +0,0 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidSkillException extends RuntimeException {
private static final long serialVersionUID = 942705284195791157L;
public InvalidSkillException() {
super("That is not a valid skill.");
}
}

View File

@@ -1,22 +0,0 @@
package com.gmail.nossr50.chat;
import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.events.chat.McMMOAdminChatEvent;
public class AdminChatManager extends ChatManager {
protected AdminChatManager(Plugin plugin) {
super(plugin, Config.getInstance().getAdminDisplayNames(), "Commands.AdminChat.Prefix");
}
@Override
public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
handleChat(new McMMOAdminChatEvent(plugin, senderName, displayName, message, isAsync));
}
@Override
protected void sendMessage() {
plugin.getServer().broadcast(message, "mcmmo.chat.adminchat");
}
}

View File

@@ -1,51 +1,78 @@
package com.gmail.nossr50.chat; package com.gmail.nossr50.chat;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.events.chat.McMMOChatEvent; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOAdminChatEvent;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
public abstract class ChatManager { public final class ChatManager {
protected Plugin plugin; public ChatManager () {}
protected boolean useDisplayNames;
protected String chatPrefix;
protected String displayName; public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message, boolean isAsync) {
protected String message; McMMOAdminChatEvent chatEvent = new McMMOAdminChatEvent(plugin, playerName, displayName, message, isAsync);
mcMMO.p.getServer().getPluginManager().callEvent(chatEvent);
protected ChatManager(Plugin plugin, boolean useDisplayNames, String chatPrefix) { if (chatEvent.isCancelled()) {
this.plugin = plugin;
this.useDisplayNames = useDisplayNames;
this.chatPrefix = chatPrefix;
}
protected void handleChat(McMMOChatEvent event) {
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return; return;
} }
displayName = useDisplayNames ? event.getDisplayName() : event.getSender(); if (Config.getInstance().getAdminDisplayNames()) {
message = LocaleLoader.getString(chatPrefix, displayName) + event.getMessage(); displayName = chatEvent.getDisplayName();
}
else {
displayName = chatEvent.getSender();
}
sendMessage(); String adminMessage = chatEvent.getMessage();
mcMMO.p.getServer().broadcast(LocaleLoader.getString("Commands.AdminChat.Prefix", displayName) + adminMessage, "mcmmo.chat.adminchat");
} }
public void handleChat(String senderName, String message) { public static void handleAdminChat(Plugin plugin, String senderName, String message) {
handleChat(senderName, senderName, message, false); handleAdminChat(plugin, senderName, senderName, message);
} }
public void handleChat(Player player, String message, boolean isAsync) { public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message) {
handleChat(player.getName(), player.getDisplayName(), message, isAsync); handleAdminChat(plugin, playerName, displayName, message, false);
} }
public void handleChat(String senderName, String displayName, String message) { public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message, boolean isAsync) {
handleChat(senderName, displayName, message, false); String partyName = party.getName();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(plugin, playerName, displayName, partyName, message, isAsync);
mcMMO.p.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return;
}
if (Config.getInstance().getPartyDisplayNames()) {
displayName = chatEvent.getDisplayName();
}
else {
displayName = chatEvent.getSender();
}
String partyMessage = chatEvent.getMessage();
for (Player member : party.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Prefix", displayName) + partyMessage);
}
mcMMO.p.getLogger().info("[P](" + partyName + ")" + "<" + ChatColor.stripColor(displayName) + "> " + partyMessage);
} }
public abstract void handleChat(String senderName, String displayName, String message, boolean isAsync); public static void handlePartyChat(Plugin plugin, Party party, String senderName, String message) {
handlePartyChat(plugin, party, senderName, senderName, message);
}
protected abstract void sendMessage(); public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message) {
handlePartyChat(plugin, party, playerName, displayName, message, false);
}
} }

View File

@@ -1,29 +0,0 @@
package com.gmail.nossr50.chat;
import java.util.HashMap;
import org.bukkit.plugin.Plugin;
public class ChatManagerFactory {
private static final HashMap<Plugin, AdminChatManager> adminChatManagers = new HashMap<Plugin, AdminChatManager>();
private static final HashMap<Plugin, PartyChatManager> partyChatManagers = new HashMap<Plugin, PartyChatManager>();
public static ChatManager getChatManager(Plugin plugin, ChatMode mode) {
switch (mode) {
case ADMIN:
if (!adminChatManagers.containsKey(plugin)) {
adminChatManagers.put(plugin, new AdminChatManager(plugin));
}
return adminChatManagers.get(plugin);
case PARTY:
if (!partyChatManagers.containsKey(plugin)) {
partyChatManagers.put(plugin, new PartyChatManager(plugin));
}
return partyChatManagers.get(plugin);
default:
return null;
}
}
}

View File

@@ -1,34 +0,0 @@
package com.gmail.nossr50.chat;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
public class PartyChatManager extends ChatManager {
private Party party;
protected PartyChatManager(Plugin plugin) {
super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix");
}
public void setParty(Party party) {
this.party = party;
}
@Override
public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync));
}
@Override
protected void sendMessage() {
for (Player member : party.getOnlineMembers()) {
member.sendMessage(message);
}
plugin.getLogger().info("[P]<" + party.getName() + ">" + message);
}
}

View File

@@ -1,66 +0,0 @@
package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class KrakenCommand implements TabExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if (!Permissions.kraken(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
UserManager.getPlayer((Player) sender).getFishingManager().unleashTheKraken();
return true;
case 1:
if (!Permissions.krakenOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
if (!CommandUtils.checkPlayerExistence(sender, args[0], mcMMOPlayer)) {
return true;
}
mcMMOPlayer.getFishingManager().unleashTheKraken();
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
default:
return ImmutableList.of();
}
}
}

View File

@@ -1,29 +1,79 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class McabilityCommand extends ToggleCommand { public class McabilityCommand implements CommandExecutor {
@Override @Override
protected boolean hasOtherPermission(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.mcabilityOthers(sender); McMMOPlayer mcMMOPlayer;
}
@Override switch (args.length) {
protected boolean hasSelfPermission(CommandSender sender) { case 0:
return Permissions.mcability(sender); if (!Permissions.mcability(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override mcMMOPlayer = UserManager.getPlayer((Player) sender);
protected void applyCommandAction() {
player.sendMessage(LocaleLoader.getString("Commands.Ability." + (mcMMOPlayer.getAbilityUse() ? "Off" : "On")));
mcMMOPlayer.toggleAbilityUse();
}
@Override if (mcMMOPlayer.getAbilityUse()) {
protected void sendSuccessMessage(CommandSender sender) { sender.sendMessage(LocaleLoader.getString("Commands.Ability.Off"));
sender.sendMessage("Ability use has been toggled for " + player.getName()); // TODO: Localize }
else {
sender.sendMessage(LocaleLoader.getString("Commands.Ability.On"));
}
mcMMOPlayer.toggleAbilityUse();
return true;
case 1:
if (!Permissions.mcabilityOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
if (mcMMOPlayer == null) {
PlayerProfile playerProfile = new PlayerProfile(args[0], false);
if (!playerProfile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
Player player = mcMMOPlayer.getPlayer();
if (!player.isOnline()) {
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
if (mcMMOPlayer.getAbilityUse()) {
player.sendMessage(LocaleLoader.getString("Commands.Ability.Off"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.Ability.On"));
}
mcMMOPlayer.toggleAbilityUse();
return true;
default:
return false;
}
} }
} }

View File

@@ -1,29 +1,88 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class McgodCommand extends ToggleCommand { public class McgodCommand implements CommandExecutor {
@Override @Override
protected boolean hasOtherPermission(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.mcgodOthers(sender); McMMOPlayer mcMMOPlayer;
}
@Override switch (args.length) {
protected boolean hasSelfPermission(CommandSender sender) { case 0:
return Permissions.mcgod(sender); if (!Permissions.mcgod(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override if (!(sender instanceof Player)) {
protected void applyCommandAction() { return false;
player.sendMessage(LocaleLoader.getString("Commands.GodMode." + (mcMMOPlayer.getGodMode() ? "Disabled" : "Enabled"))); }
mcMMOPlayer.toggleGodMode();
}
@Override mcMMOPlayer = UserManager.getPlayer((Player) sender);
protected void sendSuccessMessage(CommandSender sender) {
sender.sendMessage("God mode has been toggled for " + player.getName()); // TODO: Localize if (mcMMOPlayer == null) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
if (mcMMOPlayer.getGodMode()) {
sender.sendMessage(LocaleLoader.getString("Commands.GodMode.Disabled"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.GodMode.Enabled"));
}
mcMMOPlayer.toggleGodMode();
return true;
case 1:
if (!Permissions.mcgodOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
if (mcMMOPlayer == null) {
PlayerProfile playerProfile = new PlayerProfile(args[0], false);
if (!playerProfile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
Player player = mcMMOPlayer.getPlayer();
if (!player.isOnline()) {
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
if (mcMMOPlayer.getGodMode()) {
player.sendMessage(LocaleLoader.getString("Commands.GodMode.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.GodMode.Enabled"));
}
mcMMOPlayer.toggleGodMode();
return true;
default:
return false;
}
} }
} }

View File

@@ -1,17 +1,17 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.getspout.spoutapi.player.SpoutPlayer;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.party.PartySubcommandType; import com.gmail.nossr50.commands.party.PartySubcommandType;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.spout.SpoutUtils;
public class McmmoCommand implements CommandExecutor { public class McmmoCommand implements CommandExecutor {
@Override @Override
@@ -28,13 +28,13 @@ public class McmmoCommand implements CommandExecutor {
sender.sendMessage(mcSplit); sender.sendMessage(mcSplit);
if (Config.getInstance().getDonateMessageEnabled()) { if (Config.getInstance().getDonateMessageEnabled()) {
if (mcMMO.isSpoutEnabled() && sender instanceof Player) { if (mcMMO.spoutEnabled && sender instanceof SpoutPlayer) {
SpoutUtils.sendDonationNotification((Player) sender); SpoutPlayer spoutPlayer = (SpoutPlayer) sender;
} spoutPlayer.sendNotification(LocaleLoader.getString("Spout.Donate"), ChatColor.GREEN + "gjmcferrin@gmail.com", Material.DIAMOND);
else {
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
} }
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
} }
sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion())); sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion()));
@@ -62,52 +62,52 @@ public class McmmoCommand implements CommandExecutor {
private void displayPartyCommands(CommandSender sender) { private void displayPartyCommands(CommandSender sender) {
if (Permissions.party(sender)) { if (Permissions.party(sender)) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Commands")); sender.sendMessage(LocaleLoader.getString("Commands.Party.Commands"));
sender.sendMessage(" /party create <" + LocaleLoader.getString("Commands.Usage.PartyName") + "> " + LocaleLoader.getString("Commands.Party1")); sender.sendMessage("/party create <" + LocaleLoader.getString("Commands.Usage.PartyName") + "> " + LocaleLoader.getString("Commands.Party1"));
sender.sendMessage(" /party join <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party2")); sender.sendMessage("/party join <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party2"));
sender.sendMessage(" /party quit " + LocaleLoader.getString("Commands.Party.Quit")); sender.sendMessage("/party quit " + LocaleLoader.getString("Commands.Party.Quit"));
if (Permissions.partyChat(sender)) { if (Permissions.partyChat(sender)) {
sender.sendMessage(" /party chat " + LocaleLoader.getString("Commands.Party.Toggle")); sender.sendMessage("/party chat " + LocaleLoader.getString("Commands.Party.Toggle"));
} }
sender.sendMessage(" /party invite <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party.Invite")); sender.sendMessage("/party invite <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party.Invite"));
sender.sendMessage(" /party accept " + LocaleLoader.getString("Commands.Party.Accept")); sender.sendMessage("/party accept " + LocaleLoader.getString("Commands.Party.Accept"));
if (Permissions.partySubcommand(sender, PartySubcommandType.TELEPORT)) { if (Permissions.partySubcommand(sender, PartySubcommandType.TELEPORT)) {
sender.sendMessage(" /party teleport " + LocaleLoader.getString("Commands.Party.Teleport")); sender.sendMessage("/party teleport " + LocaleLoader.getString("Commands.Party.Teleport"));
} }
} }
} }
private void displayOtherCommands(CommandSender sender) { private void displayOtherCommands(CommandSender sender) {
sender.sendMessage(LocaleLoader.getString("Commands.Other")); sender.sendMessage(LocaleLoader.getString("Commands.Other"));
sender.sendMessage(" /mcstats " + LocaleLoader.getString("Commands.Stats")); sender.sendMessage("/mcstats " + LocaleLoader.getString("Commands.Stats"));
sender.sendMessage(" /mctop " + LocaleLoader.getString("Commands.Leaderboards")); sender.sendMessage("/mctop " + LocaleLoader.getString("Commands.Leaderboards"));
if (Permissions.skillreset(sender)) { if (Permissions.skillreset(sender)) {
sender.sendMessage(" /skillreset <skill|all> " + LocaleLoader.getString("Commands.Reset")); sender.sendMessage("/skillreset <skill|all> " + LocaleLoader.getString("Commands.Reset"));
} }
if (Permissions.mcability(sender)) { if (Permissions.mcability(sender)) {
sender.sendMessage(" /mcability " + LocaleLoader.getString("Commands.ToggleAbility")); sender.sendMessage("/mcability " + LocaleLoader.getString("Commands.ToggleAbility"));
} }
if (Permissions.adminChat(sender)) { if (Permissions.adminChat(sender)) {
sender.sendMessage(" /adminchat " + LocaleLoader.getString("Commands.AdminToggle")); sender.sendMessage("/adminchat " + LocaleLoader.getString("Commands.AdminToggle"));
} }
if (Permissions.inspect(sender)) { if (Permissions.inspect(sender)) {
sender.sendMessage(" /inspect " + LocaleLoader.getString("Commands.Inspect")); sender.sendMessage("/inspect " + LocaleLoader.getString("Commands.Inspect"));
} }
if (Permissions.mmoedit(sender)) { if (Permissions.mmoedit(sender)) {
sender.sendMessage(" /mmoedit " + LocaleLoader.getString("Commands.mmoedit")); sender.sendMessage("/mmoedit " + LocaleLoader.getString("Commands.mmoedit"));
} }
if (Permissions.mcgod(sender)) { if (Permissions.mcgod(sender)) {
sender.sendMessage(" /mcgod " + LocaleLoader.getString("Commands.mcgod")); sender.sendMessage("/mcgod " + LocaleLoader.getString("Commands.mcgod"));
} }
sender.sendMessage(" /<skill>" + LocaleLoader.getString("Commands.SkillInfo")); sender.sendMessage(LocaleLoader.getString("Commands.SkillInfo"));
} }
} }

View File

@@ -1,26 +1,28 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList; public class McnotifyCommand implements CommandExecutor {
public class McnotifyCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 0: case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On"))); if (mcMMOPlayer.useChatNotifications()) {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
}
mcMMOPlayer.toggleChatNotifications(); mcMMOPlayer.toggleChatNotifications();
return true; return true;
@@ -28,9 +30,4 @@ public class McnotifyCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
} }

View File

@@ -1,33 +1,80 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class McrefreshCommand extends ToggleCommand { public class McrefreshCommand implements CommandExecutor {
@Override @Override
protected boolean hasOtherPermission(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.mcrefreshOthers(sender); McMMOPlayer mcMMOPlayer;
}
@Override switch (args.length) {
protected boolean hasSelfPermission(CommandSender sender) { case 0:
return Permissions.mcrefresh(sender); if (!Permissions.mcrefresh(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override if (!(sender instanceof Player)) {
protected void applyCommandAction() { return false;
mcMMOPlayer.setRecentlyHurt(0); }
mcMMOPlayer.getProfile().resetCooldowns();
mcMMOPlayer.resetToolPrepMode();
mcMMOPlayer.resetAbilityMode();
player.sendMessage(LocaleLoader.getString("Ability.Generic.Refresh")); mcMMOPlayer = UserManager.getPlayer(sender.getName());
}
@Override mcMMOPlayer.setRecentlyHurt(0);
protected void sendSuccessMessage(CommandSender sender) { mcMMOPlayer.getProfile().resetCooldowns();
sender.sendMessage(LocaleLoader.getString("Commands.mcrefresh.Success", player.getName())); mcMMOPlayer.resetToolPrepMode();
mcMMOPlayer.resetAbilityMode();
sender.sendMessage(LocaleLoader.getString("Ability.Generic.Refresh"));
return true;
case 1:
if (!Permissions.mcrefreshOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
if (mcMMOPlayer == null) {
PlayerProfile playerProfile = new PlayerProfile(args[0], false);
if (!playerProfile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
Player player = mcMMOPlayer.getPlayer();
if (!player.isOnline()) {
sender.sendMessage(LocaleLoader.getString("Commands.Offline"));
return true;
}
mcMMOPlayer.setRecentlyHurt(0);
mcMMOPlayer.getProfile().resetCooldowns();
mcMMOPlayer.resetToolPrepMode();
mcMMOPlayer.resetAbilityMode();
player.sendMessage(LocaleLoader.getString("Ability.Generic.Refresh"));
sender.sendMessage(LocaleLoader.getString("Commands.mcrefresh.Success", args[0]));
return true;
default:
return false;
}
} }
} }

View File

@@ -1,141 +0,0 @@
package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList;
public class McscoreboardCommand implements TabExecutor {
private static final List<String> SCOREBOARD_TYPES = ImmutableList.of("clear", "rank", "stats", "top");
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
Player player = (Player) sender;
switch (args.length) {
case 0:
clearScoreboard(player);
return true;
case 1:
if (args[0].equalsIgnoreCase("clear")) {
clearScoreboard(player);
}
else if (args[0].equalsIgnoreCase("rank")) {
if (!Config.getInstance().getMcrankScoreboardEnabled()) {
sender.sendMessage("This scoreboard is not enabled."); //TODO: Localize
return true;
}
ScoreboardManager.setupPlayerScoreboard(player.getName());
ScoreboardManager.enablePlayerRankScoreboard(player);
}
else if (args[0].equalsIgnoreCase("stats")) {
if (!Config.getInstance().getMcstatsScoreboardsEnabled()) {
sender.sendMessage("This scoreboard is not enabled."); //TODO: Localize
return true;
}
ScoreboardManager.setupPlayerScoreboard(player.getName());
ScoreboardManager.enablePlayerStatsScoreboard(UserManager.getPlayer(player));
}
else if (args[0].equalsIgnoreCase("top")) {
if (!Config.getInstance().getMctopScoreboardEnabled()) {
sender.sendMessage("This scoreboard is not enabled."); //TODO: Localize
return true;
}
ScoreboardManager.enableGlobalStatsScoreboard(player, "all", 1);
}
else {
return false;
}
return true;
case 2:
if (!args[0].equalsIgnoreCase("top")) {
return false;
}
if (!Config.getInstance().getMctopScoreboardEnabled()) {
sender.sendMessage("This scoreboard is not enabled."); //TODO: Localize
return true;
}
if (StringUtils.isInt(args[1])) {
ScoreboardManager.enableGlobalStatsScoreboard(player, "all", Math.abs(Integer.parseInt(args[1])));
return true;
}
if (CommandUtils.isInvalidSkill(sender, args[1])) {
return true;
}
ScoreboardManager.enableGlobalStatsScoreboard(player, args[1], 1);
return true;
case 3:
if (!args[0].equalsIgnoreCase("top")) {
return false;
}
if (!Config.getInstance().getMctopScoreboardEnabled()) {
sender.sendMessage("This scoreboard is not enabled."); //TODO: Localize
return true;
}
if (CommandUtils.isInvalidSkill(sender, args[1])) {
return true;
}
if (CommandUtils.isInvalidInteger(sender, args[2])) {
return true;
}
ScoreboardManager.enableGlobalStatsScoreboard(player, args[1], Math.abs(Integer.parseInt(args[2])));
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], SCOREBOARD_TYPES, new ArrayList<String>(SCOREBOARD_TYPES.size()));
case 2:
if (args[0].equalsIgnoreCase("top")) {
return StringUtil.copyPartialMatches(args[1], SkillType.SKILL_NAMES, new ArrayList<String>(SkillType.SKILL_NAMES.size()));
}
// Fallthrough
default:
return ImmutableList.of();
}
}
private void clearScoreboard(Player player) {
player.setScoreboard(mcMMO.p.getServer().getScoreboardManager().getMainScoreboard());
player.sendMessage("Your scoreboard has been cleared!"); //TODO: Locale
}
}

View File

@@ -1,69 +0,0 @@
package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class MobhealthCommand implements TabExecutor {
private static final List<String> MOB_HEALTHBAR_TYPES;
static {
ArrayList<String> types = new ArrayList<String>();
for (MobHealthbarType type : MobHealthbarType.values()) {
types.add(type.toString());
}
Collections.sort(types);
MOB_HEALTHBAR_TYPES = ImmutableList.copyOf(types);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
switch (args.length) {
case 1:
PlayerProfile playerProfile = UserManager.getPlayer((Player) sender).getProfile();
try {
MobHealthbarType type = MobHealthbarType.valueOf(args[0].toUpperCase().trim());
playerProfile.setMobHealthbarType(type);
sender.sendMessage("Display type changed to: " + type); //TODO: Localize
return true;
}
catch (IllegalArgumentException ex) {
sender.sendMessage("Invalid type!"); //TODO: Localize
return true;
}
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], MOB_HEALTHBAR_TYPES, new ArrayList<String>(MOB_HEALTHBAR_TYPES.size()));
default:
return ImmutableList.of();
}
}
}

View File

@@ -1,84 +0,0 @@
package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public abstract class ToggleCommand implements TabExecutor {
protected McMMOPlayer mcMMOPlayer;
protected Player player;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if (!hasSelfPermission(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player);
applyCommandAction();
return true;
case 1:
if (!hasOtherPermission(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
if (!CommandUtils.checkPlayerExistence(sender, args[0], mcMMOPlayer)) {
return true;
}
player = mcMMOPlayer.getPlayer();
if (CommandUtils.isOffline(sender, player)) {
return true;
}
applyCommandAction();
sendSuccessMessage(sender);
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
default:
return ImmutableList.of();
}
}
protected abstract boolean hasOtherPermission(CommandSender sender);
protected abstract boolean hasSelfPermission(CommandSender sender);
protected abstract void applyCommandAction();
protected abstract void sendSuccessMessage(CommandSender sender);
}

View File

@@ -1,28 +1,17 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.google.common.collect.ImmutableList; public class XprateCommand implements CommandExecutor {
private static double originalRate = Config.getInstance().getExperienceGainsGlobalMultiplier();
public class XprateCommand implements TabExecutor {
private double originalRate;
public XprateCommand() {
originalRate = Config.getInstance().getExperienceGainsGlobalMultiplier();
}
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
@@ -46,8 +35,8 @@ public class XprateCommand implements TabExecutor {
return true; return true;
case 2: case 2:
if (CommandUtils.isInvalidInteger(sender, args[0])) { if (!StringUtils.isInt(args[0])) {
return true; return false;
} }
if (!Permissions.xprateSet(sender)) { if (!Permissions.xprateSet(sender)) {
@@ -55,16 +44,11 @@ public class XprateCommand implements TabExecutor {
return true; return true;
} }
if (CommandUtils.shouldDisableToggle(args[1])) { if (!args[1].equalsIgnoreCase("true") && !args[1].equalsIgnoreCase("false")) {
mcMMO.p.setXPEventEnabled(false);
}
else if (CommandUtils.shouldEnableToggle(args[1])) {
mcMMO.p.setXPEventEnabled(true);
}
else {
return false; return false;
} }
mcMMO.p.setXPEventEnabled(Boolean.valueOf(args[1]));
int newXpRate = Integer.parseInt(args[0]); int newXpRate = Integer.parseInt(args[0]);
Config.getInstance().setExperienceGainsGlobalMultiplier(newXpRate); Config.getInstance().setExperienceGainsGlobalMultiplier(newXpRate);
@@ -82,20 +66,4 @@ public class XprateCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
if (StringUtils.isInt(args[0])) {
return ImmutableList.of();
}
return StringUtil.copyPartialMatches(args[0], CommandUtils.RESET_OPTIONS, new ArrayList<String>(CommandUtils.RESET_OPTIONS.size()));
case 2:
return StringUtil.copyPartialMatches(args[1], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
default:
return ImmutableList.of();
}
}
} }

View File

@@ -1,8 +1,12 @@
package com.gmail.nossr50.commands.chat; package com.gmail.nossr50.commands.chat;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatMode; import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.locale.LocaleLoader;
public class AdminChatCommand extends ChatCommand { public class AdminChatCommand extends ChatCommand {
public AdminChatCommand() { public AdminChatCommand() {
@@ -11,6 +15,12 @@ public class AdminChatCommand extends ChatCommand {
@Override @Override
protected void handleChatSending(CommandSender sender, String[] args) { protected void handleChatSending(CommandSender sender, String[] args) {
chatManager.handleChat(sender.getName(), getDisplayName(sender), buildChatMessage(args, 0)); if (sender instanceof Player) {
Player player = (Player) sender;
ChatManager.handleAdminChat(mcMMO.p, player.getName(), player.getDisplayName(), buildChatMessage(args, 0));
}
else {
ChatManager.handleAdminChat(mcMMO.p, LocaleLoader.getString("Commands.Chat.Console"), buildChatMessage(args, 0));
}
} }
} }

View File

@@ -1,41 +1,28 @@
package com.gmail.nossr50.commands.chat; package com.gmail.nossr50.commands.chat;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.ChatMode; import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList; public abstract class ChatCommand implements CommandExecutor {
protected McMMOPlayer mcMMOPlayer;
public abstract class ChatCommand implements TabExecutor {
protected ChatMode chatMode; protected ChatMode chatMode;
protected ChatManager chatManager;
private McMMOPlayer mcMMOPlayer;
public ChatCommand(ChatMode chatMode) { public ChatCommand(ChatMode chatMode) {
this.chatMode = chatMode; this.chatMode = chatMode;
this.chatManager = ChatManagerFactory.getChatManager(mcMMO.p, chatMode);
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 0: case 0:
if (CommandUtils.noConsoleUsage(sender)) { if (!(sender instanceof Player)) {
return true; return false;
} }
mcMMOPlayer = UserManager.getPlayer((Player) sender); mcMMOPlayer = UserManager.getPlayer((Player) sender);
@@ -50,24 +37,20 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
case 1: case 1:
if (CommandUtils.shouldEnableToggle(args[0])) { if (args[0].equalsIgnoreCase("on")) {
if (CommandUtils.noConsoleUsage(sender)) { if (!(sender instanceof Player)) {
return true; return false;
} }
mcMMOPlayer = UserManager.getPlayer((Player) sender);
enableChatMode(sender); enableChatMode(sender);
return true; return true;
} }
if (CommandUtils.shouldDisableToggle(args[0])) { if (args[0].equalsIgnoreCase("off")) {
if (CommandUtils.noConsoleUsage(sender)) { if (!(sender instanceof Player)) {
return true; return false;
} }
mcMMOPlayer = UserManager.getPlayer((Player) sender);
disableChatMode(sender); disableChatMode(sender);
return true; return true;
} }
@@ -80,16 +63,6 @@ public abstract class ChatCommand implements TabExecutor {
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
default:
return ImmutableList.of();
}
}
protected String buildChatMessage(String[] args, int index) { protected String buildChatMessage(String[] args, int index) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(args[index]); builder.append(args[index]);
@@ -102,28 +75,14 @@ public abstract class ChatCommand implements TabExecutor {
return builder.toString(); return builder.toString();
} }
protected String getDisplayName(CommandSender sender) {
return (sender instanceof Player) ? ((Player) sender).getDisplayName() : LocaleLoader.getString("Commands.Chat.Console");
}
protected abstract void handleChatSending(CommandSender sender, String[] args); protected abstract void handleChatSending(CommandSender sender, String[] args);
private void enableChatMode(CommandSender sender) { private void enableChatMode(CommandSender sender) {
if (chatMode == ChatMode.PARTY && mcMMOPlayer.getParty() == null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return;
}
chatMode.enable(mcMMOPlayer); chatMode.enable(mcMMOPlayer);
sender.sendMessage(chatMode.getEnabledMessage()); sender.sendMessage(chatMode.getEnabledMessage());
} }
private void disableChatMode(CommandSender sender) { private void disableChatMode(CommandSender sender) {
if (chatMode == ChatMode.PARTY && mcMMOPlayer.getParty() == null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return;
}
chatMode.disable(mcMMOPlayer); chatMode.disable(mcMMOPlayer);
sender.sendMessage(chatMode.getDisabledMessage()); sender.sendMessage(chatMode.getDisabledMessage());
} }

View File

@@ -3,8 +3,9 @@ package com.gmail.nossr50.commands.chat;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatMode; import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.chat.PartyChatManager;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
@@ -17,18 +18,16 @@ public class PartyChatCommand extends ChatCommand {
@Override @Override
protected void handleChatSending(CommandSender sender, String[] args) { protected void handleChatSending(CommandSender sender, String[] args) {
Party party;
String message;
if (sender instanceof Player) { if (sender instanceof Player) {
party = UserManager.getPlayer((Player) sender).getParty(); Player player = (Player) sender;
Party party = UserManager.getPlayer(player).getParty();
if (party == null) { if (party == null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.None")); sender.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return; return;
} }
message = buildChatMessage(args, 0); ChatManager.handlePartyChat(mcMMO.p, party, player.getName(), player.getDisplayName(), buildChatMessage(args, 0));
} }
else { else {
if (args.length < 2) { if (args.length < 2) {
@@ -36,17 +35,14 @@ public class PartyChatCommand extends ChatCommand {
return; return;
} }
party = PartyManager.getParty(args[0]); Party party = PartyManager.getParty(args[0]);
if (party == null) { if (party == null) {
sender.sendMessage(LocaleLoader.getString("Party.InvalidName")); sender.sendMessage(LocaleLoader.getString("Party.InvalidName"));
return; return;
} }
message = buildChatMessage(args, 1); ChatManager.handlePartyChat(mcMMO.p, party, LocaleLoader.getString("Commands.Chat.Console"), buildChatMessage(args, 1));
} }
((PartyChatManager) chatManager).setParty(party);
chatManager.handleChat(sender.getName(), getDisplayName(sender), message);
} }
} }

View File

@@ -1,26 +1,38 @@
package com.gmail.nossr50.commands.database; package com.gmail.nossr50.commands.database;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.google.common.collect.ImmutableList; public class McpurgeCommand implements CommandExecutor {
public class McpurgeCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mcpurge(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
switch (args.length) { switch (args.length) {
case 0: case 0:
mcMMO.getDatabaseManager().purgePowerlessUsers(); if (Config.getInstance().getUseMySQL()) {
DatabaseManager.purgePowerlessSQL();
if (Config.getInstance().getOldUsersCutoff() != -1) { if (Config.getInstance().getOldUsersCutoff() != -1) {
mcMMO.getDatabaseManager().purgeOldUsers(); DatabaseManager.purgeOldSQL();
}
}
else {
LeaderboardManager.purgePowerlessFlatfile();
if (Config.getInstance().getOldUsersCutoff() != -1) {
LeaderboardManager.purgeOldFlatfile();
}
} }
sender.sendMessage(LocaleLoader.getString("Commands.mcpurge.Success")); sender.sendMessage(LocaleLoader.getString("Commands.mcpurge.Success"));
@@ -30,9 +42,4 @@ public class McpurgeCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
} }

View File

@@ -1,35 +1,45 @@
package com.gmail.nossr50.commands.database; package com.gmail.nossr50.commands.database;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList; public class McremoveCommand implements CommandExecutor {
public class McremoveCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mcremove(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
switch (args.length) { switch (args.length) {
case 1: case 1:
if (UserManager.getPlayer(args[0]) == null && CommandUtils.unloadedProfile(sender, mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false))) { /* MySQL */
return true; if (Config.getInstance().getUseMySQL()) {
} String tablePrefix = Config.getInstance().getMySQLTablePrefix();
if (mcMMO.getDatabaseManager().removeUser(args[0])) { if (DatabaseManager.update("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.user = '" + args[0] + "'") != 0) {
sender.sendMessage(LocaleLoader.getString("Commands.mcremove.Success", args[0])); DatabaseManager.profileCleanup(args[0]);
sender.sendMessage(LocaleLoader.getString("Commands.mcremove.Success", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
}
} }
else { else {
sender.sendMessage(args[0] + " could not be removed from the database."); // Pretty sure this should NEVER happen. if (LeaderboardManager.removeFlatFileUser(args[0])) {
DatabaseManager.profileCleanup(args[0]);
sender.sendMessage(LocaleLoader.getString("Commands.mcremove.Success", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
}
} }
return true; return true;
@@ -38,15 +48,4 @@ public class McremoveCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
default:
return ImmutableList.of();
}
}
} }

View File

@@ -1,42 +0,0 @@
package com.gmail.nossr50.commands.database;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.locale.LocaleLoader;
import com.google.common.collect.ImmutableList;
public class MmoshowdbCommand implements TabExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length != 0) {
return false;
}
else {
Class<?> clazz = DatabaseManagerFactory.getCustomDatabaseManagerClass();
if (clazz != null) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", clazz.getName()));
return true;
}
else {
if (Config.getInstance().getUseMySQL()) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", "sql"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mmoshowdb", "flatfile"));
}
return true;
}
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
}

View File

@@ -1,138 +1,51 @@
package com.gmail.nossr50.commands.database; package com.gmail.nossr50.commands.database;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.database.ConversionTask; import com.gmail.nossr50.runnables.database.SQLConversionTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList; public class MmoupdateCommand implements CommandExecutor {
public class MmoupdateCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mmoupdate(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
switch (args.length) { switch (args.length) {
case 1: case 0:
String argType = args[0]; sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Start"));
String oldType = validateName(sender, args[0]);
if (oldType == null) {
return true;
}
String newType = getCurrentDb();
if (newType.equals(oldType)) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Same", argType));
return true;
}
DatabaseManager oldDb;
if (oldType == "sql") {
oldDb = DatabaseManagerFactory.createSQLDatabaseManager();
}
else if (oldType == "flatfile") {
oldDb = DatabaseManagerFactory.createFlatfileDatabaseManager();
}
else try {
@SuppressWarnings("unchecked")
Class<? extends DatabaseManager> clazz = (Class<? extends DatabaseManager>) Class.forName(oldType);
oldDb = DatabaseManagerFactory.createCustomDatabaseManager((Class<? extends DatabaseManager>) clazz);
oldType = clazz.getSimpleName(); // For pretty-printing; we have the database now
}
catch (Throwable e) {
return false;
}
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Start", oldType, newType));
// Convert the online players right away, without waiting
// first, flush out the current data
UserManager.saveAll();
UserManager.clearAll(); UserManager.clearAll();
convertToMySQL();
for (Player player : mcMMO.p.getServer().getOnlinePlayers()) { for (Player player : mcMMO.p.getServer().getOnlinePlayers()) {
// Get the profile from the old database and save it in the new
PlayerProfile profile = oldDb.loadPlayerProfile(player.getName(), false);
if (profile.isLoaded()) {
mcMMO.getDatabaseManager().saveUser(profile);
}
// Reload from the current database via UserManager
UserManager.addUser(player); UserManager.addUser(player);
} }
// Schedule the task for all users sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Finish"));
new ConversionTask(oldDb, sender, oldType, newType).runTaskAsynchronously(mcMMO.p);
return true; return true;
default: default:
break; return false;
} }
return false;
} }
/** /**
* @return null - if type not recognized / class not found * Convert FlatFile data to MySQL data.
* empty string - if type is same as current
* normalized string - if type is recognized
*/ */
private String validateName(CommandSender sender, String type) { private void convertToMySQL() {
if (type.equalsIgnoreCase("sql") || type.equalsIgnoreCase("mysql")) { if (!Config.getInstance().getUseMySQL()) {
return "sql"; return;
} }
if (type.equalsIgnoreCase("flatfile") || type.equalsIgnoreCase("file")) { mcMMO.p.getServer().getScheduler().runTaskLaterAsynchronously(mcMMO.p, new SQLConversionTask(), 1);
return "flatfile";
}
try {
Class<?> clazz = Class.forName(type);
if (!DatabaseManager.class.isAssignableFrom(clazz)) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.InvalidType", type));
return null;
}
return type;
}
catch (Exception e) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.InvalidType", type));
return null;
}
}
private String getCurrentDb() {
if (DatabaseManagerFactory.getCustomDatabaseManagerClass() != null) {
return DatabaseManagerFactory.getCustomDatabaseManagerClass().getSimpleName();
}
if (Config.getInstance().getUseMySQL()) {
return "sql";
}
else {
return "flatfile";
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
Class<?> clazz = DatabaseManagerFactory.getCustomDatabaseManagerClass();
if (clazz != null) {
return ImmutableList.of("flatfile", "sql", clazz.getName());
}
return ImmutableList.of("flatfile", "sql");
} }
} }

View File

@@ -1,41 +1,154 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AddlevelsCommand extends ExperienceCommand { public class AddlevelsCommand implements CommandExecutor {
@Override @Override
protected boolean permissionsCheckSelf(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.addlevels(sender); PlayerProfile profile;
} int levels;
boolean allSkills = false;
SkillType skill = null;
@Override switch (args.length) {
protected boolean permissionsCheckOthers(CommandSender sender) { case 2:
return Permissions.addlevelsOthers(sender); if (!Permissions.addlevels(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override if (!(sender instanceof Player)) {
protected void handleCommand(SkillType skill) { return false;
profile.addLevels(skill, value); }
if (player != null) { if (args[0].equalsIgnoreCase("all")) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value)); allSkills = true;
}
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[1])) {
return false;
}
levels = Integer.parseInt(args[1]);
profile = UserManager.getPlayer((Player) sender).getProfile();
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.addLevels(skillType, levels);
}
}
else {
skill = SkillType.getSkill(args[0]);
profile.addLevels(skill, levels);
}
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", levels));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", levels, SkillUtils.getSkillName(skill)));
}
return true;
case 3:
if (!Permissions.addlevelsOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (args[1].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[1])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[2])) {
return false;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
levels = Integer.parseInt(args[2]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
profile = new PlayerProfile(args[0], false);
if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.addLevels(skillType, levels);
}
}
else {
skill = SkillType.getSkill(args[1]);
profile.addLevels(skill, levels);
}
profile.save(); // Since this is a temporary profile, we save it here.
}
else {
profile = mcMMOPlayer.getProfile();
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.addLevels(skillType, levels);
}
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", levels));
}
else {
skill = SkillType.getSkill(args[1]);
profile.addLevels(skill, levels);
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", levels, SkillUtils.getSkillName(skill)));
}
}
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", SkillUtils.getSkillName(skill), args[0]));
}
return true;
default:
return false;
} }
} }
@Override
protected void handlePlayerMessageAll() {
player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", value));
}
@Override
protected void handlePlayerMessageSkill() {
player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, SkillUtils.getSkillName(skill)));
}
} }

View File

@@ -1,40 +1,152 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AddxpCommand extends ExperienceCommand { public class AddxpCommand implements CommandExecutor {
@Override @Override
protected boolean permissionsCheckSelf(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.addxp(sender); int xp;
} McMMOPlayer mcMMOPlayer;
PlayerProfile profile;
boolean allSkills = false;
SkillType skill = null;
@Override switch (args.length) {
protected boolean permissionsCheckOthers(CommandSender sender) { case 2:
return Permissions.addxpOthers(sender); if (!Permissions.addxp(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override if (!(sender instanceof Player)) {
protected void handleCommand(SkillType skill) { return false;
if (player != null) { }
mcMMOPlayer.applyXpGain(skill, value);
if (args[0].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[1])) {
return false;
}
xp = Integer.parseInt(args[1]);
mcMMOPlayer = UserManager.getPlayer((Player) sender);
profile = mcMMOPlayer.getProfile();
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
mcMMOPlayer.applyXpGain(skillType, xp);
}
sender.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", xp));
}
else {
skill = SkillType.getSkill(args[0]);
mcMMOPlayer.applyXpGain(skill, xp);
sender.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", xp, SkillUtils.getSkillName(skill)));
}
return true;
case 3:
if (!Permissions.addxpOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (args[1].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[1])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[2])) {
return false;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
xp = Integer.parseInt(args[2]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
profile = new PlayerProfile(args[0], false);
if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
// TODO: Currently the offline player doesn't level up automatically
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.setSkillXpLevel(skillType, xp);
}
}
else {
skill = SkillType.getSkill(args[1]);
profile.setSkillXpLevel(skill, xp);
}
profile.save(); // Since this is a temporary profile, we save it here.
}
else {
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
mcMMOPlayer.applyXpGain(skillType, xp);
}
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", xp));
}
else {
skill = SkillType.getSkill(args[1]);
mcMMOPlayer.applyXpGain(skill, xp);
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", xp, SkillUtils.getSkillName(skill)));
}
}
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", SkillUtils.getSkillName(skill), args[0]));
}
return true;
default:
return false;
} }
else {
profile.addExperience(skill, value);
}
}
@Override
protected void handlePlayerMessageAll() {
player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", value));
}
@Override
protected void handlePlayerMessageSkill() {
player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, SkillUtils.getSkillName(skill)));
} }
} }

View File

@@ -1,172 +0,0 @@
package com.gmail.nossr50.commands.experience;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList;
public abstract class ExperienceCommand implements TabExecutor {
protected McMMOPlayer mcMMOPlayer;
protected Player player;
protected PlayerProfile profile;
protected boolean allSkills;
protected SkillType skill;
protected int value;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 2:
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if (!permissionsCheckSelf(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (!validateArguments(sender, args[0], args[1])) {
return true;
}
player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player);
profile = mcMMOPlayer.getProfile();
editValues();
allSkills = false;
return true;
case 3:
if (!permissionsCheckOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (!validateArguments(sender, args[1], args[2])) {
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
profile = mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false);
if (CommandUtils.unloadedProfile(sender, profile)) {
return true;
}
editValues();
profile.save(); // Since this is a temporary profile, we save it here.
}
else {
profile = mcMMOPlayer.getProfile();
player = mcMMOPlayer.getPlayer();
editValues();
}
handleSenderMessage(sender, args[0]);
allSkills = false;
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
case 2:
return StringUtil.copyPartialMatches(args[1], SkillType.SKILL_NAMES, new ArrayList<String>(SkillType.SKILL_NAMES.size()));
default:
return ImmutableList.of();
}
}
protected abstract boolean permissionsCheckSelf(CommandSender sender);
protected abstract boolean permissionsCheckOthers(CommandSender sender);
protected abstract void handleCommand(SkillType skill);
protected abstract void handlePlayerMessageAll();
protected abstract void handlePlayerMessageSkill();
private boolean validateArguments(CommandSender sender, String skillName, String value) {
if (isInvalidInteger(sender, value) || isInvalidSkill(sender, skillName)) {
return false;
}
return true;
}
private boolean isInvalidInteger(CommandSender sender, String value) {
if (CommandUtils.isInvalidInteger(sender, value)) {
return true;
}
this.value = Integer.parseInt(value);
return false;
}
protected boolean isInvalidSkill(CommandSender sender, String skillName) {
if (skillName.equalsIgnoreCase("all")) {
allSkills = true;
return false;
}
else if (CommandUtils.isInvalidSkill(sender, skillName)) {
return true;
}
skill = SkillType.getSkill(skillName);
return false;
}
protected void handleSenderMessage(CommandSender sender, String playerName) {
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", SkillUtils.getSkillName(skill), playerName));
}
}
protected void editValues() {
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
handleCommand(skillType);
}
if (player != null) {
handlePlayerMessageAll();
}
}
else {
handleCommand(skill);
if (player != null) {
handlePlayerMessageSkill();
}
}
}
}

View File

@@ -1,41 +1,150 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class MmoeditCommand extends ExperienceCommand { public class MmoeditCommand implements CommandExecutor {
@Override @Override
protected boolean permissionsCheckSelf(CommandSender sender) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.mmoedit(sender); PlayerProfile profile;
} int newValue;
boolean allSkills = false;
SkillType skill = null;
@Override switch (args.length) {
protected boolean permissionsCheckOthers(CommandSender sender) { case 2:
return Permissions.mmoeditOthers(sender); if (!Permissions.mmoedit(sender)) {
} sender.sendMessage(command.getPermissionMessage());
return true;
}
@Override if (!(sender instanceof Player)) {
protected void handleCommand(SkillType skill) { return false;
profile.modifySkill(skill, value); }
if (player != null) { if (args[0].equalsIgnoreCase("all")) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value - profile.getSkillLevel(skill))); allSkills = true;
}
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[1])) {
return false;
}
newValue = Integer.parseInt(args[1]);
profile = UserManager.getPlayer((Player) sender).getProfile();
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.modifySkill(skillType, newValue);
}
sender.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", newValue));
}
else {
skill = SkillType.getSkill(args[0]);
profile.modifySkill(skill, newValue);
sender.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", SkillUtils.getSkillName(skill), newValue));
}
return true;
case 3:
if (!Permissions.mmoeditOthers(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (args[1].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[1])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[2])) {
return false;
}
newValue = Integer.parseInt(args[2]);
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
profile = new PlayerProfile(args[0], false);
if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.modifySkill(skillType, newValue);
}
}
else {
skill = SkillType.getSkill(args[1]);
profile.modifySkill(skill, newValue);
}
profile.save(); // Since this is a temporary profile, we save it here.
}
else {
profile = mcMMOPlayer.getProfile();
if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
profile.modifySkill(skillType, newValue);
}
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", newValue));
}
else {
skill = SkillType.getSkill(args[1]);
profile.modifySkill(skill, newValue);
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", SkillUtils.getSkillName(skill), newValue));
}
}
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.2", SkillUtils.getSkillName(skill), args[0]));
}
return true;
default:
return false;
} }
} }
@Override
protected void handlePlayerMessageAll() {
player.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", value));
}
@Override
protected void handlePlayerMessageSkill() {
player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", SkillUtils.getSkillName(skill), value));
}
} }

View File

@@ -1,49 +1,76 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class SkillresetCommand extends ExperienceCommand { public class SkillresetCommand implements CommandExecutor {
private CommandSender sender;
private Command command;
private int argsLength;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
this.command = command; PlayerProfile profile;
this.sender = sender; boolean allSkills = false;
argsLength = args.length; SkillType skill = null;
String skillName = "";
switch (args.length) { switch (args.length) {
case 1: case 1:
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if (!Permissions.skillreset(sender)) { if (!Permissions.skillreset(sender)) {
sender.sendMessage(command.getPermissionMessage()); sender.sendMessage(command.getPermissionMessage());
return true; return true;
} }
if (isInvalidSkill(sender, args[0])) { if (!(sender instanceof Player)) {
return false;
}
if (args[0].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true; return true;
} }
player = (Player) sender; profile = UserManager.getPlayer((Player) sender).getProfile();
mcMMOPlayer = UserManager.getPlayer(player);
profile = mcMMOPlayer.getProfile(); if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
if (!Permissions.skillreset(sender, skillType)) {
sender.sendMessage(command.getPermissionMessage());
continue;
}
profile.modifySkill(skillType, 0);
}
sender.sendMessage(LocaleLoader.getString("Commands.Reset.All"));
}
else {
skill = SkillType.getSkill(args[0]);
skillName = SkillUtils.getSkillName(skill);
if (!Permissions.skillreset(sender, skill)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
profile.modifySkill(skill, 0);
sender.sendMessage(LocaleLoader.getString("Commands.Reset.Single", skillName));
}
editValues();
return true; return true;
case 2: case 2:
@@ -52,69 +79,91 @@ public class SkillresetCommand extends ExperienceCommand {
return true; return true;
} }
if (isInvalidSkill(sender, args[1])) { if (args[1].equalsIgnoreCase("all")) {
allSkills = true;
}
else if (!SkillUtils.isSkill(args[1])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(args[0]); if (!allSkills) {
skill = SkillType.getSkill(args[1]);
skillName = SkillUtils.getSkillName(skill);
if (!Permissions.skillresetOthers(sender, skill)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) { if (mcMMOPlayer == null) {
profile = mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false); profile = new PlayerProfile(args[0], false);
if (CommandUtils.unloadedProfile(sender, profile)) { if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true; return true;
} }
editValues(); if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
if (!Permissions.skillresetOthers(sender, skill)) {
sender.sendMessage(command.getPermissionMessage());
continue;
}
profile.modifySkill(skillType, 0);
}
}
else {
profile.modifySkill(skill, 0);
}
profile.save(); // Since this is a temporary profile, we save it here. profile.save(); // Since this is a temporary profile, we save it here.
} }
else { else {
profile = mcMMOPlayer.getProfile(); profile = mcMMOPlayer.getProfile();
player = mcMMOPlayer.getPlayer();
editValues(); if (allSkills) {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
if (!Permissions.skillresetOthers(sender, skillType)) {
sender.sendMessage(command.getPermissionMessage());
continue;
}
profile.modifySkill(skillType, 0);
}
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.Reset.All"));
}
else {
profile.modifySkill(skill, 0);
mcMMOPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.Reset.Single", skillName));
}
}
if (allSkills) {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0]));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.2", skillName, args[0]));
} }
handleSenderMessage(sender, args[0]);
return true; return true;
default: default:
return false; return false;
} }
} }
@Override
protected boolean permissionsCheckSelf(CommandSender sender) {
return false;
}
@Override
protected boolean permissionsCheckOthers(CommandSender sender) {
return false;
}
@Override
protected void handleCommand(SkillType skill) {
if (argsLength == 1 && !Permissions.skillreset(sender, skill) || (argsLength == 2 && !Permissions.skillresetOthers(sender, skill))) {
sender.sendMessage(command.getPermissionMessage());
return;
}
profile.modifySkill(skill, 0);
if (player != null) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, 0 - profile.getSkillLevel(skill)));
}
}
@Override
protected void handlePlayerMessageAll() {
player.sendMessage(LocaleLoader.getString("Commands.Reset.All"));
}
@Override
protected void handlePlayerMessageSkill() {
player.sendMessage(LocaleLoader.getString("Commands.Reset.Single", SkillUtils.getSkillName(skill)));
}
} }

View File

@@ -1,41 +1,85 @@
package com.gmail.nossr50.commands.hardcore; package com.gmail.nossr50.commands.hardcore;
import java.text.DecimalFormat;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
public class HardcoreCommand extends HardcoreModeCommand { public class HardcoreCommand implements CommandExecutor {
@Override @Override
protected void disable() { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (Config.getInstance().getHardcoreEnabled()) {
disableHardcore();
}
else {
enableHardcore();
}
return true;
case 1:
if (args[0].equalsIgnoreCase("on") || args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("enabled")) {
if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
enableHardcore();
return true;
}
if (args[0].equalsIgnoreCase("off") || args[0].equalsIgnoreCase("false") || args[0].equalsIgnoreCase("disabled")) {
if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
disableHardcore();
return true;
}
if (!StringUtils.isDouble(args[0])) {
return false;
}
if (!Permissions.hardcoreModify(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
DecimalFormat percent = new DecimalFormat("##0.00%");
double newPercent = Double.parseDouble(args[0]);
Config.getInstance().setHardcoreDeathStatPenaltyPercentage(newPercent);
sender.sendMessage(LocaleLoader.getString("Hardcore.PercentageChanged", percent.format(newPercent / 100D)));
return true;
default:
return false;
}
}
private void disableHardcore() {
Config.getInstance().setHardcoreEnabled(false); Config.getInstance().setHardcoreEnabled(false);
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Disabled")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Disabled"));
} }
@Override private void enableHardcore() {
protected void enable() {
Config.getInstance().setHardcoreEnabled(true); Config.getInstance().setHardcoreEnabled(true);
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Enabled")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Hardcore.Enabled"));
} }
@Override
protected boolean checkTogglePermissions() {
return Permissions.hardcoreToggle(sender);
}
@Override
protected boolean checkModifyPermissions() {
return Permissions.hardcoreModify(sender);
}
@Override
protected boolean checkEnabled() {
return Config.getInstance().getHardcoreEnabled();
}
@Override
protected void modify() {
Config.getInstance().setHardcoreDeathStatPenaltyPercentage(newPercent);
sender.sendMessage(LocaleLoader.getString("Hardcore.PercentageChanged", percent.format(newPercent / 100D)));
}
} }

View File

@@ -1,114 +0,0 @@
package com.gmail.nossr50.commands.hardcore;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.google.common.collect.ImmutableList;
public abstract class HardcoreModeCommand implements TabExecutor {
protected CommandSender sender;
protected double newPercent;
protected DecimalFormat percent;
public HardcoreModeCommand() {
percent = new DecimalFormat("##0.00%");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
this.sender = sender;
if (!checkTogglePermissions()) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (checkEnabled()) {
disable();
}
else {
enable();
}
return true;
case 1:
if (CommandUtils.shouldEnableToggle(args[0])) {
if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
enable();
return true;
}
if (CommandUtils.shouldDisableToggle(args[0])) {
if (!Permissions.hardcoreToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
disable();
return true;
}
if (isInvalidPercentage(sender, args[0])) {
return true;
}
if (!Permissions.hardcoreModify(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
modify();
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
if (StringUtils.isDouble(args[0])) {
return ImmutableList.of();
}
return StringUtil.copyPartialMatches(args[0], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
default:
return ImmutableList.of();
}
}
protected abstract boolean checkTogglePermissions();
protected abstract boolean checkModifyPermissions();
protected abstract boolean checkEnabled();
protected abstract void enable();
protected abstract void disable();
protected abstract void modify();
private boolean isInvalidPercentage(CommandSender sender, String value) {
if (CommandUtils.isInvalidDouble(sender, value)) {
return true;
}
newPercent = Double.parseDouble(value);
return false;
}
}

View File

@@ -1,41 +1,90 @@
package com.gmail.nossr50.commands.hardcore; package com.gmail.nossr50.commands.hardcore;
import java.text.DecimalFormat;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
public class VampirismCommand extends HardcoreModeCommand { public class VampirismCommand implements CommandExecutor {
@Override @Override
protected boolean checkTogglePermissions() { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return Permissions.vampirismToggle(sender); if (!Config.getInstance().getHardcoreEnabled()) {
sender.sendMessage(LocaleLoader.getString("Hardcore.Disabled"));
return true;
}
switch (args.length) {
case 0:
if (!Permissions.vampirismToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (Config.getInstance().getHardcoreVampirismEnabled()) {
disableVampirism();
}
else {
enableVampirism();
}
return true;
case 1:
if (args[0].equalsIgnoreCase("on") || args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("enabled")) {
if (!Permissions.vampirismToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
enableVampirism();
return true;
}
if (args[0].equalsIgnoreCase("off") || args[0].equalsIgnoreCase("false") || args[0].equalsIgnoreCase("disabled")) {
if (!Permissions.vampirismToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
disableVampirism();
return true;
}
if (!StringUtils.isDouble(args[0])) {
return false;
}
if (!Permissions.vampirismModify(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
DecimalFormat percent = new DecimalFormat("##0.00%");
double newPercent = Double.parseDouble(args[0]);
Config.getInstance().setHardcoreVampirismStatLeechPercentage(newPercent);
sender.sendMessage(LocaleLoader.getString("Vampirism.PercentageChanged", percent.format(newPercent / 100D)));
return true;
default:
return false;
}
} }
@Override private void disableVampirism() {
protected boolean checkModifyPermissions() {
return Permissions.vampirismModify(sender);
}
@Override
protected boolean checkEnabled() {
return Config.getInstance().getHardcoreVampirismEnabled();
}
@Override
protected void enable() {
Config.getInstance().setHardcoreVampirismEnabled(true);
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Enabled"));
}
@Override
protected void disable() {
Config.getInstance().setHardcoreVampirismEnabled(false); Config.getInstance().setHardcoreVampirismEnabled(false);
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Disabled")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Disabled"));
} }
@Override private void enableVampirism() {
protected void modify() { Config.getInstance().setHardcoreVampirismEnabled(true);
Config.getInstance().setHardcoreVampirismStatLeechPercentage(newPercent); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Enabled"));
sender.sendMessage(LocaleLoader.getString("Vampirism.PercentageChanged", percent.format(newPercent / 100D)));
} }
} }

View File

@@ -11,12 +11,15 @@ import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyAcceptCommand implements CommandExecutor { public class PartyAcceptCommand implements CommandExecutor {
private McMMOPlayer mcMMOPlayer;
private Player player;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 1: case 1:
Player player = (Player) sender; player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPartyInvite()) { if (!mcMMOPlayer.hasPartyInvite()) {
sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites")); sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites"));

View File

@@ -5,6 +5,7 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
@@ -17,7 +18,7 @@ public class PartyChangeOwnerCommand implements CommandExecutor {
case 2: case 2:
Party playerParty = UserManager.getPlayer((Player) sender).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
if (!playerParty.getMembers().contains(args[1])) { if (!playerParty.getMembers().contains(mcMMO.p.getServer().getOfflinePlayer(args[1]))) {
sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1])); sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1]));
return true; return true;
} }

View File

@@ -10,24 +10,22 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyChangePasswordCommand implements CommandExecutor { public class PartyChangePasswordCommand implements CommandExecutor {
private Party playerParty;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
playerParty = UserManager.getPlayer((Player) sender).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
switch (args.length) { switch (args.length) {
case 1: case 1:
unprotectParty(sender); unprotectParty(sender, playerParty);
return true; return true;
case 2: case 2:
if (args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("reset")) { if (args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("reset")) {
unprotectParty(sender); unprotectParty(sender, playerParty);
return true; return true;
} }
protectParty(sender, args[1]); protectParty(sender, playerParty, args[1]);
return true; return true;
default: default:
@@ -37,13 +35,13 @@ public class PartyChangePasswordCommand implements CommandExecutor {
} }
} }
private void unprotectParty(CommandSender sender) { private void unprotectParty(CommandSender sender, Party playerParty) {
playerParty.setLocked(true); playerParty.setLocked(true);
playerParty.setPassword(null); playerParty.setPassword(null);
sender.sendMessage(LocaleLoader.getString("Party.Password.Removed")); sender.sendMessage(LocaleLoader.getString("Party.Password.Removed"));
} }
private void protectParty(CommandSender sender, String password) { private void protectParty(CommandSender sender, Party playerParty, String password) {
playerParty.setLocked(true); playerParty.setLocked(true);
playerParty.setPassword(password); playerParty.setPassword(password);
sender.sendMessage(LocaleLoader.getString("Party.Password.Set", password)); sender.sendMessage(LocaleLoader.getString("Party.Password.Set", password));

View File

@@ -1,46 +1,21 @@
package com.gmail.nossr50.commands.party; package com.gmail.nossr50.commands.party;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.chat.PartyChatCommand; import com.gmail.nossr50.commands.chat.PartyChatCommand;
import com.gmail.nossr50.commands.party.teleport.PtpCommand;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class PartyCommand implements TabExecutor { public class PartyCommand implements CommandExecutor {
private McMMOPlayer mcMMOPlayer; private McMMOPlayer mcMMOPlayer;
private Player player; private Player player;
private static final List<String> PARTY_SUBCOMMANDS;
private static final List<String> EXPSHARE_COMPLETIONS = ImmutableList.of("none", "equal");
private static final List<String> ITEMSHARE_COMPLETIONS = ImmutableList.of("none", "equal", "random", "loot", "mining", "herbalism", "woodcutting", "misc");
static {
ArrayList<String> subcommands = new ArrayList<String>();
for (PartySubcommandType subcommand : PartySubcommandType.values()) {
subcommands.add(subcommand.toString());
}
Collections.sort(subcommands);
PARTY_SUBCOMMANDS = ImmutableList.copyOf(subcommands);
}
private CommandExecutor partyJoinCommand = new PartyJoinCommand(); private CommandExecutor partyJoinCommand = new PartyJoinCommand();
private CommandExecutor partyAcceptCommand = new PartyAcceptCommand(); private CommandExecutor partyAcceptCommand = new PartyAcceptCommand();
private CommandExecutor partyCreateCommand = new PartyCreateCommand(); private CommandExecutor partyCreateCommand = new PartyCreateCommand();
@@ -56,7 +31,7 @@ public class PartyCommand implements TabExecutor {
private CommandExecutor partyRenameCommand = new PartyRenameCommand(); private CommandExecutor partyRenameCommand = new PartyRenameCommand();
private CommandExecutor partyInfoCommand = new PartyInfoCommand(); private CommandExecutor partyInfoCommand = new PartyInfoCommand();
private CommandExecutor partyHelpCommand = new PartyHelpCommand(); private CommandExecutor partyHelpCommand = new PartyHelpCommand();
private CommandExecutor partyTeleportCommand = mcMMO.p.getCommand("ptp").getExecutor(); private CommandExecutor partyTeleportCommand = new PtpCommand();
private CommandExecutor partyChatCommand = new PartyChatCommand(); private CommandExecutor partyChatCommand = new PartyChatCommand();
@Override @Override
@@ -146,6 +121,7 @@ public class PartyCommand implements TabExecutor {
case OWNER: case OWNER:
return partyChangeOwnerCommand.onCommand(sender, command, label, args); return partyChangeOwnerCommand.onCommand(sender, command, label, args);
case LOCK: case LOCK:
// Fallthrough
case UNLOCK: case UNLOCK:
return partyLockCommand.onCommand(sender, command, label, args); return partyLockCommand.onCommand(sender, command, label, args);
case PASSWORD: case PASSWORD:
@@ -159,57 +135,6 @@ public class PartyCommand implements TabExecutor {
return true; return true;
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], PARTY_SUBCOMMANDS, new ArrayList<String>(PARTY_SUBCOMMANDS.size()));
case 2:
PartySubcommandType subcommand = PartySubcommandType.getSubcommand(args[0]);
if (subcommand == null) {
return ImmutableList.of();
}
switch (subcommand) {
case JOIN:
case INVITE:
case KICK:
case OWNER:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[1], playerNames, new ArrayList<String>(playerNames.size()));
case EXPSHARE:
return StringUtil.copyPartialMatches(args[1], EXPSHARE_COMPLETIONS, new ArrayList<String>(EXPSHARE_COMPLETIONS.size()));
case ITEMSHARE:
return StringUtil.copyPartialMatches(args[1], ITEMSHARE_COMPLETIONS, new ArrayList<String>(ITEMSHARE_COMPLETIONS.size()));
case LOCK:
case CHAT:
return StringUtil.copyPartialMatches(args[1], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
case PASSWORD:
return StringUtil.copyPartialMatches(args[1], CommandUtils.RESET_OPTIONS, new ArrayList<String>(CommandUtils.RESET_OPTIONS.size()));
case TELEPORT:
List<String> matches = StringUtil.copyPartialMatches(args[1], PtpCommand.TELEPORT_SUBCOMMANDS, new ArrayList<String>(PtpCommand.TELEPORT_SUBCOMMANDS.size()));
if (matches.size() == 0) {
playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[1], playerNames, new ArrayList<String>(playerNames.size()));
}
return matches;
default:
return ImmutableList.of();
}
case 3:
if (PartySubcommandType.getSubcommand(args[0]) == PartySubcommandType.ITEMSHARE && isItemShareCategory(args[1])) {
return StringUtil.copyPartialMatches(args[2], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
}
return ImmutableList.of();
default:
return ImmutableList.of();
}
}
private boolean printUsage() { private boolean printUsage() {
player.sendMessage(LocaleLoader.getString("Party.Help.0", "/party join")); player.sendMessage(LocaleLoader.getString("Party.Help.0", "/party join"));
player.sendMessage(LocaleLoader.getString("Party.Help.1", "/party create")); player.sendMessage(LocaleLoader.getString("Party.Help.1", "/party create"));
@@ -226,9 +151,4 @@ public class PartyCommand implements TabExecutor {
return newArgs; return newArgs;
} }
private boolean isItemShareCategory(String category) {
return category.equalsIgnoreCase("loot") || category.equalsIgnoreCase("mining") || category.equalsIgnoreCase("herbalism") || category.equalsIgnoreCase("woodcutting") || category.equalsIgnoreCase("misc");
}
} }

View File

@@ -12,21 +12,26 @@ import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyCreateCommand implements CommandExecutor { public class PartyCreateCommand implements CommandExecutor {
private McMMOPlayer mcMMOPlayer;
private Player player;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 2: case 2:
// Fallthrough
case 3: case 3:
Party newParty = PartyManager.getParty(args[1]); Party newParty = PartyManager.getParty(args[1]);
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
// Check to see if the party exists, and if it does cancel creating a new party // Check to see if the party exists, and if it does cancel creating a new party
if (PartyManager.checkPartyExistence(player, newParty, args[1])) { if (newParty != null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists", args[1]));
return true; return true;
} }
player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player);
// Changing parties // Changing parties
if (!PartyManager.changeOrJoinParty(mcMMOPlayer, player, mcMMOPlayer.getParty(), args[1])) { if (!PartyManager.changeOrJoinParty(mcMMOPlayer, player, mcMMOPlayer.getParty(), args[1])) {
return true; return true;

View File

@@ -17,10 +17,9 @@ public class PartyDisbandCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 1: case 1:
Party playerParty = UserManager.getPlayer((Player) sender).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, partyName, null, EventReason.KICKED_FROM_PARTY)) { if (!PartyManager.handlePartyChangeEvent(member, playerParty.getName(), null, EventReason.KICKED_FROM_PARTY)) {
return true; return true;
} }

View File

@@ -11,7 +11,6 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler; import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.party.ShareHandler.ShareMode; import com.gmail.nossr50.party.ShareHandler.ShareMode;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyExpShareCommand implements CommandExecutor { public class PartyExpShareCommand implements CommandExecutor {
@@ -28,14 +27,14 @@ public class PartyExpShareCommand implements CommandExecutor {
case 2: case 2:
playerParty = UserManager.getPlayer((Player) sender).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) { if (args[1].equalsIgnoreCase("none") || args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) {
handleChangingShareMode(ShareMode.NONE); handleChangingShareMode(ShareMode.NONE);
} }
else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even") || CommandUtils.shouldEnableToggle(args[1])) { else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even") || args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("true")) {
handleChangingShareMode(ShareMode.EQUAL); handleChangingShareMode(ShareMode.EQUAL);
} }
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "expshare", "<NONE | EQUAL>")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "expshare", "[NONE | EQUAL]"));
} }
return true; return true;
@@ -49,10 +48,8 @@ public class PartyExpShareCommand implements CommandExecutor {
private void handleChangingShareMode(ShareHandler.ShareMode mode) { private void handleChangingShareMode(ShareHandler.ShareMode mode) {
playerParty.setXpShareMode(mode); playerParty.setXpShareMode(mode);
String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Exp"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString())));
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
member.sendMessage(changeModeMessage); member.sendMessage(LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Exp"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))));
} }
} }
} }

View File

@@ -19,8 +19,6 @@ public class PartyHelpCommand implements CommandExecutor {
sender.sendMessage(LocaleLoader.getString("Party.Help.6", "/party kick")); sender.sendMessage(LocaleLoader.getString("Party.Help.6", "/party kick"));
sender.sendMessage(LocaleLoader.getString("Party.Help.7", "/party leader")); sender.sendMessage(LocaleLoader.getString("Party.Help.7", "/party leader"));
sender.sendMessage(LocaleLoader.getString("Party.Help.8", "/party disband")); sender.sendMessage(LocaleLoader.getString("Party.Help.8", "/party disband"));
sender.sendMessage(LocaleLoader.getString("Party.Help.9", "/party itemshare"));
sender.sendMessage(LocaleLoader.getString("Party.Help.10", "/party expshare"));
return true; return true;
default: default:
@@ -28,4 +26,5 @@ public class PartyHelpCommand implements CommandExecutor {
return true; return true;
} }
} }
} }

View File

@@ -7,7 +7,6 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -22,40 +21,29 @@ public class PartyInfoCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { player = (Player) sender;
case 0: McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
case 1: playerParty = mcMMOPlayer.getParty();
player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty();
displayPartyHeader(); displayPartyHeader();
displayShareModeInfo(); displayShareModeInfo();
displayMemberInfo(); displayMemberInfo();
return true; return true;
default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "info"));
return true;
}
} }
private String createMembersList() { private String createMembersList() {
StringBuilder memberList = new StringBuilder(); StringBuilder memberList = new StringBuilder();
for (String memberName : playerParty.getMembers()) { for (OfflinePlayer member : playerParty.getMembers()) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName); if (playerParty.getLeader().equalsIgnoreCase(member.getName())) {
memberList.append(ChatColor.GOLD).append(member.getName()).append(" ");
if (playerParty.getLeader().equalsIgnoreCase(memberName)) {
memberList.append(ChatColor.GOLD);
} }
else if (member.isOnline()) { else if (member.isOnline()) {
memberList.append(ChatColor.WHITE); memberList.append(ChatColor.WHITE).append(member.getName()).append(" ");
} }
else { else {
memberList.append(ChatColor.GRAY); memberList.append(ChatColor.GRAY).append(member.getName()).append(" ");
} }
memberList.append(memberName).append(" ");
} }
return memberList.toString(); return memberList.toString();
@@ -64,7 +52,7 @@ public class PartyInfoCommand implements CommandExecutor {
private void displayShareModeInfo() { private void displayShareModeInfo() {
boolean xpShareEnabled = Config.getInstance().getExpShareEnabled(); boolean xpShareEnabled = Config.getInstance().getExpShareEnabled();
boolean itemShareEnabled = Config.getInstance().getItemShareEnabled(); boolean itemShareEnabled = Config.getInstance().getItemShareEnabled();
boolean itemSharingActive = (playerParty.getItemShareMode() != ShareHandler.ShareMode.NONE); boolean itemSharingActive = playerParty.getItemShareMode() != ShareHandler.ShareMode.NONE;
if (!xpShareEnabled && !itemShareEnabled) { if (!xpShareEnabled && !itemShareEnabled) {
return; return;
@@ -109,6 +97,6 @@ public class PartyInfoCommand implements CommandExecutor {
player.sendMessage(LocaleLoader.getString("Commands.Party.Members.Header")); player.sendMessage(LocaleLoader.getString("Commands.Party.Members.Header"));
player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", membersNear, membersOnline)); player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", membersNear, membersOnline));
player.sendMessage(createMembersList()); player.sendMessage(LocaleLoader.getString("Commands.Party.Members", createMembersList()));
} }
} }

View File

@@ -5,27 +5,40 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyInviteCommand implements CommandExecutor { public class PartyInviteCommand implements CommandExecutor {
private McMMOPlayer mcMMOTarget;
private Player target;
private McMMOPlayer mcMMOPlayer;
private Player player;
private Party playerParty;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 2: case 2:
McMMOPlayer mcMMOTarget = UserManager.getPlayer(args[1]); if (!mcMMO.p.getServer().getOfflinePlayer(args[1]).isOnline()) {
sender.sendMessage(LocaleLoader.getString("Party.NotOnline", args[1]));
if (!CommandUtils.checkPlayerExistence(sender, args[1], mcMMOTarget)) { return true;
return false;
} }
Player target = mcMMOTarget.getPlayer(); mcMMOTarget = UserManager.getPlayer(args[1]);
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); if (mcMMOTarget == null) {
sender.sendMessage(LocaleLoader.getString("Party.Player.Invalid"));
return true;
}
target = mcMMOTarget.getPlayer();
mcMMOPlayer = UserManager.getPlayer((Player) sender);
player = mcMMOPlayer.getPlayer();
if (player.equals(target)) { if (player.equals(target)) {
sender.sendMessage(LocaleLoader.getString("Party.Invite.Self")); sender.sendMessage(LocaleLoader.getString("Party.Invite.Self"));
@@ -37,7 +50,7 @@ public class PartyInviteCommand implements CommandExecutor {
return true; return true;
} }
Party playerParty = mcMMOPlayer.getParty(); playerParty = mcMMOPlayer.getParty();
if (!PartyManager.canInvite(player, playerParty)) { if (!PartyManager.canInvite(player, playerParty)) {
player.sendMessage(LocaleLoader.getString("Party.Locked")); player.sendMessage(LocaleLoader.getString("Party.Locked"));

View File

@@ -6,12 +6,11 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.ItemShareType;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.party.ShareHandler.ShareMode; import com.gmail.nossr50.party.ShareHandler.ShareMode;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyItemShareCommand implements CommandExecutor { public class PartyItemShareCommand implements CommandExecutor {
@@ -27,64 +26,76 @@ public class PartyItemShareCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 2: case 2:
playerParty = UserManager.getPlayer((Player) sender).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
ShareMode mode = ShareMode.getShareMode(args[1].toUpperCase());
if (mode == null) { if (args[1].equalsIgnoreCase("none") || args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) {
handleChangingShareMode(ShareMode.NONE);
}
else if (args[1].equalsIgnoreCase("equal") || args[1].equalsIgnoreCase("even")) {
handleChangingShareMode(ShareMode.EQUAL);
}
else if (args[1].equalsIgnoreCase("random")) {
handleChangingShareMode(ShareMode.RANDOM);
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>"));
return true;
} }
handleChangingShareMode(mode);
return true; return true;
case 3: case 3:
playerParty = UserManager.getPlayer((Player) sender).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
boolean toggle = false; boolean toggle = false;
if (CommandUtils.shouldEnableToggle(args[2])) { if (args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("on") || args[2].equalsIgnoreCase("enabled")) {
toggle = true; toggle = true;
} }
else if (CommandUtils.shouldDisableToggle(args[2])) { else if (args[2].equalsIgnoreCase("false") || args[2].equalsIgnoreCase("off") || args[2].equalsIgnoreCase("disabled")) {
toggle = false; toggle = false;
} }
if (args[1].equalsIgnoreCase("loot")) {
playerParty.setSharingLootDrops(toggle);
}
else if (args[1].equalsIgnoreCase("mining")) {
playerParty.setSharingMiningDrops(toggle);
}
else if (args[1].equalsIgnoreCase("herbalism")) {
playerParty.setSharingHerbalismDrops(toggle);
}
else if (args[1].equalsIgnoreCase("woodcutting")) {
playerParty.setSharingWoodcuttingDrops(toggle);
}
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting> <true | false>"));
return true;
}
try {
handleToggleItemShareCategory(ItemShareType.valueOf(args[1].toUpperCase()), toggle);
}
catch (IllegalArgumentException ex) {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>"));
} }
notifyToggleItemShareCategory(args, toggle);
return true; return true;
default: default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>"));
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting> <true | false>"));
return true; return true;
} }
} }
private void handleChangingShareMode(ShareMode mode) { private void handleChangingShareMode(ShareHandler.ShareMode mode) {
playerParty.setItemShareMode(mode); playerParty.setItemShareMode(mode);
String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Item"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString())));
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
member.sendMessage(changeModeMessage); member.sendMessage(LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Item"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString()))));
} }
} }
private void handleToggleItemShareCategory(ItemShareType type, boolean toggle) { private void notifyToggleItemShareCategory(String[] args, boolean toggle) {
playerParty.setSharingDrops(type, toggle); String state = "disabled";
String toggleMessage = LocaleLoader.getString("Commands.Party.ToggleShareCategory", StringUtils.getCapitalized(type.toString()), toggle ? "enabled" : "disabled"); if (toggle) {
state = "enabled";
}
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
member.sendMessage(toggleMessage); member.sendMessage(LocaleLoader.getString("Commands.Party.ToggleShareCategory", StringUtils.getCapitalized(args[1]), state));
} }
} }
} }

View File

@@ -5,11 +5,11 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyJoinCommand implements CommandExecutor { public class PartyJoinCommand implements CommandExecutor {
@@ -25,15 +25,13 @@ public class PartyJoinCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 2: case 2:
// Fallthrough
case 3: case 3:
// Verify target exists and is in a different party than the player // Verify target exists and is in a different party than the player
if (!canJoinParty(sender, args[1])) { if (!canJoinParty(sender, args[1])) {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer((Player) sender);
player = mcMMOPlayer.getPlayer();
String password = getPassword(args); String password = getPassword(args);
// Make sure party passwords match // Make sure party passwords match
@@ -64,9 +62,15 @@ public class PartyJoinCommand implements CommandExecutor {
} }
private boolean canJoinParty(CommandSender sender, String targetName) { private boolean canJoinParty(CommandSender sender, String targetName) {
if (!mcMMO.p.getServer().getOfflinePlayer(targetName).isOnline()) {
sender.sendMessage(LocaleLoader.getString("Party.NotOnline", targetName));
return false;
}
mcMMOTarget = UserManager.getPlayer(targetName); mcMMOTarget = UserManager.getPlayer(targetName);
if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) { if (mcMMOTarget == null) {
sender.sendMessage(LocaleLoader.getString("Party.Player.Invalid"));
return false; return false;
} }
@@ -79,7 +83,6 @@ public class PartyJoinCommand implements CommandExecutor {
player = (Player) sender; player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player); mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty(); playerParty = mcMMOPlayer.getParty();
targetParty = mcMMOTarget.getParty(); targetParty = mcMMOTarget.getParty();

View File

@@ -19,9 +19,10 @@ public class PartyKickCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 2: case 2:
Party playerParty = UserManager.getPlayer((Player) sender).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
OfflinePlayer target = mcMMO.p.getServer().getOfflinePlayer(args[1]); OfflinePlayer target = mcMMO.p.getServer().getOfflinePlayer(args[1]);
if (!playerParty.getMembers().contains(target.getName())) { if (!playerParty.getMembers().contains(target)) {
sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1])); sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1]));
return true; return true;
} }

View File

@@ -8,7 +8,6 @@ import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyLockCommand implements CommandExecutor { public class PartyLockCommand implements CommandExecutor {
@@ -21,10 +20,10 @@ public class PartyLockCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 1: case 1:
if (args[0].equalsIgnoreCase("lock")) { if (args[0].equalsIgnoreCase("lock")) {
lockParty(sender, command.getPermissionMessage()); lockParty(sender, command);
} }
else if (args[0].equalsIgnoreCase("unlock")) { else if (args[0].equalsIgnoreCase("unlock")) {
unlockParty(sender, command.getPermissionMessage()); unlockParty(sender, command);
} }
return true; return true;
@@ -35,11 +34,11 @@ public class PartyLockCommand implements CommandExecutor {
return true; return true;
} }
if (CommandUtils.shouldEnableToggle(args[1])) { if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("true")) {
lockParty(sender, command.getPermissionMessage()); lockParty(sender, command);
} }
else if (CommandUtils.shouldDisableToggle(args[1])) { else if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) {
unlockParty(sender, command.getPermissionMessage()); unlockParty(sender, command);
} }
else { else {
sendUsageStrings(sender); sendUsageStrings(sender);
@@ -56,9 +55,9 @@ public class PartyLockCommand implements CommandExecutor {
/** /**
* Handle locking a party. * Handle locking a party.
*/ */
private void lockParty(CommandSender sender, String permissionMessage) { private void lockParty(CommandSender sender, Command command) {
if (!Permissions.partySubcommand(sender, PartySubcommandType.LOCK)) { if (!Permissions.partySubcommand(sender, PartySubcommandType.LOCK)) {
sender.sendMessage(permissionMessage); sender.sendMessage(command.getPermissionMessage());
return; return;
} }
@@ -76,9 +75,9 @@ public class PartyLockCommand implements CommandExecutor {
* *
* @return true if party is successfully unlocked, false otherwise. * @return true if party is successfully unlocked, false otherwise.
*/ */
private void unlockParty(CommandSender sender, String permissionMessage) { private void unlockParty(CommandSender sender, Command command) {
if (!Permissions.partySubcommand(sender, PartySubcommandType.UNLOCK)) { if (!Permissions.partySubcommand(sender, PartySubcommandType.UNLOCK)) {
sender.sendMessage(permissionMessage); sender.sendMessage(command.getPermissionMessage());
return; return;
} }

View File

@@ -12,12 +12,15 @@ import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyQuitCommand implements CommandExecutor { public class PartyQuitCommand implements CommandExecutor {
private Player player;
private Party playerParty;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 1: case 1:
Player player = (Player) sender; player = (Player) sender;
Party playerParty = UserManager.getPlayer(player).getParty(); playerParty = UserManager.getPlayer(player).getParty();
if (!PartyManager.handlePartyChangeEvent(player, playerParty.getName(), null, EventReason.LEFT_PARTY)) { if (!PartyManager.handlePartyChangeEvent(player, playerParty.getName(), null, EventReason.LEFT_PARTY)) {
return true; return true;
@@ -28,7 +31,7 @@ public class PartyQuitCommand implements CommandExecutor {
return true; return true;
default: default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "quit")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "[quit|q|leave]"));
return true; return true;
} }
} }

View File

@@ -6,7 +6,6 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason; import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
@@ -15,32 +14,29 @@ import com.gmail.nossr50.util.player.UserManager;
public class PartyRenameCommand implements CommandExecutor { public class PartyRenameCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String leaderName = playerParty.getLeader();
switch (args.length) { switch (args.length) {
case 2: case 2:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
Party playerParty = mcMMOPlayer.getParty();
String oldPartyName = playerParty.getName();
String newPartyName = args[1]; String newPartyName = args[1];
// This is to prevent party leaders from spamming other players with the rename message // This is to prevent party leaders from spamming other players with the rename message
if (oldPartyName.equalsIgnoreCase(newPartyName)) { if (playerParty.getName().equalsIgnoreCase(newPartyName)) {
sender.sendMessage(LocaleLoader.getString("Party.Rename.Same")); sender.sendMessage(LocaleLoader.getString("Party.Rename.Same"));
return true; return true;
} }
Player player = mcMMOPlayer.getPlayer();
Party newParty = PartyManager.getParty(newPartyName); Party newParty = PartyManager.getParty(newPartyName);
// Check to see if the party exists, and if it does cancel renaming the party // Check to see if the party exists, and if it does cancel renaming the party
if (PartyManager.checkPartyExistence(player, newParty, newPartyName)) { if (newParty != null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists", newPartyName));
return true; return true;
} }
String leaderName = playerParty.getLeader();
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, oldPartyName, newPartyName, EventReason.CHANGED_PARTIES)) { if (!PartyManager.handlePartyChangeEvent(member, playerParty.getName(), newPartyName, EventReason.CHANGED_PARTIES)) {
return true; return true;
} }

View File

@@ -0,0 +1,218 @@
package com.gmail.nossr50.commands.party;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyTeleportEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
public class PtpCommand implements CommandExecutor {
private Player player;
private McMMOPlayer mcMMOPlayer;
private Player target;
private McMMOPlayer mcMMOTarget;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
switch (args.length) {
case 1:
player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player);
if (args[0].equalsIgnoreCase("toggle")) {
if (!Permissions.partyTeleportToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
return togglePartyTeleportation();
}
if (args[0].equalsIgnoreCase("acceptany") || args[0].equalsIgnoreCase("acceptall")) {
if (!Permissions.partyTeleportAcceptAll(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
return acceptAnyTeleportRequest();
}
int ptpCooldown = Config.getInstance().getPTPCommandCooldown();
long recentlyHurt = UserManager.getPlayer(player).getRecentlyHurt();
if ((recentlyHurt * Misc.TIME_CONVERSION_FACTOR + ptpCooldown * Misc.TIME_CONVERSION_FACTOR) > System.currentTimeMillis()) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Hurt", ptpCooldown));
return true;
}
if (args[0].equalsIgnoreCase("accept")) {
if (!Permissions.partyTeleportAccept(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
return acceptTeleportRequest();
}
return sendTeleportRequest(args[0]);
default:
return false;
}
}
private boolean sendTeleportRequest(String targetName) {
if (!canTeleport(targetName)) {
return true;
}
if (!mcMMOTarget.getPtpConfirmRequired()) {
return handlePartyTeleportEvent(player, target);
}
mcMMOTarget.setPtpRequest(player);
mcMMOTarget.actualizePtpTimeout();
player.sendMessage(LocaleLoader.getString("Commands.Invite.Success"));
int ptpRequestExpire = Config.getInstance().getPTPCommandTimeout();
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName()));
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", ptpRequestExpire));
return true;
}
private boolean acceptTeleportRequest() {
if (!mcMMOPlayer.hasPtpRequest()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.NoRequests"));
return true;
}
int ptpRequestExpire = Config.getInstance().getPTPCommandTimeout();
if ((mcMMOPlayer.getPtpTimeout() + ptpRequestExpire) * Misc.TIME_CONVERSION_FACTOR < System.currentTimeMillis()) {
mcMMOPlayer.removePtpRequest();
player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired"));
return true;
}
target = mcMMOPlayer.getPtpRequest();
mcMMOPlayer.removePtpRequest();
if (!canTeleport(target.getName())) {
return true;
}
if (Config.getInstance().getPTPCommandWorldPermissions()) {
World targetWorld = target.getWorld();
World playerWorld = player.getWorld();
if (!Permissions.partyTeleportAllWorlds(target)) {
if (!Permissions.partyTeleportWorld(target, targetWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName()));
return true;
}
else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName()));
return true;
}
}
}
return handlePartyTeleportEvent(target, player);
}
private boolean acceptAnyTeleportRequest() {
if (mcMMOPlayer.getPtpConfirmRequired()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled"));
}
mcMMOPlayer.togglePtpConfirmRequired();
return true;
}
private boolean togglePartyTeleportation() {
if (mcMMOPlayer.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled"));
}
mcMMOPlayer.togglePtpUse();
return true;
}
private boolean canTeleport(String targetName) {
if (!mcMMO.p.getServer().getOfflinePlayer(targetName).isOnline()) {
player.sendMessage(LocaleLoader.getString("Party.NotOnline", targetName));
return false;
}
mcMMOTarget = UserManager.getPlayer(targetName);
if (mcMMOTarget == null) {
player.sendMessage(LocaleLoader.getString("Party.Player.Invalid"));
return false;
}
target = mcMMOTarget.getPlayer();
if (player.equals(target)) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Self"));
return false;
}
if (!PartyManager.inSameParty(player, target)) {
player.sendMessage(LocaleLoader.getString("Party.NotInYourParty", targetName));
return false;
}
if (!mcMMOTarget.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Disabled", target.getName()));
return false;
}
if (target.isDead()) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Dead"));
return false;
}
return true;
}
private boolean handlePartyTeleportEvent(Player player, Player target) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(player, target, mcMMOPlayer.getParty().getName());
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return true;
}
player.teleport(target);
player.sendMessage(LocaleLoader.getString("Party.Teleport.Player", target.getName()));
target.sendMessage(LocaleLoader.getString("Party.Teleport.Target", player.getName()));
mcMMOPlayer.actualizeRecentlyHurt();
return true;
}
}

View File

@@ -1,34 +0,0 @@
package com.gmail.nossr50.commands.party.teleport;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class PtpAcceptAnyCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.partyTeleportAcceptAll(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpConfirmRequired()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled"));
}
mcMMOPlayer.togglePtpConfirmRequired();
return true;
}
}

View File

@@ -1,64 +0,0 @@
package com.gmail.nossr50.commands.party.teleport;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class PtpAcceptCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.partyTeleportAccept(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPtpRequest()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.NoRequests"));
return true;
}
if ((mcMMOPlayer.getPtpTimeout() + Config.getInstance().getPTPCommandTimeout()) * Misc.TIME_CONVERSION_FACTOR < System.currentTimeMillis()) {
mcMMOPlayer.removePtpRequest();
player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired"));
return true;
}
Player target = mcMMOPlayer.getPtpRequest();
mcMMOPlayer.removePtpRequest();
if (!PtpCommand.canTeleport(sender, player, target.getName())) {
return true;
}
if (Config.getInstance().getPTPCommandWorldPermissions()) {
World targetWorld = target.getWorld();
World playerWorld = player.getWorld();
if (!Permissions.partyTeleportAllWorlds(target)) {
if (!Permissions.partyTeleportWorld(target, targetWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName()));
return true;
}
else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName()));
return true;
}
}
}
PtpCommand.handleTeleportWarmup(target, player);
return true;
}
}

View File

@@ -1,201 +0,0 @@
package com.gmail.nossr50.commands.party.teleport;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyTeleportEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.items.TeleportationWarmup;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList;
public class PtpCommand implements TabExecutor {
private static Player target;
private static McMMOPlayer mcMMOTarget;
public static final List<String> TELEPORT_SUBCOMMANDS = ImmutableList.of("toggle", "accept", "acceptany", "acceptall");
private CommandExecutor ptpToggleCommand = new PtpToggleCommand();
private CommandExecutor ptpAcceptAnyCommand = new PtpAcceptAnyCommand();
private CommandExecutor ptpAcceptCommand = new PtpAcceptCommand();
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
switch (args.length) {
case 1:
if (args[0].equalsIgnoreCase("toggle")) {
return ptpToggleCommand.onCommand(sender, command, label, args);
}
if (args[0].equalsIgnoreCase("acceptany") || args[0].equalsIgnoreCase("acceptall")) {
return ptpAcceptAnyCommand.onCommand(sender, command, label, args);
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown();
if (hurtCooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return true;
}
}
if (args[0].equalsIgnoreCase("accept")) {
return ptpAcceptCommand.onCommand(sender, command, label, args);
}
if (!Permissions.partyTeleportSend(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
int ptpCooldown = Config.getInstance().getPTPCommandCooldown();
long lastTeleport = mcMMOPlayer.getLastTeleport();
if (ptpCooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining));
return true;
}
}
sendTeleportRequest(sender, player, args[0]);
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
List<String> matches = StringUtil.copyPartialMatches(args[0], TELEPORT_SUBCOMMANDS, new ArrayList<String>(TELEPORT_SUBCOMMANDS.size()));
if (matches.size() == 0) {
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
}
return matches;
default:
return ImmutableList.of();
}
}
private void sendTeleportRequest(CommandSender sender, Player player, String targetName) {
if (!canTeleport(sender, player, targetName)) {
return;
}
if (!mcMMOTarget.getPtpConfirmRequired()) {
handleTeleportWarmup(player, target);
return;
}
mcMMOTarget.setPtpRequest(player);
mcMMOTarget.actualizePtpTimeout();
player.sendMessage(LocaleLoader.getString("Commands.Invite.Success"));
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request1", player.getName()));
target.sendMessage(LocaleLoader.getString("Commands.ptp.Request2", Config.getInstance().getPTPCommandTimeout()));
}
protected static boolean canTeleport(CommandSender sender, Player player, String targetName) {
mcMMOTarget = UserManager.getPlayer(targetName);
if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) {
return false;
}
target = mcMMOTarget.getPlayer();
targetName = target.getName();
if (player.equals(target)) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Self"));
return false;
}
if (!PartyManager.inSameParty(player, target)) {
player.sendMessage(LocaleLoader.getString("Party.NotInYourParty", targetName));
return false;
}
if (!mcMMOTarget.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Disabled", targetName));
return false;
}
if (!target.isValid()) {
player.sendMessage(LocaleLoader.getString("Party.Teleport.Dead"));
return false;
}
return true;
}
protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer);
mcMMOTarget = UserManager.getPlayer(targetPlayer);
long warmup = Config.getInstance().getPTPCommandWarmup();
mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer);
if (warmup > 0) {
teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup));
new TeleportationWarmup(mcMMOPlayer, mcMMOTarget).runTaskLater(mcMMO.p, 20 * warmup);
}
else {
handlePartyTeleportEvent(teleportingPlayer, targetPlayer);
}
}
public static void handlePartyTeleportEvent(Player teleportingPlayer, Player targetPlayer) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer);
McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, mcMMOPlayer.getParty().getName());
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
teleportingPlayer.teleport(targetPlayer);
teleportingPlayer.sendMessage(LocaleLoader.getString("Party.Teleport.Player", targetPlayer.getName()));
targetPlayer.sendMessage(LocaleLoader.getString("Party.Teleport.Target", teleportingPlayer.getName()));
mcMMOPlayer.actualizeRecentlyHurt();
}
}

View File

@@ -1,34 +0,0 @@
package com.gmail.nossr50.commands.party.teleport;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class PtpToggleCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.partyTeleportToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled"));
}
mcMMOPlayer.togglePtpUse();
return true;
}
}

View File

@@ -1,94 +1,80 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList; public class InspectCommand implements CommandExecutor {
public class InspectCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PlayerProfile profile;
switch (args.length) { switch (args.length) {
case 1: case 1:
if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) {
ScoreboardManager.setupPlayerScoreboard(sender.getName());
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) { if (mcMMOPlayer == null) {
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false); // Temporary Profile profile = new PlayerProfile(args[0], false); // Temporary Profile
if (CommandUtils.inspectOffline(sender, profile, Permissions.inspectOffline(sender))) { if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true; return true;
} }
if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) { // TODO: Why do we care if this is a player?
ScoreboardManager.enablePlayerInspectScoreboardOffline((Player) sender, profile); if (sender instanceof Player && !Permissions.inspectOffline(sender)) {
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
return true; return true;
} }
sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", args[0])); sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", args[0]));
sender.sendMessage(LocaleLoader.getString("Stats.Header.Gathering")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Gathering"));
CommandUtils.displaySkill(sender, profile, SkillType.EXCAVATION); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Excavation.Listener"), profile.getSkillLevel(SkillType.EXCAVATION), profile.getSkillXpLevel(SkillType.EXCAVATION), profile.getXpToLevel(SkillType.EXCAVATION)));
CommandUtils.displaySkill(sender, profile, SkillType.FISHING); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Fishing.Listener"), profile.getSkillLevel(SkillType.FISHING), profile.getSkillXpLevel(SkillType.FISHING), profile.getXpToLevel(SkillType.FISHING)));
CommandUtils.displaySkill(sender, profile, SkillType.HERBALISM); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Herbalism.Listener"), profile.getSkillLevel(SkillType.HERBALISM), profile.getSkillXpLevel(SkillType.HERBALISM), profile.getXpToLevel(SkillType.HERBALISM)));
CommandUtils.displaySkill(sender, profile, SkillType.MINING); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Mining.Listener"), profile.getSkillLevel(SkillType.MINING), profile.getSkillXpLevel(SkillType.MINING), profile.getXpToLevel(SkillType.MINING)));
CommandUtils.displaySkill(sender, profile, SkillType.WOODCUTTING); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Woodcutting.Listener"), profile.getSkillLevel(SkillType.WOODCUTTING), profile.getSkillXpLevel(SkillType.WOODCUTTING), profile.getXpToLevel(SkillType.WOODCUTTING)));
sender.sendMessage(LocaleLoader.getString("Stats.Header.Combat")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Combat"));
CommandUtils.displaySkill(sender, profile, SkillType.AXES); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Axes.Listener"), profile.getSkillLevel(SkillType.AXES), profile.getSkillXpLevel(SkillType.AXES), profile.getXpToLevel(SkillType.AXES)));
CommandUtils.displaySkill(sender, profile, SkillType.ARCHERY); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Archery.Listener"), profile.getSkillLevel(SkillType.ARCHERY), profile.getSkillXpLevel(SkillType.ARCHERY), profile.getXpToLevel(SkillType.ARCHERY)));
CommandUtils.displaySkill(sender, profile, SkillType.SWORDS); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Swords.Listener"), profile.getSkillLevel(SkillType.SWORDS), profile.getSkillXpLevel(SkillType.SWORDS), profile.getXpToLevel(SkillType.SWORDS)));
CommandUtils.displaySkill(sender, profile, SkillType.TAMING); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Taming.Listener"), profile.getSkillLevel(SkillType.TAMING), profile.getSkillXpLevel(SkillType.TAMING), profile.getXpToLevel(SkillType.TAMING)));
CommandUtils.displaySkill(sender, profile, SkillType.UNARMED); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Unarmed.Listener"), profile.getSkillLevel(SkillType.UNARMED), profile.getSkillXpLevel(SkillType.UNARMED), profile.getXpToLevel(SkillType.UNARMED)));
sender.sendMessage(LocaleLoader.getString("Stats.Header.Misc")); sender.sendMessage(LocaleLoader.getString("Stats.Header.Misc"));
CommandUtils.displaySkill(sender, profile, SkillType.ACROBATICS); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Acrobatics.Listener"), profile.getSkillLevel(SkillType.ACROBATICS), profile.getSkillXpLevel(SkillType.ACROBATICS), profile.getXpToLevel(SkillType.ACROBATICS)));
CommandUtils.displaySkill(sender, profile, SkillType.REPAIR); sender.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Repair.Listener"), profile.getSkillLevel(SkillType.REPAIR), profile.getSkillXpLevel(SkillType.REPAIR), profile.getXpToLevel(SkillType.REPAIR)));
} }
else { else {
Player target = mcMMOPlayer.getPlayer(); Player target = mcMMOPlayer.getPlayer();
if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) { if (sender instanceof Player) {
if (!Permissions.inspectOffline(sender)) { Player inspector = (Player) sender;
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
if (!Misc.isNear(inspector.getLocation(), target.getLocation(), 5.0) && !Permissions.inspectFar(inspector)) {
sender.sendMessage(LocaleLoader.getString("Inspect.TooFar"));
return true; return true;
} }
} }
else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { profile = mcMMOPlayer.getProfile();
return true;
}
if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) {
ScoreboardManager.enablePlayerInspectScoreboardOnline((Player) sender, mcMMOPlayer);
return true;
}
sender.sendMessage(LocaleLoader.getString("Inspect.Stats", target.getName())); sender.sendMessage(LocaleLoader.getString("Inspect.Stats", target.getName()));
CommandUtils.printGatheringSkills(target, sender); CommandUtils.printGatheringSkills(target, profile, sender);
CommandUtils.printCombatSkills(target, sender); CommandUtils.printCombatSkills(target, profile, sender);
CommandUtils.printMiscSkills(target, sender); CommandUtils.printMiscSkills(target, profile, sender);
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel())); sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel()));
} }
@@ -98,15 +84,4 @@ public class InspectCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
default:
return ImmutableList.of();
}
}
} }

View File

@@ -1,45 +1,44 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import java.util.ArrayList; import org.bukkit.ChatColor;
import java.util.List;
import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.database.queuemanager.McRankAsync;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList;
public class McrankCommand implements TabExecutor { public class McrankCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 0: case 0:
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if (!Permissions.mcrank(sender)) { if (!Permissions.mcrank(sender)) {
sender.sendMessage(command.getPermissionMessage()); sender.sendMessage(command.getPermissionMessage());
return true; return true;
} }
if (Config.getInstance().getMcrankScoreboardEnabled()) { if (!(sender instanceof Player)) {
ScoreboardManager.setupPlayerScoreboard(sender.getName()); return false;
ScoreboardManager.enablePlayerRankScoreboard((Player) sender); }
if (Config.getInstance().getUseMySQL()) {
sqlDisplay(sender, sender.getName());
} }
else { else {
display(sender, sender.getName()); LeaderboardManager.updateLeaderboards(); // Make sure the information is up to date
flatfileDisplay(sender, sender.getName());
} }
return true; return true;
@@ -50,27 +49,38 @@ public class McrankCommand implements TabExecutor {
return true; return true;
} }
String playerName = args[0]; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(args[0]);
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName);
if (mcMMOPlayer != null) { if (mcMMOPlayer == null) {
playerName = mcMMOPlayer.getPlayer().getName(); PlayerProfile profile = new PlayerProfile(args[0], false); // Temporary Profile
if (CommandUtils.tooFar(sender, mcMMOPlayer.getPlayer(), Permissions.mcrankFar(sender))) { if (!profile.isLoaded()) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
return true;
}
if (sender instanceof Player && !Permissions.mcrankOffline(sender)) {
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
return true; return true;
} }
} }
else if (CommandUtils.inspectOffline(sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false), Permissions.mcrankOffline(sender))) { else {
return true; Player target = mcMMOPlayer.getPlayer();
if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), 5.0) && !Permissions.mcrankFar(sender)) {
sender.sendMessage(LocaleLoader.getString("Inspect.TooFar"));
return true;
}
} }
if (sender instanceof Player && Config.getInstance().getMcrankScoreboardEnabled()) { if (Config.getInstance().getUseMySQL()) {
ScoreboardManager.setupPlayerScoreboard(sender.getName()); sqlDisplay(sender, args[0]);
ScoreboardManager.enablePlayerRankScoreboardOthers((Player) sender, playerName);
} }
else { else {
display(sender, playerName); LeaderboardManager.updateLeaderboards(); // Make sure the information is up to date
flatfileDisplay(sender, args[0]);
} }
return true; return true;
default: default:
@@ -78,18 +88,51 @@ public class McrankCommand implements TabExecutor {
} }
} }
@Override private void flatfileDisplay(CommandSender sender, String playerName) {
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading"));
switch (args.length) { sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName));
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet(); for (SkillType skillType : SkillType.values()) {
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size())); int[] rankInts = LeaderboardManager.getPlayerRank(playerName, skillType);
default:
return ImmutableList.of(); if (skillType.isChildSkill()) {
continue;
}
if ((sender instanceof Player) && !Permissions.skillEnabled((Player) sender, skillType)) {
continue;
}
if (rankInts[1] == 0) {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", SkillUtils.getSkillName(skillType), LocaleLoader.getString("Commands.mcrank.Unranked"))); // Don't bother showing ranking for players without skills
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", SkillUtils.getSkillName(skillType), rankInts[0]));
}
}
// Show the powerlevel ranking
int[] rankInts = LeaderboardManager.getPlayerRank(playerName);
if (rankInts[1] == 0) {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", LocaleLoader.getString("Commands.mcrank.Unranked"))); // Don't bother showing ranking for players without skills
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", rankInts[0]));
} }
} }
private void display(CommandSender sender, String playerName) { private void sqlDisplay(CommandSender sender, String playerName) {
new McrankCommandAsyncTask(playerName, sender).runTaskAsynchronously(mcMMO.p); //TODO: Localize messages
if (mcMMO.queueManager.contains(sender.getName())) {
sender.sendMessage(ChatColor.RED + "Please wait for your previous command to process");
}
if (!mcMMO.queueManager.queue(new McRankAsync(playerName, sender))) {
// This will only run if for some reason it is unable to add to the queue
sender.sendMessage(ChatColor.RED + "Unable to add to queue.");
}
sender.sendMessage(ChatColor.YELLOW + "Calculating mcMMO rankings...");
} }
} }

View File

@@ -1,21 +1,18 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList;
public class McstatsCommand implements TabExecutor { public class McstatsCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) { if (CommandUtils.noConsoleUsage(sender)) {
@@ -26,27 +23,22 @@ public class McstatsCommand implements TabExecutor {
case 0: case 0:
Player player = (Player) sender; Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
PlayerProfile profile = mcMMOPlayer.getProfile();
if (Config.getInstance().getMcstatsScoreboardsEnabled()) { player.sendMessage(LocaleLoader.getString("Stats.Own.Stats"));
ScoreboardManager.setupPlayerScoreboard(player.getName()); player.sendMessage(LocaleLoader.getString("mcMMO.NoSkillNote"));
ScoreboardManager.enablePlayerStatsScoreboard(mcMMOPlayer);
CommandUtils.printGatheringSkills(player, profile);
CommandUtils.printCombatSkills(player, profile);
CommandUtils.printMiscSkills(player, profile);
int powerLevelCap = Config.getInstance().getPowerLevelCap();
if (powerLevelCap != Integer.MAX_VALUE) {
player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", mcMMOPlayer.getPowerLevel(), powerLevelCap));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Stats.Own.Stats")); player.sendMessage(LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel()));
player.sendMessage(LocaleLoader.getString("mcMMO.NoSkillNote"));
CommandUtils.printGatheringSkills(player);
CommandUtils.printCombatSkills(player);
CommandUtils.printMiscSkills(player);
int powerLevelCap = Config.getInstance().getPowerLevelCap();
if (powerLevelCap != Integer.MAX_VALUE) {
player.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Capped", UserManager.getPlayer(player).getPowerLevel(), powerLevelCap));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.PowerLevel", UserManager.getPlayer(player).getPowerLevel()));
}
} }
return true; return true;
@@ -55,9 +47,4 @@ public class McstatsCommand implements TabExecutor {
return false; return false;
} }
} }
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
} }

View File

@@ -1,58 +1,69 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import java.util.ArrayList; import org.bukkit.ChatColor;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.database.queuemanager.McTopAsync;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.skills.SkillUtils;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList;
public class MctopCommand implements TabExecutor {
private SkillType skill;
public class MctopCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean useMySQL = Config.getInstance().getUseMySQL();
switch (args.length) { switch (args.length) {
case 0: case 0:
display(1, "ALL", sender, command); display(1, "ALL", sender, useMySQL, command);
return true; return true;
case 1: case 1:
if (StringUtils.isInt(args[0])) { if (StringUtils.isInt(args[0])) {
display(Math.abs(Integer.parseInt(args[0])), "ALL", sender, command); display(Integer.parseInt(args[0]), "ALL", sender, useMySQL, command);
return true; }
else if (SkillUtils.isSkill(args[0])) {
SkillType skill = SkillType.getSkill(args[0]);
if (skill.isChildSkill()) {
sender.sendMessage("Child skills are not yet supported by this command."); // TODO: Localize this
return true;
}
display(1, skill.toString(), sender, useMySQL, command);
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
} }
if (!extractSkill(sender, args[0])) {
return true;
}
display(1, skill.toString(), sender, command);
return true; return true;
case 2: case 2:
if (CommandUtils.isInvalidInteger(sender, args[1])) { if (!StringUtils.isInt(args[1])) {
return true; return false;
} }
if (!extractSkill(sender, args[0])) { if (SkillUtils.isSkill(args[0])) {
return true; SkillType skill = SkillType.getSkill(args[0]);
if (skill.isChildSkill()) {
sender.sendMessage("Child skills are not yet supported by this command."); // TODO: Localize this
return true;
}
display(Integer.parseInt(args[1]), skill.toString(), sender, useMySQL, command);
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
} }
display(Math.abs(Integer.parseInt(args[1])), skill.toString(), sender, command);
return true; return true;
default: default:
@@ -60,45 +71,69 @@ public class MctopCommand implements TabExecutor {
} }
} }
@Override private void display(int page, String skill, CommandSender sender, boolean sql, Command command) {
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, SkillType.getSkill(skill))) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], SkillType.SKILL_NAMES, new ArrayList<String>(SkillType.SKILL_NAMES.size()));
default:
return ImmutableList.of();
}
}
private void display(int page, String skill, CommandSender sender, Command command) {
if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, this.skill)) {
sender.sendMessage(command.getPermissionMessage()); sender.sendMessage(command.getPermissionMessage());
return; return;
} }
if (sender instanceof Player && Config.getInstance().getMctopScoreboardEnabled()) { if (sql) {
ScoreboardManager.enableGlobalStatsScoreboard((Player) sender, skill, page); if (skill.equalsIgnoreCase("all")) {
sqlDisplay(page, "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing", sender);
}
else {
sqlDisplay(page, skill, sender);
}
} }
else { else {
display(page, skill, sender); flatfileDisplay(page, skill, sender, command);
} }
} }
private void display(int page, String query, CommandSender sender) { private void flatfileDisplay(int page, String skill, CommandSender sender, Command command) {
new MctopCommandAsyncTask(page, query, sender).runTaskAsynchronously(mcMMO.p); LeaderboardManager.updateLeaderboards(); // Make sure we have the latest information
String[] info = LeaderboardManager.retrieveInfo(skill, page);
if (skill.equalsIgnoreCase("all")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(skill)));
}
int n = (page * 10) - 9; // Position
for (String x : info) {
if (x != null) {
String digit = String.valueOf(n);
if (n < 10) {
digit = "0" + digit;
}
String[] splitx = x.split(":");
// Format: 1. Playername - skill value
sender.sendMessage(digit + ". " + ChatColor.GREEN + splitx[1] + " - " + ChatColor.WHITE + splitx[0]);
n++;
}
}
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip"));
} }
private boolean extractSkill(CommandSender sender, String skillName) { private void sqlDisplay(int page, String query, CommandSender sender) {
if (CommandUtils.isInvalidSkill(sender, skillName)) { //TODO: Localize messages
return false; if (mcMMO.queueManager.contains(sender.getName())) {
sender.sendMessage(ChatColor.RED + "Please wait for your previous command to process");
return;
} }
skill = SkillType.getSkill(skillName); if (!mcMMO.queueManager.queue(new McTopAsync(page, query, sender))) {
// This will only run if for some reason it is unable to add to the queue
if (CommandUtils.isChildSkill(sender, skill)) { sender.sendMessage(ChatColor.RED + "Unable to add to queue.");
return false;
} }
return true; sender.sendMessage(ChatColor.YELLOW + "Calculating mcMMO rankings...");
} }
} }

View File

@@ -24,25 +24,19 @@ public class AcrobaticsCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// DODGE // DODGE
if (canDodge) { String[] dodgeStrings = calculateAbilityDisplayValues(Acrobatics.dodgeMaxBonusLevel, Acrobatics.dodgeMaxChance);
String[] dodgeStrings = calculateAbilityDisplayValues(Acrobatics.dodgeMaxBonusLevel, Acrobatics.dodgeMaxChance); dodgeChance = dodgeStrings[0];
dodgeChance = dodgeStrings[0]; dodgeChanceLucky = dodgeStrings[1];
dodgeChanceLucky = dodgeStrings[1];
}
// ROLL // ROLL
if (canRoll) { String[] rollStrings = calculateAbilityDisplayValues(Acrobatics.rollMaxBonusLevel, Acrobatics.rollMaxChance);
String[] rollStrings = calculateAbilityDisplayValues(Acrobatics.rollMaxBonusLevel, Acrobatics.rollMaxChance); rollChance = rollStrings[0];
rollChance = rollStrings[0]; rollChanceLucky = rollStrings[1];
rollChanceLucky = rollStrings[1];
}
// GRACEFUL ROLL // GRACEFUL ROLL
if (canGracefulRoll) { String[] gracefulRollStrings = calculateAbilityDisplayValues(Acrobatics.gracefulRollMaxBonusLevel, Acrobatics.gracefulRollMaxChance);
String[] gracefulRollStrings = calculateAbilityDisplayValues(Acrobatics.gracefulRollMaxBonusLevel, Acrobatics.gracefulRollMaxChance); gracefulRollChance = gracefulRollStrings[0];
gracefulRollChance = gracefulRollStrings[0]; gracefulRollChanceLucky = gracefulRollStrings[1];
gracefulRollChanceLucky = gracefulRollStrings[1];
}
} }
@Override @Override
@@ -82,15 +76,30 @@ public class AcrobaticsCommand extends SkillCommand {
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canRoll) { if (canRoll) {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.Chance", rollChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", rollChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.Chance", new Object[] { rollChance }) + LocaleLoader.getString("Perks.lucky.bonus", new Object[] { rollChanceLucky }));
}
else {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.Chance", new Object[] { rollChance }));
}
} }
if (canGracefulRoll) { if (canGracefulRoll) {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.GraceChance", gracefulRollChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", gracefulRollChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.GraceChance", new Object[] { gracefulRollChance }) + LocaleLoader.getString("Perks.lucky.bonus", new Object[] { gracefulRollChanceLucky }));
}
else {
player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.GraceChance", new Object[] { gracefulRollChance }));
}
} }
if (canDodge) { if (canDodge) {
player.sendMessage(LocaleLoader.getString("Acrobatics.DodgeChance", dodgeChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", dodgeChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Acrobatics.DodgeChance", new Object[] { dodgeChance }) + LocaleLoader.getString("Perks.lucky.bonus", new Object[] { dodgeChanceLucky }));
}
else {
player.sendMessage(LocaleLoader.getString("Acrobatics.DodgeChance", new Object[] { dodgeChance }));
}
} }
} }
} }

View File

@@ -23,24 +23,24 @@ public class ArcheryCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// SKILL SHOT // SKILL SHOT
if (canSkillShot) { double bonus = (skillValue / Archery.skillShotIncreaseLevel) * Archery.skillShotIncreasePercentage;
double bonus = (skillValue / Archery.skillShotIncreaseLevel) * Archery.skillShotIncreasePercentage;
skillShotBonus = percent.format(Math.min(bonus, Archery.skillShotMaxBonusPercentage)); if (bonus > Archery.skillShotMaxBonusPercentage) {
skillShotBonus = percent.format(Archery.skillShotMaxBonusPercentage);
}
else {
skillShotBonus = percent.format(bonus);
} }
// DAZE // DAZE
if (canDaze) { String[] dazeStrings = calculateAbilityDisplayValues(Archery.dazeMaxBonusLevel, Archery.dazeMaxBonus);
String[] dazeStrings = calculateAbilityDisplayValues(Archery.dazeMaxBonusLevel, Archery.dazeMaxBonus); dazeChance = dazeStrings[0];
dazeChance = dazeStrings[0]; dazeChanceLucky = dazeStrings[1];
dazeChanceLucky = dazeStrings[1];
}
// RETRIEVE // RETRIEVE
if (canRetrieve) { String[] retrieveStrings = calculateAbilityDisplayValues(Archery.retrieveMaxBonusLevel, Archery.retrieveMaxChance);
String[] retrieveStrings = calculateAbilityDisplayValues(Archery.retrieveMaxBonusLevel, Archery.retrieveMaxChance); retrieveChance = retrieveStrings[0];
retrieveChance = retrieveStrings[0]; retrieveChanceLucky = retrieveStrings[1];
retrieveChanceLucky = retrieveStrings[1];
}
} }
@Override @Override
@@ -84,11 +84,21 @@ public class ArcheryCommand extends SkillCommand {
} }
if (canDaze) { if (canDaze) {
player.sendMessage(LocaleLoader.getString("Archery.Combat.DazeChance", dazeChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", dazeChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Archery.Combat.DazeChance", dazeChance) + LocaleLoader.getString("Perks.lucky.bonus", dazeChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Archery.Combat.DazeChance", dazeChance));
}
} }
if (canRetrieve) { if (canRetrieve) {
player.sendMessage(LocaleLoader.getString("Archery.Combat.RetrieveChance", retrieveChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", retrieveChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Archery.Combat.RetrieveChance", retrieveChance) + LocaleLoader.getString("Perks.lucky.bonus", retrieveChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Archery.Combat.RetrieveChance", retrieveChance));
}
} }
} }
} }

View File

@@ -8,8 +8,9 @@ import com.gmail.nossr50.util.Permissions;
public class AxesCommand extends SkillCommand { public class AxesCommand extends SkillCommand {
private String critChance; private String critChance;
private String critChanceLucky; private String critChanceLucky;
private float bonusDamage; private String bonusDamage;
private float impactDamage; private String impactDamage;
private String greaterImpactDamage;
private String skullSplitterLength; private String skullSplitterLength;
private String skullSplitterLengthEndurance; private String skullSplitterLengthEndurance;
@@ -26,27 +27,25 @@ public class AxesCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// IMPACT // IMPACT
if (canImpact) { impactDamage = String.valueOf(1 + (skillValue / Axes.impactIncreaseLevel));
impactDamage = 1 + (skillValue / Axes.impactIncreaseLevel); greaterImpactDamage = String.valueOf(Axes.greaterImpactBonusDamage);
}
// SKULL SPLITTER // SKULL SPLITTER
if (canSkullSplitter) { String[] skullSplitterStrings = calculateLengthDisplayValues();
String[] skullSplitterStrings = calculateLengthDisplayValues(); skullSplitterLength = skullSplitterStrings[0];
skullSplitterLength = skullSplitterStrings[0]; skullSplitterLengthEndurance = skullSplitterStrings[1];
skullSplitterLengthEndurance = skullSplitterStrings[1];
}
// CRITICAL STRIKES // CRITICAL STRIKES
if (canCritical) { String[] criticalStrikeStrings = calculateAbilityDisplayValues(Axes.criticalHitMaxBonusLevel, Axes.criticalHitMaxChance);
String[] criticalStrikeStrings = calculateAbilityDisplayValues(Axes.criticalHitMaxBonusLevel, Axes.criticalHitMaxChance); critChance = criticalStrikeStrings[0];
critChance = criticalStrikeStrings[0]; critChanceLucky = criticalStrikeStrings[1];
critChanceLucky = criticalStrikeStrings[1];
}
// AXE MASTERY // AXE MASTERY
if (canBonusDamage) { if (skillValue >= Axes.bonusDamageMaxBonusLevel) {
bonusDamage = Math.min(skillValue / (Axes.bonusDamageMaxBonusLevel / Axes.bonusDamageMaxBonus), Axes.bonusDamageMaxBonus); bonusDamage = String.valueOf(Axes.bonusDamageMaxBonus);
}
else {
bonusDamage = String.valueOf(skillValue / (Axes.bonusDamageMaxBonusLevel / Axes.bonusDamageMaxBonus));
} }
} }
@@ -105,15 +104,25 @@ public class AxesCommand extends SkillCommand {
} }
if (canGreaterImpact) { if (canGreaterImpact) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.4"), LocaleLoader.getString("Axes.Ability.Bonus.5", Axes.greaterImpactBonusDamage))); player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.4"), LocaleLoader.getString("Axes.Ability.Bonus.5", greaterImpactDamage)));
} }
if (canCritical) { if (canCritical) {
player.sendMessage(LocaleLoader.getString("Axes.Combat.CritChance", critChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", critChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Axes.Combat.CritChance", critChance) + LocaleLoader.getString("Perks.lucky.bonus", critChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Axes.Combat.CritChance", critChance));
}
} }
if (canSkullSplitter) { if (canSkullSplitter) {
player.sendMessage(LocaleLoader.getString("Axes.Combat.SS.Length", skullSplitterLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", skullSplitterLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Axes.Combat.SS.Length", skullSplitterLength) + LocaleLoader.getString("Perks.activationtime.bonus", skullSplitterLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Axes.Combat.SS.Length", skullSplitterLength));
}
} }
} }
} }

View File

@@ -18,11 +18,9 @@ public class ExcavationCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// GIGA DRILL BREAKER // GIGA DRILL BREAKER
if (canGigaDrill) { String gigaDrillStrings[] = calculateLengthDisplayValues();
String gigaDrillStrings[] = calculateLengthDisplayValues(); gigaDrillBreakerLength = gigaDrillStrings[0];
gigaDrillBreakerLength = gigaDrillStrings[0]; gigaDrillBreakerLengthEndurance = gigaDrillStrings[1];
gigaDrillBreakerLengthEndurance = gigaDrillStrings[1];
}
} }
@Override @Override
@@ -57,7 +55,12 @@ public class ExcavationCommand extends SkillCommand {
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canGigaDrill) { if (canGigaDrill) {
player.sendMessage(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", gigaDrillBreakerLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength) + LocaleLoader.getString("Perks.activationtime.bonus", gigaDrillBreakerLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength));
}
} }
} }
} }

View File

@@ -1,8 +1,5 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import org.bukkit.block.Biome;
import org.bukkit.entity.EntityType;
import com.gmail.nossr50.config.AdvancedConfig; import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -17,15 +14,12 @@ public class FishingCommand extends SkillCommand {
private String chanceRaining = ""; private String chanceRaining = "";
private String shakeChance; private String shakeChance;
private String shakeChanceLucky; private String shakeChanceLucky;
private int fishermansDietRank; private String fishermansDietRank;
private String biteChance;
private boolean canTreasureHunt; private boolean canTreasureHunt;
private boolean canMagicHunt; private boolean canMagicHunt;
private boolean canShake; private boolean canShake;
private boolean canFishermansDiet; private boolean canFishermansDiet;
private boolean canMasterAngler;
private boolean canIceFish;
public FishingCommand() { public FishingCommand() {
super(SkillType.FISHING); super(SkillType.FISHING);
@@ -33,50 +27,27 @@ public class FishingCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
boolean isStorming = player.getWorld().hasStorm(); lootTier = UserManager.getPlayer(player).getFishingManager().getLootTier();
// TREASURE HUNTER // TREASURE HUNTER
if (canTreasureHunt) { double enchantChance = lootTier * AdvancedConfig.getInstance().getFishingMagicMultiplier();
lootTier = mcMMOPlayer.getFishingManager().getLootTier();
double enchantChance = lootTier * AdvancedConfig.getInstance().getFishingMagicMultiplier();
if (isStorming) { if (player.getWorld().hasStorm()) {
chanceRaining = LocaleLoader.getString("Fishing.Chance.Raining"); chanceRaining = LocaleLoader.getString("Fishing.Chance.Raining");
enchantChance *= 1.1D; enchantChance = enchantChance * 1.1D;
}
String[] treasureHunterStrings = calculateAbilityDisplayValues(enchantChance);
magicChance = treasureHunterStrings[0];
magicChanceLucky = treasureHunterStrings[1];
} }
String[] treasureHunterStrings = calculateAbilityDisplayValues(enchantChance);
magicChance = treasureHunterStrings[0];
magicChanceLucky = treasureHunterStrings[1];
// SHAKE // SHAKE
if (canShake) { String[] shakeStrings = calculateAbilityDisplayValues(UserManager.getPlayer(player).getFishingManager().getShakeProbability());
String[] shakeStrings = calculateAbilityDisplayValues(UserManager.getPlayer(player).getFishingManager().getShakeProbability()); shakeChance = shakeStrings[0];
shakeChance = shakeStrings[0]; shakeChanceLucky = shakeStrings[1];
shakeChanceLucky = shakeStrings[1];
}
// FISHERMAN'S DIET // FISHERMAN'S DIET
if (canFishermansDiet) { fishermansDietRank = calculateRank(Fishing.fishermansDietMaxLevel, Fishing.fishermansDietRankLevel1);
fishermansDietRank = calculateRank(Fishing.fishermansDietMaxLevel, Fishing.fishermansDietRankLevel1);
}
// MASTER ANGLER
if (canMasterAngler) {
double rawBiteChance = ((Math.max((skillValue / 200.0), 1.0)) / (isStorming ? 300 : 500));
Biome biome = player.getLocation().getBlock().getBiome();
if (biome == Biome.RIVER || biome == Biome.OCEAN) {
rawBiteChance = rawBiteChance * 2.0;
}
if (player.isInsideVehicle() && player.getVehicle().getType() == EntityType.BOAT) {
rawBiteChance = rawBiteChance * 2.0;
}
biteChance = calculateAbilityDisplayValues(rawBiteChance * 100.0)[0];
}
} }
@Override @Override
@@ -85,13 +56,11 @@ public class FishingCommand extends SkillCommand {
canMagicHunt = Permissions.magicHunter(player); canMagicHunt = Permissions.magicHunter(player);
canShake = Permissions.shake(player); canShake = Permissions.shake(player);
canFishermansDiet = Permissions.fishermansDiet(player); canFishermansDiet = Permissions.fishermansDiet(player);
canMasterAngler = Permissions.masterAngler(player);
canIceFish = Permissions.iceFishing(player);
} }
@Override @Override
protected boolean effectsHeaderPermissions() { protected boolean effectsHeaderPermissions() {
return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet || canIceFish; return canTreasureHunt || canMagicHunt || canShake;
} }
@Override @Override
@@ -113,59 +82,44 @@ public class FishingCommand extends SkillCommand {
if (canFishermansDiet) { if (canFishermansDiet) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.6"), LocaleLoader.getString("Fishing.Effect.7"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.6"), LocaleLoader.getString("Fishing.Effect.7")));
} }
if (canMasterAngler) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.8"), LocaleLoader.getString("Fishing.Effect.9")));
}
if (canIceFish) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.10"), LocaleLoader.getString("Fishing.Effect.11")));
}
} }
@Override @Override
protected boolean statsHeaderPermissions() { protected boolean statsHeaderPermissions() {
return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet || canIceFish; return canTreasureHunt || canMagicHunt || canShake;
} }
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canMasterAngler) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Chance", biteChance));
}
if (canTreasureHunt) { if (canTreasureHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", lootTier)); player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", lootTier));
} }
if (canMagicHunt) { if (canMagicHunt) {
player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", magicChance) + chanceRaining + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", magicChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", magicChance) + chanceRaining + LocaleLoader.getString("Perks.lucky.bonus", magicChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", magicChance) + chanceRaining);
}
} }
if (canShake) { if (canShake) {
int unlockLevel = AdvancedConfig.getInstance().getShakeUnlockLevel(); if (skillValue < AdvancedConfig.getInstance().getShakeUnlockLevel()) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Fishing.Ability.Locked.0", AdvancedConfig.getInstance().getShakeUnlockLevel())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Fishing.Ability.Locked.0", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake", shakeChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", shakeChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake", shakeChance) + LocaleLoader.getString("Perks.lucky.bonus", shakeChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake", shakeChance));
}
} }
} }
if (canFishermansDiet) { if (canFishermansDiet) {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.FD", fishermansDietRank)); player.sendMessage(LocaleLoader.getString("Fishing.Ability.FD", fishermansDietRank));
} }
if (canIceFish) {
int unlockLevel = AdvancedConfig.getInstance().getIceFishingUnlockLevel();
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Fishing.Ability.Locked.1", unlockLevel)));
}
else {
player.sendMessage(LocaleLoader.getString("Fishing.Ability.IceFishing"));
}
}
} }
} }

View File

@@ -12,8 +12,8 @@ public class HerbalismCommand extends SkillCommand {
private String greenTerraLengthEndurance; private String greenTerraLengthEndurance;
private String greenThumbChance; private String greenThumbChance;
private String greenThumbChanceLucky; private String greenThumbChanceLucky;
private int greenThumbStage; private String greenThumbStage;
private int farmersDietRank; private String farmersDietRank;
private String doubleDropChance; private String doubleDropChance;
private String doubleDropChanceLucky; private String doubleDropChanceLucky;
private String hylianLuckChance; private String hylianLuckChance;
@@ -23,11 +23,12 @@ public class HerbalismCommand extends SkillCommand {
private boolean hasHylianLuck; private boolean hasHylianLuck;
private boolean canGreenTerra; private boolean canGreenTerra;
private boolean canGreenThumbPlants; private boolean canGreenThumbWheat;
private boolean canGreenThumbBlocks; private boolean canGreenThumbBlocks;
private boolean canFarmersDiet; private boolean canFarmersDiet;
private boolean canDoubleDrop; private boolean canDoubleDrop;
private boolean canShroomThumb; private boolean canShroomThumb;
private boolean doubleDropsDisabled;
public HerbalismCommand() { public HerbalismCommand() {
super(SkillType.HERBALISM); super(SkillType.HERBALISM);
@@ -36,62 +37,51 @@ public class HerbalismCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// GREEN TERRA // GREEN TERRA
if (canGreenTerra) { String[] greenTerraStrings = calculateLengthDisplayValues();
String[] greenTerraStrings = calculateLengthDisplayValues(); greenTerraLength = greenTerraStrings[0];
greenTerraLength = greenTerraStrings[0]; greenTerraLengthEndurance = greenTerraStrings[1];
greenTerraLengthEndurance = greenTerraStrings[1];
}
// FARMERS DIET // FARMERS DIET
if (canFarmersDiet) { farmersDietRank = calculateRank(Herbalism.farmersDietMaxLevel, Herbalism.farmersDietRankLevel1);
farmersDietRank = calculateRank(Herbalism.farmersDietMaxLevel, Herbalism.farmersDietRankLevel1);
}
// GREEN THUMB // GREEN THUMB
if (canGreenThumbBlocks || canGreenThumbPlants) { greenThumbStage = calculateRank(Herbalism.greenThumbStageMaxLevel, Herbalism.greenThumbStageChangeLevel);
greenThumbStage = calculateRank(Herbalism.greenThumbStageMaxLevel, Herbalism.greenThumbStageChangeLevel);
String[] greenThumbStrings = calculateAbilityDisplayValues(Herbalism.greenThumbMaxLevel, Herbalism.greenThumbMaxChance); String[] greenThumbStrings = calculateAbilityDisplayValues(Herbalism.greenThumbMaxLevel, Herbalism.greenThumbMaxChance);
greenThumbChance = greenThumbStrings[0]; greenThumbChance = greenThumbStrings[0];
greenThumbChanceLucky = greenThumbStrings[1]; greenThumbChanceLucky = greenThumbStrings[1];
}
// DOUBLE DROPS // DOUBLE DROPS
if (canDoubleDrop) { String[] doubleDropStrings = calculateAbilityDisplayValues(Herbalism.doubleDropsMaxLevel, Herbalism.doubleDropsMaxChance);
String[] doubleDropStrings = calculateAbilityDisplayValues(Herbalism.doubleDropsMaxLevel, Herbalism.doubleDropsMaxChance); doubleDropChance = doubleDropStrings[0];
doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1];
doubleDropChanceLucky = doubleDropStrings[1];
}
// HYLIAN LUCK // HYLIAN LUCK
if (hasHylianLuck) { String[] hylianLuckStrings = calculateAbilityDisplayValues(Herbalism.hylianLuckMaxLevel, Herbalism.hylianLuckMaxChance);
String[] hylianLuckStrings = calculateAbilityDisplayValues(Herbalism.hylianLuckMaxLevel, Herbalism.hylianLuckMaxChance); hylianLuckChance = hylianLuckStrings[0];
hylianLuckChance = hylianLuckStrings[0]; hylianLuckChanceLucky = hylianLuckStrings[1];
hylianLuckChanceLucky = hylianLuckStrings[1];
}
// SHROOM THUMB // SHROOM THUMB
if (canShroomThumb) { String[] shroomThumbStrings = calculateAbilityDisplayValues(Herbalism.shroomThumbMaxLevel, Herbalism.shroomThumbMaxChance);
String[] shroomThumbStrings = calculateAbilityDisplayValues(Herbalism.shroomThumbMaxLevel, Herbalism.shroomThumbMaxChance); shroomThumbChance = shroomThumbStrings[0];
shroomThumbChance = shroomThumbStrings[0]; shroomThumbChanceLucky = shroomThumbStrings[1];
shroomThumbChanceLucky = shroomThumbStrings[1];
}
} }
@Override @Override
protected void permissionsCheck() { protected void permissionsCheck() {
hasHylianLuck = Permissions.hylianLuck(player); hasHylianLuck = Permissions.hylianLuck(player);
canGreenTerra = Permissions.greenTerra(player); canGreenTerra = Permissions.greenTerra(player);
canGreenThumbPlants = Permissions.greenThumbPlant(player, Material.CROPS) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.NETHER_WARTS) || Permissions.greenThumbPlant(player, Material.COCOA); canGreenThumbWheat = Permissions.greenThumbPlant(player, Material.CROPS); // TODO: This isn't really accurate - they could have perms for other crops but not wheat.
canGreenThumbBlocks = Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLE_WALL) || Permissions.greenThumbBlock(player, Material.SMOOTH_BRICK); canGreenThumbBlocks = (Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLE_WALL) || Permissions.greenThumbBlock(player, Material.SMOOTH_BRICK));
canFarmersDiet = Permissions.farmersDiet(player); canFarmersDiet = Permissions.farmersDiet(player);
canDoubleDrop = Permissions.doubleDrops(player, skill) && !skill.getDoubleDropsDisabled(); canDoubleDrop = Permissions.doubleDrops(player, skill);
doubleDropsDisabled = skill.getDoubleDropsDisabled();
canShroomThumb = Permissions.shroomThumb(player); canShroomThumb = Permissions.shroomThumb(player);
} }
@Override @Override
protected boolean effectsHeaderPermissions() { protected boolean effectsHeaderPermissions() {
return canGreenTerra || canDoubleDrop || canFarmersDiet || canGreenThumbBlocks || canGreenThumbPlants || canShroomThumb; return canGreenTerra || (canDoubleDrop && !doubleDropsDisabled) || canFarmersDiet || canGreenThumbBlocks || canGreenThumbWheat || canShroomThumb;
} }
@Override @Override
@@ -102,7 +92,7 @@ public class HerbalismCommand extends SkillCommand {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.0"), LocaleLoader.getString("Herbalism.Effect.1"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.0"), LocaleLoader.getString("Herbalism.Effect.1")));
} }
if (canGreenThumbPlants) { if (canGreenThumbWheat) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.2"), LocaleLoader.getString("Herbalism.Effect.3"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.2"), LocaleLoader.getString("Herbalism.Effect.3")));
} }
@@ -122,27 +112,37 @@ public class HerbalismCommand extends SkillCommand {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.12"), LocaleLoader.getString("Herbalism.Effect.13"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.12"), LocaleLoader.getString("Herbalism.Effect.13")));
} }
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.8"), LocaleLoader.getString("Herbalism.Effect.9"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Herbalism.Effect.8"), LocaleLoader.getString("Herbalism.Effect.9")));
} }
} }
@Override @Override
protected boolean statsHeaderPermissions() { protected boolean statsHeaderPermissions() {
return canGreenTerra || canDoubleDrop || canFarmersDiet || canGreenThumbBlocks || canGreenThumbPlants || canShroomThumb; return canGreenTerra || (canDoubleDrop && !doubleDropsDisabled) || canFarmersDiet || canGreenThumbBlocks || canGreenThumbWheat || canShroomThumb;
} }
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canGreenTerra) { if (canGreenTerra) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTe.Length", greenTerraLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", greenTerraLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTe.Length", greenTerraLength) + LocaleLoader.getString("Perks.activationtime.bonus", greenTerraLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTe.Length", greenTerraLength));
}
} }
if (canGreenThumbBlocks || canGreenThumbPlants) { if (canGreenThumbBlocks || canGreenThumbWheat) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTh.Chance", greenThumbChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", greenThumbChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTh.Chance", greenThumbChance) + LocaleLoader.getString("Perks.lucky.bonus", greenThumbChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTh.Chance", greenThumbChance));
}
} }
if (canGreenThumbPlants) { if (canGreenThumbWheat) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTh.Stage", greenThumbStage)); player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTh.Stage", greenThumbStage));
} }
@@ -151,15 +151,30 @@ public class HerbalismCommand extends SkillCommand {
} }
if (hasHylianLuck) { if (hasHylianLuck) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.HylianLuck", hylianLuckChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", hylianLuckChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.HylianLuck", hylianLuckChance) + LocaleLoader.getString("Perks.lucky.bonus", hylianLuckChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.HylianLuck", hylianLuckChance));
}
} }
if (canShroomThumb) { if (canShroomThumb) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.ShroomThumb.Chance", shroomThumbChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", shroomThumbChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.ShroomThumb.Chance", shroomThumbChance) + LocaleLoader.getString("Perks.lucky.bonus", shroomThumbChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.ShroomThumb.Chance", shroomThumbChance));
}
} }
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.DoubleDropChance", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.DoubleDropChance", doubleDropChance) + LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.DoubleDropChance", doubleDropChance));
}
} }
} }
} }

View File

@@ -6,6 +6,7 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.mining.Mining; import com.gmail.nossr50.skills.mining.Mining;
import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class MiningCommand extends SkillCommand { public class MiningCommand extends SkillCommand {
private String doubleDropChance; private String doubleDropChance;
@@ -25,6 +26,7 @@ public class MiningCommand extends SkillCommand {
private boolean canBlast; private boolean canBlast;
private boolean canBiggerBombs; private boolean canBiggerBombs;
private boolean canDemoExpert; private boolean canDemoExpert;
private boolean doubleDropsDisabled;
public MiningCommand() { public MiningCommand() {
super(SkillType.MINING); super(SkillType.MINING);
@@ -33,30 +35,23 @@ public class MiningCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// SUPER BREAKER // SUPER BREAKER
if (canSuperBreaker) { String[] superBreakerStrings = calculateLengthDisplayValues();
String[] superBreakerStrings = calculateLengthDisplayValues(); superBreakerLength = superBreakerStrings[0];
superBreakerLength = superBreakerStrings[0]; superBreakerLengthEndurance = superBreakerStrings[1];
superBreakerLengthEndurance = superBreakerStrings[1];
}
// DOUBLE DROPS // DOUBLE DROPS
if (canDoubleDrop) { String[] doubleDropStrings = calculateAbilityDisplayValues(Mining.doubleDropsMaxLevel, Mining.doubleDropsMaxChance);
String[] doubleDropStrings = calculateAbilityDisplayValues(Mining.doubleDropsMaxLevel, Mining.doubleDropsMaxChance); doubleDropChance = doubleDropStrings[0];
doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1];
doubleDropChanceLucky = doubleDropStrings[1];
}
// BLAST MINING // BLAST MINING
if (canBlast || canDemoExpert || canBiggerBombs) { MiningManager miningManager = UserManager.getPlayer(player).getMiningManager();
MiningManager miningManager = mcMMOPlayer.getMiningManager(); blastMiningRank = miningManager.getBlastMiningTier();
bonusTNTDrops = miningManager.getDropMultiplier();
blastMiningRank = miningManager.getBlastMiningTier(); oreBonus = percent.format(miningManager.getOreBonus() / 30.0D); // Base received in TNT is 30%
bonusTNTDrops = miningManager.getDropMultiplier(); debrisReduction = percent.format(miningManager.getDebrisReduction() / 30.0D); // Base received in TNT is 30%
oreBonus = percent.format(miningManager.getOreBonus() / 30.0D); // Base received in TNT is 30% blastDamageDecrease = percent.format(miningManager.getBlastDamageModifier() / 100.0D);
debrisReduction = percent.format(miningManager.getDebrisReduction() / 30.0D); // Base received in TNT is 30% blastRadiusIncrease = miningManager.getBlastRadiusModifier();
blastDamageDecrease = percent.format(miningManager.getBlastDamageModifier() / 100.0D);
blastRadiusIncrease = miningManager.getBlastRadiusModifier();
}
} }
@Override @Override
@@ -64,13 +59,14 @@ public class MiningCommand extends SkillCommand {
canBiggerBombs = Permissions.biggerBombs(player); canBiggerBombs = Permissions.biggerBombs(player);
canBlast = Permissions.remoteDetonation(player); canBlast = Permissions.remoteDetonation(player);
canDemoExpert = Permissions.demolitionsExpertise(player); canDemoExpert = Permissions.demolitionsExpertise(player);
canDoubleDrop = Permissions.doubleDrops(player, skill) && !skill.getDoubleDropsDisabled(); canDoubleDrop = Permissions.doubleDrops(player, skill);
canSuperBreaker = Permissions.superBreaker(player); canSuperBreaker = Permissions.superBreaker(player);
doubleDropsDisabled = skill.getDoubleDropsDisabled();
} }
@Override @Override
protected boolean effectsHeaderPermissions() { protected boolean effectsHeaderPermissions() {
return canBiggerBombs || canBlast || canDemoExpert || canDoubleDrop || canSuperBreaker; return canBiggerBombs || canBlast || canDemoExpert || (canDoubleDrop && !doubleDropsDisabled) || canSuperBreaker;
} }
@Override @Override
@@ -81,7 +77,7 @@ public class MiningCommand extends SkillCommand {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Mining.Effect.0"), LocaleLoader.getString("Mining.Effect.1"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Mining.Effect.0"), LocaleLoader.getString("Mining.Effect.1")));
} }
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Mining.Effect.2"), LocaleLoader.getString("Mining.Effect.3"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Mining.Effect.2"), LocaleLoader.getString("Mining.Effect.3")));
} }
@@ -100,24 +96,32 @@ public class MiningCommand extends SkillCommand {
@Override @Override
protected boolean statsHeaderPermissions() { protected boolean statsHeaderPermissions() {
return canBiggerBombs || canBlast || canDemoExpert || canDoubleDrop || canSuperBreaker; return canBiggerBombs || canBlast || canDemoExpert || (canDoubleDrop && !doubleDropsDisabled) || canSuperBreaker;
} }
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance) + LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance));
}
} }
if (canSuperBreaker) { if (canSuperBreaker) {
player.sendMessage(LocaleLoader.getString("Mining.Ability.Length", superBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", superBreakerLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Mining.Ability.Length", superBreakerLength) + LocaleLoader.getString("Perks.activationtime.bonus", superBreakerLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Mining.Ability.Length", superBreakerLength));
}
} }
if (canBlast) { if (canBlast) {
int unlockLevel = AdvancedConfig.getInstance().getBlastMiningRank1(); if (skillValue < AdvancedConfig.getInstance().getBlastMiningRank1()) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.0", AdvancedConfig.getInstance().getBlastMiningRank1())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.0", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Mining.Blast.Rank", blastMiningRank, LocaleLoader.getString("Mining.Blast.Effect", oreBonus, debrisReduction, bonusTNTDrops))); player.sendMessage(LocaleLoader.getString("Mining.Blast.Rank", blastMiningRank, LocaleLoader.getString("Mining.Blast.Effect", oreBonus, debrisReduction, bonusTNTDrops)));
@@ -125,10 +129,8 @@ public class MiningCommand extends SkillCommand {
} }
if (canBiggerBombs) { if (canBiggerBombs) {
int unlockLevel = AdvancedConfig.getInstance().getBlastMiningRank2(); if (skillValue < AdvancedConfig.getInstance().getBlastMiningRank2()) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.1", AdvancedConfig.getInstance().getBlastMiningRank2())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.1", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Mining.Blast.Radius.Increase", blastRadiusIncrease)); player.sendMessage(LocaleLoader.getString("Mining.Blast.Radius.Increase", blastRadiusIncrease));
@@ -136,10 +138,8 @@ public class MiningCommand extends SkillCommand {
} }
if (canDemoExpert) { if (canDemoExpert) {
int unlockLevel = AdvancedConfig.getInstance().getBlastMiningRank4(); if (skillValue < AdvancedConfig.getInstance().getBlastMiningRank4()) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.2", AdvancedConfig.getInstance().getBlastMiningRank4())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Mining.Ability.Locked.2", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Mining.Effect.Decrease", blastDamageDecrease)); player.sendMessage(LocaleLoader.getString("Mining.Effect.Decrease", blastDamageDecrease));

View File

@@ -1,146 +0,0 @@
package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.ranching.Ranching;
import com.gmail.nossr50.util.Permissions;
public class RanchingCommand extends SkillCommand {
private String multipleBirthChance;
private String multipleBirthChanceLucky;
private int masterHerderTime;
private String shearsMasteryChance;
private String shearsMasteryChanceLucky;
private String artisanButcherChance;
private String artisanButcherChanceLucky;
private int carnivoresDietRank;
private boolean canMultipleBirth;
private boolean canMasterHerder;
private boolean canShearsMastery;
private boolean canArtisanButcher;
private boolean canCarnivoresDiet;
public RanchingCommand() {
super(SkillType.RANCHING);
}
@Override
protected void dataCalculations() {
// MULTIPLE BIRTH
if (canMultipleBirth) {
String[] multipleBirthStrings = calculateAbilityDisplayValues(Ranching.multipleBirthIncreaseLevel, Ranching.multipleBirthMaxChance);
multipleBirthChance = multipleBirthStrings[0];
multipleBirthChanceLucky = multipleBirthStrings[1];
}
// MASTER HERDER
if (canMasterHerder) {
int masterHerderTime = (int) (300 - (skillValue / Ranching.masterHerderIncreaseLevel) * 10);
if (masterHerderTime < Ranching.masterHerderMinimumSeconds) {
masterHerderTime = Ranching.masterHerderMinimumSeconds;
}
}
// SHEARS MASTERY
if (canShearsMastery) {
String[] shearsMasteryStrings = calculateAbilityDisplayValues(Ranching.shearsMasteryMaxLevel, Ranching.shearsMasteryMaxChance);
shearsMasteryChance = shearsMasteryStrings[0];
shearsMasteryChanceLucky = shearsMasteryStrings[1];
}
// ARTISAN BUTCHER
if (canArtisanButcher) {
String[] artisanButcherStrings = calculateAbilityDisplayValues(Ranching.artisanButcherMaxLevel, Ranching.artisanButcherMaxChance);
artisanButcherChance = artisanButcherStrings[0];
artisanButcherChanceLucky = artisanButcherStrings[1];
}
// CARNIVORES DIET
if (canCarnivoresDiet) {
carnivoresDietRank = calculateRank(Ranching.carnivoresDietMaxLevel, Ranching.carnivoresDietRankLevel1);
}
}
@Override
protected void permissionsCheck() {
canMultipleBirth = Permissions.multipleBirth(player);
canMasterHerder = Permissions.masterHerder(player);
canShearsMastery = Permissions.shearsMastery(player);
canArtisanButcher = Permissions.artisanButcher(player);
canCarnivoresDiet = Permissions.carnivoresDiet(player);
}
@Override
protected boolean effectsHeaderPermissions() {
return canMultipleBirth || canMasterHerder || canShearsMastery || canArtisanButcher || canCarnivoresDiet;
}
@Override
protected void effectsDisplay() {
luckyEffectsDisplay();
if (canMultipleBirth) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Ranching.Effect.0"), LocaleLoader.getString("Ranching.Effect.1")));
}
if (canMasterHerder) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Ranching.Effect.2"), LocaleLoader.getString("Ranching.Effect.3")));
}
if (canShearsMastery) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Ranching.Effect.4"), LocaleLoader.getString("Ranching.Effect.5")));
}
if (canArtisanButcher) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Ranching.Effect.6"), LocaleLoader.getString("Ranching.Effect.7")));
}
if (canCarnivoresDiet) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Ranching.Effect.8"), LocaleLoader.getString("Ranching.Effect.9")));
}
}
@Override
protected boolean statsHeaderPermissions() {
return canMultipleBirth || canMasterHerder || canShearsMastery || canArtisanButcher || canCarnivoresDiet;
}
@Override
protected void statsDisplay() {
if (canMultipleBirth) {
int unlockLevel = Ranching.multipleBirthIncreaseLevel;
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Ranching.Ability.Locked.0", unlockLevel)));
}
else {
player.sendMessage(LocaleLoader.getString("Ranching.Ability.MultipleBirth", multipleBirthChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", multipleBirthChanceLucky) : ""));
}
}
if (canMasterHerder) {
int unlockLevel = Ranching.masterHerderIncreaseLevel;
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Ranching.Ability.Locked.1", unlockLevel)));
}
else {
player.sendMessage(LocaleLoader.getString("Ranching.Ability.MasterHerder", masterHerderTime));
}
}
if (canShearsMastery) {
player.sendMessage(LocaleLoader.getString("Ranching.Ability.ShearsMastery", shearsMasteryChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", shearsMasteryChanceLucky) : ""));
}
if (canArtisanButcher) {
player.sendMessage(LocaleLoader.getString("Ranching.Ability.ArtisanButcher", artisanButcherChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", artisanButcherChanceLucky) : ""));
}
if (canCarnivoresDiet) {
player.sendMessage(LocaleLoader.getString("Ranching.Ability.CarnivoresDiet", carnivoresDietRank));
}
}
}

View File

@@ -5,13 +5,13 @@ import org.bukkit.Material;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.repair.ArcaneForging;
import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.repair.RepairManager;
import com.gmail.nossr50.skills.repair.Repairable; import com.gmail.nossr50.skills.repair.Repairable;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class RepairCommand extends SkillCommand { public class RepairCommand extends SkillCommand {
private int arcaneForgingRank;
private String repairMasteryBonus; private String repairMasteryBonus;
private String superRepairChance; private String superRepairChance;
private String superRepairChanceLucky; private String superRepairChanceLucky;
@@ -41,10 +41,10 @@ public class RepairCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// We're using pickaxes here, not the best but it works // We're using pickaxes here, not the best but it works
Repairable diamondRepairable = mcMMO.getRepairableManager().getRepairable(Material.DIAMOND_PICKAXE.getId()); Repairable diamondRepairable = mcMMO.repairableManager.getRepairable(Material.DIAMOND_PICKAXE.getId());
Repairable goldRepairable = mcMMO.getRepairableManager().getRepairable(Material.GOLD_PICKAXE.getId()); Repairable goldRepairable = mcMMO.repairableManager.getRepairable(Material.GOLD_PICKAXE.getId());
Repairable ironRepairable = mcMMO.getRepairableManager().getRepairable(Material.IRON_PICKAXE.getId()); Repairable ironRepairable = mcMMO.repairableManager.getRepairable(Material.IRON_PICKAXE.getId());
Repairable stoneRepairable = mcMMO.getRepairableManager().getRepairable(Material.STONE_PICKAXE.getId()); Repairable stoneRepairable = mcMMO.repairableManager.getRepairable(Material.STONE_PICKAXE.getId());
// TODO: This isn't really accurate - if they don't have pickaxes loaded it doesn't always mean the repair level is 0 // TODO: This isn't really accurate - if they don't have pickaxes loaded it doesn't always mean the repair level is 0
diamondLevel = (diamondRepairable == null) ? 0 : diamondRepairable.getMinimumLevel(); diamondLevel = (diamondRepairable == null) ? 0 : diamondRepairable.getMinimumLevel();
@@ -53,16 +53,20 @@ public class RepairCommand extends SkillCommand {
stoneLevel = (stoneRepairable == null) ? 0 : stoneRepairable.getMinimumLevel(); stoneLevel = (stoneRepairable == null) ? 0 : stoneRepairable.getMinimumLevel();
// REPAIR MASTERY // REPAIR MASTERY
if (canMasterRepair) { if (skillValue >= Repair.repairMasteryMaxBonusLevel) {
repairMasteryBonus = percent.format(Math.min(((Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) * skillValue), Repair.repairMasteryMaxBonus) / 100D); repairMasteryBonus = percent.format(Repair.repairMasteryMaxBonus / 100D);
}
else {
repairMasteryBonus = percent.format(((Repair.repairMasteryMaxBonus / Repair.repairMasteryMaxBonusLevel) * skillValue) / 100D);
} }
// SUPER REPAIR // SUPER REPAIR
if (canSuperRepair) { String[] superRepairStrings = calculateAbilityDisplayValues(Repair.superRepairMaxBonusLevel, Repair.superRepairMaxChance);
String[] superRepairStrings = calculateAbilityDisplayValues(Repair.superRepairMaxBonusLevel, Repair.superRepairMaxChance); superRepairChance = superRepairStrings[0];
superRepairChance = superRepairStrings[0]; superRepairChanceLucky = superRepairStrings[1];
superRepairChanceLucky = superRepairStrings[1];
} // ARCANE FORGING
arcaneForgingRank = UserManager.getPlayer(player).getRepairManager().getArcaneForgingRank();
} }
@Override @Override
@@ -139,20 +143,23 @@ public class RepairCommand extends SkillCommand {
} }
if (canSuperRepair) { if (canSuperRepair) {
player.sendMessage(LocaleLoader.getString("Repair.Skills.Super.Chance", superRepairChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", superRepairChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Repair.Skills.Super.Chance", superRepairChance) + LocaleLoader.getString("Perks.lucky.bonus", superRepairChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Repair.Skills.Super.Chance", superRepairChance));
}
} }
if (canArcaneForge) { if (canArcaneForge) {
RepairManager repairManager = mcMMOPlayer.getRepairManager(); player.sendMessage(LocaleLoader.getString("Repair.Arcane.Rank", arcaneForgingRank));
player.sendMessage(LocaleLoader.getString("Repair.Arcane.Rank", repairManager.getArcaneForgingRank())); if (Repair.arcaneForgingEnchantLoss) {
player.sendMessage(LocaleLoader.getString("Repair.Arcane.Chance.Success", (arcaneBypass ? 100 : UserManager.getPlayer(player).getRepairManager().getKeepEnchantChance())));
if (ArcaneForging.arcaneForgingEnchantLoss) {
player.sendMessage(LocaleLoader.getString("Repair.Arcane.Chance.Success", (arcaneBypass ? 100 : repairManager.getKeepEnchantChance())));
} }
if (ArcaneForging.arcaneForgingDowngrades) { if (Repair.arcaneForgingDowngrades) {
player.sendMessage(LocaleLoader.getString("Repair.Arcane.Chance.Downgrade", (arcaneBypass ? 0 : repairManager.getDowngradeEnchantChance()))); player.sendMessage(LocaleLoader.getString("Repair.Arcane.Chance.Downgrade", (arcaneBypass ? 0 : UserManager.getPlayer(player).getRepairManager().getDowngradeEnchantChance())));
} }
} }
} }

View File

@@ -1,18 +1,14 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.config.AdvancedConfig; import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -21,20 +17,15 @@ import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.PerksUtils; import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList; public abstract class SkillCommand implements CommandExecutor {
public abstract class SkillCommand implements TabExecutor {
protected SkillType skill; protected SkillType skill;
protected String skillName; private String skillString;
protected Player player; protected Player player;
protected PlayerProfile profile; protected PlayerProfile profile;
protected McMMOPlayer mcMMOPlayer;
protected float skillValue; protected float skillValue;
protected boolean isLucky; protected boolean isLucky;
protected boolean hasEndurance; protected boolean hasEndurance;
@@ -42,12 +33,9 @@ public abstract class SkillCommand implements TabExecutor {
protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat percent = new DecimalFormat("##0.00%");
protected DecimalFormat decimal = new DecimalFormat("##0.00"); protected DecimalFormat decimal = new DecimalFormat("##0.00");
private CommandExecutor skillGuideCommand;
public SkillCommand(SkillType skill) { public SkillCommand(SkillType skill) {
this.skill = skill; this.skill = skill;
skillName = SkillUtils.getSkillName(skill); this.skillString = StringUtils.getCapitalized(skill.toString());
skillGuideCommand = new SkillGuideCommand(skill);
} }
@Override @Override
@@ -57,89 +45,96 @@ public abstract class SkillCommand implements TabExecutor {
} }
player = (Player) sender; player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player); profile = UserManager.getPlayer(player).getProfile();
switch (args.length) { if (profile == null) {
case 0: sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist"));
profile = mcMMOPlayer.getProfile(); return true;
skillValue = profile.getSkillLevel(skill);
isLucky = Permissions.lucky(sender, skill);
hasEndurance = (PerksUtils.handleActivationPerks(player, 0, 0) != 0);
permissionsCheck();
dataCalculations();
if (!skill.isChildSkill()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", skillName));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + StringUtils.getCapitalized(skill.toString()))));
if (Config.getInstance().getSkillScoreboardEnabled()) {
ScoreboardManager.setupPlayerScoreboard(player.getName());
ScoreboardManager.enablePlayerSkillScoreboard(mcMMOPlayer, skill);
}
else {
player.sendMessage(LocaleLoader.getString("Effects.Level", (int) skillValue, profile.getSkillXpLevel(skill), profile.getXpToLevel(skill)));
}
}
else {
player.sendMessage(LocaleLoader.getString("Skills.Header", skillName + " " + LocaleLoader.getString("Skills.Child")));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain.Child")));
player.sendMessage(LocaleLoader.getString("Effects.Child", (int) skillValue));
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Skills.Parents")));
Set<SkillType> parents = FamilyTree.getParents(skill);
for (SkillType parent : parents) {
player.sendMessage(SkillUtils.getSkillName(parent) + " - " + LocaleLoader.getString("Effects.Level", profile.getSkillLevel(parent), profile.getSkillXpLevel(parent), profile.getXpToLevel(parent)));
}
}
if (effectsHeaderPermissions()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Effects.Effects")));
}
effectsDisplay();
if (statsHeaderPermissions()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Commands.Stats.Self")));
}
statsDisplay();
player.sendMessage(LocaleLoader.getString("Guides.Available", skillName, skillName.toLowerCase()));
return true;
default:
return skillGuideCommand.onCommand(sender, command, label, args);
} }
skillValue = profile.getSkillLevel(skill);
isLucky = Permissions.lucky(sender, skill);
hasEndurance = (Permissions.twelveSecondActivationBoost(sender) || Permissions.eightSecondActivationBoost(sender) || Permissions.fourSecondActivationBoost(sender));
dataCalculations();
permissionsCheck();
if (!skill.isChildSkill()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", SkillUtils.getSkillName(skill)));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + skillString)));
player.sendMessage(LocaleLoader.getString("Effects.Level", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), profile.getXpToLevel(skill)));
}
else {
player.sendMessage(LocaleLoader.getString("Skills.Header", SkillUtils.getSkillName(skill) + " " + LocaleLoader.getString("Skills.Child")));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain.Child")));
player.sendMessage(LocaleLoader.getString("Effects.Child", profile.getSkillLevel(skill)));
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Skills.Parents")));
Set<SkillType> parents = FamilyTree.getParents(skill);
for (SkillType parent : parents) {
player.sendMessage(SkillUtils.getSkillName(parent) + " - " + LocaleLoader.getString("Effects.Level", profile.getSkillLevel(parent), profile.getSkillXpLevel(parent), profile.getXpToLevel(parent)));
}
}
if (effectsHeaderPermissions()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Effects.Effects")));
}
effectsDisplay();
if (statsHeaderPermissions()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Commands.Stats.Self")));
}
statsDisplay();
return SkillGuideCommand.grabGuidePageForSkill(skill, player, args);
} }
@Override protected String calculateRank(int maxLevel, int rankChangeLevel) {
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (skillValue >= maxLevel) {
switch (args.length) { return String.valueOf(maxLevel / rankChangeLevel);
case 1:
return ImmutableList.of("?");
default:
return ImmutableList.of();
} }
}
protected int calculateRank(int maxLevel, int rankChangeLevel) { return String.valueOf((int) (skillValue / rankChangeLevel));
return Math.min((int) skillValue, maxLevel) / rankChangeLevel;
} }
protected String[] calculateAbilityDisplayValues(double chance) { protected String[] calculateAbilityDisplayValues(double chance) {
String[] displayValues = new String[2]; if (isLucky) {
double luckyChance = chance * 1.3333D;
displayValues[0] = percent.format(Math.min(chance, 100.0D) / 100.0D); if (luckyChance >= 100D) {
displayValues[1] = isLucky ? percent.format(Math.min(chance * 1.3333D, 100.0D) / 100.0D) : null; return new String[] { percent.format(chance / 100.0D), percent.format(1.0D) };
}
return displayValues; return new String[] { percent.format(chance / 100.0D), percent.format(luckyChance / 100.0D) };
}
return new String[] { percent.format(chance / 100.0D), null };
} }
protected String[] calculateAbilityDisplayValues(int maxBonusLevel, double maxChance) { protected String[] calculateAbilityDisplayValues(int maxBonusLevel, double maxChance) {
return calculateAbilityDisplayValues((maxChance / maxBonusLevel) * Math.min(skillValue, maxBonusLevel)); double abilityChance;
if (skillValue >= maxBonusLevel) {
abilityChance = maxChance;
}
else {
abilityChance = (maxChance / maxBonusLevel) * skillValue;
}
if (isLucky) {
double luckyChance = abilityChance * 1.3333D;
if (luckyChance >= 100D) {
return new String[] { percent.format(abilityChance / 100.0D), percent.format(1.0D) };
}
return new String[] { percent.format(abilityChance / 100.0D), percent.format(luckyChance / 100.0D) };
}
return new String[] { percent.format(abilityChance / 100.0D), null };
} }
protected String[] calculateLengthDisplayValues() { protected String[] calculateLengthDisplayValues() {
@@ -148,7 +143,9 @@ public abstract class SkillCommand implements TabExecutor {
int enduranceLength = PerksUtils.handleActivationPerks(player, length, maxLength); int enduranceLength = PerksUtils.handleActivationPerks(player, length, maxLength);
if (maxLength != 0) { if (maxLength != 0) {
length = Math.min(length, maxLength); if (length > maxLength) {
length = maxLength;
}
} }
return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; return new String[] { String.valueOf(length), String.valueOf(enduranceLength) };
@@ -157,7 +154,7 @@ public abstract class SkillCommand implements TabExecutor {
protected void luckyEffectsDisplay() { protected void luckyEffectsDisplay() {
if (isLucky) { if (isLucky) {
String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix"); String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix");
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc", skillName))); player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc", SkillUtils.getSkillName(skill))));
} }
} }

View File

@@ -2,89 +2,106 @@ package com.gmail.nossr50.commands.skills;
import java.util.ArrayList; import java.util.ArrayList;
import org.bukkit.command.Command; import org.bukkit.entity.Player;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class SkillGuideCommand implements CommandExecutor { public final class SkillGuideCommand {
private String header; private SkillGuideCommand() {}
private String[] guide;
private String invalidPage; public static int getTotalPageNumber(String address) {
String[] addressSplit = LocaleLoader.getString(address).split("\n");
public SkillGuideCommand(SkillType skillType) { if (addressSplit.length <= 8) {
header = LocaleLoader.getString("Guides.Header", SkillUtils.getSkillName(skillType)); return 1;
guide = LocaleLoader.getString("Guides." + StringUtils.getCapitalized(skillType.toString())).split("\n"); }
invalidPage = LocaleLoader.getString("Guides.Page.Invalid"); return (addressSplit.length / 8) + 1;
} }
@Override public static ArrayList<String> grabPageContents(String header, String address, int pagenum) {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { int pageIndexStart = 0;
// Determine what string to start at
if (pagenum > 1) {
pageIndexStart = 8 * (pagenum - 1);
}
ArrayList<String> allStrings = new ArrayList<String>();
String split[] = LocaleLoader.getString(address).split("\n");
allStrings.add(LocaleLoader.getString("Guides.Header", header));
// Add targeted strings
while (allStrings.size() < 9) {
if (pageIndexStart + allStrings.size() > split.length) {
allStrings.add("");
}
else {
allStrings.add(split[pageIndexStart + allStrings.size() - 1]);
}
}
allStrings.add("Page " + pagenum + " of " + getTotalPageNumber(address));
return allStrings;
}
public static void clearChat(Player player) {
player.sendMessage("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // Dear god why?
}
public static boolean grabGuidePageForSkill(SkillType skilltype, Player player, String[] args) {
String skillName = skilltype.toString();
String capitalized = StringUtils.getCapitalized(skillName);
String localized = SkillUtils.getSkillName(skilltype);
player.sendMessage(LocaleLoader.getString("Guides.Available", localized, localized.toLowerCase()));
String address = "Guides." + capitalized;
switch (args.length) { switch (args.length) {
case 0:
// We have to specify this, otherwise we get the usage string every time we call /skillname...
return true;
case 1: case 1:
if (!args[0].equals("?")) { if (!args[0].equals("?")) {
return false; return false;
} }
sendGuide(sender, 1); SkillGuideCommand.clearChat(player);
for (String target : SkillGuideCommand.grabPageContents(localized, address, 1)) {
player.sendMessage(target);
}
return true; return true;
case 2: case 2:
int totalPages = getTotalPageNumber(); int totalPages = SkillGuideCommand.getTotalPageNumber(address);
if (!StringUtils.isInt(args[1])) { if (!StringUtils.isInt(args[1])) {
sender.sendMessage(invalidPage); player.sendMessage(LocaleLoader.getString("Guides.Page.Invalid"));
return true; return true;
} }
int pageNumber = Integer.parseInt(args[1]); if (Integer.parseInt(args[1]) > totalPages) {
player.sendMessage(LocaleLoader.getString("Guides.Page.OutOfRange", totalPages));
if (pageNumber > totalPages || pageNumber <= 0) {
sender.sendMessage(LocaleLoader.getString("Guides.Page.OutOfRange", totalPages));
return true; return true;
} }
sendGuide(sender, pageNumber); SkillGuideCommand.clearChat(player);
for (String target : SkillGuideCommand.grabPageContents(localized, address, Integer.parseInt(args[1]))) {
player.sendMessage(target);
}
return true; return true;
default: default:
return false; return false;
} }
} }
private int getTotalPageNumber() {
return (int) Math.ceil(guide.length / 8.0);
}
private void sendGuide(CommandSender sender, int pageNumber) {
for (String target : grabPageContents(pageNumber)) {
sender.sendMessage(target);
}
}
private ArrayList<String> grabPageContents(int pagenum) {
int pageIndexStart = 8 * (pagenum - 1); // Determine what string to start at
ArrayList<String> allStrings = new ArrayList<String>();
allStrings.add(header);
// Add targeted strings
while (allStrings.size() < 9) {
if (pageIndexStart + allStrings.size() > guide.length) {
allStrings.add("");
}
else {
allStrings.add(guide[pageIndexStart + (allStrings.size() - 1)]);
}
}
allStrings.add("Page " + pagenum + " of " + getTotalPageNumber());
return allStrings;
}
} }

View File

@@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.smelting.Smelting; import com.gmail.nossr50.skills.smelting.Smelting;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class SmeltingCommand extends SkillCommand { public class SmeltingCommand extends SkillCommand {
private String burnTimeModifier; private String burnTimeModifier;
@@ -13,6 +14,8 @@ public class SmeltingCommand extends SkillCommand {
private String fluxMiningChance; private String fluxMiningChance;
private String fluxMiningChanceLucky; private String fluxMiningChanceLucky;
private int vanillaXPModifier;
private boolean canFuelEfficiency; private boolean canFuelEfficiency;
private boolean canSecondSmelt; private boolean canSecondSmelt;
private boolean canFluxMine; private boolean canFluxMine;
@@ -25,23 +28,20 @@ public class SmeltingCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// FUEL EFFICIENCY // FUEL EFFICIENCY
if (canFuelEfficiency) { burnTimeModifier = decimal.format(1 + ((skillValue / Smelting.burnModifierMaxLevel) * Smelting.burnTimeMultiplier));
burnTimeModifier = decimal.format(1 + ((skillValue / Smelting.burnModifierMaxLevel) * Smelting.burnTimeMultiplier));
}
// SECOND SMELT // SECOND SMELT
if (canSecondSmelt) { String[] secondSmeltStrings = calculateAbilityDisplayValues(Smelting.secondSmeltMaxLevel, Smelting.secondSmeltMaxChance);
String[] secondSmeltStrings = calculateAbilityDisplayValues(Smelting.secondSmeltMaxLevel, Smelting.secondSmeltMaxChance); secondSmeltChance = secondSmeltStrings[0];
secondSmeltChance = secondSmeltStrings[0]; secondSmeltChanceLucky = secondSmeltStrings[1];
secondSmeltChanceLucky = secondSmeltStrings[1];
}
// FLUX MINING // FLUX MINING
if (canFluxMine) { String[] fluxMiningStrings = calculateAbilityDisplayValues(Smelting.fluxMiningChance);
String[] fluxMiningStrings = calculateAbilityDisplayValues(Smelting.fluxMiningChance); fluxMiningChance = fluxMiningStrings[0];
fluxMiningChance = fluxMiningStrings[0]; fluxMiningChanceLucky = fluxMiningStrings[1];
fluxMiningChanceLucky = fluxMiningStrings[1];
} // VANILLA XP BOOST
vanillaXPModifier = UserManager.getPlayer(player).getSmeltingManager().getVanillaXpMultiplier();
} }
@Override @Override
@@ -90,17 +90,20 @@ public class SmeltingCommand extends SkillCommand {
} }
if (canSecondSmelt) { if (canSecondSmelt) {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", secondSmeltChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance) + LocaleLoader.getString("Perks.lucky.bonus", secondSmeltChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance));
}
} }
if (canVanillaXPBoost) { if (canVanillaXPBoost) {
int unlockLevel = AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level(); if (skillValue < AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level()) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.0", AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.0", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.VanillaXPBoost", mcMMOPlayer.getSmeltingManager().getVanillaXpMultiplier())); player.sendMessage(LocaleLoader.getString("Smelting.Ability.VanillaXPBoost", vanillaXPModifier));
} }
} }
@@ -108,8 +111,11 @@ public class SmeltingCommand extends SkillCommand {
if (skillValue < Smelting.fluxMiningUnlockLevel) { if (skillValue < Smelting.fluxMiningUnlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.1", Smelting.fluxMiningUnlockLevel))); player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.1", Smelting.fluxMiningUnlockLevel)));
} }
else if (isLucky) {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.FluxMining", fluxMiningChance) + LocaleLoader.getString("Perks.lucky.bonus", fluxMiningChanceLucky));
}
else { else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.FluxMining", fluxMiningChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", fluxMiningChanceLucky) : "")); player.sendMessage(LocaleLoader.getString("Smelting.Ability.FluxMining", fluxMiningChance));
} }
} }
} }

View File

@@ -8,7 +8,7 @@ import com.gmail.nossr50.util.Permissions;
public class SwordsCommand extends SkillCommand { public class SwordsCommand extends SkillCommand {
private String counterAttackChance; private String counterAttackChance;
private String counterAttackChanceLucky; private String counterAttackChanceLucky;
private int bleedLength; private String bleedLength;
private String bleedChance; private String bleedChance;
private String bleedChanceLucky; private String bleedChanceLucky;
private String serratedStrikesLength; private String serratedStrikesLength;
@@ -25,27 +25,26 @@ public class SwordsCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// SERRATED STRIKES // SERRATED STRIKES
if (canSerratedStrike) { String[] serratedStrikesStrings = calculateLengthDisplayValues();
String[] serratedStrikesStrings = calculateLengthDisplayValues(); serratedStrikesLength = serratedStrikesStrings[0];
serratedStrikesLength = serratedStrikesStrings[0]; serratedStrikesLengthEndurance = serratedStrikesStrings[1];
serratedStrikesLengthEndurance = serratedStrikesStrings[1];
}
// BLEED // BLEED
if (canBleed) { if (skillValue >= Swords.bleedMaxBonusLevel) {
bleedLength = (skillValue >= Swords.bleedMaxBonusLevel) ? Swords.bleedMaxTicks : Swords.bleedBaseTicks; bleedLength = String.valueOf(Swords.bleedMaxTicks);
String[] bleedStrings = calculateAbilityDisplayValues(Swords.bleedMaxBonusLevel, Swords.bleedMaxChance);
bleedChance = bleedStrings[0];
bleedChanceLucky = bleedStrings[1];
} }
else {
bleedLength = String.valueOf(Swords.bleedBaseTicks);
}
String[] bleedStrings = calculateAbilityDisplayValues(Swords.bleedMaxBonusLevel, Swords.bleedMaxChance);
bleedChance = bleedStrings[0];
bleedChanceLucky = bleedStrings[1];
// COUNTER ATTACK // COUNTER ATTACK
if (canCounter) { String[] counterAttackStrings = calculateAbilityDisplayValues(Swords.counterAttackMaxBonusLevel, Swords.counterAttackMaxChance);
String[] counterAttackStrings = calculateAbilityDisplayValues(Swords.counterAttackMaxBonusLevel, Swords.counterAttackMaxChance); counterAttackChance = counterAttackStrings[0];
counterAttackChance = counterAttackStrings[0]; counterAttackChanceLucky = counterAttackStrings[1];
counterAttackChanceLucky = counterAttackStrings[1];
}
} }
@Override @Override
@@ -86,17 +85,33 @@ public class SwordsCommand extends SkillCommand {
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canCounter) { if (canCounter) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", counterAttackChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance) + LocaleLoader.getString("Perks.lucky.bonus", counterAttackChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance));
}
} }
if (canBleed) { if (canBleed) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Length", bleedLength)); player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Length", bleedLength));
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Note")); player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Note"));
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", bleedChanceLucky) : ""));
if (isLucky) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance) + LocaleLoader.getString("Perks.lucky.bonus", bleedChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance));
}
} }
if (canSerratedStrike) { if (canSerratedStrike) {
player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", serratedStrikesLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength) + LocaleLoader.getString("Perks.activationtime.bonus", serratedStrikesLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength));
}
} }
} }
} }

View File

@@ -26,11 +26,9 @@ public class TamingCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
if (canGore) { String[] goreStrings = calculateAbilityDisplayValues(Taming.goreMaxBonusLevel, Taming.goreMaxChance);
String[] goreStrings = calculateAbilityDisplayValues(Taming.goreMaxBonusLevel, Taming.goreMaxChance); goreChance = goreStrings[0];
goreChance = goreStrings[0]; goreChanceLucky = goreStrings[1];
goreChanceLucky = goreStrings[1];
}
} }
@Override @Override
@@ -156,7 +154,12 @@ public class TamingCommand extends SkillCommand {
} }
if (canGore) { if (canGore) {
player.sendMessage(LocaleLoader.getString("Taming.Combat.Chance.Gore", goreChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", goreChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Taming.Combat.Chance.Gore", goreChance) + LocaleLoader.getString("Perks.lucky.bonus", goreChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Taming.Combat.Chance.Gore", goreChance));
}
} }
} }
} }

View File

@@ -14,7 +14,7 @@ public class UnarmedCommand extends SkillCommand {
private String disarmChanceLucky; private String disarmChanceLucky;
private String ironGripChance; private String ironGripChance;
private String ironGripChanceLucky; private String ironGripChanceLucky;
private int ironArmBonus; private String ironArmBonus;
private boolean canBerserk; private boolean canBerserk;
private boolean canDisarm; private boolean canDisarm;
@@ -29,37 +29,32 @@ public class UnarmedCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// BERSERK // BERSERK
if (canBerserk) { String[] berserkStrings = calculateLengthDisplayValues();
String[] berserkStrings = calculateLengthDisplayValues(); berserkLength = berserkStrings[0];
berserkLength = berserkStrings[0]; berserkLengthEndurance = berserkStrings[1];
berserkLengthEndurance = berserkStrings[1];
}
// DISARM // DISARM
if (canDisarm) { String[] disarmStrings = calculateAbilityDisplayValues(Unarmed.disarmMaxBonusLevel, Unarmed.disarmMaxChance);
String[] disarmStrings = calculateAbilityDisplayValues(Unarmed.disarmMaxBonusLevel, Unarmed.disarmMaxChance); disarmChance = disarmStrings[0];
disarmChance = disarmStrings[0]; disarmChanceLucky = disarmStrings[1];
disarmChanceLucky = disarmStrings[1];
}
// DEFLECT // DEFLECT
if (canDeflect) { String[] deflectStrings = calculateAbilityDisplayValues(Unarmed.deflectMaxBonusLevel, Unarmed.deflectMaxChance);
String[] deflectStrings = calculateAbilityDisplayValues(Unarmed.deflectMaxBonusLevel, Unarmed.deflectMaxChance); deflectChance = deflectStrings[0];
deflectChance = deflectStrings[0]; deflectChanceLucky = deflectStrings[1];
deflectChanceLucky = deflectStrings[1];
}
// IRON ARM // IRON ARM
if (canBonusDamage) { if (skillValue >= ((Unarmed.ironArmMaxBonusDamage - 3) * Unarmed.ironArmIncreaseLevel)) {
ironArmBonus = Math.min(3 + ((int) skillValue / Unarmed.ironArmIncreaseLevel), Unarmed.ironArmMaxBonusDamage); ironArmBonus = String.valueOf(Unarmed.ironArmMaxBonusDamage);
}
else {
ironArmBonus = String.valueOf(3 + (skillValue / Unarmed.ironArmIncreaseLevel));
} }
// IRON GRIP // IRON GRIP
if (canIronGrip) { String[] ironGripStrings = calculateAbilityDisplayValues(Unarmed.ironGripMaxBonusLevel, Unarmed.ironGripMaxChance);
String[] ironGripStrings = calculateAbilityDisplayValues(Unarmed.ironGripMaxBonusLevel, Unarmed.ironGripMaxChance); ironGripChance = ironGripStrings[0];
ironGripChance = ironGripStrings[0]; ironGripChanceLucky = ironGripStrings[1];
ironGripChanceLucky = ironGripStrings[1];
}
} }
@Override @Override
@@ -113,19 +108,39 @@ public class UnarmedCommand extends SkillCommand {
} }
if (canDeflect) { if (canDeflect) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.ArrowDeflect", deflectChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", deflectChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.ArrowDeflect", deflectChance) + LocaleLoader.getString("Perks.lucky.bonus", deflectChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.ArrowDeflect", deflectChance));
}
} }
if (canDisarm) { if (canDisarm) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.Disarm", disarmChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", disarmChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.Disarm", disarmChance) + LocaleLoader.getString("Perks.lucky.bonus", disarmChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.Disarm", disarmChance));
}
} }
if (canIronGrip) { if (canIronGrip) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", ironGripChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + LocaleLoader.getString("Perks.lucky.bonus", ironGripChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance));
}
} }
if (canBerserk) { if (canBerserk) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Berserk.Length", berserkLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", berserkLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Berserk.Length", berserkLength) + LocaleLoader.getString("Perks.activationtime.bonus", berserkLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Unarmed.Ability.Berserk.Length", berserkLength));
}
} }
} }
} }

View File

@@ -15,6 +15,7 @@ public class WoodcuttingCommand extends SkillCommand {
private boolean canTreeFell; private boolean canTreeFell;
private boolean canLeafBlow; private boolean canLeafBlow;
private boolean canDoubleDrop; private boolean canDoubleDrop;
private boolean doubleDropsDisabled;
public WoodcuttingCommand() { public WoodcuttingCommand() {
super(SkillType.WOODCUTTING); super(SkillType.WOODCUTTING);
@@ -23,30 +24,27 @@ public class WoodcuttingCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// TREE FELLER // TREE FELLER
if (canTreeFell) { String[] treeFellerStrings = calculateLengthDisplayValues();
String[] treeFellerStrings = calculateLengthDisplayValues(); treeFellerLength = treeFellerStrings[0];
treeFellerLength = treeFellerStrings[0]; treeFellerLengthEndurance = treeFellerStrings[1];
treeFellerLengthEndurance = treeFellerStrings[1];
}
// DOUBLE DROPS // DOUBLE DROPS
if (canDoubleDrop) { String[] doubleDropStrings = calculateAbilityDisplayValues(Woodcutting.doubleDropsMaxLevel, Woodcutting.doubleDropsMaxChance);
String[] doubleDropStrings = calculateAbilityDisplayValues(Woodcutting.doubleDropsMaxLevel, Woodcutting.doubleDropsMaxChance); doubleDropChance = doubleDropStrings[0];
doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1];
doubleDropChanceLucky = doubleDropStrings[1];
}
} }
@Override @Override
protected void permissionsCheck() { protected void permissionsCheck() {
canTreeFell = Permissions.treeFeller(player); canTreeFell = Permissions.treeFeller(player);
canDoubleDrop = Permissions.doubleDrops(player, skill) && !skill.getDoubleDropsDisabled(); canDoubleDrop = Permissions.doubleDrops(player, skill);
canLeafBlow = Permissions.leafBlower(player); canLeafBlow = Permissions.leafBlower(player);
doubleDropsDisabled = skill.getDoubleDropsDisabled();
} }
@Override @Override
protected boolean effectsHeaderPermissions() { protected boolean effectsHeaderPermissions() {
return canDoubleDrop || canLeafBlow || canTreeFell; return (canDoubleDrop && !doubleDropsDisabled) || canLeafBlow || canTreeFell;
} }
@Override @Override
@@ -61,14 +59,14 @@ public class WoodcuttingCommand extends SkillCommand {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Woodcutting.Effect.2"), LocaleLoader.getString("Woodcutting.Effect.3"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Woodcutting.Effect.2"), LocaleLoader.getString("Woodcutting.Effect.3")));
} }
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Woodcutting.Effect.4"), LocaleLoader.getString("Woodcutting.Effect.5"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Woodcutting.Effect.4"), LocaleLoader.getString("Woodcutting.Effect.5")));
} }
} }
@Override @Override
protected boolean statsHeaderPermissions() { protected boolean statsHeaderPermissions() {
return canDoubleDrop || canLeafBlow || canTreeFell; return (canDoubleDrop && !doubleDropsDisabled) || canLeafBlow || canTreeFell;
} }
@Override @Override
@@ -84,12 +82,22 @@ public class WoodcuttingCommand extends SkillCommand {
} }
} }
if (canDoubleDrop) { if (canDoubleDrop && !doubleDropsDisabled) {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Chance.DDrop", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky) : "")); if (isLucky) {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Chance.DDrop", doubleDropChance) + LocaleLoader.getString("Perks.lucky.bonus", doubleDropChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Chance.DDrop", doubleDropChance));
}
} }
if (canTreeFell) { if (canTreeFell) {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Length", treeFellerLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", treeFellerLengthEndurance) : "")); if (hasEndurance) {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Length", treeFellerLength) + LocaleLoader.getString("Perks.activationtime.bonus", treeFellerLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Woodcutting.Ability.Length", treeFellerLength));
}
} }
} }
} }

View File

@@ -1,41 +1,12 @@
package com.gmail.nossr50.commands.spout; package com.gmail.nossr50.commands.spout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.spout.huds.HudType; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.google.common.collect.ImmutableList;
public class MchudCommand extends SpoutCommand { public class MchudCommand extends SpoutCommand {
private static final List<String> HUD_TYPES;
static {
ArrayList<String> types = new ArrayList<String>();
for (HudType type : HudType.values()) {
types.add(type.toString());
}
Collections.sort(types);
HUD_TYPES = ImmutableList.copyOf(types);
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], HUD_TYPES, new ArrayList<String>(HUD_TYPES.size()));
default:
return ImmutableList.of();
}
}
@Override @Override
protected boolean noArguments(Command command, CommandSender sender, String[] args) { protected boolean noArguments(Command command, CommandSender sender, String[] args) {
return false; return false;
@@ -43,15 +14,16 @@ public class MchudCommand extends SpoutCommand {
@Override @Override
protected boolean oneArgument(Command command, CommandSender sender, String[] args) { protected boolean oneArgument(Command command, CommandSender sender, String[] args) {
try { for (HudType hudType : HudType.values()) {
playerProfile.setHudType(HudType.valueOf(args[0].toUpperCase().trim())); if (hudType.toString().equalsIgnoreCase(args[0])) {
spoutHud.initializeXpBar(); playerProfile.setHudType(hudType);
spoutHud.updateXpBar(); spoutHud.initializeXpBar();
return true; spoutHud.updateXpBar();
} return true;
catch (IllegalArgumentException ex) { }
sender.sendMessage(LocaleLoader.getString("Commands.mchud.Invalid"));
return true;
} }
sender.sendMessage(LocaleLoader.getString("Commands.mchud.Invalid"));
return true;
} }
} }

View File

@@ -1,8 +1,8 @@
package com.gmail.nossr50.commands.spout; package com.gmail.nossr50.commands.spout;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@@ -13,7 +13,7 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public abstract class SpoutCommand implements TabExecutor { public abstract class SpoutCommand implements CommandExecutor {
protected PlayerProfile playerProfile; protected PlayerProfile playerProfile;
protected McMMOHud spoutHud; protected McMMOHud spoutHud;
@@ -23,7 +23,7 @@ public abstract class SpoutCommand implements TabExecutor {
return true; return true;
} }
if (!mcMMO.isSpoutEnabled() || !SpoutConfig.getInstance().getXPBarEnabled()) { if (!mcMMO.spoutEnabled || !SpoutConfig.getInstance().getXPBarEnabled()) {
sender.sendMessage(LocaleLoader.getString("Commands.Disabled")); sender.sendMessage(LocaleLoader.getString("Commands.Disabled"));
return true; return true;
} }

View File

@@ -1,36 +1,14 @@
package com.gmail.nossr50.commands.spout; package com.gmail.nossr50.commands.spout;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList;
public class XplockCommand extends SpoutCommand { public class XplockCommand extends SpoutCommand {
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
List<String> matches = StringUtil.copyPartialMatches(args[0], CommandUtils.TRUE_FALSE_OPTIONS, new ArrayList<String>(CommandUtils.TRUE_FALSE_OPTIONS.size()));
if (matches.size() == 0) {
return StringUtil.copyPartialMatches(args[0], SkillType.SKILL_NAMES, new ArrayList<String>(SkillType.SKILL_NAMES.size()));
}
return matches;
default:
return ImmutableList.of();
}
}
@Override @Override
protected boolean noArguments(Command command, CommandSender sender, String[] args) { protected boolean noArguments(Command command, CommandSender sender, String[] args) {
if (spoutHud.getXpBarLocked()) { if (spoutHud.getXpBarLocked()) {
@@ -44,23 +22,25 @@ public class XplockCommand extends SpoutCommand {
@Override @Override
protected boolean oneArgument(Command command, CommandSender sender, String[] args) { protected boolean oneArgument(Command command, CommandSender sender, String[] args) {
if (CommandUtils.shouldEnableToggle(args[0])) { if (args[0].equalsIgnoreCase("on")) {
lockXpBar(sender, spoutHud.getLastGained()); lockXpBar(sender, spoutHud.getLastGained());
return true; return true;
} }
if (CommandUtils.shouldDisableToggle(args[0])) { if (args[0].equalsIgnoreCase("off")) {
unlockXpBar(sender); unlockXpBar(sender);
return true; return true;
} }
if (CommandUtils.isInvalidSkill(sender, args[0])) { if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true; return true;
} }
SkillType skill = SkillType.getSkill(args[0]); SkillType skill = SkillType.getSkill(args[0]);
if (CommandUtils.isChildSkill(sender, skill)) { if (skill.isChildSkill()) {
sender.sendMessage("Child skills are not yet supported by this command."); // TODO: Localize this
return true; return true;
} }

View File

@@ -20,10 +20,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/* GENERAL */ /* GENERAL */
public int getAbilityLength() { return config.getInt("Skills.General.Ability_IncreaseLevel", 50); } public int getAbilityLength() { return config.getInt("Skills.General.Ability_IncreaseLevel", 50); }
public int getEnchantBuff() { public int getEnchantBuff() { return config.getInt("Skills.General.Ability_EnchantBuff", 5); }
int buff = config.getInt("Skills.General.Ability_EnchantBuff", 5);
return (buff <= 0) ? 1 : buff;
}
/* ACROBATICS */ /* ACROBATICS */
public double getDodgeChanceMax() { return config.getDouble("Skills.Acrobatics.Dodge_ChanceMax", 20.0D); } public double getDodgeChanceMax() { return config.getDouble("Skills.Acrobatics.Dodge_ChanceMax", 20.0D); }
@@ -37,6 +34,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getGracefulRollChanceMax() { return config.getDouble("Skills.Acrobatics.GracefulRoll_ChanceMax", 100.0D); } public double getGracefulRollChanceMax() { return config.getDouble("Skills.Acrobatics.GracefulRoll_ChanceMax", 100.0D); }
public int getGracefulRollMaxBonusLevel() { return config.getInt("Skills.Acrobatics.GracefulRoll_MaxBonusLevel", 500); } public int getGracefulRollMaxBonusLevel() { return config.getInt("Skills.Acrobatics.GracefulRoll_MaxBonusLevel", 500); }
public int getGracefulRollDamageThreshold() { return config.getInt("Skills.Acrobatics.GracefulRoll_DamageThreshold", 14); } public int getGracefulRollDamageThreshold() { return config.getInt("Skills.Acrobatics.GracefulRoll_DamageThreshold", 14); }
public int getGracefulRollSuccessModifer() { return config.getInt("Skills.Acrobatics.GracefulRoll_SuccessModifier", 2); }
public int getDodgeXPModifier() { return config.getInt("Skills.Acrobatics.Dodge_XP_Modifier", 120); } public int getDodgeXPModifier() { return config.getInt("Skills.Acrobatics.Dodge_XP_Modifier", 120); }
public int getRollXPModifier() { return config.getInt("Skills.Acrobatics.Roll_XP_Modifier", 80); } public int getRollXPModifier() { return config.getInt("Skills.Acrobatics.Roll_XP_Modifier", 80); }
@@ -54,8 +52,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getRetrieveChanceMax() { return config.getDouble("Skills.Archery.Retrieve_MaxBonus", 100.0D); } public double getRetrieveChanceMax() { return config.getDouble("Skills.Archery.Retrieve_MaxBonus", 100.0D); }
public int getRetrieveMaxBonusLevel() { return config.getInt("Skills.Archery.Retrieve_MaxBonusLevel", 1000); } public int getRetrieveMaxBonusLevel() { return config.getInt("Skills.Archery.Retrieve_MaxBonusLevel", 1000); }
public double getForceMultiplier() { return config.getDouble("Skills.Archery.Force_Multiplier", 2.0D); }
/* AXES */ /* AXES */
public int getBonusDamageAxesBonusMax() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonus", 4); } public int getBonusDamageAxesBonusMax() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonus", 4); }
public int getBonusDamageAxesMaxBonusLevel() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonusLevel", 200); } public int getBonusDamageAxesMaxBonusLevel() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonusLevel", 200); }
@@ -89,8 +85,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.Fisherman_Diet_RankChange", 200); } public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.Fisherman_Diet_RankChange", 200); }
public int getIceFishingUnlockLevel() { return config.getInt("Skills.Fishing.Ice_Fishing_UnlockLevel", 50); }
/* Shake */ /* Shake */
public int getShakeUnlockLevel() { return config.getInt("Skills.Fishing.Shake_UnlockLevel", 150); } public int getShakeUnlockLevel() { return config.getInt("Skills.Fishing.Shake_UnlockLevel", 150); }
public int getShakeChanceRank1() { return config.getInt("Skills.Fishing.Shake_Chance.Rank_1", 25); } public int getShakeChanceRank1() { return config.getInt("Skills.Fishing.Shake_Chance.Rank_1", 25); }
@@ -180,38 +174,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getBlastRadiusModifierRank7() { return config.getDouble("Skills.Mining.BlastRadiusModifier_Rank7", 4.0); } public double getBlastRadiusModifierRank7() { return config.getDouble("Skills.Mining.BlastRadiusModifier_Rank7", 4.0); }
public double getBlastRadiusModifierRank8() { return config.getDouble("Skills.Mining.BlastRadiusModifier_Rank8", 4.0); } public double getBlastRadiusModifierRank8() { return config.getDouble("Skills.Mining.BlastRadiusModifier_Rank8", 4.0); }
/* RANCHING */
public int getMultipleBirthIncreasekLevel() { return config.getInt("Skills.Ranching.MultipleBirth_IncreaseLevel", 50); }
public int getMultipleBirthMaxChance() { return config.getInt("Skills.Ranching.MultipleBirth_ChanceMax", 30); }
public int getMultipleBirthLitterModifier() { return config.getInt("Skills.Ranching.MultipleBirth_LitterModifier", 30); }
public int getMasterHerderIncreaseLevel() { return config.getInt("Skills.Ranching.MultipleBirth_IncreaseLevel", 50); }
public int getMasterHerderMaxLevel() { return config.getInt("Skills.Ranching.MultipleBirth_MaxBonusLevel", 500); }
public int getMasterHerderMinimumSeconds() { return config.getInt("Skills.Ranching.MultipleBirth_MinimumSeconds", 120); }
public int getShearsMasteryMaxLevel() { return config.getInt("Skills.Ranching.ShearsMastery_MaxBonusLevel", 500); }
public int getShearsMasteryMaxChance() { return config.getInt("Skills.Ranching.ShearsMastery_ChanceMax", 20); }
public int getShearsMasteryMaxBonus() { return config.getInt("Skills.Ranching.ShearsMastery_MaxBonus", 3); }
public int getArtisanButcherMaxLevel() { return config.getInt("Skills.Ranching.ArtisanButcher_MaxBonusLevel", 500); }
public int getArtisanButcherMaxChance() { return config.getInt("Skills.Ranching.ArtisanButcher_ChanceMax", 20); }
public int getArtisanButcherMaxBonus() { return config.getInt("Skills.Ranching.ArtisanButcher_MaxBonus", 3); }
public int getCarnivoresDietRankChange() { return config.getInt("Skills.Ranching.Carnivores_Diet_RankChange", 200); }
public int getRanchingVanillaXPBoostRank1Level() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank1Level", 100); }
public int getRanchingVanillaXPBoostRank2Level() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank2Level", 300); }
public int getRanchingVanillaXPBoostRank3Level() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank3Level", 500); }
public int getRanchingVanillaXPBoostRank4Level() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank4Level", 700); }
public int getRanchingVanillaXPBoostRank5Level() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank5Level", 900); }
public int getRanchingVanillaXPBoostRank1Multiplier() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank1Multiplier", 2); }
public int getRanchingVanillaXPBoostRank2Multiplier() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank2Multiplier", 3); }
public int getRanchingVanillaXPBoostRank3Multiplier() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank3Multiplier", 4); }
public int getRanchingVanillaXPBoostRank4Multiplier() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank4Multiplier", 5); }
public int getRanchingVanillaXPBoostRank5Multiplier() { return config.getInt("Skills.Ranching.VanillaXPBoost_Rank5Multiplier", 6); }
/* REPAIR */ /* REPAIR */
public double getRepairMasteryMaxBonus() { return config.getDouble("Skills.Repair.RepairMastery_MaxBonusPercentage", 200.0D); } public double getRepairMasteryMaxBonus() { return config.getDouble("Skills.Repair.RepairMastery_MaxBonusPercentage", 200.0D); }
public int getRepairMasteryMaxLevel() { return config.getInt("Skills.Repair.RepairMastery_MaxBonusLevel", 1000); } public int getRepairMasteryMaxLevel() { return config.getInt("Skills.Repair.RepairMastery_MaxBonusLevel", 1000); }
@@ -311,17 +273,9 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getWoodcuttingDoubleDropChance() { return config.getDouble("Skills.Woodcutting.DoubleDrops_ChanceMax", 100.0D); } public double getWoodcuttingDoubleDropChance() { return config.getDouble("Skills.Woodcutting.DoubleDrops_ChanceMax", 100.0D); }
public int getWoodcuttingDoubleDropMaxLevel() { return config.getInt("Skills.Woodcutting.DoubleDrops_MaxBonusLevel", 1000); } public int getWoodcuttingDoubleDropMaxLevel() { return config.getInt("Skills.Woodcutting.DoubleDrops_MaxBonusLevel", 1000); }
/* KRAKEN STUFF */ /* SPOUT STUFF*/
public boolean getKrakenEnabled() { return config.getBoolean("Kraken.Enabled", true); } public int getSpoutNotificationTier1() { return config.getInt("Spout.Notifications.Tier1", 200); }
public boolean getKrakenGlobalSoundsEnabled() { return config.getBoolean("Kraken.Global_Sounds", true); } public int getSpoutNotificationTier2() { return config.getInt("Spout.Notifications.Tier2", 400); }
public boolean getKrakenEscapeAllowed() { return config.getBoolean("Kraken.Allow_Escaping", false); } public int getSpoutNotificationTier3() { return config.getInt("Spout.Notifications.Tier3", 600); }
public int getKrakenTriesBeforeRelease() { return config.getInt("Kraken.Tries_Before_Release", 50); } public int getSpoutNotificationTier4() { return config.getInt("Spout.Notifications.Tier4", 800); }
public int getKrakenHealth() { return config.getInt("Kraken.Health", 50); }
public String getKrakenName() { return config.getString("Kraken.Name", "The Kraken"); }
public String getServerUnleashMessage() { return config.getString("Kraken.Unleashed_Message.Server", "(PLAYER) has unleashed the kraken!"); }
public String getPlayerUnleashMessage() { return config.getString("Kraken.Unleashed_Message.Player", "THE KRAKEN HAS BEEN UNLEASHED!"); }
public String getPlayerDefeatMessage() { return config.getString("Kraken.Defeated_Message.Killed", "You have slain the kraken!"); }
public String getPlayerEscapeMessage() { return config.getString("Kraken.Defeated_Message.Escape", "You have escaped from the kraken!"); }
public int getKrakenAttackInterval() { return config.getInt("Kraken.Attack_Interval_Seconds", 1); }
public int getKrakenAttackDamage() { return config.getInt("Kraken.Attack_Damage", 1); }
} }

View File

@@ -6,7 +6,6 @@ import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
@@ -49,36 +48,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getPartyDisplayNames() { return config.getBoolean("Commands.p.Use_Display_Names", true); } public boolean getPartyDisplayNames() { return config.getBoolean("Commands.p.Use_Display_Names", true); }
public boolean getAdminDisplayNames() { return config.getBoolean("Commands.a.Use_Display_Names", true); } public boolean getAdminDisplayNames() { return config.getBoolean("Commands.a.Use_Display_Names", true); }
/* Mob Healthbar */
public MobHealthbarType getMobHealthbarDefault() {
try {
return MobHealthbarType.valueOf(config.getString("Mob_Healthbar.Display_Type", "HEARTS").toUpperCase().trim());
}
catch (IllegalArgumentException ex) {
return MobHealthbarType.HEARTS;
}
}
public int getMobHealthbarTime() { return config.getInt("Mob_Healthbar.Display_Time", 3); }
/* Scoreboards */
public boolean getMcrankScoreboardEnabled() { return config.getBoolean("Scoreboards.Mcrank.Use", true); }
public int getMcrankScoreboardTime() { return config.getInt("Scoreboards.Mcrank.Display_Time", 10); }
public boolean getMcstatsScoreboardsEnabled() { return config.getBoolean("Scoreboards.Mcstats.Use", true); }
public int getMcstatsScoreboardTime() { return config.getInt("Scoreboards.Mcstats.Display_Time", 10); }
public boolean getMctopScoreboardEnabled() { return config.getBoolean("Scoreboards.Mctop.Use", true); }
public int getMctopScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); }
public boolean getInspectScoreboardEnabled() { return config.getBoolean("Scoreboards.Inspect.Use", true); }
public int getInspectScoreboardTime() { return config.getInt("Scoreboards.Inspect.Display_Time", 10); }
public boolean getSkillScoreboardEnabled() { return config.getBoolean("Scoreboards.Skillname.Use", true); }
public int getSkillScoreboardTime() { return config.getInt("Scoreboards.Skillname.Display_Time", 10); }
public boolean getPowerLevelsEnabled() { return config.getBoolean("Scoreboards.Power_Level.Use", false); }
/* Database Purging */ /* Database Purging */
public int getPurgeInterval() { return config.getInt("Database_Purging.Purge_Interval", -1); } public int getPurgeInterval() { return config.getInt("Database_Purging.Purge_Interval", -1); }
public int getOldUsersCutoff() { return config.getInt("Database_Purging.Old_User_Cutoff", 6); } public int getOldUsersCutoff() { return config.getInt("Database_Purging.Old_User_Cutoff", 6); }
@@ -138,8 +107,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); } public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); }
public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); } public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); }
public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); } public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); }
public int getChimaeraWarmup() { return config.getInt("Items.Chimaera_Wing.Warmup", 5); }
public int getChimaeraRecentlyHurtCooldown() { return config.getInt("Items.Chimaera_Wing.RecentlyHurt_Cooldown", 60); }
/* Particles */ /* Particles */
public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); } public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); }
@@ -147,9 +114,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); } public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); }
public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); } public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); }
public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); } public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); }
public boolean getLevelUpEffectsEnabled() { return config.getBoolean("Particles.LevelUp_Enabled", true); }
public int getLevelUpEffectsTier() { return config.getInt("Particles.LevelUp_Tier", 100); }
public boolean getLargeFireworks() { return config.getBoolean("Particles.LargeFireworks", true); }
/* PARTY SETTINGS */ /* PARTY SETTINGS */
public int getAutoPartyKickInterval() { return config.getInt("Party.AutoKick_Interval", 12); } public int getAutoPartyKickInterval() { return config.getInt("Party.AutoKick_Interval", 12); }
@@ -162,16 +126,11 @@ public class Config extends AutoUpdateConfigLoader {
public double getPartyShareRange() { return config.getDouble("Party.Sharing.Range", 75.0); } public double getPartyShareRange() { return config.getDouble("Party.Sharing.Range", 75.0); }
/* Party Teleport Settings */ /* Party Teleport Settings */
public int getPTPCommandCooldown() { return config.getInt("Commands.ptp.Cooldown", 120); } public int getPTPCommandCooldown() { return config.getInt("Commands.ptp.Cooldown", 30); }
public int getPTPCommandWarmup() { return config.getInt("Commands.ptp.Warmup", 5); }
public int getPTPCommandRecentlyHurtCooldown() { return config.getInt("Commands.ptp.RecentlyHurt_Cooldown", 60); }
public int getPTPCommandTimeout() { return config.getInt("Commands.ptp.Request_Timeout", 300); } public int getPTPCommandTimeout() { return config.getInt("Commands.ptp.Request_Timeout", 300); }
public boolean getPTPCommandConfirmRequired() { return config.getBoolean("Commands.ptp.Confirm_Required", true); } public boolean getPTPCommandConfirmRequired() { return config.getBoolean("Commands.ptp.Confirm_Required", true); }
public boolean getPTPCommandWorldPermissions() { return config.getBoolean("Commands.ptp.World_Based_Permissions", false); } public boolean getPTPCommandWorldPermissions() { return config.getBoolean("Commands.ptp.World_Based_Permissions", false); }
/* Inspect command distance */
public double getInspectDistance() { return config.getDouble("Commands.inspect.Max_Distance", 30); }
/* /*
* ABILITY SETTINGS * ABILITY SETTINGS
*/ */
@@ -230,7 +189,6 @@ public class Config extends AutoUpdateConfigLoader {
public int getSalvageAnvilId() { return config.getInt("Skills.Repair.Salvage_Anvil_ID", 41); } public int getSalvageAnvilId() { return config.getInt("Skills.Repair.Salvage_Anvil_ID", 41); }
public boolean getSalvageTools() { return config.getBoolean("Skills.Repair.Salvage_tools", true); } public boolean getSalvageTools() { return config.getBoolean("Skills.Repair.Salvage_tools", true); }
public boolean getSalvageArmor() { return config.getBoolean("Skills.Repair.Salvage_armor", true); } public boolean getSalvageArmor() { return config.getBoolean("Skills.Repair.Salvage_armor", true); }
public boolean getRepairConfirmRequired() { return config.getBoolean("Skills.Repair.Confirm_Required", true); }
/* Unarmed */ /* Unarmed */
public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); } public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); }
@@ -278,6 +236,7 @@ public class Config extends AutoUpdateConfigLoader {
*/ */
/* General Settings */ /* General Settings */
public boolean getExperienceGainsMobspawnersEnabled() { return config.getBoolean("Experience.Gains.Mobspawners.Enabled", false); }
public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience.PVP.Rewards", true); } public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience.PVP.Rewards", true); }
public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience.Gains.Multiplier.Global", 1.0); } public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience.Gains.Multiplier.Global", 1.0); }
@@ -290,9 +249,8 @@ public class Config extends AutoUpdateConfigLoader {
public double getAnimalsXP() { return config.getDouble("Experience.Combat.Multiplier.Animals", 1.0); } public double getAnimalsXP() { return config.getDouble("Experience.Combat.Multiplier.Animals", 1.0); }
public double getWitherSkeletonXP() { return config.getDouble("Experience.Combat.Multiplier.Wither_Skeleton", 4.0); } public double getWitherSkeletonXP() { return config.getDouble("Experience.Combat.Multiplier.Wither_Skeleton", 4.0); }
public double getSpawnedMobXpMultiplier() { return config.getDouble("Experience.Gains.Mobspawners.Multiplier", 0.0); }
/* XP Formula Multiplier */ /* XP Formula Multiplier */
public int getFormulaMultiplierCurve() { return config.getInt("Experience.Formula.Curve_Modifier", 20); } public int getFormulaMultiplierCurve() { return config.getInt("Experience.Formula.Curve_Modifier", 20); }
public double getFormulaSkillModifier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); } public double getForumulaMultiplier(SkillType skill) { return config.getDouble("Experience.Formula.Multiplier." + StringUtils.getCapitalized(skill.toString())); }
} }

View File

@@ -1,9 +1,7 @@
package com.gmail.nossr50.config; package com.gmail.nossr50.config;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@@ -32,11 +30,11 @@ public abstract class ConfigLoader {
protected void loadFile() { protected void loadFile() {
if (!configFile.exists()) { if (!configFile.exists()) {
plugin.debug("Creating mcMMO " + fileName + " File..."); plugin.getLogger().info("Creating mcMMO " + fileName + " File...");
createFile(); createFile();
} }
else { else {
plugin.debug("Loading mcMMO " + fileName + " File..."); plugin.getLogger().info("Loading mcMMO " + fileName + " File...");
} }
config = YamlConfiguration.loadConfiguration(configFile); config = YamlConfiguration.loadConfiguration(configFile);
@@ -45,49 +43,38 @@ public abstract class ConfigLoader {
protected abstract void loadKeys(); protected abstract void loadKeys();
protected void createFile() { protected void createFile() {
if (configFile.exists()) {
return;
}
configFile.getParentFile().mkdirs(); configFile.getParentFile().mkdirs();
InputStream inputStream = plugin.getResource(fileName); InputStream inputStream = plugin.getResource(fileName);
if (inputStream == null) { if (inputStream != null) {
plugin.getLogger().severe("Missing resource file: '" + fileName + "' please notify the plugin authors");
return;
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(configFile);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (outputStream != null) {
try {
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
try { try {
inputStream.close(); copyStreamToFile(inputStream, configFile);
} }
catch (IOException e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
else {
plugin.getLogger().severe("Missing resource file: '" + fileName + "' please notify the plugin authors");
}
}
private static void copyStreamToFile(InputStream inputStream, File file) throws Exception {
OutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
inputStream.close();
outputStream.close();
} }
} }

View File

@@ -11,7 +11,6 @@ public class HiddenConfig {
private static boolean chunkletsEnabled; private static boolean chunkletsEnabled;
private static int conversionRate; private static int conversionRate;
private static boolean useEnchantmentBuffs; private static boolean useEnchantmentBuffs;
private static boolean resendChunksAfterBlockAbility;
public HiddenConfig(String fileName) { public HiddenConfig(String fileName) {
HiddenConfig.fileName = fileName; HiddenConfig.fileName = fileName;
@@ -32,7 +31,6 @@ public class HiddenConfig {
chunkletsEnabled = config.getBoolean("Options.Chunklets", true); chunkletsEnabled = config.getBoolean("Options.Chunklets", true);
conversionRate = config.getInt("Options.ConversionRate", 1); conversionRate = config.getInt("Options.ConversionRate", 1);
useEnchantmentBuffs = config.getBoolean("Options.EnchantmentBuffs", true); useEnchantmentBuffs = config.getBoolean("Options.EnchantmentBuffs", true);
resendChunksAfterBlockAbility = config.getBoolean("Options.RefreshChunks", false);
} }
} }
@@ -47,8 +45,4 @@ public class HiddenConfig {
public boolean useEnchantmentBuffs() { public boolean useEnchantmentBuffs() {
return useEnchantmentBuffs; return useEnchantmentBuffs;
} }
public boolean resendChunksAfterBlockAbility() {
return resendChunksAfterBlockAbility;
}
} }

View File

@@ -1,7 +1,5 @@
package com.gmail.nossr50.config.party; package com.gmail.nossr50.config.party;
import java.util.HashSet;
import org.bukkit.Material; import org.bukkit.Material;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
@@ -23,20 +21,13 @@ public class ItemWeightConfig extends ConfigLoader {
} }
public int getItemWeight(Material material) { public int getItemWeight(Material material) {
return config.getInt("Item_Weights." + StringUtils.getPrettyItemString(material).replace(" ", "_"), config.getInt("Item_Weights.Default")); String materialName = StringUtils.getPrettyItemString(material).replace(" ", "_");
} int itemWeight = config.getInt("Item_Weights.Default");
public HashSet<Material> getMiscItems() { if (config.getInt("Item_Weights." + materialName) > 0) {
HashSet<Material> miscItems = new HashSet<Material>(); itemWeight = config.getInt("Item_Weights." + materialName);
for (String item : config.getStringList("Party_Shareables.Misc_Items")) {
Material material = Material.getMaterial(item.toUpperCase());
if (material != null) {
miscItems.add(material);
}
} }
return miscItems; return itemWeight;
} }
@Override @Override

View File

@@ -1,16 +1,16 @@
package com.gmail.nossr50.config.spout; package com.gmail.nossr50.config.spout;
import org.getspout.spoutapi.keyboard.Keyboard;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.spout.huds.HudType; import com.gmail.nossr50.datatypes.spout.huds.HudType;
public class SpoutConfig extends ConfigLoader { public class SpoutConfig extends ConfigLoader {
private static SpoutConfig instance; private static SpoutConfig instance;
public HudType defaultHudType;
private SpoutConfig() { private SpoutConfig() {
super("spout.yml"); super("spout.yml");
loadKeys();
} }
public static SpoutConfig getInstance() { public static SpoutConfig getInstance() {
@@ -24,26 +24,22 @@ public class SpoutConfig extends ConfigLoader {
@Override @Override
protected void loadKeys() { protected void loadKeys() {
// Setup default HUD // Setup default HUD
} String temp = config.getString("Spout.HUD.Default", "STANDARD");
public HudType getDefaultHudType() { for (HudType hudType : HudType.values()) {
try { if (hudType.toString().equalsIgnoreCase(temp)) {
return HudType.valueOf(config.getString("Spout.HUD.Default", "STANDARD").toUpperCase().trim()); defaultHudType = hudType;
break;
}
} }
catch (IllegalArgumentException ex) {
return HudType.STANDARD; if (defaultHudType == null) {
defaultHudType = HudType.STANDARD;
} }
} }
public boolean getShowPowerLevel() { return config.getBoolean("HUD.Show_Power_Level", true); } public boolean getShowPowerLevel() { return config.getBoolean("HUD.Show_Power_Level", true); }
public Keyboard getMenuKey() { public String getMenuKey() { return config.getString("Menu.Key", "KEY_M"); }
try {
return Keyboard.valueOf(config.getString("Menu.Key", "KEY_M").toUpperCase().trim());
}
catch (IllegalArgumentException ex) {
return Keyboard.KEY_M;
}
}
/* XP Bar */ /* XP Bar */
public boolean getXPBarEnabled() { return config.getBoolean("XP.Bar.Enabled", true); } public boolean getXPBarEnabled() { return config.getBoolean("XP.Bar.Enabled", true); }
@@ -66,10 +62,4 @@ public class SpoutConfig extends ConfigLoader {
public double getRetroHUDRed(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); } public double getRetroHUDRed(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); }
public double getRetroHUDGreen(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); } public double getRetroHUDGreen(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); }
public double getRetroHUDBlue(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); } public double getRetroHUDBlue(SkillType skill) { return config.getDouble("HUD.Retro.Colors." + skill.toString().toLowerCase() +".RED", 0.3); }
/* Notification Tiers */
public int getNotificationTier1() { return config.getInt("Notifications.Tier1", 200); }
public int getNotificationTier2() { return config.getInt("Notifications.Tier2", 400); }
public int getNotificationTier3() { return config.getInt("Notifications.Tier3", 600); }
public int getNotificationTier4() { return config.getInt("Notifications.Tier4", 800); }
} }

View File

@@ -9,17 +9,13 @@ import java.util.Set;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData; import org.bukkit.material.MaterialData;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionType;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure; import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure;
import com.gmail.nossr50.datatypes.treasure.FishingTreasure; import com.gmail.nossr50.datatypes.treasure.FishingTreasure;
import com.gmail.nossr50.datatypes.treasure.HylianTreasure; import com.gmail.nossr50.datatypes.treasure.HylianTreasure;
import com.gmail.nossr50.datatypes.treasure.ShakeTreasure;
import com.gmail.nossr50.datatypes.treasure.Treasure; import com.gmail.nossr50.datatypes.treasure.Treasure;
public class TreasureConfig extends ConfigLoader { public class TreasureConfig extends ConfigLoader {
@@ -37,27 +33,6 @@ public class TreasureConfig extends ConfigLoader {
public List<HylianTreasure> hylianFromFlowers = new ArrayList<HylianTreasure>(); public List<HylianTreasure> hylianFromFlowers = new ArrayList<HylianTreasure>();
public List<HylianTreasure> hylianFromPots = new ArrayList<HylianTreasure>(); public List<HylianTreasure> hylianFromPots = new ArrayList<HylianTreasure>();
public List<ShakeTreasure> shakeFromBlaze = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCaveSpider = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSpider = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromChicken = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCow = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCreeper = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromEnderman = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromGhast = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromIronGolem = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromMagmaCube = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromMushroomCow = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromPig = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromPigZombie = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSheep = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSkeleton = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSlime = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSnowman = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSquid = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromWitch = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromZombie = new ArrayList<ShakeTreasure>();
public List<FishingTreasure> fishingRewards = new ArrayList<FishingTreasure>(); public List<FishingTreasure> fishingRewards = new ArrayList<FishingTreasure>();
private TreasureConfig() { private TreasureConfig() {
@@ -117,7 +92,7 @@ public class TreasureConfig extends ConfigLoader {
reason.add("Invalid amount: " + amount); reason.add("Invalid amount: " + amount);
} }
if (id < 256 && (data > 127 || data < -128)) { if (data > 127 || data < -128) {
reason.add("Invalid data: " + data); reason.add("Invalid data: " + data);
} }
@@ -153,32 +128,15 @@ public class TreasureConfig extends ConfigLoader {
reason.add("Invalid Drop_Level: " + dropLevel); reason.add("Invalid Drop_Level: " + dropLevel);
} }
/*
* Potions
*/
ItemStack item = null;
if (config.contains("Treasures." + treasureName + ".Potion_Type")) {
String potionType = config.getString("Treasures." + treasureName + ".Potion_Type");
try {
item = new Potion(PotionType.valueOf(potionType.toUpperCase())).toItemStack(amount);
}
catch (IllegalArgumentException ex) {
reason.add("Invalid Potion_Type: " + potionType);
}
}
else {
item = (new MaterialData(id, (byte) data)).toItemStack(amount);
}
/* /*
* Drops From & Max Level * Drops From & Max Level
*/ */
ItemStack item = (new MaterialData(id, (byte) data)).toItemStack(amount);
if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Fishing", false)) { if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Fishing", false)) {
if (config.getConfigurationSection("Treasures." + treasureName + ".Drops_From").getKeys(false).size() != 1) { if (config.getConfigurationSection("Treasures." + treasureName + ".Drops_From").getKeys(false).size() != 1) {
reason.add("This can only be a fishing drop."); reason.add("Fishing drops cannot also be excavation drops");
} }
if (!config.contains("Treasures." + treasureName + ".Max_Level")) { if (!config.contains("Treasures." + treasureName + ".Max_Level")) {
@@ -192,30 +150,6 @@ public class TreasureConfig extends ConfigLoader {
treasures.put(treasureName, fTreasure); treasures.put(treasureName, fTreasure);
} }
} }
else if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Shake", false)) {
if (config.getConfigurationSection("Treasures." + treasureName + ".Drops_From").getKeys(false).size() != 1) {
reason.add("This can only be a shake drop.");
}
if (!config.contains("Treasures." + treasureName + ".Mob")) {
reason.add("Missing Mob");
}
String mobType = config.getString("Treasures." + treasureName + ".Mob");
EntityType mob = null;
try {
mob = EntityType.valueOf(mobType.toUpperCase().trim());
}
catch (IllegalArgumentException ex){
reason.add("Invalid Mob: " + mobType);
}
if (noErrorsInTreasure(reason)) {
ShakeTreasure sTreasure = new ShakeTreasure(item, xp, dropChance, dropLevel, mob);
treasures.put(treasureName, sTreasure);
}
}
else { else {
ExcavationTreasure eTreasure = new ExcavationTreasure(item, xp, dropChance, dropLevel); ExcavationTreasure eTreasure = new ExcavationTreasure(item, xp, dropChance, dropLevel);
HylianTreasure hTreasure = new HylianTreasure(item, xp, dropChance, dropLevel); HylianTreasure hTreasure = new HylianTreasure(item, xp, dropChance, dropLevel);
@@ -261,11 +195,7 @@ public class TreasureConfig extends ConfigLoader {
} }
if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Fishing", false)) { if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Fishing", false)) {
reason.add("This cannot also be a fishing drop."); reason.add("Excavation drops cannot also be fishing drops");
}
if (config.getBoolean("Treasures." + treasureName + ".Drops_From.Shake", false)) {
reason.add("This cannot also be a shake drop.");
} }
if (noErrorsInTreasure(reason) && hTreasure.getDropsFrom() == (byte) 0x0) { if (noErrorsInTreasure(reason) && hTreasure.getDropsFrom() == (byte) 0x0) {
@@ -280,7 +210,6 @@ public class TreasureConfig extends ConfigLoader {
List<String> excavationTreasures = config.getStringList("Excavation.Treasure"); List<String> excavationTreasures = config.getStringList("Excavation.Treasure");
List<String> fishingTreasures = config.getStringList("Fishing.Treasure"); List<String> fishingTreasures = config.getStringList("Fishing.Treasure");
List<String> hylianTreasures = config.getStringList("Hylian_Luck.Treasure"); List<String> hylianTreasures = config.getStringList("Hylian_Luck.Treasure");
List<String> shakeTreasures = config.getStringList("Shake.Treasure");
for (Entry<String, Treasure> nextEntry : treasures.entrySet()) { for (Entry<String, Treasure> nextEntry : treasures.entrySet()) {
String treasureKey = nextEntry.getKey(); String treasureKey = nextEntry.getKey();
@@ -293,97 +222,6 @@ public class TreasureConfig extends ConfigLoader {
fishingRewards.add((FishingTreasure) treasure); fishingRewards.add((FishingTreasure) treasure);
} }
else if (treasure instanceof ShakeTreasure) {
if (shakeTreasures == null || !shakeTreasures.contains(treasureKey)) {
continue;
}
ShakeTreasure e = (ShakeTreasure) treasure;
switch (e.getMob()) {
case BLAZE:
shakeFromBlaze.add(e);
break;
case CAVE_SPIDER:
shakeFromCaveSpider.add(e);
break;
case CHICKEN:
shakeFromChicken.add(e);
break;
case COW:
shakeFromCow.add(e);
break;
case CREEPER:
shakeFromCreeper.add(e);
break;
case ENDERMAN:
shakeFromEnderman.add(e);
break;
case GHAST:
shakeFromGhast.add(e);
break;
case IRON_GOLEM:
shakeFromIronGolem.add(e);
break;
case MAGMA_CUBE:
shakeFromMagmaCube.add(e);
break;
case MUSHROOM_COW:
shakeFromMushroomCow.add(e);
break;
case PIG:
shakeFromPig.add(e);
break;
case PIG_ZOMBIE:
shakeFromPigZombie.add(e);
break;
case SHEEP:
shakeFromSheep.add(e);
break;
case SKELETON:
shakeFromSkeleton.add(e);
break;
case SLIME:
shakeFromSlime.add(e);
break;
case SPIDER:
shakeFromSpider.add(e);
break;
case SNOWMAN:
shakeFromSnowman.add(e);
break;
case SQUID:
shakeFromSquid.add(e);
break;
case WITCH:
shakeFromWitch.add(e);
break;
case ZOMBIE:
shakeFromZombie.add(e);
break;
default:
break;
}
}
else if (treasure instanceof HylianTreasure) { else if (treasure instanceof HylianTreasure) {
if (hylianTreasures == null || !hylianTreasures.contains(treasureKey)) { if (hylianTreasures == null || !hylianTreasures.contains(treasureKey)) {
continue; continue;
@@ -442,10 +280,13 @@ public class TreasureConfig extends ConfigLoader {
} }
private boolean noErrorsInTreasure(List<String> issues) { private boolean noErrorsInTreasure(List<String> issues) {
if (issues.isEmpty()) {
return true;
}
for (String issue : issues) { for (String issue : issues) {
plugin.getLogger().warning(issue); plugin.getLogger().warning(issue);
} }
return false;
return issues.isEmpty();
} }
} }

View File

@@ -1,89 +1,667 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import java.util.List; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.DatabaseUpdateType;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.runnables.database.SQLReconnectTask;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.spout.SpoutUtils;
public interface DatabaseManager { public final class DatabaseManager {
// One month in milliseconds private static String connectionString;
public final long PURGE_TIME = 2630000000L * Config.getInstance().getOldUsersCutoff();
private static String tablePrefix = Config.getInstance().getMySQLTablePrefix();
private static Connection connection = null;
// Scale waiting time by this much per failed attempt
private static final double SCALING_FACTOR = 40;
// Minimum wait in nanoseconds (default 500ms)
private static final long MIN_WAIT = 500L * 1000000L;
// Maximum time to wait between reconnects (default 5 minutes)
private static final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
// How long to wait when checking if connection is valid (default 3 seconds)
private static final int VALID_TIMEOUT = 3;
// When next to try connecting to Database in nanoseconds
private static long nextReconnectTimestamp = 0L;
// How many connection attempts have failed
private static int reconnectAttempt = 0;
private static final long ONE_MONTH = 2630000000L;
private DatabaseManager() {}
/** /**
* Purge users with 0 power level from the database. * Attempt to connect to the mySQL database.
*/ */
public void purgePowerlessUsers(); public static void connect() {
Config configInstance = Config.getInstance();
connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName();
try {
mcMMO.p.getLogger().info("Attempting connection to MySQL...");
// Force driver to load if not yet loaded
Class.forName("com.mysql.jdbc.Driver");
Properties connectionProperties = new Properties();
connectionProperties.put("user", configInstance.getMySQLUserName());
connectionProperties.put("password", configInstance.getMySQLUserPassword());
connectionProperties.put("autoReconnect", "false");
connectionProperties.put("maxReconnects", "0");
connection = DriverManager.getConnection(connectionString, connectionProperties);
mcMMO.p.getLogger().info("Connection to MySQL was a success!");
}
catch (SQLException ex) {
connection = null;
if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
mcMMO.p.getLogger().info("Connection to MySQL failed!");
}
}
catch (ClassNotFoundException ex) {
connection = null;
if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
mcMMO.p.getLogger().info("MySQL database driver not found!");
}
}
}
/** /**
* Purge users who haven't logged on in over a certain time frame from the database. * Attempt to create the database structure.
*/ */
public void purgeOldUsers(); public static void createStructure() {
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
+ "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`user` varchar(40) NOT NULL,"
+ "`lastlogin` int(32) unsigned NOT NULL,"
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
+ "PRIMARY KEY (`user_id`),"
+ "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
+ "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`),"
+ "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
+ "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`),"
+ "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
+ "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`),"
+ "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
+ "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
checkDatabaseStructure(DatabaseUpdateType.FISHING);
checkDatabaseStructure(DatabaseUpdateType.BLAST_MINING);
checkDatabaseStructure(DatabaseUpdateType.CASCADE_DELETE);
checkDatabaseStructure(DatabaseUpdateType.INDEX);
}
/** /**
* Remove a user from the database. * Attempt to write the SQL query.
* *
* @param playerName The name of the user to remove * @param sql Query to write.
* @return true if the user was successfully removed, false otherwise * @return true if the query was successfully written, false otherwise.
*/ */
public boolean removeUser(String playerName); public static boolean write(String sql) {
if (!checkConnected()) {
return false;
}
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
statement.executeUpdate();
return true;
}
catch (SQLException ex) {
printErrors(ex);
return false;
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
return false;
}
}
}
}
/** /**
* Save a user to the database. * Returns the number of rows affected by either a DELETE or UPDATE query
* *
* @param profile The profile of the player to save * @param sql SQL query to execute
* @return the number of rows affected
*/ */
public void saveUser(PlayerProfile profile); public static int update(String sql) {
int ret = 0;
if (checkConnected()) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
ret = statement.executeUpdate();
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
}
return ret;
}
/** /**
* Retrieve leaderboard info. * Get the Integer. Only return first row / first field.
*
* @param skillName The skill to retrieve info on
* @param pageNumber Which page in the leaderboards to retrieve
* @param statsPerPage The number of stats per page
* @return the requested leaderboard information
*/
public List<PlayerStat> readLeaderboard(String skillName, int pageNumber, int statsPerPage);
/**
* Retrieve rank info.
* *
* @param playerName The name of the user to retrieve the rankings for * @param sql SQL query to execute
* @return the requested rank information * @return the value in the first row / first field
*/ */
public Map<String, Integer> readRank(String playerName); public static int getInt(String sql) {
ResultSet resultSet = null;
int result = 0;
if (checkConnected()) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
result = resultSet.getInt(1);
}
else {
result = 0;
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
}
return result;
}
/** /**
* Add a new user to the database. * Check connection status and re-establish if dead or stale.
* *
* @param playerName The name of the player to be added to the database * If the very first immediate attempt fails, further attempts
* will be made in progressively larger intervals up to MAX_WAIT
* intervals.
*
* This allows for MySQL to time out idle connections as needed by
* server operator, without affecting McMMO, while still providing
* protection against a database outage taking down Bukkit's tick
* processing loop due to attemping a database connection each
* time McMMO needs the database.
*
* @return the boolean value for whether or not we are connected
*/ */
public void newUser(String playerName); public static boolean checkConnected() {
boolean isClosed = true;
boolean isValid = false;
boolean exists = (connection != null);
// If we're waiting for server to recover then leave early
if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
return false;
}
if (exists) {
try {
isClosed = connection.isClosed();
}
catch (SQLException e) {
isClosed = true;
e.printStackTrace();
printErrors(e);
}
if (!isClosed) {
try {
isValid = connection.isValid(VALID_TIMEOUT);
}
catch (SQLException e) {
// Don't print stack trace because it's valid to lose idle connections to the server and have to restart them.
isValid = false;
}
}
}
// Leave if all ok
if (exists && !isClosed && isValid) {
// Housekeeping
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
// Cleanup after ourselves for GC and MySQL's sake
if (exists && !isClosed) {
try {
connection.close();
}
catch (SQLException ex) {
// This is a housekeeping exercise, ignore errors
}
}
// Try to connect again
connect();
// Leave if connection is good
try {
if (connection != null && !connection.isClosed()) {
// Schedule a database save if we really had an outage
if (reconnectAttempt > 1) {
mcMMO.p.getServer().getScheduler().scheduleSyncDelayedTask(mcMMO.p, new SQLReconnectTask(), 5);
}
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
}
catch (SQLException e) {
// Failed to check isClosed, so presume connection is bad and attempt later
e.printStackTrace();
printErrors(e);
}
reconnectAttempt++;
nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt * SCALING_FACTOR * MIN_WAIT)));
return false;
}
/** /**
* Load a player from the database. * Read SQL query.
* *
* @param playerName The name of the player to load from the database * @param sql SQL query to read
* @param createNew Whether to create a new record if the player is not * @return the rows in this SQL query
* found
* @return The player's data, or an unloaded PlayerProfile if not found
* and createNew is false
*/ */
public PlayerProfile loadPlayerProfile(String playerName, boolean createNew); public static HashMap<Integer, ArrayList<String>> read(String sql) {
ResultSet resultSet;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
if (checkConnected()) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
}
rows.put(resultSet.getRow(), column);
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
}
return rows;
}
public static Map<String, Integer> readSQLRank(String playerName) {
ResultSet resultSet;
Map<String, Integer> skills = new HashMap<String, Integer>();
if (checkConnected()) {
try {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
String skillName = skillType.name().toLowerCase();
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = '" + playerName + "')";
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = '" + playerName + "') ORDER BY user";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put(skillType.name(), rank + resultSet.getRow());
break;
}
}
statement.close();
}
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
"AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > " +
"(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "')";
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
"AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing = " +
"(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "') ORDER BY user";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put("ALL", rank + resultSet.getRow());
break;
}
}
statement.close();
}
catch (SQLException ex) {
printErrors(ex);
}
}
return skills;
}
public static void purgePowerlessSQL() {
mcMMO.p.getLogger().info("Purging powerless users...");
HashMap<Integer, ArrayList<String>> usernames;
usernames = read("SELECT u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u " + "WHERE s.user_id = u.id AND " +
"(s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0");
write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM " +
"(SELECT u.id FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u " + "WHERE s.user_id = u.id " +
"AND (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0) AS p)");
int purgedUsers = 0;
for (int i = 1; i <= usernames.size(); i++) {
String playerName = usernames.get(i).get(0);
if (playerName == null || mcMMO.p.getServer().getOfflinePlayer(playerName).isOnline()) {
continue;
}
profileCleanup(playerName);
purgedUsers++;
}
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
public static void purgeOldSQL() {
mcMMO.p.getLogger().info("Purging old users...");
long currentTime = System.currentTimeMillis();
long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
HashMap<Integer, ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")");
write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM (SELECT id FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")) AS p)");
int purgedUsers = 0;
for (int i = 1; i <= usernames.size(); i++) {
String playerName = usernames.get(i).get(0);
if (playerName == null) {
continue;
}
profileCleanup(playerName);
purgedUsers++;
}
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
public static void profileCleanup(String playerName) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName);
if (mcMMOPlayer != null) {
Player player = mcMMOPlayer.getPlayer();
McMMOHud spoutHud = mcMMOPlayer.getProfile().getSpoutHud();
if (spoutHud != null) {
spoutHud.removeWidgets();
}
UserManager.remove(playerName);
if (player.isOnline()) {
UserManager.addUser(player);
if (mcMMO.spoutEnabled) {
SpoutUtils.reloadSpoutPlayer(player);
}
}
}
}
/** /**
* Get all users currently stored in the database. * Check database structure for missing values.
* *
* @return list of playernames * @param update Type of data to check updates for
*/ */
public List<String> getStoredUsers(); private static void checkDatabaseStructure(DatabaseUpdateType update) {
String sql = null;
ResultSet resultSet = null;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
/** switch (update) {
* Convert all users from this database to the provided database using case BLAST_MINING:
* {@link #saveUser(PlayerProfile)}. sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
* break;
* @param the DatabaseManager to save to
*/ case CASCADE_DELETE:
public void convertUsers(DatabaseManager destination); write("ALTER TABLE `" + tablePrefix + "huds` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
write("ALTER TABLE `" + tablePrefix + "experience` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
write("ALTER TABLE `" + tablePrefix + "cooldowns` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
write("ALTER TABLE `" + tablePrefix + "skills` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
break;
case FISHING:
sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
break;
case INDEX:
if (read("SHOW INDEX FROM " + tablePrefix + "skills").size() != 13 && checkConnected()) {
mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
write("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_taming` (`taming`) USING BTREE, "
+ "ADD INDEX `idx_mining` (`mining`) USING BTREE, "
+ "ADD INDEX `idx_woodcutting` (`woodcutting`) USING BTREE, "
+ "ADD INDEX `idx_repair` (`repair`) USING BTREE, "
+ "ADD INDEX `idx_unarmed` (`unarmed`) USING BTREE, "
+ "ADD INDEX `idx_herbalism` (`herbalism`) USING BTREE, "
+ "ADD INDEX `idx_excavation` (`excavation`) USING BTREE, "
+ "ADD INDEX `idx_archery` (`archery`) USING BTREE, "
+ "ADD INDEX `idx_swords` (`swords`) USING BTREE, "
+ "ADD INDEX `idx_axes` (`axes`) USING BTREE, "
+ "ADD INDEX `idx_acrobatics` (`acrobatics`) USING BTREE, "
+ "ADD INDEX `idx_fishing` (`fishing`) USING BTREE;");
}
break;
default:
break;
}
PreparedStatement statement = null;
try {
if (!checkConnected()) {
return;
}
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
}
rows.put(resultSet.getRow(), column);
}
}
catch (SQLException ex) {
switch (update) {
case BLAST_MINING:
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
break;
case FISHING:
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
break;
default:
break;
}
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore the error, we're leaving
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore the error, we're leaving
}
}
}
}
private static void printErrors(SQLException ex) {
mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
}
} }

View File

@@ -1,66 +0,0 @@
package com.gmail.nossr50.database;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
public class DatabaseManagerFactory {
private static Class<? extends DatabaseManager> customManager = null;
public static DatabaseManager getDatabaseManager() {
if (customManager != null) {
try {
return createCustomDatabaseManager(customManager);
} catch (Exception e) {
mcMMO.p.debug("Could not create custom database manager");
e.printStackTrace();
} catch (Throwable e) {
mcMMO.p.debug("Failed to create custom database manager");
e.printStackTrace();
}
mcMMO.p.debug("Falling back on " + (Config.getInstance().getUseMySQL() ? "SQL" : "Flatfile") + " database");
}
return Config.getInstance().getUseMySQL() ? new SQLDatabaseManager() : new FlatfileDatabaseManager();
}
/**
* Sets the custom DatabaseManager class for McMMO to use. This should be
* called prior to mcMMO enabling.
* <p>
* The provided class must have an empty constructor, which is the one
* that will be used.
* <p>
* This method is intended for API use, but it should not be considered
* stable. This method is subject to change and/or removal in future
* versions.
*
* @param man the DatabaseManager class to use
* @throws IllegalArgumentException if the provided class does not have
* an empty constructor
*/
public static void setCustomDatabaseManagerClass(Class<? extends DatabaseManager> clazz) {
try {
clazz.getConstructor((Class<?>) null);
customManager = clazz;
} catch (Throwable e) {
throw new IllegalArgumentException("Provided database manager class must have an empty constructor", e);
}
}
public static Class<? extends DatabaseManager> getCustomDatabaseManagerClass() {
return customManager;
}
// For data conversion purposes
public static FlatfileDatabaseManager createFlatfileDatabaseManager() {
return new FlatfileDatabaseManager();
}
public static SQLDatabaseManager createSQLDatabaseManager() {
return new SQLDatabaseManager();
}
public static DatabaseManager createCustomDatabaseManager(Class<? extends DatabaseManager> clazz) throws Throwable {
return customManager.getConstructor((Class<?>) null).newInstance((Object[]) null);
}
}

View File

@@ -1,719 +0,0 @@
package com.gmail.nossr50.database;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.util.Misc;
public final class FlatfileDatabaseManager implements DatabaseManager {
private final HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>();
private final List<PlayerStat> powerLevels = new ArrayList<PlayerStat>();
private long lastUpdate = 0;
private final long UPDATE_WAIT_TIME = 600000L; // 10 minutes
private final File usersFile;
private static final Object fileWritingLock = new Object();
protected FlatfileDatabaseManager() {
usersFile = new File(mcMMO.getUsersFilePath());
checkStructure();
updateLeaderboards();
}
public void purgePowerlessUsers() {
int purgedUsers = 0;
mcMMO.p.getLogger().info("Purging powerless users...");
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
// This code is O(n) instead of O(n²)
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
Map<SkillType, Integer> skills = getSkillMapFromLine(character);
boolean powerless = true;
for (int skill : skills.values()) {
if (skill != 0) {
powerless = false;
break;
}
}
// If they're still around, rewrite them to the file.
if (!powerless) {
writer.append(line).append("\r\n");
}
else {
purgedUsers++;
Misc.profileCleanup(character[0]);
}
}
// Write the new file
out = new FileWriter(usersFilePath);
out.write(writer.toString());
}
catch (IOException e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
tryClose(in);
tryClose(out);
}
}
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
public void purgeOldUsers() {
int removedPlayers = 0;
long currentTime = System.currentTimeMillis();
mcMMO.p.getLogger().info("Purging old users...");
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
// This code is O(n) instead of O(n²)
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
String name = character[0];
OfflinePlayer player = Bukkit.getOfflinePlayer(name);
boolean old = true;
if (player != null) {
old = (currentTime - player.getLastPlayed()) > PURGE_TIME;
}
if (!old) {
writer.append(line).append("\r\n");
}
else {
removedPlayers++;
Misc.profileCleanup(name);
}
}
// Write the new file
out = new FileWriter(usersFilePath);
out.write(writer.toString());
}
catch (IOException e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
tryClose(in);
tryClose(out);
}
}
mcMMO.p.getLogger().info("Purged " + removedPlayers + " users from the database.");
}
public boolean removeUser(String playerName) {
boolean worked = false;
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
if (!worked && line.split(":")[0].equalsIgnoreCase(playerName)) {
mcMMO.p.getLogger().info("User found, removing...");
worked = true;
continue; // Skip the player
}
writer.append(line).append("\r\n");
}
out = new FileWriter(usersFilePath); // Write out the new file
out.write(writer.toString());
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
tryClose(in);
tryClose(out);
}
}
Misc.profileCleanup(playerName);
return worked;
}
public void saveUser(PlayerProfile profile) {
String playerName = profile.getPlayerName();
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
// Open the file
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line;
// While not at the end of the file
while ((line = in.readLine()) != null) {
// Read the line in and copy it to the output it's not the player we want to edit
if (!line.split(":")[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
// Otherwise write the new player information
writer.append(playerName).append(":");
writer.append(profile.getSkillLevel(SkillType.MINING)).append(":");
writer.append(":");
writer.append(":");
writer.append(profile.getSkillXpLevel(SkillType.MINING)).append(":");
writer.append(profile.getSkillLevel(SkillType.WOODCUTTING)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.WOODCUTTING)).append(":");
writer.append(profile.getSkillLevel(SkillType.REPAIR)).append(":");
writer.append(profile.getSkillLevel(SkillType.UNARMED)).append(":");
writer.append(profile.getSkillLevel(SkillType.HERBALISM)).append(":");
writer.append(profile.getSkillLevel(SkillType.EXCAVATION)).append(":");
writer.append(profile.getSkillLevel(SkillType.ARCHERY)).append(":");
writer.append(profile.getSkillLevel(SkillType.SWORDS)).append(":");
writer.append(profile.getSkillLevel(SkillType.AXES)).append(":");
writer.append(profile.getSkillLevel(SkillType.ACROBATICS)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.REPAIR)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.UNARMED)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.HERBALISM)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.EXCAVATION)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.ARCHERY)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.SWORDS)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.AXES)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.ACROBATICS)).append(":");
writer.append(":");
writer.append(profile.getSkillLevel(SkillType.TAMING)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.TAMING)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.BERSERK)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.TREE_FELLER)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.GREEN_TERRA)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.SERRATED_STRIKES)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.SKULL_SPLITTER)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.SUPER_BREAKER)).append(":");
HudType hudType = profile.getHudType();
writer.append(hudType == null ? "STANDARD" : hudType.toString()).append(":");
writer.append(profile.getSkillLevel(SkillType.FISHING)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.FISHING)).append(":");
writer.append((int) profile.getSkillDATS(AbilityType.BLAST_MINING)).append(":");
writer.append(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR).append(":");
MobHealthbarType mobHealthbarType = profile.getMobHealthbarType();
writer.append(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":");
writer.append("\r\n");
}
}
// Write the new file
out = new FileWriter(usersFilePath);
out.write(writer.toString());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
tryClose(in);
tryClose(out);
}
}
}
public List<PlayerStat> readLeaderboard(String skillName, int pageNumber, int statsPerPage) {
updateLeaderboards();
List<PlayerStat> statsList = skillName.equalsIgnoreCase("all") ? powerLevels : playerStatHash.get(SkillType.getSkill(skillName));
int fromIndex = (Math.max(pageNumber, 1) - 1) * statsPerPage;
return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size()));
}
public Map<String, Integer> readRank(String playerName) {
updateLeaderboards();
Map<String, Integer> skills = new HashMap<String, Integer>();
for (SkillType skill : SkillType.nonChildSkills()) {
skills.put(skill.name(), getPlayerRank(playerName, playerStatHash.get(skill)));
}
skills.put("ALL", getPlayerRank(playerName, powerLevels));
return skills;
}
public void newUser(String playerName) {
BufferedWriter out = null;
synchronized (fileWritingLock) {
try {
// Open the file to write the player
out = new BufferedWriter(new FileWriter(mcMMO.getUsersFilePath(), true));
// Add the player to the end
out.append(playerName).append(":");
out.append("0:"); // Mining
out.append(":");
out.append(":");
out.append("0:"); // Xp
out.append("0:"); // Woodcutting
out.append("0:"); // WoodCuttingXp
out.append("0:"); // Repair
out.append("0:"); // Unarmed
out.append("0:"); // Herbalism
out.append("0:"); // Excavation
out.append("0:"); // Archery
out.append("0:"); // Swords
out.append("0:"); // Axes
out.append("0:"); // Acrobatics
out.append("0:"); // RepairXp
out.append("0:"); // UnarmedXp
out.append("0:"); // HerbalismXp
out.append("0:"); // ExcavationXp
out.append("0:"); // ArcheryXp
out.append("0:"); // SwordsXp
out.append("0:"); // AxesXp
out.append("0:"); // AcrobaticsXp
out.append(":");
out.append("0:"); // Taming
out.append("0:"); // TamingXp
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("STANDARD").append(":"); // HUD
out.append("0:"); // Fishing
out.append("0:"); // FishingXp
out.append("0:"); // Blast Mining
out.append(String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)).append(":"); // LastLogin
out.append(Config.getInstance().getMobHealthbarDefault().toString()).append(":"); // Mob Healthbar HUD
// Add more in the same format as the line above
out.newLine();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
tryClose(out);
}
}
}
public PlayerProfile loadPlayerProfile(String playerName, boolean create) {
BufferedReader in = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
// Open the user file
in = new BufferedReader(new FileReader(usersFilePath));
String line;
while ((line = in.readLine()) != null) {
// Find if the line contains the player we want.
String[] character = line.split(":");
if (!character[0].equalsIgnoreCase(playerName)) {
continue;
}
PlayerProfile p = loadFromLine(character);
in.close();
return p;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
tryClose(in);
}
}
if (create) {
newUser(playerName);
return new PlayerProfile(playerName, true);
}
return new PlayerProfile(playerName);
}
public void convertUsers(DatabaseManager destination) {
BufferedReader in = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
// Open the user file
in = new BufferedReader(new FileReader(usersFilePath));
String line;
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
try {
destination.saveUser(loadFromLine(character));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
tryClose(in);
}
}
}
public boolean checkConnected() {
// Not implemented
return true;
}
public List<String> getStoredUsers() {
ArrayList<String> users = new ArrayList<String>();
BufferedReader in = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
// Open the user file
in = new BufferedReader(new FileReader(usersFilePath));
String line;
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
users.add(character[0]);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
tryClose(in);
}
}
return users;
}
/**
* Update the leader boards.
*/
private void updateLeaderboards() {
// Only update FFS leaderboards every 10 minutes.. this puts a lot of strain on the server (depending on the size of the database) and should not be done frequently
if (System.currentTimeMillis() < lastUpdate + UPDATE_WAIT_TIME) {
return;
}
String usersFilePath = mcMMO.getUsersFilePath();
lastUpdate = System.currentTimeMillis(); // Log when the last update was run
powerLevels.clear(); // Clear old values from the power levels
// Initialize lists
List<PlayerStat> mining = new ArrayList<PlayerStat>();
List<PlayerStat> woodcutting = new ArrayList<PlayerStat>();
List<PlayerStat> herbalism = new ArrayList<PlayerStat>();
List<PlayerStat> excavation = new ArrayList<PlayerStat>();
List<PlayerStat> acrobatics = new ArrayList<PlayerStat>();
List<PlayerStat> repair = new ArrayList<PlayerStat>();
List<PlayerStat> swords = new ArrayList<PlayerStat>();
List<PlayerStat> axes = new ArrayList<PlayerStat>();
List<PlayerStat> archery = new ArrayList<PlayerStat>();
List<PlayerStat> unarmed = new ArrayList<PlayerStat>();
List<PlayerStat> taming = new ArrayList<PlayerStat>();
List<PlayerStat> fishing = new ArrayList<PlayerStat>();
BufferedReader in = null;
// Read from the FlatFile database and fill our arrays with information
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
String line = "";
ArrayList<String> players = new ArrayList<String>();
while ((line = in.readLine()) != null) {
String[] data = line.split(":");
String playerName = data[0];
int powerLevel = 0;
// Prevent the same player from being added multiple times (I'd like to note that this shouldn't happen...)
if (players.contains(playerName)) {
continue;
}
players.add(playerName);
Map<SkillType, Integer> skills = getSkillMapFromLine(data);
powerLevel += putStat(acrobatics, playerName, skills.get(SkillType.ACROBATICS));
powerLevel += putStat(archery, playerName, skills.get(SkillType.ARCHERY));
powerLevel += putStat(axes, playerName, skills.get(SkillType.AXES));
powerLevel += putStat(excavation, playerName, skills.get(SkillType.EXCAVATION));
powerLevel += putStat(fishing, playerName, skills.get(SkillType.FISHING));
powerLevel += putStat(herbalism, playerName, skills.get(SkillType.HERBALISM));
powerLevel += putStat(mining, playerName, skills.get(SkillType.MINING));
powerLevel += putStat(repair, playerName, skills.get(SkillType.REPAIR));
powerLevel += putStat(swords, playerName, skills.get(SkillType.SWORDS));
powerLevel += putStat(taming, playerName, skills.get(SkillType.TAMING));
powerLevel += putStat(unarmed, playerName, skills.get(SkillType.UNARMED));
powerLevel += putStat(woodcutting, playerName, skills.get(SkillType.WOODCUTTING));
putStat(powerLevels, playerName, powerLevel);
}
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
tryClose(in);
}
}
SkillComparator c = new SkillComparator();
Collections.sort(mining, c);
Collections.sort(woodcutting, c);
Collections.sort(repair, c);
Collections.sort(unarmed, c);
Collections.sort(herbalism, c);
Collections.sort(excavation, c);
Collections.sort(archery, c);
Collections.sort(swords, c);
Collections.sort(axes, c);
Collections.sort(acrobatics, c);
Collections.sort(taming, c);
Collections.sort(fishing, c);
Collections.sort(powerLevels, c);
playerStatHash.put(SkillType.MINING, mining);
playerStatHash.put(SkillType.WOODCUTTING, woodcutting);
playerStatHash.put(SkillType.REPAIR, repair);
playerStatHash.put(SkillType.UNARMED, unarmed);
playerStatHash.put(SkillType.HERBALISM, herbalism);
playerStatHash.put(SkillType.EXCAVATION, excavation);
playerStatHash.put(SkillType.ARCHERY, archery);
playerStatHash.put(SkillType.SWORDS, swords);
playerStatHash.put(SkillType.AXES, axes);
playerStatHash.put(SkillType.ACROBATICS, acrobatics);
playerStatHash.put(SkillType.TAMING, taming);
playerStatHash.put(SkillType.FISHING, fishing);
}
/**
* Checks that the file is present and valid
*/
private void checkStructure() {
if (usersFile.exists()) {
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
// If they're valid, rewrite them to the file.
if (character.length >= 37) {
writer.append(line).append("\r\n");
} else {
// Placeholder, repair row if needed (I.E. when new skills are added and such)
}
}
// Write the new file
out = new FileWriter(usersFilePath);
out.write(writer.toString());
}
catch (IOException e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
tryClose(in);
tryClose(out);
}
}
return;
}
usersFile.getParentFile().mkdir();
try {
mcMMO.p.debug("Creating mcmmo.users file...");
new File(mcMMO.getUsersFilePath()).createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void tryClose(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private Integer getPlayerRank(String playerName, List<PlayerStat> statsList) {
if (statsList == null) {
return null;
}
int currentPos = 1;
for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) {
return currentPos;
}
currentPos++;
}
return null;
}
private int putStat(List<PlayerStat> statList, String playerName, int statValue) {
statList.add(new PlayerStat(playerName, statValue));
return statValue;
}
private class SkillComparator implements Comparator<PlayerStat> {
@Override
public int compare(PlayerStat o1, PlayerStat o2) {
return (o2.statVal - o1.statVal);
}
}
private PlayerProfile loadFromLine(String[] character) throws Exception {
Map<SkillType, Integer> skills = getSkillMapFromLine(character); // Skill levels
Map<SkillType, Float> skillsXp = new HashMap<SkillType, Float>(); // Skill & XP
Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); // Ability & Cooldown
HudType hudType;
MobHealthbarType mobHealthbarType;
// TODO on updates, put new values in a try{} ?
skillsXp.put(SkillType.TAMING, (float) Integer.valueOf(character[25]));
skillsXp.put(SkillType.MINING, (float) Integer.valueOf(character[4]));
skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(character[15]));
skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(character[6]));
skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(character[16]));
skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(character[17]));
skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(character[18]));
skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(character[19]));
skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(character[20]));
skillsXp.put(SkillType.AXES, (float) Integer.valueOf(character[21]));
skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(character[22]));
skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(character[35]));
// Taming - Unused
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(character[32]));
// Repair - Unused
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(character[28]));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(character[26]));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(character[29]));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(character[27]));
// Archery - Unused
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(character[30]));
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(character[31]));
// Acrobatics - Unused
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(character[36]));
try {
hudType = HudType.valueOf(character[33]);
}
catch (Exception e) {
hudType = HudType.STANDARD; // Shouldn't happen unless database is being tampered with
}
try {
mobHealthbarType = MobHealthbarType.valueOf(character[38]);
}
catch (Exception e) {
mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
}
return new PlayerProfile(character[0], skills, skillsXp, skillsDATS, hudType, mobHealthbarType);
}
private Map<SkillType, Integer> getSkillMapFromLine(String[] character) {
Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level
skills.put(SkillType.TAMING, Integer.valueOf(character[24]));
skills.put(SkillType.MINING, Integer.valueOf(character[1]));
skills.put(SkillType.REPAIR, Integer.valueOf(character[7]));
skills.put(SkillType.WOODCUTTING, Integer.valueOf(character[5]));
skills.put(SkillType.UNARMED, Integer.valueOf(character[8]));
skills.put(SkillType.HERBALISM, Integer.valueOf(character[9]));
skills.put(SkillType.EXCAVATION, Integer.valueOf(character[10]));
skills.put(SkillType.ARCHERY, Integer.valueOf(character[11]));
skills.put(SkillType.SWORDS, Integer.valueOf(character[12]));
skills.put(SkillType.AXES, Integer.valueOf(character[13]));
skills.put(SkillType.ACROBATICS, Integer.valueOf(character[14]));
skills.put(SkillType.FISHING, Integer.valueOf(character[34]));
return skills;
}
}

View File

@@ -0,0 +1,403 @@
package com.gmail.nossr50.database;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils;
public final class LeaderboardManager {
private static HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>();
private static List<PlayerStat> powerLevels = new ArrayList<PlayerStat>();
private static long lastUpdate = 0;
private static final long UPDATE_WAIT_TIME = 600000L; // 10 minutes
private static final long ONE_MONTH = 2630000000L;
private LeaderboardManager() {}
/**
* Update the leader boards.
*/
public static void updateLeaderboards() {
// Only update FFS leaderboards every 10 minutes.. this puts a lot of strain on the server (depending on the size of the database) and should not be done frequently
if (System.currentTimeMillis() < lastUpdate + UPDATE_WAIT_TIME) {
return;
}
lastUpdate = System.currentTimeMillis(); // Log when the last update was run
powerLevels.clear(); // Clear old values from the power levels
// Initialize lists
List<PlayerStat> mining = new ArrayList<PlayerStat>();
List<PlayerStat> woodcutting = new ArrayList<PlayerStat>();
List<PlayerStat> herbalism = new ArrayList<PlayerStat>();
List<PlayerStat> excavation = new ArrayList<PlayerStat>();
List<PlayerStat> acrobatics = new ArrayList<PlayerStat>();
List<PlayerStat> repair = new ArrayList<PlayerStat>();
List<PlayerStat> swords = new ArrayList<PlayerStat>();
List<PlayerStat> axes = new ArrayList<PlayerStat>();
List<PlayerStat> archery = new ArrayList<PlayerStat>();
List<PlayerStat> unarmed = new ArrayList<PlayerStat>();
List<PlayerStat> taming = new ArrayList<PlayerStat>();
List<PlayerStat> fishing = new ArrayList<PlayerStat>();
// Read from the FlatFile database and fill our arrays with information
try {
FileReader file = new FileReader(mcMMO.getUsersFilePath());
BufferedReader in = new BufferedReader(file);
String line = "";
ArrayList<String> players = new ArrayList<String>();
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
String p = character[0];
int powerLevel = 0;
// Prevent the same player from being added multiple times (I'd like to note that this shouldn't happen...)
if (players.contains(p)) {
continue;
}
players.add(p);
if (character.length > 1 && StringUtils.isInt(character[1])) {
mining.add(new PlayerStat(p, Integer.parseInt(character[1])));
powerLevel += Integer.parseInt(character[1]);
}
if (character.length > 5 && StringUtils.isInt(character[5])) {
woodcutting.add(new PlayerStat(p, Integer.parseInt(character[5])));
powerLevel += Integer.parseInt(character[5]);
}
if (character.length > 7 && StringUtils.isInt(character[7])) {
repair.add(new PlayerStat(p, Integer.parseInt(character[7])));
powerLevel += Integer.parseInt(character[7]);
}
if (character.length > 8 && StringUtils.isInt(character[8])) {
unarmed.add(new PlayerStat(p, Integer.parseInt(character[8])));
powerLevel += Integer.parseInt(character[8]);
}
if (character.length > 9 && StringUtils.isInt(character[9])) {
herbalism.add(new PlayerStat(p, Integer.parseInt(character[9])));
powerLevel += Integer.parseInt(character[9]);
}
if (character.length > 10 && StringUtils.isInt(character[10])) {
excavation.add(new PlayerStat(p, Integer.parseInt(character[10])));
powerLevel += Integer.parseInt(character[10]);
}
if (character.length > 11 && StringUtils.isInt(character[11])) {
archery.add(new PlayerStat(p, Integer.parseInt(character[11])));
powerLevel += Integer.parseInt(character[11]);
}
if (character.length > 12 && StringUtils.isInt(character[12])) {
swords.add(new PlayerStat(p, Integer.parseInt(character[12])));
powerLevel += Integer.parseInt(character[12]);
}
if (character.length > 13 && StringUtils.isInt(character[13])) {
axes.add(new PlayerStat(p, Integer.parseInt(character[13])));
powerLevel += Integer.parseInt(character[13]);
}
if (character.length > 14 && StringUtils.isInt(character[14])) {
acrobatics.add(new PlayerStat(p, Integer.parseInt(character[14])));
powerLevel += Integer.parseInt(character[14]);
}
if (character.length > 24 && StringUtils.isInt(character[24])) {
taming.add(new PlayerStat(p, Integer.parseInt(character[24])));
powerLevel += Integer.parseInt(character[24]);
}
if (character.length > 34 && StringUtils.isInt(character[34])) {
fishing.add(new PlayerStat(p, Integer.parseInt(character[34])));
powerLevel += Integer.parseInt(character[34]);
}
powerLevels.add(new PlayerStat(p, powerLevel));
}
in.close();
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + mcMMO.getUsersFilePath() + " (Are you sure you formatted it correctly?)" + e.toString());
}
SkillComparator c = new SkillComparator();
Collections.sort(mining, c);
Collections.sort(woodcutting, c);
Collections.sort(repair, c);
Collections.sort(unarmed, c);
Collections.sort(herbalism, c);
Collections.sort(excavation, c);
Collections.sort(archery, c);
Collections.sort(swords, c);
Collections.sort(axes, c);
Collections.sort(acrobatics, c);
Collections.sort(taming, c);
Collections.sort(fishing, c);
Collections.sort(powerLevels, c);
playerStatHash.put(SkillType.MINING, mining);
playerStatHash.put(SkillType.WOODCUTTING, woodcutting);
playerStatHash.put(SkillType.REPAIR, repair);
playerStatHash.put(SkillType.UNARMED, unarmed);
playerStatHash.put(SkillType.HERBALISM, herbalism);
playerStatHash.put(SkillType.EXCAVATION, excavation);
playerStatHash.put(SkillType.ARCHERY, archery);
playerStatHash.put(SkillType.SWORDS, swords);
playerStatHash.put(SkillType.AXES, axes);
playerStatHash.put(SkillType.ACROBATICS, acrobatics);
playerStatHash.put(SkillType.TAMING, taming);
playerStatHash.put(SkillType.FISHING, fishing);
}
/**
* Retrieve leaderboard info.
*
* @param skillType Skill to retrieve info on.
* @param pageNumber Which page in the leaderboards to retrieve
* @return the requested leaderboard information
*/
public static String[] retrieveInfo(String skillType, int pageNumber) {
String[] info = new String[10];
List<PlayerStat> statsList;
if (skillType.equalsIgnoreCase("all")) {
statsList = powerLevels;
}
else {
statsList = playerStatHash.get(SkillType.getSkill(skillType));
}
int destination;
// How many lines to skip through
if (pageNumber == 1) {
destination = 0;
}
else {
destination = (pageNumber * 10) - 9;
}
int currentPos = 0;
for (PlayerStat ps : statsList) {
if (currentPos == 10) {
break;
}
if (destination > 1) {
destination--;
continue;
}
info[currentPos] = ps.name + ":" + ps.statVal;
currentPos++;
}
return info;
}
public static int[] getPlayerRank(String playerName) {
int currentPos = 1;
if (powerLevels != null) {
for (PlayerStat stat : powerLevels) {
if (stat.name.equalsIgnoreCase(playerName)) {
return new int[] {currentPos, stat.statVal};
}
currentPos++;
continue;
}
return new int[] {0, 0};
}
return new int[] {0, 0};
}
public static int[] getPlayerRank(String playerName, SkillType skillType) {
int currentPos = 1;
List<PlayerStat> statsList = playerStatHash.get(skillType);
if (statsList != null) {
for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) {
return new int[] {currentPos, stat.statVal};
}
currentPos++;
continue;
}
return new int[] {0, 0};
}
return new int[] {0, 0};
}
public static boolean removeFlatFileUser(String playerName) {
boolean worked = false;
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
try {
FileReader file = new FileReader(usersFilePath);
in = new BufferedReader(file);
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
if (!line.split(":")[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
mcMMO.p.getLogger().info("User found, removing...");
worked = true;
continue; // Skip the player
}
}
out = new FileWriter(usersFilePath); // Write out the new file
out.write(writer.toString());
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
return worked;
}
public static void purgePowerlessFlatfile() {
mcMMO.p.getLogger().info("Purging powerless users...");
int purgedUsers = 0;
for (PlayerStat stat : powerLevels) {
if (stat.statVal == 0 && removeFlatFileUser(stat.name) && !mcMMO.p.getServer().getOfflinePlayer(stat.name).isOnline()) {
purgedUsers++;
}
}
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
public static void purgeOldFlatfile() {
mcMMO.p.getLogger().info("Purging old users...");
int purgedUsers = removeOldFlatfileUsers();
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
private static int removeOldFlatfileUsers() {
int removedPlayers = 0;
long currentTime = System.currentTimeMillis();
long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
try {
FileReader file = new FileReader(usersFilePath);
in = new BufferedReader(file);
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
String[] splitLine = line.split(":");
if (splitLine.length > 37) {
if (currentTime - (StringUtils.getLong(line.split(":")[37]) * 1000) <= purgeTime) {
writer.append(line).append("\r\n");
}
else {
mcMMO.p.getLogger().info("User found, removing...");
removedPlayers++;
continue; // Skip the player
}
}
else {
writer.append(line).append("\r\n");
}
}
out = new FileWriter(usersFilePath); // Write out the new file
out.write(writer.toString());
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
return removedPlayers;
}
private static class SkillComparator implements Comparator<PlayerStat> {
@Override
public int compare(PlayerStat o1, PlayerStat o2) {
return (o2.statVal - o1.statVal);
}
}
}

View File

@@ -0,0 +1,63 @@
package com.gmail.nossr50.database.queuemanager;
import java.util.concurrent.LinkedBlockingQueue;
public class AsyncQueueManager implements Runnable {
private LinkedBlockingQueue<Queueable> queue;
private boolean running;
public AsyncQueueManager() {
this.queue = new LinkedBlockingQueue<Queueable>();
this.running = true;
}
@Override
public void run() {
while(running) {
try {
queue.take().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean queue(Queueable task) {
return queue.offer(task);
}
public boolean contains(String player) {
return queue.contains(new EqualString(player));
}
public void disable() {
running = false;
// Throw one more Queueable into queue to unblock take()
queue.add(new EndThread());
}
private class EqualString {
private String player;
public EqualString(String player) {
this.player = player;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Queueable) {
return ((Queueable)obj).getPlayer().equalsIgnoreCase(player);
}
return false;
}
}
private class EndThread implements Queueable {
@Override
public void run() { }
@Override
public String getPlayer() { return null; }
}
}

View File

@@ -0,0 +1,62 @@
package com.gmail.nossr50.database.queuemanager;
import java.util.Map;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.gmail.nossr50.datatypes.skills.SkillType;
public class McRankAsync implements Queueable {
private final String playerName;
private final CommandSender sender;
private String player;
public McRankAsync(String playerName, CommandSender sender) {
this.playerName = playerName;
this.sender = sender;
this.player = sender.getName();
}
@Override
public void run() {
final Map<String, Integer> skills = DatabaseManager.readSQLRank(playerName);
mcMMO.p.getServer().getScheduler().scheduleSyncDelayedTask(mcMMO.p, new Runnable() {
@Override
public void run() {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading"));
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName));
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
if (skills.get(skillType.name()) == null) {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", SkillUtils.getSkillName(skillType), LocaleLoader.getString("Commands.mcrank.Unranked")));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Skill", SkillUtils.getSkillName(skillType), skills.get(skillType.name())));
}
}
if (skills.get("ALL") == null) {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", LocaleLoader.getString("Commands.mcrank.Unranked")));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Overall", skills.get("ALL")));
}
}
}, 1L);
}
@Override
public String getPlayer() {
return player;
}
}

View File

@@ -0,0 +1,64 @@
package com.gmail.nossr50.database.queuemanager;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils;
public class McTopAsync implements Queueable {
private CommandSender sender;
private String query;
private int page;
private String player;
public McTopAsync(int page, String query, CommandSender sender) {
this.page = page;
this.query = query;
this.sender = sender;
this.player = sender.getName();
}
@Override
public void run() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
final HashMap<Integer, ArrayList<String>> userslist = DatabaseManager.read("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT " + ((page * 10) - 10) + ",10");
mcMMO.p.getServer().getScheduler().scheduleSyncDelayedTask(mcMMO.p, new Runnable() {
@Override
public void run() {
if (query.equalsIgnoreCase("taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(query)));
}
int place = (page * 10) - 9;
for (int i = 1; i <= 10; i++) {
if (userslist.get(i) == null) {
break;
}
// Format: 1. Playername - skill value
sender.sendMessage(place + ". " + ChatColor.GREEN + userslist.get(i).get(1) + " - " + ChatColor.WHITE + userslist.get(i).get(0));
place++;
}
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip"));
}
}, 1L);
}
@Override
public String getPlayer() {
return player;
}
}

View File

@@ -0,0 +1,6 @@
package com.gmail.nossr50.database.queuemanager;
public interface Queueable {
public void run();
public String getPlayer();
}

View File

@@ -1,7 +0,0 @@
package com.gmail.nossr50.datatypes;
public enum MobHealthbarType {
HEARTS,
BAR,
DISABLED;
}

View File

@@ -3,9 +3,6 @@ package com.gmail.nossr50.datatypes.database;
public enum DatabaseUpdateType { public enum DatabaseUpdateType {
FISHING, FISHING,
BLAST_MINING, BLAST_MINING,
INDEX, CASCADE_DELETE,
MOB_HEALTHBARS, INDEX;
PARTY_NAMES,
KILL_ORPHANS,
;
} }

Some files were not shown because too many files have changed in this diff Show More