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

Compare commits

...

64 Commits

Author SHA1 Message Date
T00thpick1
f3eb7fb17b Fix this 2013-06-25 18:23:27 -04:00
T00thpick1
39d6030e3e Try this jjacobson 2013-06-25 16:56:55 -04:00
TfT_02
de46277bea Realized that it wasn't only happening in the Nether 2013-06-24 17:10:39 +02:00
TfT_02
6d7d811814 Fixed bug with Ice Fishing in the Nether
Fixes  #1218
2013-06-24 16:25:49 +02:00
GJ
98b98256b7 Make our oldUserRemover actually work... 2013-06-13 12:23:58 -04:00
GJ
abd389f4de Try to speed up our PartyKickTask a bit. 2013-06-13 12:18:18 -04:00
GJ
602956a555 Fix duplicate prefix sending with party chat & logging. 2013-06-13 11:10:46 -04:00
GJ
8d0601babc Fix bug where all ranks less than 10 show as 0 with /mctop. 2013-06-13 10:56:46 -04:00
GJ
050be563bf Less magic numbers. 2013-06-12 19:26:09 -04:00
GJ
965dbda101 Clean up some stuff with our DATS. 2013-06-12 19:20:05 -04:00
GJ
f2b2cd9cc0 Oops. 2013-06-12 15:59:51 -04:00
GJ
3a78e1b487 More code duplication removal. 2013-06-12 15:56:42 -04:00
GJ
db637f0bc9 Remove more code duplication. 2013-06-12 15:41:26 -04:00
GJ
b15f1dde28 We don't need that potato. 2013-06-12 15:15:56 -04:00
GJ
28a78d820a Tidy up our InventoryListener. 2013-06-12 15:10:43 -04:00
GJ
a1792fe125 We were calling deflect twice. Also made individual functions for each
type of combat.
2013-06-07 15:47:00 -04:00
T00thpick1
3f7b17961f Reset mob healthbars on death to avoid conflicting with loot plugins 2013-06-07 15:46:59 -04:00
GJ
0ea07d4bc7 Fixed bug where spawned arrows could throw
ArrayIndexOutOfBoundsException. Fixes #1171
2013-06-07 15:46:59 -04:00
GJ
190b7ee1f5 ChatManagers... 2013-06-07 15:46:58 -04:00
GJ
4ff4271da2 These should be protected. 2013-06-07 15:46:57 -04:00
T00thpick1
8705974e08 Use a single manager to handle our databases. 2013-06-07 15:46:57 -04:00
TfT_02
de0487d16f This should make it work properly 2013-06-07 15:46:56 -04:00
TfT_02
fc0c386ecb Fixing this as pointed out by Riking 2013-06-07 15:46:55 -04:00
TfT_02
86db4251a2 Check visibility before range 2013-06-07 15:46:55 -04:00
TfT_02
effe5ec305 We were deprecating these kind of permission nodes 2013-06-07 15:46:54 -04:00
TfT_02
8fb92292bd Move adding users to UserManager from onLogin to onJoin 2013-06-07 15:46:54 -04:00
TfT_02
375fa4f75c Added permission node to prevent inspecting hidden players 2013-06-07 15:46:53 -04:00
TfT_02
da25b02e0a Only set the item in hand null if it's actually a fishing rod 2013-06-07 15:46:53 -04:00
GJ
d43ae17bd2 Tweak a few things on the UpdateChecker. 2013-06-07 15:46:52 -04:00
Kane York
f81a763d6c Use finally to close the update checker stream 2013-06-07 15:46:52 -04:00
Kane York
385f8ca0b3 Reduce code duplication in ExperienceAPI 2013-06-07 15:46:46 -04:00
GJ
0ba4bc25c7 Use player objects instead of names - should be more efficient and less
buggy.
2013-05-28 13:33:20 -04:00
GJ
b0eb4b93a8 Cleaner way to avoid salvaging chainmail. 2013-05-28 12:59:10 -04:00
GJ
54f135aebd We're checking this twice and shouldn't be. 2013-05-28 12:53:12 -04:00
GJ
10e369f9c5 Increased auto-fishing detection. 2013-05-28 12:42:39 -04:00
TfT_02
1ae9b0f4d2 Animals can also have the "Spawned Entity" tag 2013-05-26 17:55:24 +02:00
T00thpick1
198ee6a7ed I think this is case sensitive 2013-05-26 11:51:42 -04:00
TfT_02
2414ddf485 Fix broken Tree Feller
Fixes #1139
2013-05-25 14:45:24 +02:00
GJ
2cd52db8c9 The ; is important. 2013-05-22 22:30:40 -04:00
GJ
5e00636761 And a little more... 2013-05-22 22:30:09 -04:00
GJ
a82cc9609b Cleaning up a bit. 2013-05-22 22:13:40 -04:00
T00thpick1
45c6c20ccd Null parties! Hurray! 2013-05-22 21:20:35 -04:00
GJ
7a61f55e49 Remove some code duplication in our ShareHandler. 2013-05-22 17:22:06 -04:00
GJ
aa0b77a64c Updates to our parties. 2013-05-22 13:02:26 -04:00
GJ
030c8e59d7 The other way leaks memory like a sieve. 2013-05-22 00:01:19 -04:00
GJ
f21fbe2d40 Make repair & salvage respect the sneaking settings. Fixes #1108 2013-05-21 22:34:06 -04:00
GJ
9a5f4b638f Little more cleaning. 2013-05-21 14:15:28 -04:00
GJ
9aa49a09da Little more cleanup. 2013-05-21 14:03:00 -04:00
GJ
bf8945ac59 Try to clean CombatUtils a bit... 2013-05-21 13:36:44 -04:00
GJ
d9926bab4e Try to clean up our poor EntityListener... 2013-05-21 13:27:52 -04:00
GJ
38ba2c21e5 Back to normal development. 2013-05-21 12:22:11 -04:00
GJ
a48fb30edf New beta! 2013-05-21 12:20:50 -04:00
GJ
92ec04bd46 Better boolean handling. 2013-05-21 11:44:16 -04:00
GJ
0b6372a6ea Don't run these calculations twice. Also, pretty sure one of these was
bugged.
2013-05-21 11:41:39 -04:00
GJ
4f8b66f94d Clean up our block listener some. 2013-05-21 11:11:55 -04:00
GJ
0c52b3016c We've got these functions, might as well use them. 2013-05-21 10:02:09 -04:00
GJ
a2f80569e3 Fire McMMOPlayerLevelUp events for our experience commands, when
applicable. Fixes #921
2013-05-21 09:31:25 -04:00
GJ
87df536a1f Only check for kraken if you're actually fishing. 2013-05-21 09:14:54 -04:00
T00thpick1
12e70490d8 Cooldowns messages need to be affected by perks too 2013-05-20 22:35:34 -04:00
TfT_02
23b1518dc0 More formatting :) 2013-05-20 17:28:02 -04:00
T00thpick1
6dbf2e0d95 FishingTreasureEvent, FishingShakeEvent and MagicHunterEvent 2013-05-20 17:27:59 -04:00
GJ
60304e9643 Because Minecraft does stupid things with "/" in the chat.
Fixes #994
2013-05-20 08:56:02 -04:00
GJ
614557e2fa It'd be nice if Ice Fishing actually worked. 2013-05-20 08:07:39 -04:00
TfT_02
e312e95aed Refactor to a more descriptive name,
also fixes a small typo.
2013-05-20 10:55:17 +02:00
104 changed files with 2929 additions and 2800 deletions

View File

@@ -28,6 +28,8 @@ Version 1.4.06-dev
+ Added multiplier to Archery XP based on bow force + Added multiplier to Archery XP based on bow force
+ Added information about /party itemshare and /party expshare to the party help page + 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 option to use scoreboards for power level display instead of Spout.
+ Added permission node to prevent inspecting hidden players
= Fixed bug where spawned arrows could throw ArrayIndexOutOfBoundsException
= Fixed bug where custom Spout titles were overwritten by mcMMO. = 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 Nether Quartz wasn't included in Smelting or item sharing
= Fixed bug where players were able to join the same party multiple times = Fixed bug where players were able to join the same party multiple times
@@ -48,6 +50,8 @@ Version 1.4.06-dev
= Fixed bug where Blast Mining would drop wrong items = 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 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 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
! Changed Spout notification tiers to be stored in SpoutConfig instead of AdvancedConfig ! Changed Spout notification tiers to be stored in SpoutConfig instead of AdvancedConfig
! Changed Berserk to add items to inventory rather than denying pickup ! 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 Call of the Wild, newly summoned pet's will have a custom name. (added permission node to disable this)

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-dev5</version> <version>1.4.06-dev6</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>

View File

@@ -4,6 +4,9 @@ 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;
@@ -22,7 +25,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) {
ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, displayName, message); getPartyChatManager(plugin, party).handleChat(sender, displayName, message);
} }
/** /**
@@ -36,7 +39,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 party, String message) { public static void sendPartyChat(Plugin plugin, String sender, String party, String message) {
ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, sender, message); getPartyChatManager(plugin, party).handleChat(sender, message);
} }
/** /**
@@ -50,7 +53,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) {
ChatManager.handleAdminChat(plugin, sender, displayName, message); ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, displayName, message);
} }
/** /**
@@ -63,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 message) { public static void sendAdminChat(Plugin plugin, String sender, String message) {
ChatManager.handleAdminChat(plugin, sender, sender, message); ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, message);
} }
/** /**
@@ -73,7 +76,7 @@ public final class ChatAPI {
* @return true if the player is using party chat, false otherwise * @return true if the player is using party chat, false otherwise
*/ */
public static boolean isUsingPartyChat(Player player) { public static boolean isUsingPartyChat(Player player) {
return isUsingPartyChat(player.getName()); return UserManager.getPlayer(player).getPartyChatMode();
} }
/** /**
@@ -93,7 +96,7 @@ public final class ChatAPI {
* @return true if the player is using admin chat, false otherwise * @return true if the player is using admin chat, false otherwise
*/ */
public static boolean isUsingAdminChat(Player player) { public static boolean isUsingAdminChat(Player player) {
return isUsingAdminChat(player.getName()); return UserManager.getPlayer(player).getAdminChatMode();
} }
/** /**
@@ -112,7 +115,7 @@ public final class ChatAPI {
* @param player The player to toggle party chat on. * @param player The player to toggle party chat on.
*/ */
public static void togglePartyChat(Player player) { public static void togglePartyChat(Player player) {
togglePartyChat(player.getName()); UserManager.getPlayer(player).togglePartyChat();
} }
/** /**
@@ -121,7 +124,7 @@ public final class ChatAPI {
* @param playerName The name of the player to toggle party chat on. * @param playerName The name of the player to toggle party chat on.
*/ */
public static void togglePartyChat(String playerName) { public static void togglePartyChat(String playerName) {
UserManager.getPlayer(playerName).setPartyChat(!isUsingPartyChat(playerName)); UserManager.getPlayer(playerName).togglePartyChat();
} }
/** /**
@@ -130,7 +133,7 @@ public final class ChatAPI {
* @param player The player to toggle admin chat on. * @param player The player to toggle admin chat on.
*/ */
public static void toggleAdminChat(Player player) { public static void toggleAdminChat(Player player) {
toggleAdminChat(player.getName()); UserManager.getPlayer(player).toggleAdminChat();
} }
/** /**
@@ -139,6 +142,13 @@ public final class ChatAPI {
* @param playerName The name of the player to toggle party chat on. * @param playerName The name of the player to toggle party chat on.
*/ */
public static void toggleAdminChat(String playerName) { public static void toggleAdminChat(String playerName) {
UserManager.getPlayer(playerName).setAdminChat(!isUsingAdminChat(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

@@ -15,6 +15,37 @@ import com.gmail.nossr50.util.player.UserManager;
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
* other API calls in this class.
* </br>
* This function is designed for API usage.
*
* @param skillType A string that may or may not be a skill
* @return true if this is a valid mcMMO skill
*/
public static boolean isValidSkillType(String skillType) {
return SkillType.getSkill(skillType) != null;
}
/**
* 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();
}
/** /**
* Adds raw XP to the player. * Adds raw XP to the player.
* </br> * </br>
@@ -27,13 +58,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @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) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, XP);
} }
/** /**
@@ -49,13 +74,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addRawXPOffline(String playerName, String skillType, int XP) { public static void addRawXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); addOfflineXP(playerName, getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, XP);
} }
/** /**
@@ -70,13 +89,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addMultipliedXP(Player player, String skillType, int XP) { public static void addMultipliedXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
@@ -92,13 +105,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addMultipliedXPOffline(String playerName, String skillType, int XP) { public static void addMultipliedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); addOfflineXP(playerName, getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
@@ -113,11 +120,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addModifiedXP(Player player, String skillType, int XP) { public static void addModifiedXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier())); UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
@@ -135,17 +138,14 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addModifiedXPOffline(String playerName, String skillType, int XP) { public static void addModifiedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier())); addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
* Adds XP to the player, calculates for XP Rate, skill modifiers and perks. May be shared with the party. * 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.
* *
@@ -156,13 +156,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @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) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).beginXpGain(getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).beginXpGain(skill, XP);
} }
/** /**
@@ -178,17 +172,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getXP(Player player, String skillType) { public static int getXP(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillXpLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(skill);
} }
/** /**
@@ -205,17 +189,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getOfflineXP(String playerName, String skillType) { public static int getOfflineXP(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillXpLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getSkillXpLevel(skill);
} }
/** /**
@@ -231,17 +205,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static float getXPRaw(Player player, String skillType) { public static float getXPRaw(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillXpLevelRaw(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return UserManager.getPlayer(player).getProfile().getSkillXpLevelRaw(skill);
} }
/** /**
@@ -258,17 +222,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static float getOfflineXPRaw(String playerName, String skillType) { public static float getOfflineXPRaw(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillXpLevelRaw(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getSkillXpLevelRaw(skill);
} }
/** /**
@@ -284,17 +238,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getXPToNextLevel(Player player, String skillType) { public static int getXPToNextLevel(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getXpToLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return UserManager.getPlayer(player).getProfile().getXpToLevel(skill);
} }
/** /**
@@ -311,17 +255,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getOfflineXPToNextLevel(String playerName, String skillType) { public static int getOfflineXPToNextLevel(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getXpToLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getXpToLevel(skill);
} }
/** /**
@@ -337,15 +271,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getXPRemaining(Player player, String skillType) { public static int getXPRemaining(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getNonChildSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
PlayerProfile profile = UserManager.getPlayer(player).getProfile(); PlayerProfile profile = UserManager.getPlayer(player).getProfile();
@@ -366,15 +292,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getOfflineXPRemaining(String playerName, String skillType) { public static int getOfflineXPRemaining(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getNonChildSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
@@ -393,13 +311,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addLevel(Player player, String skillType, int levels) { public static void addLevel(Player player, String skillType, int levels) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().addLevels(getSkillType(skillType), levels);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().addLevels(skill, levels);
} }
/** /**
@@ -416,11 +328,7 @@ public final class ExperienceAPI {
*/ */
public static void addLevelOffline(String playerName, String skillType, int levels) { public static void addLevelOffline(String playerName, String skillType, int levels) {
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) { if (skill.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skill); Set<SkillType> parentSkills = FamilyTree.getParents(skill);
@@ -449,13 +357,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevel(Player player, String skillType) { public static int getLevel(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillLevel(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return UserManager.getPlayer(player).getProfile().getSkillLevel(skill);
} }
/** /**
@@ -471,13 +373,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static int getLevelOffline(String playerName, String skillType) { public static int getLevelOffline(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillLevel(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getSkillLevel(skill);
} }
/** /**
@@ -506,11 +402,7 @@ public final class ExperienceAPI {
int powerLevel = 0; int powerLevel = 0;
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
for (SkillType type : SkillType.values()) { for (SkillType type : SkillType.nonChildSkills()) {
if (type.isChildSkill()) {
continue;
}
powerLevel += profile.getSkillLevel(type); powerLevel += profile.getSkillLevel(type);
} }
@@ -528,13 +420,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevelCap(String skillType) { public static int getLevelCap(String skillType) {
SkillType skill = SkillType.getSkill(skillType); return Config.getInstance().getLevelCap(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return Config.getInstance().getLevelCap(skill);
} }
/** /**
@@ -560,13 +446,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void setLevel(Player player, String skillType, int skillLevel) { public static void setLevel(Player player, String skillType, int skillLevel) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().modifySkill(getSkillType(skillType), skillLevel);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().modifySkill(skill, skillLevel);
} }
/** /**
@@ -582,13 +462,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @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 setLevelOffline(String playerName, String skillType, int skillLevel) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).modifySkill(getSkillType(skillType), skillLevel);
if (skill == null) {
throw new InvalidSkillException();
}
getOfflineProfile(playerName).modifySkill(skill, skillLevel);
} }
/** /**
@@ -604,17 +478,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void setXP(Player player, String skillType, int newValue) { public static void setXP(Player player, String skillType, int newValue) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().setSkillXpLevel(getNonChildSkillType(skillType), newValue);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
UserManager.getPlayer(player).getProfile().setSkillXpLevel(skill, newValue);
} }
/** /**
@@ -631,17 +495,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void setXPOffline(String playerName, String skillType, int newValue) { public static void setXPOffline(String playerName, String skillType, int newValue) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).setSkillXpLevel(getNonChildSkillType(skillType), newValue);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
getOfflineProfile(playerName).setSkillXpLevel(skill, newValue);
} }
/** /**
@@ -657,17 +511,7 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void removeXP(Player player, String skillType, int xp) { public static void removeXP(Player player, String skillType, int xp) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().removeXp(getNonChildSkillType(skillType), xp);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
UserManager.getPlayer(player).getProfile().removeXp(skill, xp);
} }
/** /**
@@ -684,26 +528,11 @@ public final class ExperienceAPI {
* @throws UnsupportedOperationException if the given skill is a child skill * @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void removeXPOffline(String playerName, String skillType, int xp) { public static void removeXPOffline(String playerName, String skillType, int xp) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).removeXp(getNonChildSkillType(skillType), xp);
if (skill == null) {
throw new InvalidSkillException();
} }
if (skill.isChildSkill()) { // Utility methods follow.
throw new UnsupportedOperationException("Child skills do not have XP");
}
getOfflineProfile(playerName).removeXp(skill, xp);
}
/**
* Add XP to an offline player.
*
* @param playerName The player to check
* @param skillType The skill to check
* @param XP The amount of XP to award.
*/
private static void addOfflineXP(String playerName, SkillType skill, int XP) { private static void addOfflineXP(String playerName, SkillType skill, int XP) {
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
@@ -731,4 +560,24 @@ public final class ExperienceAPI {
return profile; 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

@@ -77,14 +77,13 @@ 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(); party = new Party(playerName, partyName);
party.setName(partyName);
party.setLeader(player.getName());
} }
PartyManager.addToParty(player, UserManager.getPlayer(player), party); PartyManager.addToParty(playerName, UserManager.getPlayer(player), party);
} }
/** /**

View File

@@ -0,0 +1,22 @@
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,78 +1,51 @@
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.mcMMO; import com.gmail.nossr50.events.chat.McMMOChatEvent;
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 final class ChatManager { public abstract class ChatManager {
public ChatManager() {} protected Plugin plugin;
protected boolean useDisplayNames;
protected String chatPrefix;
public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message, boolean isAsync) { protected String displayName;
McMMOAdminChatEvent chatEvent = new McMMOAdminChatEvent(plugin, playerName, displayName, message, isAsync); protected String message;
mcMMO.p.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) { protected ChatManager(Plugin plugin, boolean useDisplayNames, String chatPrefix) {
this.plugin = plugin;
this.useDisplayNames = useDisplayNames;
this.chatPrefix = chatPrefix;
}
protected void handleChat(McMMOChatEvent event) {
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return; return;
} }
if (Config.getInstance().getAdminDisplayNames()) { displayName = useDisplayNames ? event.getDisplayName() : event.getSender();
displayName = chatEvent.getDisplayName(); message = LocaleLoader.getString(chatPrefix, displayName) + event.getMessage();
}
else { sendMessage();
displayName = chatEvent.getSender();
} }
String adminMessage = chatEvent.getMessage(); public void handleChat(String senderName, String message) {
handleChat(senderName, senderName, message, false);
mcMMO.p.getServer().broadcast(LocaleLoader.getString("Commands.AdminChat.Prefix", displayName) + adminMessage, "mcmmo.chat.adminchat");
} }
public static void handleAdminChat(Plugin plugin, String senderName, String message) { public void handleChat(Player player, String message, boolean isAsync) {
handleAdminChat(plugin, senderName, senderName, message); handleChat(player.getName(), player.getDisplayName(), message, isAsync);
} }
public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message) { public void handleChat(String senderName, String displayName, String message) {
handleAdminChat(plugin, playerName, displayName, message, false); handleChat(senderName, displayName, message, false);
} }
public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message, boolean isAsync) { public abstract void handleChat(String senderName, String displayName, String message, boolean isAsync);
String partyName = party.getName();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(plugin, playerName, displayName, partyName, message, isAsync); protected abstract void sendMessage();
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 static void handlePartyChat(Plugin plugin, Party party, String senderName, String message) {
handlePartyChat(plugin, party, senderName, senderName, message);
}
public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message) {
handlePartyChat(plugin, party, playerName, displayName, message, false);
}
} }

View File

@@ -0,0 +1,29 @@
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

@@ -0,0 +1,34 @@
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

@@ -7,6 +7,7 @@ import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -29,7 +30,7 @@ public class KrakenCommand implements TabExecutor {
return true; return true;
} }
UserManager.getPlayer(sender.getName()).getFishingManager().unleashTheKraken(); UserManager.getPlayer((Player) sender).getFishingManager().unleashTheKraken();
return true; return true;
case 1: case 1:

View File

@@ -108,6 +108,6 @@ public class McmmoCommand implements CommandExecutor {
sender.sendMessage(" /mcgod " + LocaleLoader.getString("Commands.mcgod")); sender.sendMessage(" /mcgod " + LocaleLoader.getString("Commands.mcgod"));
} }
sender.sendMessage(LocaleLoader.getString("Commands.SkillInfo")); sender.sendMessage(" /<skill>" + LocaleLoader.getString("Commands.SkillInfo"));
} }
} }

View File

@@ -5,6 +5,7 @@ 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.command.TabExecutor; import org.bukkit.command.TabExecutor;
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;
@@ -17,7 +18,7 @@ public class McnotifyCommand implements TabExecutor {
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(sender.getName()); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On"))); sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On")));
mcMMOPlayer.toggleChatNotifications(); mcMMOPlayer.toggleChatNotifications();

View File

@@ -7,6 +7,7 @@ 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.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.MobHealthbarType; import com.gmail.nossr50.datatypes.MobHealthbarType;
@@ -38,7 +39,7 @@ public class MobhealthCommand implements TabExecutor {
switch (args.length) { switch (args.length) {
case 1: case 1:
PlayerProfile playerProfile = UserManager.getPlayer(sender.getName()).getProfile(); PlayerProfile playerProfile = UserManager.getPlayer((Player) sender).getProfile();
try { try {
MobHealthbarType type = MobHealthbarType.valueOf(args[0].toUpperCase().trim()); MobHealthbarType type = MobHealthbarType.valueOf(args[0].toUpperCase().trim());

View File

@@ -33,8 +33,8 @@ public abstract class ToggleCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
applyCommandAction(); applyCommandAction();
return true; return true;

View File

@@ -1,12 +1,8 @@
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() {
@@ -15,12 +11,6 @@ public class AdminChatCommand extends ChatCommand {
@Override @Override
protected void handleChatSending(CommandSender sender, String[] args) { protected void handleChatSending(CommandSender sender, String[] args) {
if (sender instanceof Player) { chatManager.handleChat(sender.getName(), getDisplayName(sender), buildChatMessage(args, 0));
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

@@ -6,8 +6,12 @@ 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.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; 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.locale.LocaleLoader;
@@ -18,10 +22,12 @@ import com.google.common.collect.ImmutableList;
public abstract class ChatCommand implements TabExecutor { public abstract class ChatCommand implements TabExecutor {
protected ChatMode chatMode; protected ChatMode chatMode;
protected ChatManager chatManager;
private McMMOPlayer mcMMOPlayer; 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
@@ -32,7 +38,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
if (chatMode.isEnabled(mcMMOPlayer)) { if (chatMode.isEnabled(mcMMOPlayer)) {
disableChatMode(sender); disableChatMode(sender);
@@ -49,7 +55,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
enableChatMode(sender); enableChatMode(sender);
return true; return true;
@@ -60,7 +66,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
disableChatMode(sender); disableChatMode(sender);
return true; return true;
@@ -96,6 +102,10 @@ 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) {

View File

@@ -3,9 +3,8 @@ 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;
@@ -18,16 +17,18 @@ 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) {
Player player = (Player) sender; party = UserManager.getPlayer((Player) sender).getParty();
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;
} }
ChatManager.handlePartyChat(mcMMO.p, party, player.getName(), player.getDisplayName(), buildChatMessage(args, 0)); message = buildChatMessage(args, 0);
} }
else { else {
if (args.length < 2) { if (args.length < 2) {
@@ -35,14 +36,17 @@ public class PartyChatCommand extends ChatCommand {
return; return;
} }
Party party = PartyManager.getParty(args[0]); 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;
} }
ChatManager.handlePartyChat(mcMMO.p, party, LocaleLoader.getString("Commands.Chat.Console"), buildChatMessage(args, 1)); message = buildChatMessage(args, 1);
} }
((PartyChatManager) chatManager).setParty(party);
chatManager.handleChat(sender.getName(), getDisplayName(sender), message);
} }
} }

View File

@@ -2,7 +2,9 @@ package com.gmail.nossr50.commands.experience;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO;
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.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
@@ -21,6 +23,10 @@ public class AddlevelsCommand extends ExperienceCommand {
@Override @Override
protected void handleCommand(SkillType skill) { protected void handleCommand(SkillType skill) {
profile.addLevels(skill, value); profile.addLevels(skill, value);
if (player != null) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value));
}
} }
@Override @Override

View File

@@ -46,8 +46,8 @@ public abstract class ExperienceCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
profile = mcMMOPlayer.getProfile(); profile = mcMMOPlayer.getProfile();
editValues(); editValues();

View File

@@ -2,7 +2,9 @@ package com.gmail.nossr50.commands.experience;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO;
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.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
@@ -21,6 +23,10 @@ public class MmoeditCommand extends ExperienceCommand {
@Override @Override
protected void handleCommand(SkillType skill) { protected void handleCommand(SkillType skill) {
profile.modifySkill(skill, value); profile.modifySkill(skill, value);
if (player != null) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value - profile.getSkillLevel(skill)));
}
} }
@Override @Override

View File

@@ -2,9 +2,12 @@ package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command; import org.bukkit.command.Command;
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.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.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.commands.CommandUtils;
@@ -37,8 +40,8 @@ public class SkillresetCommand extends ExperienceCommand {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
profile = mcMMOPlayer.getProfile(); profile = mcMMOPlayer.getProfile();
editValues(); editValues();
@@ -84,13 +87,11 @@ public class SkillresetCommand extends ExperienceCommand {
@Override @Override
protected boolean permissionsCheckSelf(CommandSender sender) { protected boolean permissionsCheckSelf(CommandSender sender) {
// TODO Auto-generated method stub
return false; return false;
} }
@Override @Override
protected boolean permissionsCheckOthers(CommandSender sender) { protected boolean permissionsCheckOthers(CommandSender sender) {
// TODO Auto-generated method stub
return false; return false;
} }
@@ -102,6 +103,10 @@ public class SkillresetCommand extends ExperienceCommand {
} }
profile.modifySkill(skill, 0); profile.modifySkill(skill, 0);
if (player != null) {
mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, 0 - profile.getSkillLevel(skill)));
}
} }
@Override @Override

View File

@@ -15,8 +15,8 @@ public class PartyAcceptCommand 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 1: case 1:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPartyInvite()) { if (!mcMMOPlayer.hasPartyInvite()) {
sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites")); sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites"));

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.party;
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 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;
@@ -14,7 +15,7 @@ public class PartyChangeOwnerCommand 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:
Party playerParty = UserManager.getPlayer(sender.getName()).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
if (!playerParty.getMembers().contains(args[1])) { if (!playerParty.getMembers().contains(args[1])) {
sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1])); sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1]));

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.party;
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 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;
@@ -13,7 +14,7 @@ public class PartyChangePasswordCommand 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) {
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
switch (args.length) { switch (args.length) {
case 1: case 1:

View File

@@ -70,8 +70,8 @@ public class PartyCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
if (args.length < 1) { if (args.length < 1) {
if (!mcMMOPlayer.inParty()) { if (!mcMMOPlayer.inParty()) {

View File

@@ -19,8 +19,8 @@ public class PartyCreateCommand implements CommandExecutor {
case 3: case 3:
Party newParty = PartyManager.getParty(args[1]); Party newParty = PartyManager.getParty(args[1]);
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); 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 (PartyManager.checkPartyExistence(player, newParty, args[1])) {

View File

@@ -16,7 +16,7 @@ public class PartyDisbandCommand 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 1: case 1:
Party playerParty = UserManager.getPlayer(sender.getName()).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String partyName = playerParty.getName(); String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {

View File

@@ -26,7 +26,7 @@ public class PartyExpShareCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 2: case 2:
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) { if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) {
handleChangingShareMode(ShareMode.NONE); handleChangingShareMode(ShareMode.NONE);

View File

@@ -25,8 +25,8 @@ public class PartyInfoCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 0: case 0:
case 1: case 1:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty(); playerParty = mcMMOPlayer.getParty();
displayPartyHeader(); displayPartyHeader();

View File

@@ -24,8 +24,8 @@ public class PartyInviteCommand implements CommandExecutor {
} }
Player target = mcMMOTarget.getPlayer(); Player target = mcMMOTarget.getPlayer();
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (player.equals(target)) { if (player.equals(target)) {
sender.sendMessage(LocaleLoader.getString("Party.Invite.Self")); sender.sendMessage(LocaleLoader.getString("Party.Invite.Self"));

View File

@@ -26,7 +26,7 @@ public class PartyItemShareCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 2: case 2:
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
ShareMode mode = ShareMode.getShareMode(args[1].toUpperCase()); ShareMode mode = ShareMode.getShareMode(args[1].toUpperCase());
if (mode == null) { if (mode == null) {
@@ -38,7 +38,7 @@ public class PartyItemShareCommand implements CommandExecutor {
return true; return true;
case 3: case 3:
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
boolean toggle = false; boolean toggle = false;
if (CommandUtils.shouldEnableToggle(args[2])) { if (CommandUtils.shouldEnableToggle(args[2])) {

View File

@@ -77,8 +77,8 @@ public class PartyJoinCommand implements CommandExecutor {
return false; return false;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty(); playerParty = mcMMOPlayer.getParty();
targetParty = mcMMOTarget.getParty(); targetParty = mcMMOTarget.getParty();

View File

@@ -18,7 +18,7 @@ public class PartyKickCommand 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:
Party playerParty = UserManager.getPlayer(sender.getName()).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.getName())) {

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.party;
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 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;
@@ -15,7 +16,7 @@ public class PartyLockCommand 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) {
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
switch (args.length) { switch (args.length) {
case 1: case 1:

View File

@@ -17,7 +17,7 @@ public class PartyRenameCommand 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:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
Party playerParty = mcMMOPlayer.getParty(); Party playerParty = mcMMOPlayer.getParty();
String oldPartyName = playerParty.getName(); String oldPartyName = playerParty.getName();

View File

@@ -18,8 +18,8 @@ public class PtpAcceptAnyCommand implements CommandExecutor {
return true; return true;
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpConfirmRequired()) { if (mcMMOPlayer.getPtpConfirmRequired()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled")); player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled"));

View File

@@ -21,8 +21,8 @@ public class PtpAcceptCommand implements CommandExecutor {
return true; return true;
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPtpRequest()) { if (!mcMMOPlayer.hasPtpRequest()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.NoRequests")); player.sendMessage(LocaleLoader.getString("Commands.ptp.NoRequests"));

View File

@@ -51,16 +51,20 @@ public class PtpCommand implements TabExecutor {
return ptpAcceptAnyCommand.onCommand(sender, command, label, args); return ptpAcceptAnyCommand.onCommand(sender, command, label, args);
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int recentlyhurt_cooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown(); int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)) { if (hurtCooldown > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return true; return true;
} }
}
if (args[0].equalsIgnoreCase("accept")) { if (args[0].equalsIgnoreCase("accept")) {
return ptpAcceptCommand.onCommand(sender, command, label, args); return ptpAcceptCommand.onCommand(sender, command, label, args);
@@ -74,10 +78,14 @@ public class PtpCommand implements TabExecutor {
int ptpCooldown = Config.getInstance().getPTPCommandCooldown(); int ptpCooldown = Config.getInstance().getPTPCommandCooldown();
long lastTeleport = mcMMOPlayer.getLastTeleport(); long lastTeleport = mcMMOPlayer.getLastTeleport();
if (!SkillUtils.cooldownOver(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player)) { if (ptpCooldown > 0) {
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player))); int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining));
return true; return true;
} }
}
sendTeleportRequest(sender, player, args[0]); sendTeleportRequest(sender, player, args[0]);
return true; return true;

View File

@@ -18,8 +18,8 @@ public class PtpToggleCommand implements CommandExecutor {
return true; return true;
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpEnabled()) { if (mcMMOPlayer.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled")); player.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled"));

View File

@@ -69,7 +69,13 @@ public class InspectCommand implements TabExecutor {
else { else {
Player target = mcMMOPlayer.getPlayer(); Player target = mcMMOPlayer.getPlayer();
if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) {
if (!Permissions.inspectOffline(sender)) {
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
return true;
}
}
else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) {
return true; return true;
} }

View File

@@ -24,8 +24,8 @@ public class McstatsCommand implements TabExecutor {
switch (args.length) { switch (args.length) {
case 0: case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (Config.getInstance().getMcstatsScoreboardsEnabled()) { if (Config.getInstance().getMcstatsScoreboardsEnabled()) {
ScoreboardManager.setupPlayerScoreboard(player.getName()); ScoreboardManager.setupPlayerScoreboard(player.getName());

View File

@@ -3,7 +3,6 @@ package com.gmail.nossr50.commands.player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
@@ -12,10 +11,7 @@ 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.FlatfileDatabaseManager;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask; import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
@@ -84,39 +80,11 @@ public class MctopCommand implements TabExecutor {
ScoreboardManager.enableGlobalStatsScoreboard((Player) sender, skill, page); ScoreboardManager.enableGlobalStatsScoreboard((Player) sender, skill, page);
} }
else { else {
if (Config.getInstance().getUseMySQL()) { display(page, skill, sender);
sqlDisplay(page, skill, sender);
}
else {
flatfileDisplay(page, skill, sender);
}
} }
} }
private void flatfileDisplay(int page, String skill, CommandSender sender) { private void display(int page, String query, CommandSender sender) {
FlatfileDatabaseManager.updateLeaderboards(); // Make sure we have the latest information
if (skill.equalsIgnoreCase("all")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(skill)));
}
int position = (page * 10) - 9;
for (PlayerStat stat : FlatfileDatabaseManager.retrieveInfo(skill, page, 10)) {
String digit = (position < 10) ? "0" : "" + String.valueOf(position);
// Format: 1. Playername - skill value
sender.sendMessage(digit + ". " + ChatColor.GREEN + stat.name + " - " + ChatColor.WHITE + stat.statVal);
position++;
}
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip"));
}
private void sqlDisplay(int page, String query, CommandSender sender) {
new MctopCommandAsyncTask(page, query, sender).runTaskAsynchronously(mcMMO.p); new MctopCommandAsyncTask(page, query, sender).runTaskAsynchronously(mcMMO.p);
} }

View File

@@ -56,8 +56,8 @@ public abstract class SkillCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
switch (args.length) { switch (args.length) {
case 0: case 0:

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.spout;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
@@ -27,7 +28,7 @@ public abstract class SpoutCommand implements TabExecutor {
return true; return true;
} }
playerProfile = UserManager.getPlayer(sender.getName()).getProfile(); playerProfile = UserManager.getPlayer((Player) sender).getProfile();
spoutHud = playerProfile.getSpoutHud(); spoutHud = playerProfile.getSpoutHud();
if (spoutHud == null) { if (spoutHud == null) {

View File

@@ -46,9 +46,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getVerboseLoggingEnabled() { return config.getBoolean("General.Verbose_Logging", false); } public boolean getVerboseLoggingEnabled() { return config.getBoolean("General.Verbose_Logging", false); }
public boolean getConfigOverwriteEnabled() { return config.getBoolean("General.Config_Update_Overwrite", true); } public boolean getConfigOverwriteEnabled() { return config.getBoolean("General.Config_Update_Overwrite", true); }
public boolean getPotatoEnabled() { return config.getBoolean("General.Potato_Explosion_Enabled", false); }
public int getPotatoChance() { return config.getInt("General.Potato_Explosion_Chance", 1); }
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); }
@@ -293,9 +290,9 @@ 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); } 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 getForumulaMultiplier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); } public double getFormulaSkillModifier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
} }

View File

@@ -442,13 +442,10 @@ 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,63 +1,79 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import java.io.File; import java.util.List;
import java.io.IOException; import java.util.Map;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
public class DatabaseManager { public interface DatabaseManager {
private final mcMMO plugin; public final long PURGE_TIME = 2630000000L * Config.getInstance().getOldUsersCutoff();
private final boolean isUsingSQL;
private File usersFile;
public DatabaseManager(final mcMMO plugin, final boolean isUsingSQL) { /**
this.plugin = plugin; * Purge users with 0 power level from the database.
this.isUsingSQL = isUsingSQL; */
public void purgePowerlessUsers();
if (isUsingSQL) { /**
SQLDatabaseManager.checkConnected(); * Purge users who haven't logged on in over a certain time frame from the database.
SQLDatabaseManager.createStructure(); */
} public void purgeOldUsers();
else {
usersFile = new File(mcMMO.getUsersFilePath());
createFlatfileDatabase();
FlatfileDatabaseManager.updateLeaderboards();
}
}
public void purgePowerlessUsers() { /**
plugin.getLogger().info("Purging powerless users..."); * Remove a user from the database.
plugin.getLogger().info("Purged " + (isUsingSQL ? SQLDatabaseManager.purgePowerlessSQL() : FlatfileDatabaseManager.purgePowerlessFlatfile()) + " users from the database."); *
} * @param playerName The name of the user to remove
* @return true if the user was successfully removed, false otherwise
*/
public boolean removeUser(String playerName);
public void purgeOldUsers() { /**
plugin.getLogger().info("Purging old users..."); * Save a user to the database.
plugin.getLogger().info("Purged " + (isUsingSQL ? SQLDatabaseManager.purgeOldSQL() : FlatfileDatabaseManager.removeOldFlatfileUsers()) + " users from the database."); *
} * @param profile The profile of the player to save
*/
public void saveUser(PlayerProfile profile);
public boolean removeUser(String playerName) { /**
if (isUsingSQL ? SQLDatabaseManager.removeUserSQL(playerName) : FlatfileDatabaseManager.removeFlatFileUser(playerName)) { * Retrieve leaderboard info.
Misc.profileCleanup(playerName); *
return true; * @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);
return false; /**
} * Retrieve rank info.
*
* @param playerName The name of the user to retrieve the rankings for
* @return the requested rank information
*/
public Map<String, Integer> readRank(String playerName);
private void createFlatfileDatabase() { /**
if (usersFile.exists()) { * Add a new user to the database.
return; *
} * @param playerName The name of the player to be added to the database
*/
public void newUser(String playerName);
usersFile.getParentFile().mkdir(); /**
* Load a player from the database.
*
* @param playerName The name of the player to load from the database
* @return The player's data
*/
public List<String> loadPlayerData(String playerName);
try { /**
plugin.debug("Creating mcmmo.users file..."); * Convert player data to a different storage format.
new File(mcMMO.getUsersFilePath()).createNewFile(); *
} * @param data The player's data
catch (IOException e) { * @return true if the conversion was successful, false otherwise
e.printStackTrace(); * @throws Exception
} */
} public boolean convert(String[] data) throws Exception;
} }

View File

@@ -0,0 +1,9 @@
package com.gmail.nossr50.database;
import com.gmail.nossr50.config.Config;
public class DatabaseManagerFactory {
public static DatabaseManager getDatabaseManager() {
return Config.getInstance().getUseMySQL() ? new SQLDatabaseManager() : new FlatfileDatabaseManager();
}
}

View File

@@ -1,6 +1,8 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
@@ -11,26 +13,372 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.bukkit.OfflinePlayer;
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.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.database.PlayerStat; 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.skills.SkillType;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.util.Misc;
public final class FlatfileDatabaseManager { public final class FlatfileDatabaseManager implements DatabaseManager {
private static HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>(); private final HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>();
private static List<PlayerStat> powerLevels = new ArrayList<PlayerStat>(); private final List<PlayerStat> powerLevels = new ArrayList<PlayerStat>();
private static long lastUpdate = 0; private long lastUpdate = 0;
private static final long UPDATE_WAIT_TIME = 600000L; // 10 minutes private final long UPDATE_WAIT_TIME = 600000L; // 10 minutes
private static final long ONE_MONTH = 2630000000L; private final File usersFile;
private FlatfileDatabaseManager() {} protected FlatfileDatabaseManager() {
usersFile = new File(mcMMO.getUsersFilePath());
createDatabase();
updateLeaderboards();
}
public void purgePowerlessUsers() {
int purgedUsers = 0;
mcMMO.p.getLogger().info("Purging powerless users...");
for (PlayerStat stat : powerLevels) {
if (stat.statVal == 0 && mcMMO.p.getServer().getPlayerExact(stat.name) == null && removeUser(stat.name)) {
purgedUsers++;
}
}
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...");
for (OfflinePlayer player : mcMMO.p.getServer().getOfflinePlayers()) {
if (!player.isOnline() && (currentTime - player.getLastPlayed() > PURGE_TIME && removeUser(player.getName()))) {
removedPlayers++;
}
}
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();
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 {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
Misc.profileCleanup(playerName);
return worked;
}
public void saveUser(PlayerProfile profile) {
String playerName = profile.getPlayerName();
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
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 {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
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) {
try {
// Open the file to write the player
BufferedWriter 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();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public List<String> loadPlayerData(String playerName) {
List<String> playerData = new ArrayList<String>();
try {
// Open the user file
FileReader file = new FileReader(mcMMO.getUsersFilePath());
BufferedReader in = new BufferedReader(file);
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;
}
// Skill levels
playerData.add(character[24]); // Taming
playerData.add(character[1]); // Mining
playerData.add(character[7]); // Repair
playerData.add(character[5]); // Woodcutting
playerData.add(character[8]); // Unarmed
playerData.add(character[9]); // Herbalism
playerData.add(character[10]); // Excavation
playerData.add(character[11]); // Archery
playerData.add(character[12]); // Swords
playerData.add(character[13]); // Axes
playerData.add(character[14]); // Acrobatics
playerData.add(character[34]); // Fishing
// Experience
playerData.add(character[25]); // Taming
playerData.add(character[4]); // Mining
playerData.add(character[15]); // Repair
playerData.add(character[6]); // Woodcutting
playerData.add(character[16]); // Unarmed
playerData.add(character[17]); // Herbalism
playerData.add(character[18]); // Excavation
playerData.add(character[19]); // Archery
playerData.add(character[20]); // Swords
playerData.add(character[21]); // Axes
playerData.add(character[22]); // Acrobatics
playerData.add(character[35]); // Fishing
// Cooldowns
playerData.add(null); // Taming
playerData.add(character[32]); // SuperBreaker
playerData.add(null); // Repair
playerData.add(character[28]); // Tree Feller
playerData.add(character[26]); // Beserk
playerData.add(character[29]); // Green Terra
playerData.add(character[27]); // Giga Drill Breaker
playerData.add(null); // Archery
playerData.add(character[30]); // Serrated Strikes
playerData.add(character[31]); // Skull Splitter
playerData.add(null); // Acrobatics
playerData.add(character[36]); // Blast Mining
playerData.add(character.length > 33 ? character[33] : null); // HudType
playerData.add(character.length > 38 ? character[38] : null); // MobHealthBar
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return playerData;
}
public boolean convert(String[] character) throws Exception {
// Not implemented
return false;
}
public boolean checkConnected() {
// Not implemented
return false;
}
/** /**
* Update the leader boards. * Update the leader boards.
*/ */
public static void updateLeaderboards() { 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 // 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) { if (System.currentTimeMillis() < lastUpdate + UPDATE_WAIT_TIME) {
return; return;
@@ -62,7 +410,6 @@ public final class FlatfileDatabaseManager {
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
String[] data = line.split(":"); String[] data = line.split(":");
String playerName = data[0]; String playerName = data[0];
int powerLevel = 0; int powerLevel = 0;
@@ -124,160 +471,29 @@ public final class FlatfileDatabaseManager {
playerStatHash.put(SkillType.FISHING, fishing); playerStatHash.put(SkillType.FISHING, fishing);
} }
/** private void createDatabase() {
* Retrieve leaderboard info. if (usersFile.exists()) {
* return;
* @param skillType Skill to retrieve info on.
* @param pageNumber Which page in the leaderboards to retrieve
* @return the requested leaderboard information
*/
public static List<PlayerStat> retrieveInfo(String skillType, int pageNumber, int statsPerPage) {
List<PlayerStat> statsList = skillType.equalsIgnoreCase("all") ? powerLevels : playerStatHash.get(SkillType.getSkill(skillType));
int fromIndex = (Math.max(pageNumber, 1) - 1) * statsPerPage;
return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size()));
} }
public static boolean removeFlatFileUser(String playerName) { usersFile.getParentFile().mkdir();
boolean worked = false;
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
try { try {
FileReader file = new FileReader(usersFilePath); mcMMO.p.debug("Creating mcmmo.users file...");
in = new BufferedReader(file); new File(mcMMO.getUsersFilePath()).createNewFile();
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 { catch (IOException e) {
mcMMO.p.getLogger().info("User found, removing..."); e.printStackTrace();
worked = true;
continue; // Skip the player
} }
} }
out = new FileWriter(usersFilePath); // Write out the new file private Integer getPlayerRank(String playerName, List<PlayerStat> statsList) {
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 int purgePowerlessFlatfile() {
mcMMO.p.getLogger().info("Purging powerless users...");
int purgedUsers = 0;
for (PlayerStat stat : powerLevels) {
if (stat.statVal == 0 && !mcMMO.p.getServer().getOfflinePlayer(stat.name).isOnline() && removeFlatFileUser(stat.name)) {
purgedUsers++;
}
}
return purgedUsers;
}
public 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 Integer getPlayerRank(String playerName, List<PlayerStat> statsList) {
int currentPos = 1;
if (statsList == null) { if (statsList == null) {
return null; return null;
} }
int currentPos = 1;
for (PlayerStat stat : statsList) { for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) { if (stat.name.equalsIgnoreCase(playerName)) {
return currentPos; return currentPos;
@@ -289,40 +505,18 @@ public final class FlatfileDatabaseManager {
return null; return null;
} }
public static Map<String, Integer> getPlayerRanks(String playerName) { private int loadStat(List<PlayerStat> statList, String playerName, String[] data, int dataIndex) {
updateLeaderboards(); if (data.length <= dataIndex) {
Map<String, Integer> skills = new HashMap<String, Integer>();
for (SkillType skill : SkillType.values()) {
if (skill.isChildSkill()) {
continue;
}
skills.put(skill.name(), getPlayerRank(playerName, playerStatHash.get(skill)));
}
skills.put("ALL", getPlayerRank(playerName, powerLevels));
return skills;
}
public static List<PlayerStat> getPlayerStats(String skillName) {
return (skillName.equalsIgnoreCase("all")) ? powerLevels : playerStatHash.get(SkillType.getSkill(skillName));
}
private static int loadStat(List<PlayerStat> statList, String playerName, String[] data, int dataIndex) {
if (data.length > dataIndex) {
int statValue = Integer.parseInt(data[dataIndex]);
statList.add(new PlayerStat(playerName, statValue));
return statValue;
}
return 0; return 0;
} }
private static class SkillComparator implements Comparator<PlayerStat> { int statValue = Integer.parseInt(data[dataIndex]);
statList.add(new PlayerStat(playerName, statValue));
return statValue;
}
private class SkillComparator implements Comparator<PlayerStat> {
@Override @Override
public int compare(PlayerStat o1, PlayerStat o2) { public int compare(PlayerStat o1, PlayerStat o2) {
return (o2.statVal - o1.statVal); return (o2.statVal - o1.statVal);

View File

@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@@ -12,7 +11,8 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler.ShareMode; import com.gmail.nossr50.party.ShareHandler.ShareMode;
public class Party { public class Party {
private LinkedHashSet<String> members = new LinkedHashSet<String>(); private final LinkedHashSet<String> members = new LinkedHashSet<String>();
private String leader; private String leader;
private String name; private String name;
private String password; private String password;
@@ -27,6 +27,30 @@ public class Party {
private boolean shareWoodcuttingDrops = true; private boolean shareWoodcuttingDrops = true;
private boolean shareMiscDrops = true; private boolean shareMiscDrops = true;
public Party(String name) {
this.name = name;
}
public Party(String leader, String name) {
this.leader = leader;
this.name = name;
this.locked = true;
}
public Party(String leader, String name, String password) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = true;
}
public Party(String leader, String name, String password, boolean locked) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = locked;
}
public LinkedHashSet<String> getMembers() { public LinkedHashSet<String> getMembers() {
return members; return members;
} }
@@ -35,9 +59,10 @@ public class Party {
List<Player> onlineMembers = new ArrayList<Player>(); List<Player> onlineMembers = new ArrayList<Player>();
for (String memberName : members) { for (String memberName : members) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName); Player member = mcMMO.p.getServer().getPlayerExact(memberName);
if (member.isOnline()) {
onlineMembers.add(member.getPlayer()); if (member != null) {
onlineMembers.add(member);
} }
} }
@@ -166,4 +191,28 @@ public class Party {
return; return;
} }
} }
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Party)) {
return false;
}
Party other = (Party) obj;
if ((this.getName() == null) || (other.getName() == null)) {
return false;
}
return this.getName().equals(other.getName());
}
@Override
public int hashCode() {
return super.hashCode();
}
} }

View File

@@ -7,7 +7,6 @@ import java.util.Set;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
@@ -54,7 +53,7 @@ public class McMMOPlayer {
* we make sure that all class inheriting from SkillManager are instanced. * we make sure that all class inheriting from SkillManager are instanced.
* Which solution is better, I let you decide. - bm01 * Which solution is better, I let you decide. - bm01
*/ */
private Map<SkillType, SkillManager> skillManagers = new HashMap<SkillType, SkillManager>(); private final Map<SkillType, SkillManager> skillManagers = new HashMap<SkillType, SkillManager>();
private Party party; private Party party;
private Party invite; private Party invite;
@@ -76,11 +75,11 @@ public class McMMOPlayer {
private int lastSalvageClick; private int lastSalvageClick;
private boolean godMode; private boolean godMode;
private Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>();
private Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>();
private Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>(); private final Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>();
private Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>(); private final Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>();
private int recentlyHurt; private int recentlyHurt;
private int respawnATS; private int respawnATS;
@@ -202,10 +201,10 @@ public class McMMOPlayer {
* Set the mode of an ability. * Set the mode of an ability.
* *
* @param ability The ability to check * @param ability The ability to check
* @param bool True if the ability is active, false otherwise * @param isActive True if the ability is active, false otherwise
*/ */
public void setAbilityMode(AbilityType ability, boolean bool) { public void setAbilityMode(AbilityType ability, boolean isActive) {
abilityMode.put(ability, bool); abilityMode.put(ability, isActive);
} }
/** /**
@@ -222,10 +221,10 @@ public class McMMOPlayer {
* Set the informed state of an ability. * Set the informed state of an ability.
* *
* @param ability The ability to check * @param ability The ability to check
* @param bool True if the ability is informed, false otherwise * @param isInformed True if the ability is informed, false otherwise
*/ */
public void setAbilityInformed(AbilityType ability, boolean bool) { public void setAbilityInformed(AbilityType ability, boolean isInformed) {
abilityInformed.put(ability, bool); abilityInformed.put(ability, isInformed);
} }
/** /**
@@ -263,10 +262,10 @@ public class McMMOPlayer {
* Set the current prep mode of a tool. * Set the current prep mode of a tool.
* *
* @param tool Tool to set the mode for * @param tool Tool to set the mode for
* @param bool true if the tool should be prepped, false otherwise * @param isPrepared true if the tool should be prepped, false otherwise
*/ */
public void setToolPreparationMode(ToolType tool, boolean bool) { public void setToolPreparationMode(ToolType tool, boolean isPrepared) {
toolMode.put(tool, bool); toolMode.put(tool, isPrepared);
} }
/** /**
@@ -332,7 +331,7 @@ public class McMMOPlayer {
} }
public void actualizeTeleportCommenceLocation(Player player) { public void actualizeTeleportCommenceLocation(Player player) {
setTeleportCommenceLocation(player.getLocation()); teleportCommence = player.getLocation();
} }
/* /*
@@ -441,11 +440,7 @@ public class McMMOPlayer {
public int getPowerLevel() { public int getPowerLevel() {
int powerLevel = 0; int powerLevel = 0;
for (SkillType type : SkillType.values()) { for (SkillType type : SkillType.nonChildSkills()) {
if (type.isChildSkill()) {
continue;
}
if (Permissions.skillEnabled(player, type)) { if (Permissions.skillEnabled(player, type)) {
powerLevel += profile.getSkillLevel(type); powerLevel += profile.getSkillLevel(type);
} }
@@ -504,6 +499,10 @@ public class McMMOPlayer {
* @param xp Experience amount to add * @param xp Experience amount to add
*/ */
public void applyXpGain(SkillType skillType, float xp) { public void applyXpGain(SkillType skillType, float xp) {
if (!Permissions.skillEnabled(player, skillType)) {
return;
}
if (skillType.isChildSkill()) { if (skillType.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skillType); Set<SkillType> parentSkills = FamilyTree.getParents(skillType);
@@ -514,10 +513,6 @@ public class McMMOPlayer {
return; return;
} }
if (!Permissions.skillEnabled(player, skillType)) {
return;
}
McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skillType, xp); McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skillType, xp);
mcMMO.p.getServer().getPluginManager().callEvent(event); mcMMO.p.getServer().getPluginManager().callEvent(event);
@@ -533,7 +528,7 @@ public class McMMOPlayer {
spoutHud.setLastGained(skillType); spoutHud.setLastGained(skillType);
} }
isUsingUnarmed = skillType == SkillType.UNARMED; isUsingUnarmed = (skillType == SkillType.UNARMED);
SkillUtils.xpCheckSkill(skillType, player, profile); SkillUtils.xpCheckSkill(skillType, player, profile);
} }
@@ -566,11 +561,7 @@ public class McMMOPlayer {
} }
public boolean hasPartyInvite() { public boolean hasPartyInvite() {
if (invite != null) { return (invite != null);
return true;
}
return false;
} }
public void setParty(Party party) { public void setParty(Party party) {
@@ -582,11 +573,7 @@ public class McMMOPlayer {
} }
public boolean inParty() { public boolean inParty() {
if (party != null) { return (party != null);
return true;
}
return false;
} }
public void removeParty() { public void removeParty() {
@@ -614,11 +601,7 @@ public class McMMOPlayer {
} }
public boolean hasPtpRequest() { public boolean hasPtpRequest() {
if (ptpRequest != null) { return (ptpRequest != null);
return true;
}
return false;
} }
public void removePtpRequest() { public void removePtpRequest() {
@@ -650,11 +633,7 @@ public class McMMOPlayer {
} }
public void setItemShareModifier(int modifier) { public void setItemShareModifier(int modifier) {
if (modifier < 10) { itemShareModifier = Math.max(10, modifier);
modifier = 10;
}
itemShareModifier = modifier;
} }
/* /*
@@ -697,15 +676,14 @@ public class McMMOPlayer {
* @return Modified experience * @return Modified experience
*/ */
private float modifyXpGain(SkillType skillType, float xp) { private float modifyXpGain(SkillType skillType, float xp) {
if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() < profile.getSkillLevel(skillType) + 1) || (Config.getInstance().getPowerLevelCap() < getPowerLevel() + 1)) { if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() <= profile.getSkillLevel(skillType)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) {
return 0; return 0;
} }
xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()); xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
if (Config.getInstance().getToolModsEnabled()) { if (Config.getInstance().getToolModsEnabled()) {
ItemStack item = player.getItemInHand(); CustomTool tool = ModUtils.getToolFromItemStack(player.getItemInHand());
CustomTool tool = ModUtils.getToolFromItemStack(item);
if (tool != null) { if (tool != null) {
xp *= tool.getXpMultiplier(); xp *= tool.getXpMultiplier();

View File

@@ -1,11 +1,7 @@
package com.gmail.nossr50.datatypes.player; package com.gmail.nossr50.datatypes.player;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -14,18 +10,15 @@ import org.bukkit.scoreboard.Scoreboard;
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.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.MobHealthbarType; 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.datatypes.spout.huds.HudType; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.datatypes.spout.huds.McMMOHud; import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.skills.child.FamilyTree; import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.Misc;
public class PlayerProfile { public class PlayerProfile {
private final String playerName; private final String playerName;
private int userId;
private boolean loaded; private boolean loaded;
/* HUDs */ /* HUDs */
@@ -49,28 +42,19 @@ public class PlayerProfile {
skillsDATS.put(abilityType, 0); skillsDATS.put(abilityType, 0);
} }
for (SkillType skillType : SkillType.values()) { for (SkillType skillType : SkillType.nonChildSkills()) {
if (skillType.isChildSkill()) {
continue;
}
skills.put(skillType, 0); skills.put(skillType, 0);
skillsXp.put(skillType, 0F); skillsXp.put(skillType, 0F);
} }
if (!loadPlayer() && addNew) { if (!loadPlayer() && addNew) {
addPlayer(); mcMMO.getDatabaseManager().newUser(playerName);
loaded = true; loaded = true;
} }
} }
public void save() { public void save() {
if (Config.getInstance().getUseMySQL()) { mcMMO.getDatabaseManager().saveUser(this);
saveMySQL();
}
else {
saveFlatfile();
}
} }
public String getPlayerName() { public String getPlayerName() {
@@ -272,123 +256,60 @@ public class PlayerProfile {
} }
private boolean loadPlayer() { private boolean loadPlayer() {
return Config.getInstance().getUseMySQL() ? loadMySQL() : loadFlatfile(); List<String> playerData = mcMMO.getDatabaseManager().loadPlayerData(playerName);
}
private void addPlayer() { if (playerData == null || playerData.isEmpty()) {
if (Config.getInstance().getUseMySQL()) {
addMySQLPlayer();
}
else {
addFlatfilePlayer();
}
}
private boolean loadMySQL() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
ArrayList<String> playerData = SQLDatabaseManager.read(
"SELECT " +
"u.id, " +
"s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, " +
"e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, " +
"c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, " +
"h.hudtype, h.mobhealthbar " +
"FROM " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"WHERE u.user = '" + playerName + "'"
).get(1);
if (playerData == null || playerData.size() == 0) {
userId = SQLDatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
// Check if user doesn't exist
if (userId == 0) {
return false; return false;
} }
// Write missing table rows skills.put(SkillType.TAMING, Integer.valueOf(playerData.get(0)));
SQLDatabaseManager.write("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")"); skills.put(SkillType.MINING, Integer.valueOf(playerData.get(1)));
SQLDatabaseManager.write("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")"); skills.put(SkillType.REPAIR, Integer.valueOf(playerData.get(2)));
SQLDatabaseManager.write("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")"); skills.put(SkillType.WOODCUTTING, Integer.valueOf(playerData.get(3)));
SQLDatabaseManager.write("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (" + userId + ",'" + mobHealthbarType.name() + "')"); skills.put(SkillType.UNARMED, Integer.valueOf(playerData.get(4)));
skills.put(SkillType.HERBALISM, Integer.valueOf(playerData.get(5)));
skills.put(SkillType.EXCAVATION, Integer.valueOf(playerData.get(6)));
skills.put(SkillType.ARCHERY, Integer.valueOf(playerData.get(7)));
skills.put(SkillType.SWORDS, Integer.valueOf(playerData.get(8)));
skills.put(SkillType.AXES, Integer.valueOf(playerData.get(9)));
skills.put(SkillType.ACROBATICS, Integer.valueOf(playerData.get(10)));
skills.put(SkillType.FISHING, Integer.valueOf(playerData.get(11)));
// Re-read data skillsXp.put(SkillType.TAMING, (float) Integer.valueOf(playerData.get(12)));
playerData = SQLDatabaseManager.read( skillsXp.put(SkillType.MINING, (float) Integer.valueOf(playerData.get(13)));
"SELECT " + skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(playerData.get(14)));
"u.id, " + skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(playerData.get(15)));
"s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, " + skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(playerData.get(16)));
"e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, " + skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(playerData.get(17)));
"c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, " + skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(playerData.get(18)));
"h.hudtype, h.mobhealthbar " + skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(playerData.get(19)));
"FROM " + tablePrefix + "users u " + skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(playerData.get(20)));
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + skillsXp.put(SkillType.AXES, (float) Integer.valueOf(playerData.get(21)));
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " + skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(playerData.get(22)));
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(playerData.get(23)));
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"WHERE u.user = '" + playerName + "'"
).get(1);
// Should never happen but just in case // Taming 24 - Unused
if (playerData == null || playerData.size() == 0) { skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(playerData.get(25)));
return false; // Repair 26 - Unused
} skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(playerData.get(27)));
} skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(playerData.get(28)));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(playerData.get(29)));
userId = Integer.valueOf(playerData.get(0)); skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(playerData.get(30)));
// Archery 31 - Unused
skills.put(SkillType.TAMING, Integer.valueOf(playerData.get(1))); skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(playerData.get(32)));
skills.put(SkillType.MINING, Integer.valueOf(playerData.get(2))); skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(playerData.get(33)));
skills.put(SkillType.REPAIR, Integer.valueOf(playerData.get(3))); // Acrobatics 34 - Unused
skills.put(SkillType.WOODCUTTING, Integer.valueOf(playerData.get(4))); skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(playerData.get(35)));
skills.put(SkillType.UNARMED, Integer.valueOf(playerData.get(5)));
skills.put(SkillType.HERBALISM, Integer.valueOf(playerData.get(6)));
skills.put(SkillType.EXCAVATION, Integer.valueOf(playerData.get(7)));
skills.put(SkillType.ARCHERY, Integer.valueOf(playerData.get(8)));
skills.put(SkillType.SWORDS, Integer.valueOf(playerData.get(9)));
skills.put(SkillType.AXES, Integer.valueOf(playerData.get(10)));
skills.put(SkillType.ACROBATICS, Integer.valueOf(playerData.get(11)));
skills.put(SkillType.FISHING, Integer.valueOf(playerData.get(12)));
skillsXp.put(SkillType.TAMING, (float) Integer.valueOf(playerData.get(13)));
skillsXp.put(SkillType.MINING, (float) Integer.valueOf(playerData.get(14)));
skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(playerData.get(15)));
skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(playerData.get(16)));
skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(playerData.get(17)));
skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(playerData.get(18)));
skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(playerData.get(19)));
skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(playerData.get(20)));
skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(playerData.get(21)));
skillsXp.put(SkillType.AXES, (float) Integer.valueOf(playerData.get(22)));
skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(playerData.get(23)));
skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(playerData.get(24)));
// Taming 25 - Unused
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(playerData.get(26)));
// Repair 27 - Unused
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(playerData.get(28)));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(playerData.get(29)));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(playerData.get(30)));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(playerData.get(31)));
// Archery 32 - Unused
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(playerData.get(33)));
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(playerData.get(34)));
// Acrobatics 35 - Unused
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(playerData.get(36)));
try { try {
hudType = HudType.valueOf(playerData.get(37)); hudType = HudType.valueOf(playerData.get(36));
} }
catch (Exception e) { catch (Exception e) {
// Shouldn't happen unless database is being tampered with hudType = HudType.STANDARD; // Shouldn't happen unless database is being tampered with
hudType = HudType.STANDARD;
} }
try { try {
mobHealthbarType = MobHealthbarType.valueOf(playerData.get(38)); mobHealthbarType = MobHealthbarType.valueOf(playerData.get(37));
} }
catch (Exception e) { catch (Exception e) {
mobHealthbarType = Config.getInstance().getMobHealthbarDefault(); mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
@@ -397,277 +318,4 @@ public class PlayerProfile {
loaded = true; loaded = true;
return true; return true;
} }
private void addMySQLPlayer() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES ('" + playerName + "'," + System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR + ")");
userId = SQLDatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (" + userId + ", '" + mobHealthbarType.name() + "')");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
}
private void addFlatfilePlayer() {
try {
// Open the file to write the player
BufferedWriter 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(hudType == null ? "STANDARD" : hudType.toString()).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(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":"); // Mob Healthbar HUD
// Add more in the same format as the line above
out.newLine();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private boolean loadFlatfile() {
try {
// Open the user file
FileReader file = new FileReader(mcMMO.getUsersFilePath());
BufferedReader in = new BufferedReader(file);
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;
}
loadSkillData(SkillType.MINING, character, 1);
loadSkillData(SkillType.WOODCUTTING, character, 5);
loadSkillData(SkillType.REPAIR, character, 7);
loadSkillData(SkillType.UNARMED, character, 8);
loadSkillData(SkillType.HERBALISM, character, 9);
loadSkillData(SkillType.EXCAVATION, character, 10);
loadSkillData(SkillType.ARCHERY, character, 11);
loadSkillData(SkillType.SWORDS, character, 12);
loadSkillData(SkillType.AXES, character, 13);
loadSkillData(SkillType.ACROBATICS, character, 14);
loadSkillData(SkillType.TAMING, character, 24);
loadSkillData(SkillType.FISHING, character, 34);
loadSkillXpData(SkillType.MINING, character, 4);
loadSkillXpData(SkillType.WOODCUTTING, character, 6);
loadSkillXpData(SkillType.REPAIR, character, 15);
loadSkillXpData(SkillType.UNARMED, character, 16);
loadSkillXpData(SkillType.HERBALISM, character, 17);
loadSkillXpData(SkillType.EXCAVATION, character, 18);
loadSkillXpData(SkillType.ARCHERY, character, 19);
loadSkillXpData(SkillType.SWORDS, character, 20);
loadSkillXpData(SkillType.AXES, character, 21);
loadSkillXpData(SkillType.ACROBATICS, character, 22);
loadSkillXpData(SkillType.TAMING, character, 25);
loadSkillXpData(SkillType.FISHING, character, 35);
loadDATSData(AbilityType.BERSERK, character, 26);
loadDATSData(AbilityType.GIGA_DRILL_BREAKER, character, 27);
loadDATSData(AbilityType.TREE_FELLER, character, 28);
loadDATSData(AbilityType.GREEN_TERRA, character, 29);
loadDATSData(AbilityType.SERRATED_STRIKES, character, 30);
loadDATSData(AbilityType.SKULL_SPLITTER, character, 31);
loadDATSData(AbilityType.SUPER_BREAKER, character, 32);
loadDATSData(AbilityType.BLAST_MINING, character, 36);
hudType = character.length > 33 ? HudType.valueOf(character[33]) : null;
mobHealthbarType = character.length > 38 ? MobHealthbarType.valueOf(character[38]) : null;
loaded = true;
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return loaded;
}
private void saveMySQL() {
if (Config.getInstance().getUseMySQL()) {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
SQLDatabaseManager.write("UPDATE " + tablePrefix + "users SET lastlogin = " + ((int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)) + " WHERE id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "huds SET "
+ " hudtype = '" + (hudType == null ? "STANDARD" : hudType.toString() + "'")
+ ", mobhealthbar = '" + (mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString() + "'")
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = " + skillsDATS.get(AbilityType.SUPER_BREAKER)
+ ", woodcutting = " + skillsDATS.get(AbilityType.TREE_FELLER)
+ ", unarmed = " + skillsDATS.get(AbilityType.BERSERK)
+ ", herbalism = " + skillsDATS.get(AbilityType.GREEN_TERRA)
+ ", excavation = " + skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)
+ ", swords = " + skillsDATS.get(AbilityType.SERRATED_STRIKES)
+ ", axes = " + skillsDATS.get(AbilityType.SKULL_SPLITTER)
+ ", blast_mining = " + skillsDATS.get(AbilityType.BLAST_MINING)
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "skills SET "
+ " taming = " + skills.get(SkillType.TAMING)
+ ", mining = " + skills.get(SkillType.MINING)
+ ", repair = " + skills.get(SkillType.REPAIR)
+ ", woodcutting = " + skills.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skills.get(SkillType.UNARMED)
+ ", herbalism = " + skills.get(SkillType.HERBALISM)
+ ", excavation = " + skills.get(SkillType.EXCAVATION)
+ ", archery = " + skills.get(SkillType.ARCHERY)
+ ", swords = " + skills.get(SkillType.SWORDS)
+ ", axes = " + skills.get(SkillType.AXES)
+ ", acrobatics = " + skills.get(SkillType.ACROBATICS)
+ ", fishing = " + skills.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "experience SET "
+ " taming = " + getSkillXpLevel(SkillType.TAMING)
+ ", mining = " + getSkillXpLevel(SkillType.MINING)
+ ", repair = " + getSkillXpLevel(SkillType.REPAIR)
+ ", woodcutting = " + getSkillXpLevel(SkillType.WOODCUTTING)
+ ", unarmed = " + getSkillXpLevel(SkillType.UNARMED)
+ ", herbalism = " + getSkillXpLevel(SkillType.HERBALISM)
+ ", excavation = " + getSkillXpLevel(SkillType.EXCAVATION)
+ ", archery = " + getSkillXpLevel(SkillType.ARCHERY)
+ ", swords = " + getSkillXpLevel(SkillType.SWORDS)
+ ", axes = " + getSkillXpLevel(SkillType.AXES)
+ ", acrobatics = " + getSkillXpLevel(SkillType.ACROBATICS)
+ ", fishing = " + getSkillXpLevel(SkillType.FISHING)
+ " WHERE user_id = " + userId);
}
}
private void saveFlatfile() {
try {
// Open the file
BufferedReader in = new BufferedReader(new FileReader(mcMMO.getUsersFilePath()));
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(skills.get(SkillType.MINING)).append(":");
writer.append(":");
writer.append(":");
writer.append(getSkillXpLevel(SkillType.MINING)).append(":");
writer.append(skills.get(SkillType.WOODCUTTING)).append(":");
writer.append(getSkillXpLevel(SkillType.WOODCUTTING)).append(":");
writer.append(skills.get(SkillType.REPAIR)).append(":");
writer.append(skills.get(SkillType.UNARMED)).append(":");
writer.append(skills.get(SkillType.HERBALISM)).append(":");
writer.append(skills.get(SkillType.EXCAVATION)).append(":");
writer.append(skills.get(SkillType.ARCHERY)).append(":");
writer.append(skills.get(SkillType.SWORDS)).append(":");
writer.append(skills.get(SkillType.AXES)).append(":");
writer.append(skills.get(SkillType.ACROBATICS)).append(":");
writer.append(getSkillXpLevel(SkillType.REPAIR)).append(":");
writer.append(getSkillXpLevel(SkillType.UNARMED)).append(":");
writer.append(getSkillXpLevel(SkillType.HERBALISM)).append(":");
writer.append(getSkillXpLevel(SkillType.EXCAVATION)).append(":");
writer.append(getSkillXpLevel(SkillType.ARCHERY)).append(":");
writer.append(getSkillXpLevel(SkillType.SWORDS)).append(":");
writer.append(getSkillXpLevel(SkillType.AXES)).append(":");
writer.append(getSkillXpLevel(SkillType.ACROBATICS)).append(":");
writer.append(":");
writer.append(skills.get(SkillType.TAMING)).append(":");
writer.append(getSkillXpLevel(SkillType.TAMING)).append(":");
writer.append(skillsDATS.get(AbilityType.BERSERK)).append(":");
writer.append(skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)).append(":");
writer.append(skillsDATS.get(AbilityType.TREE_FELLER)).append(":");
writer.append(skillsDATS.get(AbilityType.GREEN_TERRA)).append(":");
writer.append(skillsDATS.get(AbilityType.SERRATED_STRIKES)).append(":");
writer.append(skillsDATS.get(AbilityType.SKULL_SPLITTER)).append(":");
writer.append(skillsDATS.get(AbilityType.SUPER_BREAKER)).append(":");
writer.append(hudType == null ? "STANDARD" : hudType.toString()).append(":");
writer.append(skills.get(SkillType.FISHING)).append(":");
writer.append(getSkillXpLevel(SkillType.FISHING)).append(":");
writer.append(skillsDATS.get(AbilityType.BLAST_MINING)).append(":");
writer.append(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR).append(":");
writer.append(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":");
writer.append("\r\n");
}
}
in.close();
// Write the new file
FileWriter out = new FileWriter(mcMMO.getUsersFilePath());
out.write(writer.toString());
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void loadSkillXpData(SkillType skill, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skillsXp.put(skill, (float) Integer.valueOf(data[dataIndex]));
}
}
private void loadSkillData(SkillType skill, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skills.put(skill, Integer.valueOf(data[dataIndex]));
}
}
private void loadDATSData(AbilityType ability, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skillsDATS.put(ability, Integer.valueOf(data[dataIndex]));
}
}
} }

View File

@@ -68,6 +68,13 @@ public enum AbilityType {
null), null),
LEAF_BLOWER( LEAF_BLOWER(
null,
null,
null,
null,
null),
BLOCK_CRACKER(
null, null,
null, null,
null, null,
@@ -144,7 +151,6 @@ public enum AbilityType {
* @return true if the player has permissions, false otherwise * @return true if the player has permissions, false otherwise
*/ */
public boolean getPermissions(Player player) { public boolean getPermissions(Player player) {
switch (this) { switch (this) {
case BERSERK: case BERSERK:
return Permissions.berserk(player); return Permissions.berserk(player);
@@ -152,6 +158,9 @@ public enum AbilityType {
case BLAST_MINING: case BLAST_MINING:
return Permissions.remoteDetonation(player); return Permissions.remoteDetonation(player);
case BLOCK_CRACKER:
return Permissions.blockCracker(player);
case GIGA_DRILL_BREAKER: case GIGA_DRILL_BREAKER:
return Permissions.gigaDrillBreaker(player); return Permissions.gigaDrillBreaker(player);
@@ -189,6 +198,9 @@ public enum AbilityType {
case BERSERK: case BERSERK:
return (BlockUtils.affectedByGigaDrillBreaker(blockState) || blockState.getType() == Material.SNOW); return (BlockUtils.affectedByGigaDrillBreaker(blockState) || blockState.getType() == Material.SNOW);
case BLOCK_CRACKER:
return BlockUtils.affectedByBlockCracker(blockState);
case GIGA_DRILL_BREAKER: case GIGA_DRILL_BREAKER:
return BlockUtils.affectedByGigaDrillBreaker(blockState); return BlockUtils.affectedByGigaDrillBreaker(blockState);

View File

@@ -108,7 +108,7 @@ public enum SkillType {
} }
public double getXpModifier() { public double getXpModifier() {
return Config.getInstance().getForumulaMultiplier(this); return Config.getInstance().getFormulaSkillModifier(this);
} }
public static SkillType getSkill(String skillName) { public static SkillType getSkill(String skillName) {

View File

@@ -56,11 +56,7 @@ public class McMMOHud {
} }
public boolean isMenuOpened() { public boolean isMenuOpened() {
if (menu != null) { return (menu != null);
return true;
}
return false;
} }
public void openMenu() { public void openMenu() {

View File

@@ -17,7 +17,7 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
public McMMOPlayerLevelUpEvent(Player player, SkillType skill, int levelsGained) { public McMMOPlayerLevelUpEvent(Player player, SkillType skill, int levelsGained) {
super(player, skill); super(player, skill);
this.setLevelsGained(levelsGained); this.levelsGained = levelsGained;
} }
/** /**

View File

@@ -0,0 +1,45 @@
package com.gmail.nossr50.events.skills.fishing;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
public class McMMOPlayerFishingTreasureEvent extends McMMOPlayerSkillEvent implements Cancellable {
private boolean cancelled = false;
private ItemStack treasure;
private int xp;
public McMMOPlayerFishingTreasureEvent(Player player, ItemStack treasure, int xp) {
super(player, SkillType.FISHING);
this.treasure = treasure;
this.xp = xp;
}
public ItemStack getTreasure() {
return treasure;
}
public void setTreasure(ItemStack item) {
this.treasure = item;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean newValue) {
this.cancelled = newValue;
}
public int getXp() {
return xp;
}
public void setXp(int xp) {
this.xp = xp;
}
}

View File

@@ -0,0 +1,21 @@
package com.gmail.nossr50.events.skills.fishing;
import java.util.Map;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent {
private Map<Enchantment, Integer> enchants;
public McMMOPlayerMagicHunterEvent(Player player, ItemStack treasure, int xp, Map<Enchantment, Integer> enchants) {
super(player, treasure, xp);
this.enchants = enchants;
}
public Map<Enchantment, Integer> getEnchantments() {
return enchants;
}
}

View File

@@ -0,0 +1,36 @@
package com.gmail.nossr50.events.skills.fishing;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
public class McMMOPlayerShakeEvent extends McMMOPlayerSkillEvent implements Cancellable {
private boolean cancelled = false;
private ItemStack drop;
public McMMOPlayerShakeEvent(Player player, ItemStack drop) {
super(player, SkillType.FISHING);
this.drop = drop;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean newValue) {
this.cancelled = newValue;
}
public ItemStack getDrop() {
return drop;
}
public void setDrop(ItemStack drop) {
this.drop = drop;
}
}

View File

@@ -28,14 +28,12 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent; import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.events.fake.FakeBlockDamageEvent; import com.gmail.nossr50.events.fake.FakeBlockDamageEvent;
import com.gmail.nossr50.events.fake.FakePlayerAnimationEvent;
import com.gmail.nossr50.runnables.StickyPistonTrackerTask; import com.gmail.nossr50.runnables.StickyPistonTrackerTask;
import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager; import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.smelting.SmeltingManager; import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager; import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.ItemUtils;
@@ -72,9 +70,11 @@ public class BlockListener implements Listener {
} }
for (Block b : blocks) { for (Block b : blocks) {
if (b.getRelative(direction).hasMetadata(mcMMO.blockMetadataKey)) { Block nextBlock = b.getRelative(direction);
mcMMO.getPlaceStore().setTrue(b.getRelative(direction));
b.getRelative(direction).removeMetadata(mcMMO.blockMetadataKey, plugin); if (nextBlock.hasMetadata(mcMMO.blockMetadataKey)) {
mcMMO.getPlaceStore().setTrue(nextBlock);
nextBlock.removeMetadata(mcMMO.blockMetadataKey, plugin);
} }
} }
} }
@@ -106,15 +106,14 @@ public class BlockListener implements Listener {
} }
BlockState blockState = event.getBlock().getState(); BlockState blockState = event.getBlock().getState();
int blockId = blockState.getTypeId();
/* Check if the blocks placed should be monitored so they do not give out XP in the future */ /* Check if the blocks placed should be monitored so they do not give out XP in the future */
if (BlockUtils.shouldBeWatched(blockState)) { if (BlockUtils.shouldBeWatched(blockState)) {
mcMMO.getPlaceStore().setTrue(blockState); mcMMO.getPlaceStore().setTrue(blockState);
} }
if (Repair.anvilMessagesEnabled && (blockId == Repair.repairAnvilId || blockId == Repair.salvageAnvilId)) { if (Repair.anvilMessagesEnabled && BlockUtils.isMcMMOAnvil(blockState)) {
UserManager.getPlayer(player).getRepairManager().placedAnvilCheck(blockId); UserManager.getPlayer(player).getRepairManager().placedAnvilCheck(blockState.getTypeId());
} }
} }
@@ -323,41 +322,31 @@ public class BlockListener implements Listener {
ItemStack heldItem = player.getItemInHand(); ItemStack heldItem = player.getItemInHand();
Block block = event.getBlock(); Block block = event.getBlock();
BlockState blockState = block.getState(); BlockState blockState = block.getState();
HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager();
/* /*
* ABILITY TRIGGER CHECKS * ABILITY TRIGGER CHECKS
* *
* We don't need to check permissions here because they've already been checked for the ability to even activate. * We don't need to check permissions here because they've already been checked for the ability to even activate.
*/ */
if (herbalismManager.canGreenTerraBlock(blockState)) { if (mcMMOPlayer.getAbilityMode(AbilityType.GREEN_TERRA) && BlockUtils.canMakeMossy(blockState)) {
if (herbalismManager.processGreenTerra(blockState)) { if (mcMMOPlayer.getHerbalismManager().processGreenTerra(blockState)) {
blockState.update(true); blockState.update(true);
} }
} }
else if (mcMMOPlayer.getAbilityMode(AbilityType.BERSERK)) { else if (mcMMOPlayer.getAbilityMode(AbilityType.BERSERK) && heldItem.getType() == Material.AIR) {
if (SkillUtils.triggerCheck(player, block, AbilityType.BERSERK)) { if (SkillUtils.triggerCheck(player, block, AbilityType.BERSERK)) {
if (heldItem.getType() == Material.AIR) {
plugin.getServer().getPluginManager().callEvent(new FakePlayerAnimationEvent(player));
event.setInstaBreak(true); event.setInstaBreak(true);
player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch()); player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
} }
} else if (Permissions.blockCracker(player) && SkillUtils.triggerCheck(player, block, AbilityType.BLOCK_CRACKER)) {
// Another perm check for the cracked blocks activation if (mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) {
else if (BlockUtils.affectedByBlockCracker(blockState)) {
UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager();
if (unarmedManager.canUseBlockCracker() && SkillUtils.blockBreakSimulate(block, player, false) && unarmedManager.blockCrackerCheck(blockState)) {
blockState.update(); blockState.update();
} }
} }
} }
else if (BlockUtils.isLeaves(blockState)) { else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && SkillUtils.triggerCheck(player, block, AbilityType.LEAF_BLOWER)) {
if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && SkillUtils.blockBreakSimulate(block, player, true)) {
event.setInstaBreak(true); event.setInstaBreak(true);
player.playSound(blockState.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch()); player.playSound(blockState.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
} }
} }
} }
}

View File

@@ -28,6 +28,7 @@ import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
@@ -59,20 +60,32 @@ public class EntityListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityShootBow(EntityShootBowEvent event) { public void onEntityShootBow(EntityShootBowEvent event) {
ItemStack bow = event.getBow();
if (bow != null) {
Entity projectile = event.getProjectile(); Entity projectile = event.getProjectile();
if (projectile instanceof Arrow) { if (!(projectile instanceof Arrow)) {
if (bow.containsEnchantment(Enchantment.ARROW_INFINITE)) { return;
}
ItemStack bow = event.getBow();
if (bow != null && bow.containsEnchantment(Enchantment.ARROW_INFINITE)) {
projectile.setMetadata(mcMMO.infiniteArrowKey, mcMMO.metadataValue); projectile.setMetadata(mcMMO.infiniteArrowKey, mcMMO.metadataValue);
} }
projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(plugin, Math.min(event.getForce() * AdvancedConfig.getInstance().getForceMultiplier(), 1.0))); projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(plugin, Math.min(event.getForce() * AdvancedConfig.getInstance().getForceMultiplier(), 1.0)));
projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(plugin, Archery.locationToString(projectile.getLocation()))); projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(plugin, Archery.locationToString(projectile.getLocation())));
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile projectile = event.getEntity();
if (!(projectile instanceof Arrow) || projectile.hasMetadata(mcMMO.bowForceKey)) {
return;
} }
projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(plugin, 1.0));
projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(plugin, Archery.locationToString(projectile.getLocation())));
} }
/** /**
@@ -81,7 +94,7 @@ public class EntityListener implements Listener {
* @param event The event to watch * @param event The event to watch
*/ */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (!(entity instanceof FallingBlock)) { if (!(entity instanceof FallingBlock)) {
@@ -107,7 +120,13 @@ public class EntityListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event instanceof FakeEntityDamageByEntityEvent || event.getDamage() <= 0) { if (event instanceof FakeEntityDamageByEntityEvent) {
return;
}
int damage = event.getDamage();
if (damage <= 0) {
return; return;
} }
@@ -117,13 +136,14 @@ public class EntityListener implements Listener {
return; return;
} }
Entity attacker = event.getDamager();
LivingEntity target = (LivingEntity) defender; LivingEntity target = (LivingEntity) defender;
if (CombatUtils.isInvincible(target, event.getDamage())) { if (CombatUtils.isInvincible(target, damage)) {
return; return;
} }
Entity attacker = event.getDamager();
if (attacker instanceof Projectile) { if (attacker instanceof Projectile) {
attacker = ((Projectile) attacker).getShooter(); attacker = ((Projectile) attacker).getShooter();
} }
@@ -150,7 +170,7 @@ public class EntityListener implements Listener {
} }
} }
CombatUtils.combatChecks(event, attacker, target); CombatUtils.processCombatAttack(event, attacker, target);
} }
/** /**
@@ -160,7 +180,13 @@ public class EntityListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof FakeEntityDamageEvent || event.getDamage() <= 0) { if (event instanceof FakeEntityDamageEvent) {
return;
}
int damage = event.getDamage();
if (damage <= 0) {
return; return;
} }
@@ -170,13 +196,14 @@ public class EntityListener implements Listener {
return; return;
} }
DamageCause cause = event.getCause();
LivingEntity livingEntity = (LivingEntity) entity; LivingEntity livingEntity = (LivingEntity) entity;
if (CombatUtils.isInvincible(livingEntity, event.getDamage())) { if (CombatUtils.isInvincible(livingEntity, damage)) {
return; return;
} }
DamageCause cause = event.getCause();
if (livingEntity instanceof Player) { if (livingEntity instanceof Player) {
Player player = (Player) entity; Player player = (Player) entity;
@@ -296,6 +323,30 @@ public class EntityListener implements Listener {
} }
} }
/**
* Monitor EntityDeath events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDeathLowest(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
if (Misc.isNPCEntity(entity)) {
return;
}
if (entity.hasMetadata(mcMMO.customNameKey)) {
entity.setCustomName(entity.getMetadata(mcMMO.customNameKey).get(0).asString());
entity.removeMetadata(mcMMO.customNameKey, mcMMO.p);
}
if (entity.hasMetadata(mcMMO.customVisibleKey)) {
entity.setCustomNameVisible(entity.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean());
entity.removeMetadata(mcMMO.customVisibleKey, mcMMO.p);
}
}
/** /**
* Monitor EntityDeath events. * Monitor EntityDeath events.
* *
@@ -309,7 +360,6 @@ public class EntityListener implements Listener {
return; return;
} }
entity.setFireTicks(0);
BleedTimerTask.remove(entity); BleedTimerTask.remove(entity);
Archery.arrowRetrievalCheck(entity); Archery.arrowRetrievalCheck(entity);
} }
@@ -348,7 +398,10 @@ public class EntityListener implements Listener {
public void onExplosionPrime(ExplosionPrimeEvent event) { public void onExplosionPrime(ExplosionPrimeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof TNTPrimed && entity.hasMetadata(mcMMO.tntMetadataKey)) { if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(mcMMO.tntMetadataKey)) {
return;
}
// We can make this assumption because we (should) be the only ones using this exact metadata // We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString()); Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
@@ -362,7 +415,6 @@ public class EntityListener implements Listener {
event.setRadius(miningManager.biggerBombs(event.getRadius())); event.setRadius(miningManager.biggerBombs(event.getRadius()));
} }
} }
}
/** /**
* Handle EntityExplode events that involve modifying the event. * Handle EntityExplode events that involve modifying the event.
@@ -373,7 +425,10 @@ public class EntityListener implements Listener {
public void onEnitityExplode(EntityExplodeEvent event) { public void onEnitityExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof TNTPrimed && entity.hasMetadata(mcMMO.tntMetadataKey)) { if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(mcMMO.tntMetadataKey)) {
return;
}
// We can make this assumption because we (should) be the only ones using this exact metadata // We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString()); Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
@@ -388,7 +443,6 @@ public class EntityListener implements Listener {
event.setYield(0); event.setYield(0);
} }
} }
}
/** /**
* Handle FoodLevelChange events that involve modifying the event. * Handle FoodLevelChange events that involve modifying the event.
@@ -399,7 +453,10 @@ public class EntityListener implements Listener {
public void onFoodLevelChange(FoodLevelChangeEvent event) { public void onFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof Player) { if (!(entity instanceof Player)) {
return;
}
Player player = (Player) entity; Player player = (Player) entity;
if (Misc.isNPCEntity(player)) { if (Misc.isNPCEntity(player)) {
@@ -457,7 +514,6 @@ public class EntityListener implements Listener {
return; return;
} }
} }
}
/** /**
* Monitor EntityTame events. * Monitor EntityTame events.
@@ -486,7 +542,10 @@ public class EntityListener implements Listener {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
Entity target = event.getTarget(); Entity target = event.getTarget();
if (entity instanceof Tameable && target instanceof Player) { if (!(entity instanceof Tameable) || !(target instanceof Player)) {
return;
}
Player player = (Player) target; Player player = (Player) target;
Tameable tameable = (Tameable) entity; Tameable tameable = (Tameable) entity;
@@ -498,8 +557,6 @@ public class EntityListener implements Listener {
// So we can make some assumptions here, about our casting and our check // So we can make some assumptions here, about our casting and our check
if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) { if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) {
event.setCancelled(true); event.setCancelled(true);
return;
}
} }
} }
} }

View File

@@ -1,11 +1,6 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -18,16 +13,12 @@ import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.skills.smelting.SmeltingManager; import com.gmail.nossr50.runnables.PlayerUpdateInventoryTask;
import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
@@ -41,7 +32,7 @@ public class InventoryListener implements Listener {
this.plugin = plugin; this.plugin = plugin;
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
HumanEntity player = event.getPlayer(); HumanEntity player = event.getPlayer();
@@ -49,25 +40,14 @@ public class InventoryListener implements Listener {
return; return;
} }
Inventory inventory = event.getInventory(); Block furnaceBlock = Misc.processInventoryOpenorCloseEvent(event);
if (inventory instanceof FurnaceInventory) { if (furnaceBlock != null && !furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
Furnace furnace = (Furnace) inventory.getHolder();
if (furnace == null) {
return;
}
if (furnace.getBurnTime() == 0) {
Block furnaceBlock = furnace.getBlock();
if (!furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
furnaceBlock.setMetadata(mcMMO.furnaceMetadataKey, new FixedMetadataValue(plugin, player.getName())); furnaceBlock.setMetadata(mcMMO.furnaceMetadataKey, new FixedMetadataValue(plugin, player.getName()));
} }
} }
}
}
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
HumanEntity player = event.getPlayer(); HumanEntity player = event.getPlayer();
@@ -75,37 +55,23 @@ public class InventoryListener implements Listener {
return; return;
} }
Inventory inventory = event.getInventory(); Block furnaceBlock = Misc.processInventoryOpenorCloseEvent(event);
if (inventory instanceof FurnaceInventory) { if (furnaceBlock != null && furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
Furnace furnace = (Furnace) inventory.getHolder();
if (furnace == null) {
return;
}
if (furnace.getBurnTime() == 0) {
Block furnaceBlock = furnace.getBlock();
if (furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
furnaceBlock.removeMetadata(mcMMO.furnaceMetadataKey, plugin); furnaceBlock.removeMetadata(mcMMO.furnaceMetadataKey, plugin);
} }
} }
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceBurnEvent(FurnaceBurnEvent event) { public void onFurnaceBurnEvent(FurnaceBurnEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack smelting = Misc.getSmeltingFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmeltable(smelting)) {
ItemStack smelting = ((Furnace) furnaceState).getInventory().getSmelting(); return;
List<MetadataValue> metadata = furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey); }
if (!metadata.isEmpty() && smelting != null && ItemUtils.isSmeltable(smelting)) { Player player = Misc.getPlayerFromFurnace(furnaceBlock);
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(metadata.get(0).asString());
if (Misc.isNPCEntity(player) || !Permissions.fuelEfficiency(player)) { if (Misc.isNPCEntity(player) || !Permissions.fuelEfficiency(player)) {
return; return;
@@ -113,63 +79,41 @@ public class InventoryListener implements Listener {
event.setBurnTime(UserManager.getPlayer(player).getSmeltingManager().fuelEfficiency(event.getBurnTime())); event.setBurnTime(UserManager.getPlayer(player).getSmeltingManager().fuelEfficiency(event.getBurnTime()));
} }
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) { public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack smelting = Misc.getSmeltingFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmeltable(smelting)) {
ItemStack smelting = ((Furnace) furnaceState).getInventory().getSmelting();
List<MetadataValue> metadata = furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey);
if (Config.getInstance().getPotatoEnabled() && smelting.getType() == Material.POTATO_ITEM) {
if ((Config.getInstance().getPotatoChance() / 100.0) >= Misc.getRandom().nextDouble()) {
event.setCancelled(true);
furnaceState.getWorld().createExplosion(furnaceState.getLocation(), 4F, true);
return; return;
} }
}
if (!metadata.isEmpty() && smelting != null && ItemUtils.isSmeltable(smelting)) { Player player = Misc.getPlayerFromFurnace(furnaceBlock);
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(metadata.get(0).asString());
if (Misc.isNPCEntity(player) || !Permissions.skillEnabled(player, SkillType.SMELTING)) { if (Misc.isNPCEntity(player) || !Permissions.skillEnabled(player, SkillType.SMELTING)) {
return; return;
} }
event.setResult(UserManager.getPlayer(player).getSmeltingManager().smeltProcessing(event.getSource().getType(), event.getResult())); event.setResult(UserManager.getPlayer(player).getSmeltingManager().smeltProcessing(smelting.getType(), event.getResult()));
}
}
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceExtractEvent(FurnaceExtractEvent event) { public void onFurnaceExtractEvent(FurnaceExtractEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack result = Misc.getResultFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmelted(result)) {
ItemStack result = ((Furnace) furnaceState).getInventory().getResult();
List<MetadataValue> metadata = furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey);
if (!metadata.isEmpty() && result != null && ItemUtils.isSmelted(result)) {
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(metadata.get(0).asString());
if (Misc.isNPCEntity(player)) {
return; return;
} }
SmeltingManager smeltingManager = UserManager.getPlayer(player).getSmeltingManager(); Player player = Misc.getPlayerFromFurnace(furnaceBlock);
if (smeltingManager.canUseVanillaXpBoost()) { if (Misc.isNPCEntity(player) || !Permissions.vanillaXpBoost(player, SkillType.SMELTING)) {
event.setExpToDrop(smeltingManager.vanillaXPBoost(event.getExpToDrop())); return;
}
}
} }
event.setExpToDrop(UserManager.getPlayer(player).getSmeltingManager().vanillaXPBoost(event.getExpToDrop()));
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@@ -179,18 +123,18 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCraftItem(CraftItemEvent event) { public void onCraftItem(CraftItemEvent event) {
ItemStack result = event.getRecipe().getResult();
final HumanEntity whoClicked = event.getWhoClicked(); final HumanEntity whoClicked = event.getWhoClicked();
if (!ItemUtils.isMcMMOItem(result) || Misc.isNPCEntity(whoClicked) || !(whoClicked instanceof Player)) { if (Misc.isNPCEntity(whoClicked) || !(whoClicked instanceof Player)) {
return; return;
} }
mcMMO.p.getServer().getScheduler().runTaskLater(mcMMO.p, new Runnable() { ItemStack result = event.getRecipe().getResult();
@Override
public void run() { if (!ItemUtils.isMcMMOItem(result)) {
((Player) whoClicked).updateInventory(); return;
} }
}, 0);
new PlayerUpdateInventoryTask((Player) whoClicked).runTaskLater(plugin, 0);
} }
} }

View File

@@ -21,8 +21,6 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerFishEvent; import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerRespawnEvent;
@@ -30,6 +28,9 @@ import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
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.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;
@@ -127,27 +128,6 @@ public class PlayerListener implements Listener {
} }
} }
/**
* Monitor PlayerLogin events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
if (event.getResult() != Result.ALLOWED) {
return;
}
Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
return;
}
UserManager.addUser(player).actualizeRespawnATS();
ScoreboardManager.enablePowerLevelDisplay(player);
}
/** /**
* Handle PlayerDropItem events that involve modifying the event. * Handle PlayerDropItem events that involve modifying the event.
* *
@@ -180,11 +160,11 @@ public class PlayerListener implements Listener {
case FISHING: case FISHING:
if (!Permissions.krakenBypass(player)) { if (!Permissions.krakenBypass(player)) {
event.setCancelled(fishingManager.exploitPrevention()); event.setCancelled(fishingManager.exploitPrevention());
}
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
}
if (fishingManager.canMasterAngler()) { if (fishingManager.canMasterAngler()) {
fishingManager.masterAngler(event.getHook()); fishingManager.masterAngler(event.getHook());
@@ -209,7 +189,7 @@ public class PlayerListener implements Listener {
case IN_GROUND: case IN_GROUND:
Fish hook = event.getHook(); Fish hook = event.getHook();
Block block = hook.getLocation().getBlock(); Block block = event.getPlayer().getTargetBlock(null, 100);
if (fishingManager.canIceFish(block)) { if (fishingManager.canIceFish(block)) {
event.setCancelled(true); event.setCancelled(true);
@@ -285,6 +265,13 @@ public class PlayerListener implements Listener {
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
return;
}
UserManager.addUser(player).actualizeRespawnATS();
ScoreboardManager.enablePowerLevelDisplay(player);
if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) { if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) {
Motd.displayAll(player); Motd.displayAll(player);
} }
@@ -343,6 +330,7 @@ public class PlayerListener implements Listener {
case RIGHT_CLICK_BLOCK: case RIGHT_CLICK_BLOCK:
int blockID = block.getTypeId(); int blockID = block.getTypeId();
if ((Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && player.isSneaking()) || !Config.getInstance().getAbilitiesOnlyActivateWhenSneaking()) {
/* REPAIR CHECKS */ /* REPAIR CHECKS */
if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) { if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
RepairManager repairManager = mcMMOPlayer.getRepairManager(); RepairManager repairManager = mcMMOPlayer.getRepairManager();
@@ -355,7 +343,7 @@ public class PlayerListener implements Listener {
} }
} }
/* SALVAGE CHECKS */ /* SALVAGE CHECKS */
else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem) && !ItemUtils.isChainmailArmor(heldItem)) { else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) {
RepairManager repairManager = mcMMOPlayer.getRepairManager(); RepairManager repairManager = mcMMOPlayer.getRepairManager();
event.setCancelled(true); event.setCancelled(true);
@@ -365,6 +353,7 @@ public class PlayerListener implements Listener {
player.updateInventory(); player.updateInventory();
} }
} }
}
/* BLAST MINING CHECK */ /* BLAST MINING CHECK */
else if (miningManager.canDetonate()) { else if (miningManager.canDetonate()) {
if (blockID == Material.TNT.getId()) { if (blockID == Material.TNT.getId()) {
@@ -380,6 +369,7 @@ public class PlayerListener implements Listener {
case LEFT_CLICK_BLOCK: case LEFT_CLICK_BLOCK:
blockID = block.getTypeId(); blockID = block.getTypeId();
if ((Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && player.isSneaking()) || !Config.getInstance().getAbilitiesOnlyActivateWhenSneaking()) {
/* REPAIR CHECKS */ /* REPAIR CHECKS */
if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) { if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
RepairManager repairManager = mcMMOPlayer.getRepairManager(); RepairManager repairManager = mcMMOPlayer.getRepairManager();
@@ -400,6 +390,7 @@ public class PlayerListener implements Listener {
player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Salvage.Pretty.Name"))); player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Salvage.Pretty.Name")));
} }
} }
}
break; break;
@@ -540,6 +531,8 @@ public class PlayerListener implements Listener {
return; return;
} }
ChatManager chatManager = null;
if (mcMMOPlayer.getPartyChatMode()) { if (mcMMOPlayer.getPartyChatMode()) {
Party party = mcMMOPlayer.getParty(); Party party = mcMMOPlayer.getParty();
@@ -549,11 +542,15 @@ public class PlayerListener implements Listener {
return; return;
} }
ChatManager.handlePartyChat(plugin, party, player.getName(), player.getDisplayName(), event.getMessage(), event.isAsynchronous()); chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.PARTY);
event.setCancelled(true); ((PartyChatManager) chatManager).setParty(party);
} }
else if (mcMMOPlayer.getAdminChatMode()) { else if (mcMMOPlayer.getAdminChatMode()) {
ChatManager.handleAdminChat(plugin, player.getName(), player.getDisplayName(), event.getMessage(), event.isAsynchronous()); chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN);
}
if (chatManager != null) {
chatManager.handleChat(player, event.getMessage(), event.isAsynchronous());
event.setCancelled(true); event.setCancelled(true);
} }
} }

View File

@@ -4,7 +4,6 @@ import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -19,8 +18,7 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.blockmeta.conversion.BlockStoreConversionMain; import com.gmail.nossr50.util.blockmeta.conversion.BlockStoreConversionMain;
public class WorldListener implements Listener { public class WorldListener implements Listener {
private ArrayList<BlockStoreConversionMain> converters = new ArrayList<BlockStoreConversionMain>(); private final ArrayList<BlockStoreConversionMain> converters = new ArrayList<BlockStoreConversionMain>();
private final mcMMO plugin; private final mcMMO plugin;
public WorldListener(final mcMMO plugin) { public WorldListener(final mcMMO plugin) {
@@ -34,14 +32,14 @@ public class WorldListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent event) { public void onStructureGrow(StructureGrowEvent event) {
Location location = event.getLocation(); if (!mcMMO.getPlaceStore().isTrue(event.getLocation().getBlock())) {
return;
}
if (mcMMO.getPlaceStore().isTrue(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld())) {
for (BlockState blockState : event.getBlocks()) { for (BlockState blockState : event.getBlocks()) {
mcMMO.getPlaceStore().setFalse(blockState); mcMMO.getPlaceStore().setFalse(blockState);
} }
} }
}
/** /**
* Monitor WorldInit events. * Monitor WorldInit events.
@@ -51,9 +49,8 @@ public class WorldListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
World world = event.getWorld(); World world = event.getWorld();
File dataDir = new File(world.getWorldFolder(), "mcmmo_data");
if (!dataDir.exists() || plugin == null) { if (!new File(world.getWorldFolder(), "mcmmo_data").exists() || plugin == null) {
return; return;
} }

View File

@@ -23,6 +23,7 @@ import com.gmail.nossr50.config.mods.CustomToolConfig;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.config.treasure.TreasureConfig; import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.database.DatabaseManager; import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.listeners.BlockListener; import com.gmail.nossr50.listeners.BlockListener;
import com.gmail.nossr50.listeners.EntityListener; import com.gmail.nossr50.listeners.EntityListener;
import com.gmail.nossr50.listeners.InventoryListener; import com.gmail.nossr50.listeners.InventoryListener;
@@ -44,6 +45,7 @@ import com.gmail.nossr50.skills.repair.RepairableManagerFactory;
import com.gmail.nossr50.skills.repair.config.RepairConfigManager; import com.gmail.nossr50.skills.repair.config.RepairConfigManager;
import com.gmail.nossr50.util.ChimaeraWing; import com.gmail.nossr50.util.ChimaeraWing;
import com.gmail.nossr50.util.LogFilter; import com.gmail.nossr50.util.LogFilter;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.UpdateChecker; import com.gmail.nossr50.util.UpdateChecker;
import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManager; import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManager;
@@ -109,7 +111,7 @@ public class mcMMO extends JavaPlugin {
combatTagEnabled = getServer().getPluginManager().getPlugin("CombatTag") != null; combatTagEnabled = getServer().getPluginManager().getPlugin("CombatTag") != null;
databaseManager = new DatabaseManager(this, Config.getInstance().getUseMySQL()); databaseManager = DatabaseManagerFactory.getDatabaseManager();
registerEvents(); registerEvents();
registerCustomRecipes(); registerCustomRecipes();
@@ -227,12 +229,17 @@ public class mcMMO extends JavaPlugin {
return placeStore; return placeStore;
} }
public static RepairableManager getRepairableManager() {
return repairableManager;
}
public static DatabaseManager getDatabaseManager() { public static DatabaseManager getDatabaseManager() {
return databaseManager; return databaseManager;
} }
public static RepairableManager getRepairableManager() { @Deprecated
return repairableManager; public static void setDatabaseManager(DatabaseManager databaseManager) {
mcMMO.databaseManager = databaseManager;
} }
public static boolean isSpoutEnabled() { public static boolean isSpoutEnabled() {
@@ -255,7 +262,10 @@ public class mcMMO extends JavaPlugin {
} }
private void checkForUpdates() { private void checkForUpdates() {
if (Config.getInstance().getUpdateCheckEnabled()) { if (!Config.getInstance().getUpdateCheckEnabled()) {
return;
}
try { try {
updateAvailable = UpdateChecker.updateAvailable(); updateAvailable = UpdateChecker.updateAvailable();
} }
@@ -268,11 +278,9 @@ public class mcMMO extends JavaPlugin {
getLogger().info(LocaleLoader.getString("UpdateChecker.newavailable")); getLogger().info(LocaleLoader.getString("UpdateChecker.newavailable"));
} }
} }
}
private void loadConfigFiles() { private void loadConfigFiles() {
// Force the loading of config files // Force the loading of config files
Config configInstance = Config.getInstance();
TreasureConfig.getInstance(); TreasureConfig.getInstance();
HiddenConfig.getInstance(); HiddenConfig.getInstance();
AdvancedConfig.getInstance(); AdvancedConfig.getInstance();
@@ -280,19 +288,19 @@ public class mcMMO extends JavaPlugin {
List<Repairable> repairables = new ArrayList<Repairable>(); List<Repairable> repairables = new ArrayList<Repairable>();
if (configInstance.getToolModsEnabled()) { if (Config.getInstance().getToolModsEnabled()) {
repairables.addAll(CustomToolConfig.getInstance().getLoadedRepairables()); repairables.addAll(CustomToolConfig.getInstance().getLoadedRepairables());
} }
if (configInstance.getArmorModsEnabled()) { if (Config.getInstance().getArmorModsEnabled()) {
repairables.addAll(CustomArmorConfig.getInstance().getLoadedRepairables()); repairables.addAll(CustomArmorConfig.getInstance().getLoadedRepairables());
} }
if (configInstance.getBlockModsEnabled()) { if (Config.getInstance().getBlockModsEnabled()) {
CustomBlockConfig.getInstance(); CustomBlockConfig.getInstance();
} }
if (configInstance.getEntityModsEnabled()) { if (Config.getInstance().getEntityModsEnabled()) {
CustomEntityConfig.getInstance(); CustomEntityConfig.getInstance();
} }
@@ -303,14 +311,16 @@ public class mcMMO extends JavaPlugin {
repairableManager.registerRepairables(repairables); repairableManager.registerRepairables(repairables);
// Check if Repair Anvil and Salvage Anvil have different itemID's // Check if Repair Anvil and Salvage Anvil have different itemID's
if (configInstance.getSalvageAnvilId() == configInstance.getRepairAnvilId()) { if (Config.getInstance().getSalvageAnvilId() == Config.getInstance().getRepairAnvilId()) {
getLogger().warning("Can't use the same itemID for Repair/Salvage Anvils!"); getLogger().warning("Can't use the same itemID for Repair/Salvage Anvils!");
} }
} }
private void setupSpout() { private void setupSpout() {
// Check for Spout if (!getServer().getPluginManager().isPluginEnabled("Spout")) {
if (getServer().getPluginManager().isPluginEnabled("Spout")) { return;
}
spoutEnabled = true; spoutEnabled = true;
SpoutConfig.getInstance(); SpoutConfig.getInstance();
@@ -318,7 +328,6 @@ public class mcMMO extends JavaPlugin {
SpoutUtils.preCacheFiles(); SpoutUtils.preCacheFiles();
SpoutUtils.reloadSpoutPlayers(); // Handle spout players after a /reload SpoutUtils.reloadSpoutPlayers(); // Handle spout players after a /reload
} }
}
private void registerEvents() { private void registerEvents() {
PluginManager pluginManager = getServer().getPluginManager(); PluginManager pluginManager = getServer().getPluginManager();
@@ -344,23 +353,23 @@ public class mcMMO extends JavaPlugin {
new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks); new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks);
// Bleed timer (Runs every two seconds) // Bleed timer (Runs every two seconds)
new BleedTimerTask().runTaskTimer(this, 40, 40); new BleedTimerTask().runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR);
// Old & Powerless User remover // Old & Powerless User remover
long purgeIntervalTicks = Config.getInstance().getPurgeInterval() * 60 * 60 * 20; long purgeIntervalTicks = Config.getInstance().getPurgeInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;
if (purgeIntervalTicks == 0) { if (purgeIntervalTicks == 0) {
new UserPurgeTask().runTaskLater(this, 40); // Start 2 seconds after startup. new UserPurgeTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
} }
else if (purgeIntervalTicks > 0) { else if (purgeIntervalTicks > 0) {
new UserPurgeTask().runTaskTimer(this, purgeIntervalTicks, purgeIntervalTicks); new UserPurgeTask().runTaskTimer(this, purgeIntervalTicks, purgeIntervalTicks);
} }
// Automatically remove old members from parties // Automatically remove old members from parties
long kickIntervalTicks = Config.getInstance().getAutoPartyKickInterval() * 60 * 60 * 20; long kickIntervalTicks = Config.getInstance().getAutoPartyKickInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;
if (kickIntervalTicks == 0) { if (kickIntervalTicks == 0) {
new PartyAutoKickTask().runTaskLater(this, 40); // Start 2 seconds after startup. new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
} }
else if (kickIntervalTicks > 0) { else if (kickIntervalTicks > 0) {
new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks); new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks);

View File

@@ -64,14 +64,11 @@ public final class PartyManager {
return false; return false;
} }
Party firstParty = firstMcMMOPlayer.getParty(); if (firstMcMMOPlayer.getParty() == null || secondMcMMOPlayer.getParty() == null) {
Party secondParty = secondMcMMOPlayer.getParty();
if (firstParty == null || secondParty == null || firstParty != secondParty) {
return false; return false;
} }
return true; return firstMcMMOPlayer.getParty().equals(secondMcMMOPlayer.getParty());
} }
/** /**
@@ -83,13 +80,15 @@ public final class PartyManager {
*/ */
public static List<Player> getNearMembers(Player player, Party party, double range) { public static List<Player> getNearMembers(Player player, Party party, double range) {
List<Player> nearMembers = new ArrayList<Player>(); List<Player> nearMembers = new ArrayList<Player>();
if (party != null) { if (party != null) {
for (Player member : party.getOnlineMembers()) { for (Player member : party.getOnlineMembers()) {
if (!player.getName().equalsIgnoreCase(member.getName()) && !member.isDead() && Misc.isNear(player.getLocation(), member.getLocation(), range)) { if (!player.equals(member) && member.isValid() && Misc.isNear(player.getLocation(), member.getLocation(), range)) {
nearMembers.add(member); nearMembers.add(member);
} }
} }
} }
return nearMembers; return nearMembers;
} }
@@ -100,13 +99,9 @@ public final class PartyManager {
* @return all the players in the player's party * @return all the players in the player's party
*/ */
public static LinkedHashSet<String> getAllMembers(Player player) { public static LinkedHashSet<String> getAllMembers(Player player) {
Party party = UserManager.getPlayer(player).getParty(); Party party = getPlayerParty(player.getName());
if (party == null) { return party == null ? null : party.getMembers();
return null;
}
return party.getMembers();
} }
/** /**
@@ -116,13 +111,7 @@ public final class PartyManager {
* @return all online players in this party * @return all online players in this party
*/ */
public static List<Player> getOnlineMembers(String partyName) { public static List<Player> getOnlineMembers(String partyName) {
Party party = getParty(partyName); return getOnlineMembers(getParty(partyName));
if (party == null) {
return null;
}
return party.getOnlineMembers();
} }
/** /**
@@ -132,13 +121,11 @@ public final class PartyManager {
* @return all online players in this party * @return all online players in this party
*/ */
public static List<Player> getOnlineMembers(Player player) { public static List<Player> getOnlineMembers(Player player) {
Party party = getPlayerParty(player.getName()); return getOnlineMembers(getPlayerParty(player.getName()));
if (party == null) {
return null;
} }
return getOnlineMembers(party.getName()); private static List<Player> getOnlineMembers(Party party) {
return party == null ? null : party.getOnlineMembers();
} }
/** /**
@@ -192,29 +179,24 @@ public final class PartyManager {
*/ */
public static void removeFromParty(OfflinePlayer player, Party party) { public static void removeFromParty(OfflinePlayer player, Party party) {
LinkedHashSet<String> members = party.getMembers(); LinkedHashSet<String> members = party.getMembers();
String playerName = player.getName();
members.remove(player.getName()); members.remove(playerName);
if (members.isEmpty()) { if (members.isEmpty()) {
parties.remove(party); parties.remove(party);
} }
else { else {
// If the leaving player was the party leader, appoint a new leader from the party members // If the leaving player was the party leader, appoint a new leader from the party members
if (party.getLeader().equalsIgnoreCase(player.getName())) { if (party.getLeader().equalsIgnoreCase(playerName)) {
String newLeader = members.iterator().next(); String newLeader = members.iterator().next();
party.setLeader(newLeader); party.setLeader(newLeader);
} }
informPartyMembersQuit(player, party); informPartyMembersQuit(party, playerName);
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player.getName()); processPartyLeaving(UserManager.getPlayer(player));
if (mcMMOPlayer != null) {
mcMMOPlayer.removeParty();
mcMMOPlayer.setPartyChat(false);
mcMMOPlayer.setItemShareModifier(10);
}
} }
/** /**
@@ -223,19 +205,10 @@ public final class PartyManager {
* @param party The party to remove * @param party The party to remove
*/ */
public static void disbandParty(Party party) { public static void disbandParty(Party party) {
LinkedHashSet<String> members = party.getMembers(); for (String memberName : party.getMembers()) {
processPartyLeaving(UserManager.getPlayer(memberName));
for (String memberName : members) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(memberName);
if (mcMMOPlayer != null) {
mcMMOPlayer.removeParty();
mcMMOPlayer.setPartyChat(false);
mcMMOPlayer.setItemShareModifier(10);
}
} }
members.clear();
parties.remove(party); parties.remove(party);
} }
@@ -249,29 +222,25 @@ public final class PartyManager {
*/ */
public static void createParty(Player player, McMMOPlayer mcMMOPlayer, String partyName, String password) { public static void createParty(Player player, McMMOPlayer mcMMOPlayer, String partyName, String password) {
partyName = partyName.replace(".", ""); partyName = partyName.replace(".", "");
Party party = getParty(partyName); Party party = getParty(partyName);
String playerName = player.getName();
if (party == null) { if (party != null) {
party = new Party();
party.setName(partyName);
party.setLeader(player.getName());
party.setLocked(true); // Parties are now invite-only by default, can be set to open with /party unlock
if (password != null) {
party.setPassword(password);
player.sendMessage(LocaleLoader.getString("Party.Password.Set", password));
}
parties.add(party);
}
else {
player.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists")); player.sendMessage(LocaleLoader.getString("Commands.Party.AlreadyExists"));
return; return;
} }
party = new Party(playerName, partyName, password);
if (password != null) {
player.sendMessage(LocaleLoader.getString("Party.Password.Set", password));
}
parties.add(party);
player.sendMessage(LocaleLoader.getString("Commands.Party.Create", party.getName())); player.sendMessage(LocaleLoader.getString("Commands.Party.Create", party.getName()));
addToParty(player, mcMMOPlayer, party); addToParty(playerName, mcMMOPlayer, party);
} }
/** /**
@@ -283,16 +252,12 @@ public final class PartyManager {
* @param password the password for this party, null if there was no password * @param password the password for this party, null if there was no password
*/ */
public static void joinParty(Player player, McMMOPlayer mcMMOPlayer, Party party, String password) { public static void joinParty(Player player, McMMOPlayer mcMMOPlayer, Party party, String password) {
if (!checkPartyPassword(player, party, password)) { if (!checkPartyPassword(player, party, password) || mcMMOPlayer.getParty() == party) {
return;
}
if (mcMMOPlayer.getParty() == party) {
return; return;
} }
player.sendMessage(LocaleLoader.getString("Commands.Party.Join", party.getName())); player.sendMessage(LocaleLoader.getString("Commands.Party.Join", party.getName()));
addToParty(player, mcMMOPlayer, party); addToParty(player.getName(), mcMMOPlayer, party);
} }
/** /**
@@ -304,11 +269,17 @@ public final class PartyManager {
* @return true if the player can join the party * @return true if the player can join the party
*/ */
public static boolean checkPartyPassword(Player player, Party party, String password) { public static boolean checkPartyPassword(Player player, Party party, String password) {
// Don't care about passwords if it isn't locked if (!party.isLocked()) {
if (party.isLocked()) { return true;
}
String partyPassword = party.getPassword(); String partyPassword = party.getPassword();
if (partyPassword != null) { if (partyPassword == null) {
player.sendMessage(LocaleLoader.getString("Party.Locked"));
return false;
}
if (password == null) { if (password == null) {
player.sendMessage(LocaleLoader.getString("Party.Password.None")); player.sendMessage(LocaleLoader.getString("Party.Password.None"));
return false; return false;
@@ -317,15 +288,10 @@ public final class PartyManager {
player.sendMessage(LocaleLoader.getString("Party.Password.Incorrect")); player.sendMessage(LocaleLoader.getString("Party.Password.Incorrect"));
return false; return false;
} }
}
else { else {
player.sendMessage(LocaleLoader.getString("Party.Locked"));
return false;
}
}
return true; return true;
} }
}
/** /**
* Accept a party invitation * Accept a party invitation
@@ -346,7 +312,7 @@ public final class PartyManager {
player.sendMessage(LocaleLoader.getString("Commands.Invite.Accepted", invite.getName())); player.sendMessage(LocaleLoader.getString("Commands.Invite.Accepted", invite.getName()));
mcMMOPlayer.removePartyInvite(); mcMMOPlayer.removePartyInvite();
addToParty(player, mcMMOPlayer, invite); addToParty(player.getName(), mcMMOPlayer, invite);
} }
/** /**
@@ -356,15 +322,15 @@ public final class PartyManager {
* @param mcMMOPlayer The player to add to the party * @param mcMMOPlayer The player to add to the party
* @param party The party * @param party The party
*/ */
public static void addToParty(OfflinePlayer player, McMMOPlayer mcMMOPlayer, Party party) { public static void addToParty(String playerName, McMMOPlayer mcMMOPlayer, Party party) {
if (mcMMOPlayer.getParty() == party) { if (mcMMOPlayer.getParty() == party) {
return; return;
} }
informPartyMembersJoin(player, party); informPartyMembersJoin(party, playerName);
mcMMOPlayer.setParty(party); mcMMOPlayer.setParty(party);
party.getMembers().add(player.getName()); party.getMembers().add(playerName);
} }
/** /**
@@ -415,11 +381,7 @@ public final class PartyManager {
* @return true if the player can invite * @return true if the player can invite
*/ */
public static boolean canInvite(Player player, Party party) { public static boolean canInvite(Player player, Party party) {
if (party.isLocked() && !party.getLeader().equalsIgnoreCase(player.getName())) { return !(party.isLocked() && !party.getLeader().equalsIgnoreCase(player.getName()));
return false;
}
return true;
} }
/** /**
@@ -429,13 +391,7 @@ public final class PartyManager {
* @return true if this is a valid party, false otherwise * @return true if this is a valid party, false otherwise
*/ */
public static boolean isParty(String partyName) { public static boolean isParty(String partyName) {
for (Party party : parties) { return getParty(partyName) != null;
if (party.getName().equals(partyName)) {
return true;
}
}
return false;
} }
/** /**
@@ -449,9 +405,8 @@ public final class PartyManager {
YamlConfiguration partiesFile = YamlConfiguration.loadConfiguration(partyFile); YamlConfiguration partiesFile = YamlConfiguration.loadConfiguration(partyFile);
for (String partyName : partiesFile.getConfigurationSection("").getKeys(false)) { for (String partyName : partiesFile.getConfigurationSection("").getKeys(false)) {
Party party = new Party(); Party party = new Party(partyName);
party.setName(partyName);
party.setLeader(partiesFile.getString(partyName + ".Leader")); party.setLeader(partiesFile.getString(partyName + ".Leader"));
party.setPassword(partiesFile.getString(partyName + ".Password")); party.setPassword(partiesFile.getString(partyName + ".Password"));
party.setLocked(partiesFile.getBoolean(partyName + ".Locked")); party.setLocked(partiesFile.getBoolean(partyName + ".Locked"));
@@ -524,30 +479,36 @@ public final class PartyManager {
} }
/** /**
* Notify party members when a player joins * Notify party members when a player joins.
* *
* @param player The player that joins
* @param party The concerned party * @param party The concerned party
* @param playerName The name of the player that joined
*/ */
private static void informPartyMembersJoin(OfflinePlayer player, Party party) { private static void informPartyMembersJoin(Party party, String playerName) {
for (Player member : party.getOnlineMembers()) { for (Player member : party.getOnlineMembers()) {
if (!member.equals(player)) { member.sendMessage(LocaleLoader.getString("Party.InformedOnJoin", playerName));
member.sendMessage(LocaleLoader.getString("Party.InformedOnJoin", player.getName()));
}
} }
} }
/** /**
* Notify party members when a party member quits. * Notify party members when a party member quits.
* *
* @param player The player that quits
* @param party The concerned party * @param party The concerned party
* @param playerName The name of the player that left
*/ */
private static void informPartyMembersQuit(OfflinePlayer player, Party party) { private static void informPartyMembersQuit(Party party, String playerName) {
for (Player member : party.getOnlineMembers()) { for (Player member : party.getOnlineMembers()) {
if (!member.equals(player)) { member.sendMessage(LocaleLoader.getString("Party.InformedOnQuit", playerName));
member.sendMessage(LocaleLoader.getString("Party.InformedOnQuit", player.getName()));
} }
} }
private static void processPartyLeaving(McMMOPlayer mcMMOPlayer) {
if (mcMMOPlayer == null) {
return;
}
mcMMOPlayer.removeParty();
mcMMOPlayer.setPartyChat(false);
mcMMOPlayer.setItemShareModifier(10);
} }
} }

View File

@@ -65,12 +65,7 @@ public final class ShareHandler {
} }
double partySize = nearMembers.size() + 1; double partySize = nearMembers.size() + 1;
double shareBonus = Config.getInstance().getPartyShareBonusBase() + partySize * Config.getInstance().getPartyShareBonusIncrease(); double shareBonus = Math.min(Config.getInstance().getPartyShareBonusBase() + partySize * Config.getInstance().getPartyShareBonusIncrease(), Config.getInstance().getPartyShareBonusCap());
if (shareBonus > Config.getInstance().getPartyShareBonusCap()) {
shareBonus = Config.getInstance().getPartyShareBonusCap();
}
float splitXp = (float) (xp / partySize * shareBonus); float splitXp = (float) (xp / partySize * shareBonus);
for (Player member : nearMembers) { for (Player member : nearMembers) {
@@ -78,7 +73,6 @@ public final class ShareHandler {
} }
mcMMOPlayer.beginUnsharedXpGain(skillType, splitXp); mcMMOPlayer.beginUnsharedXpGain(skillType, splitXp);
return true; return true;
case NONE: case NONE:
@@ -96,32 +90,43 @@ public final class ShareHandler {
*/ */
public static boolean handleItemShare(Item drop, McMMOPlayer mcMMOPlayer) { public static boolean handleItemShare(Item drop, McMMOPlayer mcMMOPlayer) {
ItemStack itemStack = drop.getItemStack(); ItemStack itemStack = drop.getItemStack();
Party party = mcMMOPlayer.getParty();
Player player = mcMMOPlayer.getPlayer();
Player winningPlayer = null;
ItemStack newStack = itemStack.clone();
newStack.setAmount(1);
ItemShareType dropType = ItemShareType.getShareType(itemStack); ItemShareType dropType = ItemShareType.getShareType(itemStack);
if (dropType == null || !party.sharingDrops(dropType)) { if (dropType == null) {
return false; return false;
} }
switch (party.getItemShareMode()) { Party party = mcMMOPlayer.getParty();
case EQUAL:
McMMOPlayer mcMMOTarget; if (!party.sharingDrops(dropType)) {
return false;
}
ShareMode shareMode = party.getItemShareMode();
if (shareMode == ShareMode.NONE) {
return false;
}
Player player = mcMMOPlayer.getPlayer();
nearMembers = PartyManager.getNearMembers(player, party, Config.getInstance().getPartyShareRange()); nearMembers = PartyManager.getNearMembers(player, party, Config.getInstance().getPartyShareRange());
if (nearMembers.isEmpty()) { if (nearMembers.isEmpty()) {
return false; return false;
} }
Player winningPlayer = null;
ItemStack newStack = itemStack.clone();
nearMembers.add(player); nearMembers.add(player);
partySize = nearMembers.size(); partySize = nearMembers.size();
drop.remove(); drop.remove();
newStack.setAmount(1);
switch (shareMode) {
case EQUAL:
int itemWeight = ItemWeightConfig.getInstance().getItemWeight(itemStack.getType()); int itemWeight = ItemWeightConfig.getInstance().getItemWeight(itemStack.getType());
for (int i = 0; i < itemStack.getAmount(); i++) { for (int i = 0; i < itemStack.getAmount(); i++) {
@@ -132,7 +137,11 @@ public final class ShareHandler {
int itemShareModifier = mcMMOMember.getItemShareModifier(); int itemShareModifier = mcMMOMember.getItemShareModifier();
int diceRoll = Misc.getRandom().nextInt(itemShareModifier); int diceRoll = Misc.getRandom().nextInt(itemShareModifier);
if (diceRoll > highestRoll) { if (diceRoll <= highestRoll) {
mcMMOMember.setItemShareModifier(itemShareModifier + itemWeight);
continue;
}
highestRoll = diceRoll; highestRoll = diceRoll;
if (winningPlayer != null) { if (winningPlayer != null) {
@@ -142,54 +151,32 @@ public final class ShareHandler {
winningPlayer = member; winningPlayer = member;
} }
else {
mcMMOMember.setItemShareModifier(itemShareModifier + itemWeight);
}
}
mcMMOTarget = UserManager.getPlayer(winningPlayer); McMMOPlayer mcMMOTarget = UserManager.getPlayer(winningPlayer);
mcMMOTarget.setItemShareModifier(mcMMOTarget.getItemShareModifier() - itemWeight); mcMMOTarget.setItemShareModifier(mcMMOTarget.getItemShareModifier() - itemWeight);
awardDrop(winningPlayer, newStack);
if (winningPlayer.getInventory().addItem(newStack).size() != 0) {
winningPlayer.getWorld().dropItemNaturally(winningPlayer.getLocation(), newStack);
} }
winningPlayer.updateInventory();
}
return true; return true;
case RANDOM: case RANDOM:
nearMembers = PartyManager.getNearMembers(player, party, Config.getInstance().getPartyShareRange());
if (nearMembers.isEmpty()) {
return false;
}
partySize = nearMembers.size() + 1;
drop.remove();
for (int i = 0; i < itemStack.getAmount(); i++) { for (int i = 0; i < itemStack.getAmount(); i++) {
int randomMember = Misc.getRandom().nextInt(partySize); winningPlayer = nearMembers.get(Misc.getRandom().nextInt(partySize));
awardDrop(winningPlayer, newStack);
if (randomMember >= nearMembers.size()) {
winningPlayer = player;
}
else {
winningPlayer = nearMembers.get(randomMember);
} }
if (winningPlayer.getInventory().addItem(newStack).size() != 0) {
winningPlayer.getWorld().dropItemNaturally(winningPlayer.getLocation(), newStack);
}
winningPlayer.updateInventory();
}
return true; return true;
case NONE:
default: default:
return false; return false;
} }
} }
private static void awardDrop(Player winningPlayer, ItemStack drop) {
if (winningPlayer.getInventory().addItem(drop).size() != 0) {
winningPlayer.getWorld().dropItemNaturally(winningPlayer.getLocation(), drop);
}
winningPlayer.updateInventory();
}
} }

View File

@@ -0,0 +1,17 @@
package com.gmail.nossr50.runnables;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
public class PlayerUpdateInventoryTask extends BukkitRunnable {
private Player player;
public PlayerUpdateInventoryTask(Player player) {
this.player = player;
}
@Override
public void run() {
player.updateInventory();
}
}

View File

@@ -6,9 +6,6 @@ import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.FlatfileDatabaseManager;
import com.gmail.nossr50.database.SQLDatabaseManager;
public class McrankCommandAsyncTask extends BukkitRunnable { public class McrankCommandAsyncTask extends BukkitRunnable {
private final String playerName; private final String playerName;
@@ -21,8 +18,9 @@ public class McrankCommandAsyncTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
Map<String, Integer> skills = Config.getInstance().getUseMySQL() ? SQLDatabaseManager.readSQLRank(playerName) : FlatfileDatabaseManager.getPlayerRanks(playerName); Map<String, Integer> skills = mcMMO.getDatabaseManager().readRank(playerName);
new McrankCommandDisplayTask(skills, sender, playerName).runTaskLater(mcMMO.p, 1); new McrankCommandDisplayTask(skills, sender, playerName).runTaskLater(mcMMO.p, 1);
} }
} }

View File

@@ -31,8 +31,8 @@ public class McrankCommandDisplayTask extends BukkitRunnable {
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading")); sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Heading"));
sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName)); sender.sendMessage(LocaleLoader.getString("Commands.mcrank.Player", playerName));
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.nonChildSkills()) {
if (skill.isChildSkill() || (player != null && !Permissions.skillEnabled(player, skill))) { if (player != null && !Permissions.skillEnabled(player, skill)) {
continue; continue;
} }

View File

@@ -1,31 +1,28 @@
package com.gmail.nossr50.runnables.commands; package com.gmail.nossr50.runnables.commands;
import java.util.ArrayList; import java.util.List;
import java.util.Collection;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.database.SQLDatabaseManager;
public class MctopCommandAsyncTask extends BukkitRunnable { public class MctopCommandAsyncTask extends BukkitRunnable {
private CommandSender sender; private CommandSender sender;
private String query; private String skill;
private int page; private int page;
public MctopCommandAsyncTask(int page, String query, CommandSender sender) { public MctopCommandAsyncTask(int page, String skill, CommandSender sender) {
this.page = page; this.page = page;
this.query = query.equalsIgnoreCase("ALL") ? "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing" : query; this.skill = skill;
this.sender = sender; this.sender = sender;
} }
@Override @Override
public void run() { public void run() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix(); final List<PlayerStat> userStats = mcMMO.getDatabaseManager().readLeaderboard(skill, page, 10);
final Collection<ArrayList<String>> userStats = SQLDatabaseManager.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").values();
new MctopCommandDisplayTask(userStats, page, tablePrefix, sender).runTaskLater(mcMMO.p, 1); new MctopCommandDisplayTask(userStats, page, skill, sender).runTaskLater(mcMMO.p, 1);
} }
} }

View File

@@ -1,44 +1,44 @@
package com.gmail.nossr50.runnables.commands; package com.gmail.nossr50.runnables.commands;
import java.util.ArrayList; import java.util.List;
import java.util.Collection;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
public class MctopCommandDisplayTask extends BukkitRunnable { public class MctopCommandDisplayTask extends BukkitRunnable {
private Collection<ArrayList<String>> userStats; private List<PlayerStat> userStats;
private CommandSender sender; private CommandSender sender;
private String query; private String skill;
private int page; private int page;
public MctopCommandDisplayTask(Collection<ArrayList<String>> userStats, int page, String query, CommandSender sender) { public MctopCommandDisplayTask(List<PlayerStat> userStats, int page, String skill, CommandSender sender) {
this.userStats = userStats; this.userStats = userStats;
this.page = page; this.page = page;
this.query = query; this.skill = skill;
this.sender = sender; this.sender = sender;
} }
@Override @Override
public void run() { public void run() {
if (query.equalsIgnoreCase("taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing")) { if (skill.equalsIgnoreCase("all")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
} }
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(query))); sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(skill)));
} }
int place = (page * 10) - 9; int place = (page * 10) - 9;
for (ArrayList<String> stat : userStats) { for (PlayerStat stat : userStats) {
String digit = (place < 10) ? "0" : "" + String.valueOf(place); String digit = ((place < 10) ? "0" : "") + String.valueOf(place);
// Format: 1. Playername - skill value // Format: 1. Playername - skill value
sender.sendMessage(digit + ". " + ChatColor.GREEN + stat.get(1) + " - " + ChatColor.WHITE + stat.get(0)); sender.sendMessage(digit + ". " + ChatColor.GREEN + stat.name + " - " + ChatColor.WHITE + stat.statVal);
place++; place++;
} }

View File

@@ -6,270 +6,28 @@ import java.io.FileReader;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.StringUtils;
public class SQLConversionTask extends BukkitRunnable { public class SQLConversionTask extends BukkitRunnable {
private String tablePrefix = Config.getInstance().getMySQLTablePrefix();
@Override @Override
public void run() { public void run() {
String location = mcMMO.getUsersFilePath(); String location = mcMMO.getUsersFilePath();
try { try {
FileReader file = new FileReader(location); BufferedReader in = new BufferedReader(new FileReader(location));
BufferedReader in = new BufferedReader(file);
String line = ""; String line = "";
String playerName = null; int converted = 0;
String mining = null;
String woodcutting = null;
String repair = null;
String unarmed = null;
String herbalism = null;
String excavation = null;
String archery = null;
String swords = null;
String axes = null;
String acrobatics = null;
String taming = null;
String fishing = null;
String miningXP = null;
String woodCuttingXP = null;
String repairXP = null;
String unarmedXP = null;
String herbalismXP = null;
String excavationXP = null;
String archeryXP = null;
String swordsXP = null;
String axesXP = null;
String acrobaticsXP = null;
String tamingXP = null;
String fishingXP = null;
int id = 0;
int theCount = 0;
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
// Find if the line contains the player we want. // Find if the line contains the player we want.
String[] character = line.split(":"); String[] playerData = line.split(":");
playerName = character[0]; if (mcMMO.getDatabaseManager().convert(playerData)) {
converted++;
// Check for things we don't want put in the DB
if (playerName == null || playerName.equalsIgnoreCase("null") || playerName.equalsIgnoreCase("#Storage place for user information")) {
continue;
}
if (character.length > 1) {
mining = character[1];
}
if (character.length > 4) {
miningXP = character[4];
}
if (character.length > 5) {
woodcutting = character[5];
}
if (character.length > 6) {
woodCuttingXP = character[6];
}
if (character.length > 7) {
repair = character[7];
}
if (character.length > 8) {
unarmed = character[8];
}
if (character.length > 9) {
herbalism = character[9];
}
if (character.length > 10) {
excavation = character[10];
}
if (character.length > 11) {
archery = character[11];
}
if (character.length > 12) {
swords = character[12];
}
if (character.length > 13) {
axes = character[13];
}
if (character.length > 14) {
acrobatics = character[14];
}
if (character.length > 15) {
repairXP = character[15];
}
if (character.length > 16) {
unarmedXP = character[16];
}
if (character.length > 17) {
herbalismXP = character[17];
}
if (character.length > 18) {
excavationXP = character[18];
}
if (character.length > 19) {
archeryXP = character[19];
}
if (character.length > 20) {
swordsXP = character[20];
}
if (character.length > 21) {
axesXP = character[21];
}
if (character.length > 22) {
acrobaticsXP = character[22];
}
if (character.length > 24) {
taming = character[24];
}
if (character.length > 25) {
tamingXP = character[25];
}
if (character.length > 34) {
fishing = character[34];
}
if (character.length > 35) {
fishingXP = character[35];
}
// Check to see if the user is in the DB
id = SQLDatabaseManager.getInt("SELECT id FROM "
+ tablePrefix
+ "users WHERE user = '" + playerName + "'");
if (id > 0) {
theCount++;
// Update the skill values
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "users SET lastlogin = " + 0
+ " WHERE id = " + id);
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "skills SET "
+ " taming = taming+" + StringUtils.getInt(taming)
+ ", mining = mining+" + StringUtils.getInt(mining)
+ ", repair = repair+" + StringUtils.getInt(repair)
+ ", woodcutting = woodcutting+" + StringUtils.getInt(woodcutting)
+ ", unarmed = unarmed+" + StringUtils.getInt(unarmed)
+ ", herbalism = herbalism+" + StringUtils.getInt(herbalism)
+ ", excavation = excavation+" + StringUtils.getInt(excavation)
+ ", archery = archery+" + StringUtils.getInt(archery)
+ ", swords = swords+" + StringUtils.getInt(swords)
+ ", axes = axes+" + StringUtils.getInt(axes)
+ ", acrobatics = acrobatics+" + StringUtils.getInt(acrobatics)
+ ", fishing = fishing+" + StringUtils.getInt(fishing)
+ " WHERE user_id = " + id);
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "experience SET "
+ " taming = " + StringUtils.getInt(tamingXP)
+ ", mining = " + StringUtils.getInt(miningXP)
+ ", repair = " + StringUtils.getInt(repairXP)
+ ", woodcutting = " + StringUtils.getInt(woodCuttingXP)
+ ", unarmed = " + StringUtils.getInt(unarmedXP)
+ ", herbalism = " + StringUtils.getInt(herbalismXP)
+ ", excavation = " + StringUtils.getInt(excavationXP)
+ ", archery = " + StringUtils.getInt(archeryXP)
+ ", swords = " + StringUtils.getInt(swordsXP)
+ ", axes = " + StringUtils.getInt(axesXP)
+ ", acrobatics = " + StringUtils.getInt(acrobaticsXP)
+ ", fishing = " + StringUtils.getInt(fishingXP)
+ " WHERE user_id = " + id);
}
else {
theCount++;
// Create the user in the DB
SQLDatabaseManager.write("INSERT INTO "
+ tablePrefix
+ "users (user, lastlogin) VALUES ('"
+ playerName + "',"
+ System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR + ")");
id = SQLDatabaseManager.getInt("SELECT id FROM "
+ tablePrefix
+ "users WHERE user = '"
+ playerName + "'");
SQLDatabaseManager.write("INSERT INTO "
+ tablePrefix
+ "skills (user_id) VALUES (" + id + ")");
SQLDatabaseManager.write("INSERT INTO "
+ tablePrefix
+ "experience (user_id) VALUES (" + id
+ ")");
// Update the skill values
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "users SET lastlogin = " + 0
+ " WHERE id = " + id);
/*
Database.write("UPDATE "
+ tablePrefix
+ "users SET party = '" + party
+ "' WHERE id = " + id);
*/
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "skills SET "
+ " taming = taming+" + StringUtils.getInt(taming)
+ ", mining = mining+" + StringUtils.getInt(mining)
+ ", repair = repair+" + StringUtils.getInt(repair)
+ ", woodcutting = woodcutting+" + StringUtils.getInt(woodcutting)
+ ", unarmed = unarmed+" + StringUtils.getInt(unarmed)
+ ", herbalism = herbalism+" + StringUtils.getInt(herbalism)
+ ", excavation = excavation+" + StringUtils.getInt(excavation)
+ ", archery = archery+" + StringUtils.getInt(archery)
+ ", swords = swords+" + StringUtils.getInt(swords)
+ ", axes = axes+" + StringUtils.getInt(axes)
+ ", acrobatics = acrobatics+" + StringUtils.getInt(acrobatics)
+ ", fishing = fishing+" + StringUtils.getInt(fishing)
+ " WHERE user_id = " + id);
SQLDatabaseManager.write("UPDATE "
+ tablePrefix
+ "experience SET "
+ " taming = " + StringUtils.getInt(tamingXP)
+ ", mining = " + StringUtils.getInt(miningXP)
+ ", repair = " + StringUtils.getInt(repairXP)
+ ", woodcutting = " + StringUtils.getInt(woodCuttingXP)
+ ", unarmed = " + StringUtils.getInt(unarmedXP)
+ ", herbalism = " + StringUtils.getInt(herbalismXP)
+ ", excavation = " + StringUtils.getInt(excavationXP)
+ ", archery = " + StringUtils.getInt(archeryXP)
+ ", swords = " + StringUtils.getInt(swordsXP)
+ ", axes = " + StringUtils.getInt(axesXP)
+ ", acrobatics = " + StringUtils.getInt(acrobaticsXP)
+ ", fishing = " + StringUtils.getInt(fishingXP)
+ " WHERE user_id = " + id);
} }
} }
mcMMO.p.getLogger().info("[mcMMO] MySQL Updated from users file, " + theCount + " items added/updated to MySQL DB"); mcMMO.p.getLogger().info("MySQL Updated from users file, " + converted + " items added/updated to MySQL DB");
in.close(); in.close();
} }
catch (Exception e) { catch (Exception e) {

View File

@@ -10,7 +10,7 @@ import com.gmail.nossr50.util.player.UserManager;
public class SQLReconnectTask extends BukkitRunnable { public class SQLReconnectTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
if (SQLDatabaseManager.checkConnected()) { if (((SQLDatabaseManager) mcMMO.getDatabaseManager()).checkConnected()) {
UserManager.saveAll(); // Save all profiles UserManager.saveAll(); // Save all profiles
UserManager.clearAll(); // Clear the profiles UserManager.clearAll(); // Clear the profiles

View File

@@ -28,8 +28,6 @@ public class ChimaeraWingWarmup extends BukkitRunnable {
private void checkChimaeraWingTeleport() { private void checkChimaeraWingTeleport() {
Player player = mcMMOPlayer.getPlayer(); Player player = mcMMOPlayer.getPlayer();
Location previousLocation = mcMMOPlayer.getTeleportCommenceLocation(); Location previousLocation = mcMMOPlayer.getTeleportCommenceLocation();
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
ItemStack inHand = player.getItemInHand();
mcMMOPlayer.setTeleportCommenceLocation(null); mcMMOPlayer.setTeleportCommenceLocation(null);
@@ -38,17 +36,24 @@ public class ChimaeraWingWarmup extends BukkitRunnable {
return; return;
} }
ItemStack inHand = player.getItemInHand();
if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) { if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name"))); player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name")));
return; return;
} }
int recentlyhurt_cooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown(); long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)) { if (hurtCooldown > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return; return;
} }
}
ChimaeraWing.chimaeraExecuteTeleport(); ChimaeraWing.chimaeraExecuteTeleport();
} }

View File

@@ -47,12 +47,16 @@ public class TeleportationWarmup extends BukkitRunnable {
return; return;
} }
int recentlyhurt_cooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown(); int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, teleportingPlayer)) { if (hurtCooldown > 0) {
teleportingPlayer.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, teleportingPlayer))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, teleportingPlayer);
if (timeRemaining > 0) {
teleportingPlayer.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return; return;
} }
}
PtpCommand.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); PtpCommand.handlePartyTeleportEvent(teleportingPlayer, targetPlayer);
} }

View File

@@ -2,7 +2,6 @@ package com.gmail.nossr50.runnables.party;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -15,29 +14,25 @@ import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
public class PartyAutoKickTask extends BukkitRunnable { public class PartyAutoKickTask extends BukkitRunnable {
private final static long KICK_TIME = 24L * 60L * 60L * 1000L * Config.getInstance().getAutoPartyKickTime();
@Override @Override
public void run() { public void run() {
updatePartyMembers();
}
private void updatePartyMembers() {
HashMap<OfflinePlayer, Party> toRemove = new HashMap<OfflinePlayer, Party>(); HashMap<OfflinePlayer, Party> toRemove = new HashMap<OfflinePlayer, Party>();
List<String> processedPlayers = new ArrayList<String>(); List<String> processedPlayers = new ArrayList<String>();
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
long kickTime = 24L * 60L * 60L * 1000L * Config.getInstance().getAutoPartyKickTime();
for (Iterator<Party> partyIterator = PartyManager.getParties().iterator(); partyIterator.hasNext();) {
Party party = partyIterator.next();
for (Party party : PartyManager.getParties()) {
for (String memberName : party.getMembers()) { for (String memberName : party.getMembers()) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName); OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName);
boolean isProcessed = processedPlayers.contains(memberName);
if ((currentTime - member.getLastPlayed() > kickTime) || processedPlayers.contains(memberName)) { if ((!member.isOnline() && (currentTime - member.getLastPlayed() > KICK_TIME)) || isProcessed) {
toRemove.put(member, party); toRemove.put(member, party);
} }
if (!processedPlayers.contains(memberName)) { if (!isProcessed) {
processedPlayers.add(memberName); processedPlayers.add(memberName);
} }
} }

View File

@@ -11,6 +11,7 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent; import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AbilityDisableTask extends BukkitRunnable { public class AbilityDisableTask extends BukkitRunnable {
@@ -59,6 +60,6 @@ public class AbilityDisableTask extends BukkitRunnable {
} }
SkillUtils.sendSkillMessage(player, ability.getAbilityPlayerOff(player)); SkillUtils.sendSkillMessage(player, ability.getAbilityPlayerOff(player));
new AbilityCooldownTask(mcMMOPlayer, ability).runTaskLaterAsynchronously(mcMMO.p, ability.getCooldown() * 20); new AbilityCooldownTask(mcMMOPlayer, ability).runTaskLaterAsynchronously(mcMMO.p, PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TICK_CONVERSION_FACTOR);
} }
} }

View File

@@ -19,8 +19,7 @@ public class ChildConfig extends AutoUpdateConfigLoader {
protected void loadKeys() { protected void loadKeys() {
config.setDefaults(YamlConfiguration.loadConfiguration(plugin.getResource("child.yml"))); config.setDefaults(YamlConfiguration.loadConfiguration(plugin.getResource("child.yml")));
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.childSkills()) {
if (skill.isChildSkill()) {
plugin.debug("Finding parents of " + skill.name()); plugin.debug("Finding parents of " + skill.name());
List<String> parentNames = config.getStringList(StringUtils.getCapitalized(skill.name())); List<String> parentNames = config.getStringList(StringUtils.getCapitalized(skill.name()));
@@ -29,7 +28,7 @@ public class ChildConfig extends AutoUpdateConfigLoader {
for (String name : parentNames) { for (String name : parentNames) {
try { try {
SkillType parentSkill = Enum.valueOf(SkillType.class, name.toUpperCase()); SkillType parentSkill = SkillType.valueOf(name.toUpperCase());
FamilyTree.enforceNotChildSkill(parentSkill); FamilyTree.enforceNotChildSkill(parentSkill);
parentSkills.add(parentSkill); parentSkills.add(parentSkill);
} }
@@ -57,7 +56,6 @@ public class ChildConfig extends AutoUpdateConfigLoader {
FamilyTree.registerParent(skill, parentSkill); FamilyTree.registerParent(skill, parentSkill);
} }
} }
}
FamilyTree.closeRegistration(); FamilyTree.closeRegistration();
} }

View File

@@ -2,7 +2,9 @@ package com.gmail.nossr50.skills.fishing;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
@@ -37,6 +39,9 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.treasure.FishingTreasure; import com.gmail.nossr50.datatypes.treasure.FishingTreasure;
import com.gmail.nossr50.datatypes.treasure.ShakeTreasure; import com.gmail.nossr50.datatypes.treasure.ShakeTreasure;
import com.gmail.nossr50.events.fake.FakePlayerFishEvent; import com.gmail.nossr50.events.fake.FakePlayerFishEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerFishingTreasureEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerMagicHunterEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerShakeEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.skills.KrakenAttackTask; import com.gmail.nossr50.runnables.skills.KrakenAttackTask;
import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.skills.SkillManager;
@@ -52,6 +57,7 @@ public class FishingManager extends SkillManager {
private int fishingTries = 0; private int fishingTries = 0;
private long fishingTimestamp = 0L; private long fishingTimestamp = 0L;
private Location fishingTarget;
public FishingManager(McMMOPlayer mcMMOPlayer) { public FishingManager(McMMOPlayer mcMMOPlayer) {
super(mcMMOPlayer, SkillType.FISHING); super(mcMMOPlayer, SkillType.FISHING);
@@ -108,13 +114,15 @@ public class FishingManager extends SkillManager {
mcMMO.p.getServer().broadcastMessage(ChatColor.RED + AdvancedConfig.getInstance().getServerUnleashMessage().replace("(PLAYER)", player.getDisplayName())); mcMMO.p.getServer().broadcastMessage(ChatColor.RED + AdvancedConfig.getInstance().getServerUnleashMessage().replace("(PLAYER)", player.getDisplayName()));
} }
if (player.getItemInHand().getType() == Material.FISHING_ROD) {
player.setItemInHand(null); player.setItemInHand(null);
}
Creature kraken = (Creature) world.spawnEntity(player.getEyeLocation(), (Misc.getRandom().nextInt(100) == 0 ? EntityType.CHICKEN : EntityType.SQUID)); Creature kraken = (Creature) world.spawnEntity(player.getEyeLocation(), (Misc.getRandom().nextInt(100) == 0 ? EntityType.CHICKEN : EntityType.SQUID));
kraken.setCustomName(AdvancedConfig.getInstance().getKrakenName()); kraken.setCustomName(AdvancedConfig.getInstance().getKrakenName());
if (!kraken.isValid()) { if (!kraken.isValid()) {
int attackInterval = AdvancedConfig.getInstance().getKrakenAttackInterval() * 20; int attackInterval = AdvancedConfig.getInstance().getKrakenAttackInterval() * Misc.TICK_CONVERSION_FACTOR;
new KrakenAttackTask(kraken, player, player.getLocation()).runTaskTimer(mcMMO.p, attackInterval, attackInterval); new KrakenAttackTask(kraken, player, player.getLocation()).runTaskTimer(mcMMO.p, attackInterval, attackInterval);
if (!forceSpawn) { if (!forceSpawn) {
@@ -127,7 +135,7 @@ public class FishingManager extends SkillManager {
kraken.setMaxHealth(AdvancedConfig.getInstance().getKrakenHealth()); kraken.setMaxHealth(AdvancedConfig.getInstance().getKrakenHealth());
kraken.setHealth(kraken.getMaxHealth()); kraken.setHealth(kraken.getMaxHealth());
int attackInterval = AdvancedConfig.getInstance().getKrakenAttackInterval() * 20; int attackInterval = AdvancedConfig.getInstance().getKrakenAttackInterval() * Misc.TICK_CONVERSION_FACTOR;
new KrakenAttackTask(kraken, player).runTaskTimer(mcMMO.p, attackInterval, attackInterval); new KrakenAttackTask(kraken, player).runTaskTimer(mcMMO.p, attackInterval, attackInterval);
if (!forceSpawn) { if (!forceSpawn) {
@@ -142,11 +150,24 @@ public class FishingManager extends SkillManager {
return false; return false;
} }
Block targetBlock = getPlayer().getTargetBlock(null, 100);
if (!targetBlock.isLiquid()) {
return false;
}
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
boolean hasFished = currentTime < fishingTimestamp + FISHING_COOLDOWN_SECONDS; boolean hasFished = (currentTime < fishingTimestamp + FISHING_COOLDOWN_SECONDS);
fishingTries = hasFished ? fishingTries + 1 : Math.max(fishingTries - 1, 0); fishingTries = hasFished ? fishingTries + 1 : Math.max(fishingTries - 1, 0);
fishingTimestamp = currentTime; fishingTimestamp = currentTime;
Location targetLocation = targetBlock.getLocation();
boolean sameTarget = (fishingTarget != null && fishingTarget.equals(targetLocation));
fishingTries = sameTarget ? fishingTries + 1 : Math.max(fishingTries - 1, 0);
fishingTarget = targetLocation;
return unleashTheKraken(false); return unleashTheKraken(false);
} }
@@ -161,9 +182,9 @@ public class FishingManager extends SkillManager {
// Make sure this is a body of water, not just a block of ice. // Make sure this is a body of water, not just a block of ice.
Biome biome = block.getBiome(); Biome biome = block.getBiome();
boolean isFrozenBiome = (biome == Biome.FROZEN_OCEAN || biome == Biome.FROZEN_RIVER); boolean isFrozenBiome = (biome == Biome.FROZEN_OCEAN || biome == Biome.FROZEN_RIVER || biome == Biome.TAIGA || biome == Biome.TAIGA_HILLS || biome == Biome.ICE_PLAINS || biome == Biome.ICE_MOUNTAINS);
if (!isFrozenBiome && block.getRelative(BlockFace.DOWN, 3).getType() == (Material.STATIONARY_WATER)) { if (!isFrozenBiome && (block.getRelative(BlockFace.DOWN, 3).getType() != Material.STATIONARY_WATER)) {
return false; return false;
} }
@@ -269,14 +290,44 @@ public class FishingManager extends SkillManager {
treasureXp = treasure.getXp(); treasureXp = treasure.getXp();
ItemStack treasureDrop = treasure.getDrop().clone(); // Not cloning is bad, m'kay? ItemStack treasureDrop = treasure.getDrop().clone(); // Not cloning is bad, m'kay?
if (Permissions.magicHunter(player) && ItemUtils.isEnchantable(treasureDrop) && handleMagicHunter(treasureDrop)) { McMMOPlayerFishingTreasureEvent event;
player.sendMessage(LocaleLoader.getString("Fishing.MagicFound")); Map<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
if (Permissions.magicHunter(player) && ItemUtils.isEnchantable(treasureDrop)) {
enchants = handleMagicHunter(treasureDrop);
event = new McMMOPlayerMagicHunterEvent(player, treasureDrop, treasureXp, enchants);
}
else {
event = new McMMOPlayerFishingTreasureEvent(player, treasureDrop, treasureXp);
}
mcMMO.p.getServer().getPluginManager().callEvent(event);
treasureDrop = event.getTreasure();
treasureXp = event.getXp();
if (event.isCancelled()) {
treasureDrop = null;
treasureXp = 0;
} }
// Drop the original catch at the feet of the player and set the treasure as the real catch // Drop the original catch at the feet of the player and set the treasure as the real catch
if (treasureDrop != null) {
boolean enchanted = false;
if (!enchants.isEmpty()) {
treasureDrop.addUnsafeEnchantments(enchants);
enchanted = true;
}
if (enchanted) {
player.sendMessage(LocaleLoader.getString("Fishing.MagicFound"));
}
Misc.dropItem(player.getEyeLocation(), fishingCatch.getItemStack()); Misc.dropItem(player.getEyeLocation(), fishingCatch.getItemStack());
fishingCatch.setItemStack(treasureDrop); fishingCatch.setItemStack(treasureDrop);
} }
}
applyXpGain(Config.getInstance().getFishingBaseXP() + treasureXp); applyXpGain(Config.getInstance().getFishingBaseXP() + treasureXp);
} }
@@ -351,6 +402,14 @@ public class FishingManager extends SkillManager {
break; break;
} }
McMMOPlayerShakeEvent event = new McMMOPlayerShakeEvent(getPlayer(), drop);
drop = event.getDrop();
if (event.isCancelled() || drop == null) {
return;
}
Misc.dropItem(target.getLocation(), drop); Misc.dropItem(target.getLocation(), drop);
CombatUtils.dealDamage(target, Math.max(target.getMaxHealth() / 4, 1)); // Make it so you can shake a mob no more than 4 times. CombatUtils.dealDamage(target, Math.max(target.getMaxHealth() / 4, 1)); // Make it so you can shake a mob no more than 4 times.
} }
@@ -399,7 +458,7 @@ public class FishingManager extends SkillManager {
* @param treasureDrop The {@link ItemStack} to enchant * @param treasureDrop The {@link ItemStack} to enchant
* @return true if the item has been enchanted * @return true if the item has been enchanted
*/ */
private boolean handleMagicHunter(ItemStack treasureDrop) { private Map<Enchantment, Integer> handleMagicHunter(ItemStack treasureDrop) {
Player player = getPlayer(); Player player = getPlayer();
int activationChance = this.activationChance; int activationChance = this.activationChance;
@@ -407,8 +466,10 @@ public class FishingManager extends SkillManager {
activationChance *= Fishing.STORM_MODIFIER; activationChance *= Fishing.STORM_MODIFIER;
} }
Map<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
if (Misc.getRandom().nextInt(activationChance) > getLootTier() * AdvancedConfig.getInstance().getFishingMagicMultiplier()) { if (Misc.getRandom().nextInt(activationChance) > getLootTier() * AdvancedConfig.getInstance().getFishingMagicMultiplier()) {
return false; return enchants;
} }
List<Enchantment> possibleEnchantments = getPossibleEnchantments(treasureDrop); List<Enchantment> possibleEnchantments = getPossibleEnchantments(treasureDrop);
@@ -416,7 +477,6 @@ public class FishingManager extends SkillManager {
// This make sure that the order isn't always the same, for example previously Unbreaking had a lot more chance to be used than any other enchant // This make sure that the order isn't always the same, for example previously Unbreaking had a lot more chance to be used than any other enchant
Collections.shuffle(possibleEnchantments, Misc.getRandom()); Collections.shuffle(possibleEnchantments, Misc.getRandom());
boolean enchanted = false;
int specificChance = 1; int specificChance = 1;
for (Enchantment possibleEnchantment : possibleEnchantments) { for (Enchantment possibleEnchantment : possibleEnchantments) {
@@ -424,13 +484,12 @@ public class FishingManager extends SkillManager {
continue; continue;
} }
treasureDrop.addEnchantment(possibleEnchantment, Math.max(Misc.getRandom().nextInt(possibleEnchantment.getMaxLevel()) + 1, possibleEnchantment.getStartLevel())); enchants.put(possibleEnchantment, Math.max(Misc.getRandom().nextInt(possibleEnchantment.getMaxLevel()) + 1, possibleEnchantment.getStartLevel()));
specificChance++; specificChance++;
enchanted = true;
} }
return enchanted; return enchants;
} }
private List<Enchantment> getPossibleEnchantments(ItemStack treasureDrop) { private List<Enchantment> getPossibleEnchantments(ItemStack treasureDrop) {

View File

@@ -109,7 +109,7 @@ public class MiningManager extends SkillManager {
getProfile().setSkillDATS(AbilityType.BLAST_MINING, System.currentTimeMillis()); getProfile().setSkillDATS(AbilityType.BLAST_MINING, System.currentTimeMillis());
mcMMOPlayer.setAbilityInformed(AbilityType.BLAST_MINING, false); mcMMOPlayer.setAbilityInformed(AbilityType.BLAST_MINING, false);
new AbilityCooldownTask(mcMMOPlayer, AbilityType.BLAST_MINING).runTaskLaterAsynchronously(mcMMO.p, AbilityType.BLAST_MINING.getCooldown() * 20); new AbilityCooldownTask(mcMMOPlayer, AbilityType.BLAST_MINING).runTaskLaterAsynchronously(mcMMO.p, AbilityType.BLAST_MINING.getCooldown() * Misc.TICK_CONVERSION_FACTOR);
} }
/** /**
@@ -284,12 +284,10 @@ public class MiningManager extends SkillManager {
private boolean blastMiningCooldownOver() { private boolean blastMiningCooldownOver() {
Player player = getPlayer(); Player player = getPlayer();
PlayerProfile profile = getProfile(); PlayerProfile profile = getProfile();
int timeRemaining = SkillUtils.calculateTimeLeft(profile.getSkillDATS(AbilityType.BLAST_MINING) * Misc.TIME_CONVERSION_FACTOR, AbilityType.BLAST_MINING.getCooldown(), player);
long oldTime = profile.getSkillDATS(AbilityType.BLAST_MINING) * Misc.TIME_CONVERSION_FACTOR; if (timeRemaining > 0) {
int cooldown = AbilityType.BLAST_MINING.getCooldown(); player.sendMessage(LocaleLoader.getString("Skills.TooTired", timeRemaining));
if (!SkillUtils.cooldownOver(oldTime, cooldown, player)) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", SkillUtils.calculateTimeLeft(oldTime, cooldown, player)));
return false; return false;
} }

View File

@@ -29,11 +29,11 @@ public class Repair {
* @return true if the item is salvageable, false otherwise * @return true if the item is salvageable, false otherwise
*/ */
public static boolean isSalvageable(ItemStack item) { public static boolean isSalvageable(ItemStack item) {
if (Config.getInstance().getSalvageTools() && (ItemUtils.isMinecraftTool(item) || ItemUtils.isStringTool(item) || item.getType() == Material.BUCKET)) { if (Config.getInstance().getSalvageTools() && ItemUtils.isMinecraftTool(item)) {
return true; return true;
} }
if (Config.getInstance().getSalvageArmor() && ItemUtils.isMinecraftArmor(item)) { if (Config.getInstance().getSalvageArmor() && !ItemUtils.isChainmailArmor(item) && ItemUtils.isMinecraftArmor(item)) {
return true; return true;
} }

View File

@@ -88,21 +88,14 @@ public class RepairConfig extends ConfigLoader {
} }
protected List<Repairable> getLoadedRepairables() { protected List<Repairable> getLoadedRepairables() {
if (repairables == null) { return repairables == null ? new ArrayList<Repairable>() : repairables;
return new ArrayList<Repairable>();
}
return repairables;
} }
private boolean noErrorsInRepairable(List<String> issues) { private boolean noErrorsInRepairable(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

@@ -28,10 +28,6 @@ public class SmeltingManager extends SkillManager {
return getSkillLevel() >= Smelting.fluxMiningUnlockLevel && BlockUtils.affectedByFluxMining(blockState) && Permissions.fluxMining(getPlayer()) && !mcMMO.getPlaceStore().isTrue(blockState); return getSkillLevel() >= Smelting.fluxMiningUnlockLevel && BlockUtils.affectedByFluxMining(blockState) && Permissions.fluxMining(getPlayer()) && !mcMMO.getPlaceStore().isTrue(blockState);
} }
public boolean canUseVanillaXpBoost() {
return getSkillLevel() >= Smelting.Tier.ONE.getLevel() && Permissions.vanillaXpBoost(getPlayer(), skill);
}
/** /**
* Process the Flux Mining ability. * Process the Flux Mining ability.
* *
@@ -122,6 +118,6 @@ public class SmeltingManager extends SkillManager {
} }
} }
return 0; return 1;
} }
} }

View File

@@ -230,14 +230,10 @@ public final class Woodcutting {
short finalDurability = (short) (inHand.getDurability() + durabilityLoss); short finalDurability = (short) (inHand.getDurability() + durabilityLoss);
short maxDurability = ModUtils.isCustomTool(inHand) ? ModUtils.getToolFromItemStack(inHand).getDurability() : inHandMaterial.getMaxDurability(); short maxDurability = ModUtils.isCustomTool(inHand) ? ModUtils.getToolFromItemStack(inHand).getDurability() : inHandMaterial.getMaxDurability();
boolean overMax = (finalDurability >= maxDurability);
if (finalDurability >= maxDurability) { inHand.setDurability(overMax ? maxDurability : finalDurability);
inHand.setDurability(maxDurability); return !overMax;
return false;
}
inHand.setDurability(finalDurability);
return true;
} }
/** /**

View File

@@ -7,7 +7,7 @@ import org.bukkit.material.CocoaPlant;
import org.bukkit.material.CocoaPlant.CocoaPlantSize; import org.bukkit.material.CocoaPlant.CocoaPlantSize;
import org.bukkit.material.NetherWarts; import org.bukkit.material.NetherWarts;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.skills.repair.Repair;
public final class BlockUtils { public final class BlockUtils {
private BlockUtils() {} private BlockUtils() {}
@@ -306,9 +306,9 @@ public final class BlockUtils {
* @param blockState The {@link BlockState} of the block to check * @param blockState The {@link BlockState} of the block to check
* @return true if the block is an mcMMO anvil, false otherwise * @return true if the block is an mcMMO anvil, false otherwise
*/ */
private static boolean isMcMMOAnvil(BlockState blockState) { public static boolean isMcMMOAnvil(BlockState blockState) {
int blockId = blockState.getTypeId(); int blockId = blockState.getTypeId();
return blockId == Config.getInstance().getRepairAnvilId() || blockId == Config.getInstance().getSalvageAnvilId(); return blockId == Repair.repairAnvilId || blockId == Repair.salvageAnvilId;
} }
} }

View File

@@ -35,9 +35,13 @@ public final class ChimaeraWing {
* @param player Player whose item usage to check * @param player Player whose item usage to check
*/ */
public static void activationCheck(Player player) { public static void activationCheck(Player player) {
if (!Config.getInstance().getChimaeraEnabled()) {
return;
}
ItemStack inHand = player.getItemInHand(); ItemStack inHand = player.getItemInHand();
if (!Config.getInstance().getChimaeraEnabled() || !ItemUtils.isChimaeraWing(inHand)) { if (!ItemUtils.isChimaeraWing(inHand)) {
return; return;
} }
@@ -48,32 +52,43 @@ public final class ChimaeraWing {
mcMMOPlayer = UserManager.getPlayer(player); mcMMOPlayer = UserManager.getPlayer(player);
location = player.getLocation();
int amount = inHand.getAmount();
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
long lastTeleport = mcMMOPlayer.getLastTeleport();
if (mcMMOPlayer.getTeleportCommenceLocation() != null) { if (mcMMOPlayer.getTeleportCommenceLocation() != null) {
return; return;
} }
if (Config.getInstance().getChimaeraCooldown() > 0 && !SkillUtils.cooldownOver(lastTeleport * Misc.TIME_CONVERSION_FACTOR, Config.getInstance().getChimaeraCooldown(), player)) { int amount = inHand.getAmount();
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, Config.getInstance().getChimaeraCooldown(), player)));
return;
}
int recentlyhurt_cooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)));
return;
}
if (amount < Config.getInstance().getChimaeraUseCost()) { if (amount < Config.getInstance().getChimaeraUseCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name"))); player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name")));
return; return;
} }
long lastTeleport = mcMMOPlayer.getLastTeleport();
int cooldown = Config.getInstance().getChimaeraCooldown();
if (cooldown > 0 ) {
int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, cooldown, player);
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining));
return;
}
}
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown();
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;
}
}
location = player.getLocation();
if (Config.getInstance().getChimaeraPreventUseUnderground()) { if (Config.getInstance().getChimaeraPreventUseUnderground()) {
if (location.getY() < player.getWorld().getHighestBlockYAt(location)) { if (location.getY() < player.getWorld().getHighestBlockYAt(location)) {
player.setItemInHand(new ItemStack(getChimaeraWing(amount - Config.getInstance().getChimaeraUseCost()))); player.setItemInHand(new ItemStack(getChimaeraWing(amount - Config.getInstance().getChimaeraUseCost())));

View File

@@ -21,11 +21,7 @@ public final class HardcoreManager {
PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile();
int totalLost = 0; int totalLost = 0;
for (SkillType skillType : SkillType.values()) { for (SkillType skillType : SkillType.nonChildSkills()) {
if (skillType.isChildSkill()) {
continue;
}
int playerSkillLevel = playerProfile.getSkillLevel(skillType); int playerSkillLevel = playerProfile.getSkillLevel(skillType);
if (playerSkillLevel <= 0) { if (playerSkillLevel <= 0) {
@@ -52,11 +48,7 @@ public final class HardcoreManager {
PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile(); PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile();
int totalStolen = 0; int totalStolen = 0;
for (SkillType skillType : SkillType.values()) { for (SkillType skillType : SkillType.nonChildSkills()) {
if (skillType.isChildSkill()) {
continue;
}
int killerSkillLevel = killerProfile.getSkillLevel(skillType); int killerSkillLevel = killerProfile.getSkillLevel(skillType);
int victimSkillLevel = victimProfile.getSkillLevel(skillType); int victimSkillLevel = victimProfile.getSkillLevel(skillType);

View File

@@ -461,6 +461,10 @@ public class ItemUtils {
} }
public static boolean isSmeltable(ItemStack item) { public static boolean isSmeltable(ItemStack item) {
if (item == null) {
return false;
}
switch (item.getType()) { switch (item.getType()) {
case COAL_ORE: case COAL_ORE:
case DIAMOND_ORE: case DIAMOND_ORE:
@@ -479,6 +483,10 @@ public class ItemUtils {
} }
public static boolean isSmelted(ItemStack item) { public static boolean isSmelted(ItemStack item) {
if (item == null) {
return false;
}
switch (item.getType()) { switch (item.getType()) {
case COAL: case COAL:
case DIAMOND: case DIAMOND:

View File

@@ -1,15 +1,23 @@
package com.gmail.nossr50.util; package com.gmail.nossr50.util;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import java.util.Random; import java.util.Random;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryEvent;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.MetadataValue;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -20,8 +28,11 @@ import com.gmail.nossr50.util.spout.SpoutUtils;
public final class Misc { public final class Misc {
private static Random random = new Random(); private static Random random = new Random();
public static final int PLAYER_RESPAWN_COOLDOWN_SECONDS = 5;
public static final int TIME_CONVERSION_FACTOR = 1000; public static final int TIME_CONVERSION_FACTOR = 1000;
public static final int TICK_CONVERSION_FACTOR = 20;
public static final int PLAYER_RESPAWN_COOLDOWN_SECONDS = 5;
public static final double SKILL_MESSAGE_MAX_SENDING_DISTANCE = 10.0; public static final double SKILL_MESSAGE_MAX_SENDING_DISTANCE = 10.0;
// Sound Pitches & Volumes from CB // Sound Pitches & Volumes from CB
@@ -204,6 +215,52 @@ public final class Misc {
} }
} }
public static Block processInventoryOpenorCloseEvent(InventoryEvent event) {
Inventory inventory = event.getInventory();
if (!(inventory instanceof FurnaceInventory)) {
return null;
}
Furnace furnace = (Furnace) inventory.getHolder();
if (furnace == null || furnace.getBurnTime() != 0) {
return null;
}
return furnace.getBlock();
}
public static Player getPlayerFromFurnace(Block furnaceBlock) {
List<MetadataValue> metadata = furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey);
if (metadata.isEmpty()) {
return null;
}
return mcMMO.p.getServer().getPlayerExact(metadata.get(0).asString());
}
public static ItemStack getSmeltingFromFurnace(Block furnaceBlock) {
BlockState furnaceState = furnaceBlock.getState();
if (!(furnaceState instanceof Furnace)) {
return null;
}
return ((Furnace) furnaceState).getInventory().getSmelting();
}
public static ItemStack getResultFromFurnace(Block furnaceBlock) {
BlockState furnaceState = furnaceBlock.getState();
if (!(furnaceState instanceof Furnace)) {
return null;
}
return ((Furnace) furnaceState).getInventory().getResult();
}
public static Random getRandom() { public static Random getRandom() {
return random; return random;
} }

View File

@@ -83,7 +83,7 @@ public final class MobHealthbarUtils {
target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, false)); target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, false));
} }
new MobHealthDisplayUpdaterTask(target).runTaskLater(mcMMO.p, displayTime * 20); // Clear health display after 3 seconds new MobHealthDisplayUpdaterTask(target).runTaskLater(mcMMO.p, displayTime * Misc.TICK_CONVERSION_FACTOR); // Clear health display after 3 seconds
} }
} }

View File

@@ -48,6 +48,7 @@ public final class Permissions {
public static boolean inspect(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect")); } public static boolean inspect(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect")); }
public static boolean inspectFar(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.far")); } public static boolean inspectFar(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.far")); }
public static boolean inspectHidden(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.hidden")); }
public static boolean inspectOffline(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.offline")); } public static boolean inspectOffline(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.offline")); }
public static boolean kraken(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.kraken"); } public static boolean kraken(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.kraken"); }

View File

@@ -11,11 +11,7 @@ public class StringUtils {
* @return the capitalized string * @return the capitalized string
*/ */
public static String getCapitalized(String target) { public static String getCapitalized(String target) {
String firstLetter = target.substring(0, 1); return target.substring(0, 1).toUpperCase() + target.substring(1).toLowerCase();
String remainder = target.substring(1);
String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
return capitalized;
} }
/** /**
@@ -100,22 +96,6 @@ public class StringUtils {
} }
} }
/**
* Determine if a string represents a Long
*
* @param string String to check
* @return true if the string is a Long, false otherwise
*/
public static boolean isLong(String string) {
try {
Long.parseLong(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
/** /**
* Determine if a string represents a Double * Determine if a string represents a Double
* *
@@ -131,5 +111,4 @@ public class StringUtils {
return false; return false;
} }
} }
} }

View File

@@ -15,33 +15,26 @@ public class UpdateChecker {
private UpdateChecker() {} private UpdateChecker() {}
public static boolean updateAvailable() throws Exception { public static boolean updateAvailable() throws Exception {
String checkType = "release"; String checkType = Config.getInstance().getPreferBeta() ? "latest" : "release";
if (Config.getInstance().getPreferBeta()) {
checkType = "latest";
}
String version = mcMMO.p.getDescription().getVersion(); String version = mcMMO.p.getDescription().getVersion();
URL url = new URL("http://api.bukget.org/api2/bukkit/plugin/mcmmo/" + checkType);
InputStreamReader isr; InputStreamReader isr;
try { try {
isr = new InputStreamReader(url.openStream()); isr = new InputStreamReader(new URL("http://api.bukget.org/api2/bukkit/plugin/mcmmo/" + checkType).openStream());
} }
catch (UnknownHostException e) { catch (UnknownHostException e) {
return false; return false;
} }
String newVersion;
try { try {
JSONParser jp = new JSONParser(); Object o = new JSONParser().parse(isr);
Object o = jp.parse(isr);
if (!(o instanceof JSONObject)) { if (!(o instanceof JSONObject)) {
isr.close();
return false; return false;
} }
JSONObject jo = (JSONObject) o; JSONObject versions = (JSONObject) ((JSONObject) o).get("versions");
jo = (JSONObject) jo.get("versions"); String newVersion = (String) versions.get("version");
newVersion = (String) jo.get("version");
String[] oldTokens = version.replaceAll("(?i)(-)(.+?)(-)", "-").split("[.]|-b"); String[] oldTokens = version.replaceAll("(?i)(-)(.+?)(-)", "-").split("[.]|-b");
String[] newTokens = newVersion.replaceAll("(?i)(-)(.+?)(-)", "-").split("[.]|-b"); String[] newTokens = newVersion.replaceAll("(?i)(-)(.+?)(-)", "-").split("[.]|-b");
@@ -49,22 +42,26 @@ public class UpdateChecker {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
Integer newVer = Integer.parseInt(newTokens[i]); Integer newVer = Integer.parseInt(newTokens[i]);
Integer oldVer; Integer oldVer;
try { try {
oldVer = Integer.parseInt(oldTokens[i]); oldVer = Integer.parseInt(oldTokens[i]);
} }
catch (NumberFormatException e) { catch (NumberFormatException e) {
oldVer = 0; oldVer = 0;
} }
if (oldVer < newVer) { if (oldVer < newVer) {
isr.close();
return true; return true;
} }
} }
return false; return false;
} }
catch (ParseException e) { catch (ParseException e) {
isr.close();
return false; return false;
} }
finally {
isr.close();
}
} }
} }

View File

@@ -55,6 +55,14 @@ public final class CommandUtils {
return false; return false;
} }
public static boolean hidden(CommandSender sender, Player target, boolean hasPermission) {
if (sender instanceof Player && !((Player)sender).canSee(target) && !hasPermission) {
return true;
}
return false;
}
public static boolean noConsoleUsage(CommandSender sender) { public static boolean noConsoleUsage(CommandSender sender) {
if (sender instanceof Player) { if (sender instanceof Player) {
return false; return false;

View File

@@ -73,9 +73,11 @@ public final class UserManager {
*/ */
public static McMMOPlayer getPlayer(String playerName) { public static McMMOPlayer getPlayer(String playerName) {
List<Player> matches = mcMMO.p.getServer().matchPlayer(playerName); List<Player> matches = mcMMO.p.getServer().matchPlayer(playerName);
if (matches.size() == 1) { if (matches.size() == 1) {
playerName = matches.get(0).getName(); playerName = matches.get(0).getName();
} }
return players.get(playerName); return players.get(playerName);
} }

View File

@@ -1,7 +1,6 @@
package com.gmail.nossr50.util.scoreboards; package com.gmail.nossr50.util.scoreboards;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -15,13 +14,12 @@ import org.bukkit.scoreboard.Scoreboard;
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.FlatfileDatabaseManager;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.PlayerStat;
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.runnables.scoreboards.ScoreboardChangeTask; import com.gmail.nossr50.runnables.scoreboards.ScoreboardChangeTask;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
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;
@@ -182,8 +180,8 @@ public class ScoreboardManager {
PlayerProfile profile = mcMMOPlayer.getProfile(); PlayerProfile profile = mcMMOPlayer.getProfile();
Server server = mcMMO.p.getServer(); Server server = mcMMO.p.getServer();
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.nonChildSkills()) {
if (skill.isChildSkill() || !Permissions.skillEnabled(player, skill)) { if (!Permissions.skillEnabled(player, skill)) {
continue; continue;
} }
@@ -199,10 +197,10 @@ public class ScoreboardManager {
Server server = mcMMO.p.getServer(); Server server = mcMMO.p.getServer();
Integer rank; Integer rank;
Map<String, Integer> skills = Config.getInstance().getUseMySQL() ? SQLDatabaseManager.readSQLRank(playerName) : FlatfileDatabaseManager.getPlayerRanks(playerName); Map<String, Integer> skills = mcMMO.getDatabaseManager().readRank(playerName);
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.nonChildSkills()) {
if (skill.isChildSkill() || !Permissions.skillEnabled(player, skill)) { if (!Permissions.skillEnabled(player, skill)) {
continue; continue;
} }
@@ -226,13 +224,9 @@ public class ScoreboardManager {
Server server = mcMMO.p.getServer(); Server server = mcMMO.p.getServer();
Integer rank; Integer rank;
Map<String, Integer> skills = Config.getInstance().getUseMySQL() ? SQLDatabaseManager.readSQLRank(targetName) : FlatfileDatabaseManager.getPlayerRanks(targetName); Map<String, Integer> skills = mcMMO.getDatabaseManager().readRank(targetName);
for (SkillType skill : SkillType.values()) {
if (skill.isChildSkill()) {
continue;
}
for (SkillType skill : SkillType.nonChildSkills()) {
rank = skills.get(skill.name()); rank = skills.get(skill.name());
if (rank != null) { if (rank != null) {
@@ -257,8 +251,8 @@ public class ScoreboardManager {
int powerLevel = 0; int powerLevel = 0;
int skillLevel; int skillLevel;
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.nonChildSkills()) {
if (skill.isChildSkill() || !Permissions.skillEnabled(target, skill)) { if (!Permissions.skillEnabled(target, skill)) {
continue; continue;
} }
@@ -277,11 +271,7 @@ public class ScoreboardManager {
int powerLevel = 0; int powerLevel = 0;
int skillLevel; int skillLevel;
for (SkillType skill : SkillType.values()) { for (SkillType skill : SkillType.nonChildSkills()) {
if (skill.isChildSkill()) {
continue;
}
skillLevel = targetProfile.getSkillLevel(skill); skillLevel = targetProfile.getSkillLevel(skill);
objective.getScore(server.getOfflinePlayer(SkillUtils.getSkillName(skill))).setScore(skillLevel); objective.getScore(server.getOfflinePlayer(SkillUtils.getSkillName(skill))).setScore(skillLevel);
powerLevel += skillLevel; powerLevel += skillLevel;
@@ -297,24 +287,7 @@ public class ScoreboardManager {
String endPosition = String.valueOf(position + 14); String endPosition = String.valueOf(position + 14);
Server server = mcMMO.p.getServer(); Server server = mcMMO.p.getServer();
if (Config.getInstance().getUseMySQL()) { for (PlayerStat stat : mcMMO.getDatabaseManager().readLeaderboard(skillName, pageNumber, 15)) {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
String query = (skillName.equalsIgnoreCase("all") ? "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing" : skillName);
final Collection<ArrayList<String>> userStats = SQLDatabaseManager.read("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT " + ((pageNumber * 15) - 15) + ",15").values();
for (ArrayList<String> stat : userStats) {
String playerName = stat.get(1);
playerName = (playerName.equals(player.getName()) ? ChatColor.GOLD : "") + playerName;
if (playerName.length() > 16) {
playerName = playerName.substring(0, 16);
}
objective.getScore(server.getOfflinePlayer(playerName)).setScore(Integer.valueOf(stat.get(0)));
}
}
else {
for (PlayerStat stat : FlatfileDatabaseManager.retrieveInfo(skillName, pageNumber, 15)) {
String playerName = stat.name; String playerName = stat.name;
playerName = (playerName.equals(player.getName()) ? ChatColor.GOLD : "") + playerName; playerName = (playerName.equals(player.getName()) ? ChatColor.GOLD : "") + playerName;
@@ -324,7 +297,6 @@ public class ScoreboardManager {
objective.getScore(server.getOfflinePlayer(playerName)).setScore(stat.statVal); objective.getScore(server.getOfflinePlayer(playerName)).setScore(stat.statVal);
} }
}
objective.setDisplayName(objective.getDisplayName() + " (" + startPosition + " - " + endPosition + ")"); objective.setDisplayName(objective.getDisplayName() + " (" + startPosition + " - " + endPosition + ")");
objective.setDisplaySlot(DisplaySlot.SIDEBAR); objective.setDisplaySlot(DisplaySlot.SIDEBAR);
@@ -338,7 +310,7 @@ public class ScoreboardManager {
enablePowerLevelDisplay(player); enablePowerLevelDisplay(player);
if (displayTime != -1 && !SCOREBOARD_TASKS.contains(playerName)) { if (displayTime != -1 && !SCOREBOARD_TASKS.contains(playerName)) {
new ScoreboardChangeTask(player, oldScoreboard).runTaskLater(mcMMO.p, displayTime * 20); new ScoreboardChangeTask(player, oldScoreboard).runTaskLater(mcMMO.p, displayTime * Misc.TICK_CONVERSION_FACTOR);
SCOREBOARD_TASKS.add(playerName); SCOREBOARD_TASKS.add(playerName);
} }
} }

View File

@@ -15,7 +15,6 @@ import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@@ -24,6 +23,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageEvent;
import com.gmail.nossr50.events.fake.FakePlayerAnimationEvent;
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.runnables.skills.AwardCombatXpTask; import com.gmail.nossr50.runnables.skills.AwardCombatXpTask;
@@ -46,46 +46,8 @@ import com.gmail.nossr50.util.player.UserManager;
public final class CombatUtils { public final class CombatUtils {
private CombatUtils() {} private CombatUtils() {}
/** private static void processSwordCombat(LivingEntity target, Player player, int damage) {
* Apply combat modifiers and process and XP gain.
*
* @param event The event to run the combat checks on.
*/
public static void combatChecks(EntityDamageByEntityEvent event, Entity attacker, LivingEntity target) {
Entity damager = event.getDamager();
if (attacker instanceof Player && damager.getType() == EntityType.PLAYER) {
Player player = (Player) attacker;
if (Misc.isNPCEntity(player)) {
return;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
ItemStack heldItem = player.getItemInHand();
if (target instanceof Tameable) {
if (heldItem.getType() == Material.BONE) {
TamingManager tamingManager = mcMMOPlayer.getTamingManager();
if (tamingManager.canUseBeastLore()) {
tamingManager.beastLore(target);
event.setCancelled(true);
return;
}
}
if (isFriendlyPet(player, (Tameable) target)) {
return;
}
}
if (ItemUtils.isSword(heldItem)) {
if (!shouldProcessSkill(target, SkillType.SWORDS)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.SWORDS)) {
SwordsManager swordsManager = mcMMOPlayer.getSwordsManager(); SwordsManager swordsManager = mcMMOPlayer.getSwordsManager();
if (swordsManager.canActivateAbility()) { if (swordsManager.canActivateAbility()) {
@@ -97,18 +59,14 @@ public final class CombatUtils {
} }
if (swordsManager.canUseSerratedStrike()) { if (swordsManager.canUseSerratedStrike()) {
swordsManager.serratedStrikes(target, event.getDamage()); swordsManager.serratedStrikes(target, damage);
} }
startGainXp(mcMMOPlayer, target, SkillType.SWORDS); startGainXp(mcMMOPlayer, target, SkillType.SWORDS);
} }
}
else if (ItemUtils.isAxe(heldItem)) {
if (!shouldProcessSkill(target, SkillType.AXES)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.AXES)) { private static void processAxeCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
AxesManager axesManager = mcMMOPlayer.getAxesManager(); AxesManager axesManager = mcMMOPlayer.getAxesManager();
if (axesManager.canActivateAbility()) { if (axesManager.canActivateAbility()) {
@@ -136,13 +94,9 @@ public final class CombatUtils {
startGainXp(mcMMOPlayer, target, SkillType.AXES); startGainXp(mcMMOPlayer, target, SkillType.AXES);
} }
}
else if (heldItem.getType() == Material.AIR) {
if (!shouldProcessSkill(target, SkillType.UNARMED)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.UNARMED)) { private static void processUnarmedCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager(); UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager();
if (unarmedManager.canActivateAbility()) { if (unarmedManager.canActivateAbility()) {
@@ -163,25 +117,8 @@ public final class CombatUtils {
startGainXp(mcMMOPlayer, target, SkillType.UNARMED); startGainXp(mcMMOPlayer, target, SkillType.UNARMED);
} }
}
}
switch (damager.getType()) { private static void processTamingCombat(LivingEntity target, Player master, Wolf wolf, EntityDamageByEntityEvent event) {
case WOLF:
Wolf wolf = (Wolf) damager;
if (wolf.isTamed() && wolf.getOwner() instanceof Player) {
Player master = (Player) wolf.getOwner();
if (Misc.isNPCEntity(master)) {
return;
}
if (!shouldProcessSkill(target, SkillType.TAMING)) {
return;
}
if (Permissions.skillEnabled(master, SkillType.TAMING)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master);
TamingManager tamingManager = mcMMOPlayer.getTamingManager(); TamingManager tamingManager = mcMMOPlayer.getTamingManager();
@@ -199,29 +136,8 @@ public final class CombatUtils {
startGainXp(mcMMOPlayer, target, SkillType.TAMING); startGainXp(mcMMOPlayer, target, SkillType.TAMING);
} }
}
break; private static void processArcheryCombat(LivingEntity target, Player player, EntityDamageByEntityEvent event, Entity arrow) {
case ARROW:
LivingEntity shooter = ((Arrow) damager).getShooter();
/* Break instead of return due to Dodge/Counter/Deflect abilities */
if (shooter == null || !(shooter instanceof Player)) {
break;
}
if (!shouldProcessSkill(target, SkillType.ARCHERY)) {
break;
}
Player player = (Player) shooter;
if (Misc.isNPCEntity(player)) {
break;
}
if (Permissions.skillEnabled(player, SkillType.ARCHERY)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager(); ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager();
@@ -245,15 +161,114 @@ public final class CombatUtils {
event.setDamage(archeryManager.dazeCheck((Player) target, event.getDamage())); event.setDamage(archeryManager.dazeCheck((Player) target, event.getDamage()));
} }
if (!damager.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canTrackArrows()) { if (!arrow.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canTrackArrows()) {
archeryManager.trackArrows(target); archeryManager.trackArrows(target);
} }
archeryManager.distanceXpBonus(target, damager); archeryManager.distanceXpBonus(target, arrow);
startGainXp(mcMMOPlayer, target, SkillType.ARCHERY, damager.getMetadata(mcMMO.bowForceKey).get(0).asDouble()); startGainXp(mcMMOPlayer, target, SkillType.ARCHERY, arrow.getMetadata(mcMMO.bowForceKey).get(0).asDouble());
} }
/**
* Apply combat modifiers and process and XP gain.
*
* @param event The event to run the combat checks on.
*/
public static void processCombatAttack(EntityDamageByEntityEvent event, Entity attacker, LivingEntity target) {
Entity damager = event.getDamager();
if (attacker instanceof Player && damager.getType() == EntityType.PLAYER) {
Player player = (Player) attacker;
if (Misc.isNPCEntity(player)) {
return;
}
ItemStack heldItem = player.getItemInHand();
if (target instanceof Tameable) {
if (heldItem.getType() == Material.BONE) {
TamingManager tamingManager = UserManager.getPlayer(player).getTamingManager();
if (tamingManager.canUseBeastLore()) {
tamingManager.beastLore(target);
event.setCancelled(true);
return;
}
}
if (isFriendlyPet(player, (Tameable) target)) {
return;
}
}
if (ItemUtils.isSword(heldItem)) {
if (!shouldProcessSkill(target, SkillType.SWORDS)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.SWORDS)) {
processSwordCombat(target, player, event.getDamage());
}
}
else if (ItemUtils.isAxe(heldItem)) {
if (!shouldProcessSkill(target, SkillType.AXES)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.AXES)) {
processAxeCombat(target, player, event);
}
}
else if (heldItem.getType() == Material.AIR) {
if (!shouldProcessSkill(target, SkillType.UNARMED)) {
return;
}
if (Permissions.skillEnabled(player, SkillType.UNARMED)) {
processUnarmedCombat(target, player, event);
}
}
}
switch (damager.getType()) {
case WOLF:
Wolf wolf = (Wolf) damager;
AnimalTamer tamer = wolf.getOwner();
if (tamer == null || !(tamer instanceof Player) || !shouldProcessSkill(target, SkillType.TAMING)) {
break;
}
Player master = (Player) tamer;
if (Misc.isNPCEntity(master)) {
break;
}
if (Permissions.skillEnabled(master, SkillType.TAMING)) {
processTamingCombat(target, master, wolf, event);
}
break;
case ARROW:
LivingEntity shooter = ((Arrow) damager).getShooter();
if (shooter == null || !(shooter instanceof Player) || !shouldProcessSkill(target, SkillType.ARCHERY)) {
break;
}
Player player = (Player) shooter;
if (Misc.isNPCEntity(player)) {
break;
}
if (Permissions.skillEnabled(player, SkillType.ARCHERY)) {
processArcheryCombat(target, player, event, damager);
}
break; break;
default: default:
@@ -261,12 +276,11 @@ public final class CombatUtils {
} }
if (target instanceof Player) { if (target instanceof Player) {
Player player = (Player) target; if (Misc.isNPCEntity(target)) {
if (Misc.isNPCEntity(player)) {
return; return;
} }
Player player = (Player) target;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
AcrobaticsManager acrobaticsManager = mcMMOPlayer.getAcrobaticsManager(); AcrobaticsManager acrobaticsManager = mcMMOPlayer.getAcrobaticsManager();
@@ -285,24 +299,6 @@ public final class CombatUtils {
swordsManager.counterAttackChecks((LivingEntity) damager, event.getDamage()); swordsManager.counterAttackChecks((LivingEntity) damager, event.getDamage());
} }
} }
if (damager.getType() == EntityType.ARROW) {
LivingEntity shooter = ((Arrow) damager).getShooter();
if (shooter instanceof Player || !SkillType.UNARMED.getPVEEnabled()) {
return;
}
UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager();
if (unarmedManager.canDeflect()) {
event.setCancelled(unarmedManager.deflectCheck());
if (event.isCancelled()) {
return;
}
}
}
} }
else if (attacker instanceof Player) { else if (attacker instanceof Player) {
Player player = (Player) attacker; Player player = (Player) attacker;
@@ -381,23 +377,19 @@ public final class CombatUtils {
*/ */
public static void applyAbilityAoE(Player attacker, LivingEntity target, int damage, SkillType type) { public static void applyAbilityAoE(Player attacker, LivingEntity target, int damage, SkillType type) {
int numberOfTargets = Misc.getTier(attacker.getItemInHand()); // The higher the weapon tier, the more targets you hit int numberOfTargets = Misc.getTier(attacker.getItemInHand()); // The higher the weapon tier, the more targets you hit
int damageAmount = damage; int damageAmount = Math.max(damage, 1);
if (damageAmount < 1) {
damageAmount = 1;
}
for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) { for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) {
if (Misc.isNPCEntity(entity) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) {
continue;
}
if (numberOfTargets <= 0) { if (numberOfTargets <= 0) {
break; break;
} }
PlayerAnimationEvent armswing = new PlayerAnimationEvent(attacker); if (Misc.isNPCEntity(entity) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) {
mcMMO.p.getServer().getPluginManager().callEvent(armswing); continue;
}
LivingEntity livingEntity = (LivingEntity) entity;
mcMMO.p.getServer().getPluginManager().callEvent(new FakePlayerAnimationEvent(attacker));
switch (type) { switch (type) {
case SWORDS: case SWORDS:
@@ -405,8 +397,7 @@ public final class CombatUtils {
((Player) entity).sendMessage(LocaleLoader.getString("Swords.Combat.SS.Struck")); ((Player) entity).sendMessage(LocaleLoader.getString("Swords.Combat.SS.Struck"));
} }
BleedTimerTask.add((LivingEntity) entity, Swords.serratedStrikesBleedTicks); BleedTimerTask.add(livingEntity, Swords.serratedStrikesBleedTicks);
break; break;
case AXES: case AXES:
@@ -420,7 +411,7 @@ public final class CombatUtils {
break; break;
} }
dealDamage((LivingEntity) entity, damageAmount, attacker); dealDamage(livingEntity, damageAmount, attacker);
numberOfTargets--; numberOfTargets--;
} }
} }
@@ -510,11 +501,11 @@ public final class CombatUtils {
} }
break; break;
} }
}
if (target.hasMetadata(mcMMO.entityMetadataKey)) { if (target.hasMetadata(mcMMO.entityMetadataKey)) {
baseXP *= Config.getInstance().getSpawnedMobXpMultiplier(); baseXP *= Config.getInstance().getSpawnedMobXpMultiplier();
} }
}
baseXP *= 10; baseXP *= 10;
} }
@@ -575,16 +566,11 @@ public final class CombatUtils {
* @return true if the entity is invincible, false otherwise * @return true if the entity is invincible, false otherwise
*/ */
public static boolean isInvincible(LivingEntity entity, int eventDamage) { public static boolean isInvincible(LivingEntity entity, int eventDamage) {
/* /*
* So apparently if you do more damage to a LivingEntity than its last damage int you bypass the invincibility. * So apparently if you do more damage to a LivingEntity than its last damage int you bypass the invincibility.
* So yeah, this is for that. * So yeah, this is for that.
*/ */
if ((entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage())) { return (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage());
return true;
}
return false;
} }
/** /**
@@ -601,9 +587,7 @@ public final class CombatUtils {
if (tamer instanceof Player) { if (tamer instanceof Player) {
Player owner = (Player) tamer; Player owner = (Player) tamer;
if (owner == attacker || PartyManager.inSameParty(attacker, owner)) { return (owner == attacker || PartyManager.inSameParty(attacker, owner));
return true;
}
} }
} }
@@ -611,15 +595,6 @@ public final class CombatUtils {
} }
public static boolean shouldProcessSkill(Entity target, SkillType skill) { public static boolean shouldProcessSkill(Entity target, SkillType skill) {
boolean process; return (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) ? skill.getPVPEnabled() : skill.getPVEEnabled();
if (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) {
process = skill.getPVPEnabled();
}
else {
process = skill.getPVEEnabled();
}
return process;
} }
} }

View File

@@ -55,25 +55,6 @@ public class SkillUtils {
return currentFoodLevel + foodChange; return currentFoodLevel + foodChange;
} }
/**
* Checks to see if the cooldown for an item or ability is expired.
*
* @param oldTime The time the ability or item was last used
* @param cooldown The amount of time that must pass between uses
* @param player The player whose cooldown is being checked
* @return true if the cooldown is over, false otherwise
*/
public static boolean cooldownOver(long oldTime, int cooldown, Player player) {
long currentTime = System.currentTimeMillis();
int adjustedCooldown = PerksUtils.handleCooldownPerks(player, cooldown);
if (currentTime - oldTime >= (adjustedCooldown * Misc.TIME_CONVERSION_FACTOR)) {
return true;
}
return false;
}
/** /**
* Calculate the time remaining until the cooldown expires. * Calculate the time remaining until the cooldown expires.
* *
@@ -96,15 +77,14 @@ public class SkillUtils {
return; return;
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
AbilityType ability = skill.getAbility();
ToolType tool = skill.getTool();
ItemStack inHand = player.getItemInHand(); ItemStack inHand = player.getItemInHand();
if (ModUtils.isCustomTool(inHand) && !ModUtils.getToolFromItemStack(inHand).isAbilityEnabled()) { if (ModUtils.isCustomTool(inHand) && !ModUtils.getToolFromItemStack(inHand).isAbilityEnabled()) {
return; return;
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.getAbilityUse()) { if (!mcMMOPlayer.getAbilityUse()) {
return; return;
} }
@@ -116,6 +96,8 @@ public class SkillUtils {
} }
PlayerProfile playerProfile = mcMMOPlayer.getProfile(); PlayerProfile playerProfile = mcMMOPlayer.getProfile();
AbilityType ability = skill.getAbility();
ToolType tool = skill.getTool();
/* /*
* Woodcutting & Axes need to be treated differently. * Woodcutting & Axes need to be treated differently.
@@ -123,8 +105,10 @@ public class SkillUtils {
*/ */
if (ability.getPermissions(player) && tool.inHand(inHand) && !mcMMOPlayer.getToolPreparationMode(tool)) { if (ability.getPermissions(player) && tool.inHand(inHand) && !mcMMOPlayer.getToolPreparationMode(tool)) {
if (skill != SkillType.WOODCUTTING && skill != SkillType.AXES) { if (skill != SkillType.WOODCUTTING && skill != SkillType.AXES) {
if (!mcMMOPlayer.getAbilityMode(ability) && !cooldownOver(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)) { int timeRemaining = calculateTimeLeft(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player);
player.sendMessage(LocaleLoader.getString("Skills.TooTired", calculateTimeLeft(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)));
if (!mcMMOPlayer.getAbilityMode(ability) && timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", timeRemaining));
return; return;
} }
} }
@@ -135,7 +119,7 @@ public class SkillUtils {
mcMMOPlayer.setToolPreparationATS(tool, System.currentTimeMillis()); mcMMOPlayer.setToolPreparationATS(tool, System.currentTimeMillis());
mcMMOPlayer.setToolPreparationMode(tool, true); mcMMOPlayer.setToolPreparationMode(tool, true);
new ToolLowerTask(mcMMOPlayer, tool).runTaskLaterAsynchronously(mcMMO.p, 4 * 20); new ToolLowerTask(mcMMOPlayer, tool).runTaskLaterAsynchronously(mcMMO.p, 4 * Misc.TICK_CONVERSION_FACTOR);
} }
} }
@@ -202,11 +186,7 @@ public class SkillUtils {
return isLocalizedSkill(skillName); return isLocalizedSkill(skillName);
} }
if (SkillType.getSkill(skillName) != null) { return SkillType.getSkill(skillName) != null;
return true;
}
return false;
} }
private static boolean isLocalizedSkill(String skillName) { private static boolean isLocalizedSkill(String skillName) {
@@ -234,15 +214,11 @@ public class SkillUtils {
* @return true if the player has combat skills, false otherwise * @return true if the player has combat skills, false otherwise
*/ */
public static boolean hasCombatSkills(Player player) { public static boolean hasCombatSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.AXES) return Permissions.skillEnabled(player, SkillType.AXES)
|| Permissions.skillEnabled(player, SkillType.ARCHERY) || Permissions.skillEnabled(player, SkillType.ARCHERY)
|| Permissions.skillEnabled(player, SkillType.SWORDS) || Permissions.skillEnabled(player, SkillType.SWORDS)
|| Permissions.skillEnabled(player, SkillType.TAMING) || Permissions.skillEnabled(player, SkillType.TAMING)
|| Permissions.skillEnabled(player, SkillType.UNARMED)) { || Permissions.skillEnabled(player, SkillType.UNARMED);
return true;
}
return false;
} }
/** /**
@@ -252,15 +228,11 @@ public class SkillUtils {
* @return true if the player has gathering skills, false otherwise * @return true if the player has gathering skills, false otherwise
*/ */
public static boolean hasGatheringSkills(Player player) { public static boolean hasGatheringSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.EXCAVATION) return Permissions.skillEnabled(player, SkillType.EXCAVATION)
|| Permissions.skillEnabled(player, SkillType.FISHING) || Permissions.skillEnabled(player, SkillType.FISHING)
|| Permissions.skillEnabled(player, SkillType.HERBALISM) || Permissions.skillEnabled(player, SkillType.HERBALISM)
|| Permissions.skillEnabled(player, SkillType.MINING) || Permissions.skillEnabled(player, SkillType.MINING)
|| Permissions.skillEnabled(player, SkillType.WOODCUTTING)) { || Permissions.skillEnabled(player, SkillType.WOODCUTTING);
return true;
}
return false;
} }
/** /**
@@ -270,13 +242,9 @@ public class SkillUtils {
* @return true if the player has misc skills, false otherwise * @return true if the player has misc skills, false otherwise
*/ */
public static boolean hasMiscSkills(Player player) { public static boolean hasMiscSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.ACROBATICS) return Permissions.skillEnabled(player, SkillType.ACROBATICS)
|| Permissions.skillEnabled(player, SkillType.SMELTING) || Permissions.skillEnabled(player, SkillType.SMELTING)
|| Permissions.skillEnabled(player, SkillType.REPAIR)) { || Permissions.skillEnabled(player, SkillType.REPAIR);
return true;
}
return false;
} }
/** /**
@@ -294,18 +262,20 @@ public class SkillUtils {
Player player = mcMMOPlayer.getPlayer(); Player player = mcMMOPlayer.getPlayer();
PlayerProfile playerProfile = mcMMOPlayer.getProfile(); PlayerProfile playerProfile = mcMMOPlayer.getProfile();
int timeRemaining = calculateTimeLeft(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player);
/* /*
* Axes and Woodcutting are odd because they share the same tool. * Axes and Woodcutting are odd because they share the same tool.
* We show them the too tired message when they take action. * We show them the too tired message when they take action.
*/ */
if (type == SkillType.WOODCUTTING || type == SkillType.AXES) { if (type == SkillType.WOODCUTTING || type == SkillType.AXES) {
if (!mcMMOPlayer.getAbilityMode(ability) && !cooldownOver(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)) { if (!mcMMOPlayer.getAbilityMode(ability) && timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", calculateTimeLeft(playerProfile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player))); player.sendMessage(LocaleLoader.getString("Skills.TooTired", timeRemaining));
return; return;
} }
} }
if (!mcMMOPlayer.getAbilityMode(ability) && cooldownOver(playerProfile.getSkillDATS(ability), ability.getCooldown(), player)) { if (!mcMMOPlayer.getAbilityMode(ability) && timeRemaining <= 0) {
McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(player, type); McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(player, type);
mcMMO.p.getServer().getPluginManager().callEvent(event); mcMMO.p.getServer().getPluginManager().callEvent(event);
@@ -330,7 +300,7 @@ public class SkillUtils {
handleAbilitySpeedIncrease(player); handleAbilitySpeedIncrease(player);
} }
new AbilityDisableTask(mcMMOPlayer, ability).runTaskLater(mcMMO.p, ticks * 20); new AbilityDisableTask(mcMMOPlayer, ability).runTaskLater(mcMMO.p, ticks * Misc.TICK_CONVERSION_FACTOR);
} }
} }
@@ -347,6 +317,7 @@ public class SkillUtils {
switch (ability) { switch (ability) {
case BERSERK: case BERSERK:
case BLOCK_CRACKER:
case LEAF_BLOWER: case LEAF_BLOWER:
if (!ability.blockCheck(block.getState())) { if (!ability.blockCheck(block.getState())) {
activate = false; activate = false;
@@ -421,14 +392,8 @@ public class SkillUtils {
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
int ticks = 0; SkillType skill = mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER) ? SkillType.MINING : SkillType.EXCAVATION;
int ticks = PerksUtils.handleActivationPerks(player, 2 + (mcMMOPlayer.getProfile().getSkillLevel(skill) / AdvancedConfig.getInstance().getAbilityLength()), skill.getAbility().getMaxTicks()) * Misc.TICK_CONVERSION_FACTOR;
if (mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER)) {
ticks = ((int) (mcMMOPlayer.getProfile().getSkillDATS(AbilityType.SUPER_BREAKER) - (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR))) * 20;
}
else if (mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER)) {
ticks = ((int) (mcMMOPlayer.getProfile().getSkillDATS(AbilityType.GIGA_DRILL_BREAKER) - (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR))) * 20;
}
PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10); PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10);
player.addPotionEffect(abilityBuff, true); player.addPotionEffect(abilityBuff, true);
@@ -444,9 +409,6 @@ public class SkillUtils {
playerInventory.setItem(i, removeAbilityBuff(item)); playerInventory.setItem(i, removeAbilityBuff(item));
} }
} }
else {
player.removePotionEffect(PotionEffectType.FAST_DIGGING);
}
} }
public static ItemStack removeAbilityBuff(ItemStack item) { public static ItemStack removeAbilityBuff(ItemStack item) {
@@ -491,7 +453,7 @@ public class SkillUtils {
* @param shouldArmSwing true if an armswing event should be fired, false otherwise * @param shouldArmSwing true if an armswing event should be fired, false otherwise
* @return true if the event wasn't cancelled, false otherwise * @return true if the event wasn't cancelled, false otherwise
*/ */
public static boolean blockBreakSimulate(Block block, Player player, Boolean shouldArmSwing) { public static boolean blockBreakSimulate(Block block, Player player, boolean shouldArmSwing) {
PluginManager pluginManger = mcMMO.p.getServer().getPluginManager(); PluginManager pluginManger = mcMMO.p.getServer().getPluginManager();
// Support for NoCheat // Support for NoCheat
@@ -505,11 +467,7 @@ public class SkillUtils {
FakeBlockBreakEvent breakEvent = new FakeBlockBreakEvent(block, player); FakeBlockBreakEvent breakEvent = new FakeBlockBreakEvent(block, player);
pluginManger.callEvent(breakEvent); pluginManger.callEvent(breakEvent);
if (!damageEvent.isCancelled() && !breakEvent.isCancelled()) { return !damageEvent.isCancelled() && !breakEvent.isCancelled();
return true;
}
return false;
} }
public static boolean activationSuccessful(Player player, SkillType skill, double maxChance, int maxLevel) { public static boolean activationSuccessful(Player player, SkillType skill, double maxChance, int maxLevel) {

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