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

Compare commits

..

398 Commits

Author SHA1 Message Date
GJ
9b2f4b7bde Because the old beta broke all the things. 2013-05-16 16:23:12 -04:00
GJ
24e5147a2a This was never an issue. 2013-05-16 16:13:53 -04:00
T00thpick1
0423a7831d Those were right the first time... 2013-05-16 15:55:25 -04:00
T00thpick1
feea22b3a4 Correctly order 2013-05-16 15:52:49 -04:00
T00thpick1
7f40a9f284 Explicitely state columns wanted to account for altered tables 2013-05-16 15:50:19 -04:00
GJ
bc706109e0 Fix issue with tables without party names. 2013-05-16 13:37:22 -04:00
GJ
a25bddba5e Back to active development. 2013-05-16 10:55:13 -04:00
GJ
ab897724d3 Weekly beta! 2013-05-16 10:54:40 -04:00
GJ
a7861fc54b Move all miscellaneous Spout code to a single location. 2013-05-16 10:51:18 -04:00
GJ
936bec8ff5 Unused import. 2013-05-16 09:32:48 -04:00
GJ
01d10971a1 Calling things that many times is BAD. 2013-05-16 09:32:27 -04:00
T00thpick1
12e388a392 Null checks 2013-05-16 09:30:02 -04:00
T00thpick1
fb450671d6 Alternative SQL player loading 2013-05-16 09:29:59 -04:00
GJ
fca5f9ec98 We shouldn't need to do this. If issues arise, then there's a bug in
Bukkit that needs patching.
2013-05-16 09:23:35 -04:00
GJ
c9ae6436bd Because we forget things too often. 2013-05-16 08:41:57 -04:00
GJ
b6c4d2b4ad Fixed bug where Nether Quartz wasn't included in Smelting or item
sharing
2013-05-16 08:13:01 -04:00
GJ
27ab2f5b12 Update localization files. 2013-05-16 07:35:00 -04:00
T00thpick1
9b08062a58 Typo 2013-05-15 20:36:43 -04:00
T00thpick1
401bdfa9ac Reset ability modes safely 2013-05-15 20:35:30 -04:00
TfT_02
68d8d6dd30 Added permission node to bypass the fishing exploit prevention
Permission node: `mcmmo.bypass.kraken` false by default.
2013-05-15 23:35:17 +02:00
GJ
2a57d7007d Don't go through everything twice. Also, those were horrible variable
names.
2013-05-15 17:28:47 -04:00
GJ
fd675ac291 Changed Spout notification tiers to be stored in SpoutConfig instead of
AdvancedConfig. Also restructured some Spout stuff for easier
readability.
2013-05-15 17:08:43 -04:00
GJ
41f020bbb7 Cleaning up our listeners, as well as some Spout stuff. 2013-05-15 15:39:40 -04:00
GJ
00dee500e0 Caching options is bad, and so was that way of getting the menu key. 2013-05-15 15:28:05 -04:00
GJ
36bdb8a63e Fixed mcMMO overwritting Spout titles set by other plugins. 2013-05-15 15:14:47 -04:00
GJ
aa9eb0868c Add option to use scoreboards for power level display, similar to the
Spout titles. This will NOT override any existing plugin that uses the
overhead scoreboard slot.
2013-05-15 15:13:11 -04:00
T00thpick1
48aafa9834 Unused import 2013-05-15 14:27:31 -04:00
T00thpick1
78f53f294a Debris should drop normal drops 2013-05-15 13:02:21 -04:00
TfT_02
3158c7e3eb List /party itemshare and /party expshare in /party ?
Closes #913
2013-05-15 19:00:34 +02:00
GJ
47d27ebf31 Update changelog. 2013-05-15 09:29:54 -04:00
GJ
bc3773ae75 Because apparently you can have metadata and an empty list too.
Fixes #1080
2013-05-15 09:29:24 -04:00
GJ
d8ddd27d71 Calculate bonus XP based on initial arrow location, rather than final
shooter location.
2013-05-15 08:35:12 -04:00
GJ
8d5696507a Add bow force multiplier to Archery XP. 2013-05-15 01:20:12 -04:00
T00thpick1
9ec376a228 Unused import and update changelog 2013-05-15 00:53:01 -04:00
T00thpick1
a05a0da9fb Mob Spawner XP multiplier 2013-05-15 00:48:18 -04:00
T00thpick1
5029ad9d93 Apply Perks after cutoff 2013-05-14 23:54:54 -04:00
T00thpick1
1444be665c No reason to specify MyISAM 2013-05-14 23:54:52 -04:00
GJ
3dedb94bdc Add new Experience API functions and clarify some old ones. 2013-05-14 23:30:36 -04:00
T00thpick1
c0f6c15a80 Fix SQL Syntax 2013-05-14 23:28:45 -04:00
T00thpick1
00626a4893 Update changelog.txt 2013-05-14 23:03:26 -04:00
T00thpick1
b416a59bb7 Don't cache config options to prepare for eventual config reload support 2013-05-14 22:59:16 -04:00
GJ
bf96fb2214 Update changelog 2013-05-14 22:45:10 -04:00
GJ
2e79c8d770 Properly track infinite arrows. 2013-05-14 22:45:09 -04:00
T00thpick1
6c9d1c4953 Make SQL removes delete from all tables 2013-05-14 22:20:06 -04:00
T00thpick1
df8df192d3 Update Changelog 2013-05-14 19:57:18 -04:00
T00thpick1
e5f43462c8 Certain operations do not work with child skills 2013-05-14 19:31:40 -04:00
GJ
1867a3e040 If they aren't in a party, they shouldn't be in party chat mode. 2013-05-14 13:10:54 -04:00
GJ
6818f98de3 Feedback is good. 2013-05-14 13:10:07 -04:00
GJ
f910c76248 Conventions. 2013-05-14 12:46:45 -04:00
GJ
975cbf0bf8 The cache should be here, not in the manager. 2013-05-14 12:46:04 -04:00
GJ
f10b3cef01 Config option for escaping from the Kraken. 2013-05-14 12:43:02 -04:00
T00thpick1
ad39c94773 AbilityDeactivateEvent 2013-05-14 12:18:52 -04:00
T00thpick1
f189ab30e5 Default should be default 2013-05-14 11:32:57 -04:00
GJ
0ad18ee971 Fix some config formatting issues. 2013-05-14 11:32:22 -04:00
GJ
501f5de55a Fixing everything you guys broke while I was gone... 2013-05-14 11:28:50 -04:00
T00thpick1
0b18ae8ff2 Formatting and things 2013-05-13 22:28:42 -04:00
T00thpick1
de12970486 New api event 2013-05-13 22:28:39 -04:00
Glitchfinder
7550b99aaa Patching more NPEs involving invbalid players, plus mob health bars. 2013-05-13 18:46:19 -07:00
Glitchfinder
ed5a43966d Patching NPEs involving invalid player objects and player interactions. 2013-05-13 18:46:18 -07:00
Glitchfinder
95ea6703f1 Fixing an NPE involving invalid players chatting. 2013-05-13 18:46:17 -07:00
T00thpick1
55f9092aa6 Fireworks adjustment 2013-05-13 21:23:16 -04:00
Glitchfinder
5f50a46603 Setting the treasure config to only enforce data limits for blocks. 2013-05-13 20:22:09 -04:00
Paul J Thordarson
c5e6704530 Magic Hunter fix and optimization
There was a small bug in magic hunter, where it tried to apply an
enchantment level between 1 and the Enchantment.getMaxLevel(), however
it didn't take into account Enchantment.getStartLevel(), so when it
tried to apply an enchantment level below the start level, an
IllegalArgumentException was being thrown and the magic hunter event
wasn't happening.

Also, it's potentially inefficient to recalculate which enchantments
are possible for each ItemStack every time, so I added a HashMap to
cache the possibleEnchantments for each material type, then check this
cache instead of just looping to regenerate the list each time.
2013-05-13 20:22:08 -04:00
T00thpick1
8552192894 Only apply permissions when skill is enabled 2013-05-13 20:19:50 -04:00
NuclearW
0261d16140 Give no mcMMO xp for skeletons that spawn as a spider jokey pair from spawners. 2013-05-11 18:54:25 -04:00
NuclearW
2b414526e5 Unleash the Quacken! 2013-05-09 11:04:34 -04:00
NuclearW
c0b7eb526a Change Squid variables to Creature. 2013-05-09 11:00:28 -04:00
t00thpick1
7b7196a8c4 Potatoes shouldn't explode by default 2013-05-05 23:00:14 -03:00
t00thpick1
f648289035 Potato fixes 2013-05-05 22:58:04 -03:00
TfT_02
8a0b1d548d Add item weights for armor and tools in the default file 2013-05-05 11:32:10 +02:00
NuclearW
1f17d5d11e Move the comment section attached to the Kraken in advanced.yml
This is to fix a shortcoming in the autoupdate-config loader, which will attach related comments to nodes.
Issue: A nodes will get comments from another node of the same name, anywhere else in the config.
Solution: Move the comment to be attached to the "Kraken" node.

Long term: This can be a known bug and worked around by the team, or can be addressed more seriously by looking into changing how comments are applied to configs.  For now, this is a patch solution that should work fine.

Fixes #1043
2013-05-05 05:27:11 -04:00
TfT_02
18efd09421 Remove \' since it somehow breaks the name display
For some reason using \' will show the pets name as:
"<player-name>'s {1}"
2013-05-05 00:36:58 +02:00
TfT_02
18d3b30647 Add a missing space 2013-05-04 23:34:19 +02:00
GJ
7f0243b2df For Iaccidentally. 2013-05-03 18:16:42 -04:00
GJ
33610c8997 Whoops. 2013-05-03 16:15:34 -04:00
GJ
8e0a1f4f70 Summon the kraken at will! 2013-05-03 16:14:03 -04:00
GJ
b07cf6bdde It's now possible to run away from the Kraken. 2013-05-03 15:49:29 -04:00
GJ
7ed218ee7f Cleanup this task a bit. 2013-05-03 13:43:23 -04:00
GJ
3aedeea220 Remove client-side rain if the player kills the kraken. 2013-05-03 12:11:52 -04:00
GJ
4f9b7b2609 Because you might be legitimately fishing at 5 seconds. 2013-05-03 07:51:59 -04:00
GJ
09abab1b5d Kraken sounds can now be set to either player-only or global (default). 2013-05-03 07:51:58 -04:00
GJ
499713c8e7 Because autoclicking to shake is OK. 2013-05-03 07:51:57 -04:00
GJ
cb953a1619 Disable global chat spam from the kraken by setting the server message
to an empty string in the config.
2013-05-03 07:51:56 -04:00
TfT_02
3ab4938f3d Also need to locale these two strings
Closes #1019
2013-05-02 21:08:20 +02:00
TfT_02
f6e9fd9f3a Add more localisation 2013-05-02 21:02:12 +02:00
GJ
8dab75f3cb Can't use brackets in YAML. 2013-05-02 08:48:17 -04:00
GJ
b36096e54d Fixed bug where non-player arrows couldn't be deflected. 2013-05-02 08:23:18 -04:00
GJ
0574de4a29 Configure the Kraken! 2013-05-02 07:56:29 -04:00
GJ
6d6bc3de76 Trim player names to 16 chars when needed. 2013-05-02 07:16:07 -04:00
GJ
5c4c3cf59c The Kraken hates boats. 2013-05-01 22:50:12 -04:00
GJ
0033c8864e A dead kraken can't attack. 2013-05-01 22:17:48 -04:00
GJ
e7c749ee3a Added boosts to Fishing chance depending on conditions. Also, the
kraken, now with 100% more sound!
2013-05-01 21:57:42 -04:00
GJ
5c026be0cd Don't need those. 2013-05-01 21:19:29 -04:00
GJ
c465546871 Unleash the Kraken! 2013-05-01 21:17:59 -04:00
GJ
3322677d32 Added "Ice Fishing" ability to Fishing 2013-05-01 10:18:19 -04:00
GJ
76cf0ebb01 Only play ability effects if there's room above the player. 2013-05-01 08:59:45 -04:00
GJ
d34a0cca30 Fix issue with using /mcpurge, /mcremove, and /mmoupdate from the
console. These commands now default to OP, because frankly there are
much worse things someone can do with OP status than mess with the mcMMO
database.
2013-05-01 08:40:01 -04:00
GJ
a77a916fcc One more time... 2013-04-30 17:31:06 -04:00
GJ
e1ebb96545 Still need to remove from pending even if offline. 2013-04-30 15:47:19 -04:00
GJ
d85a6bec43 Don't create a task we'll possibly never run. 2013-04-30 15:19:41 -04:00
GJ
78eb7787e9 We don't need this any more. 2013-04-30 15:13:55 -04:00
GJ
b55ce30b2d Clean up our main class a bit more. Still not perfect, but it's getting
there.
2013-04-30 15:07:29 -04:00
GJ
14050cf096 Oops. 2013-04-30 14:24:31 -04:00
GJ
5930128b7f Add soft-depend on CombatTag so it loads before mcMMO, allowing us to
ensure the name check is ONLY run if CombatTag is installed.
2013-04-30 13:53:21 -04:00
GJ
08be78fa35 Avoid possible IllegalStateException if player has logged out before
this processes.
2013-04-30 10:02:28 -04:00
GJ
88f43d9a91 Add command to clear or change scoreboards. 2013-04-30 09:48:53 -04:00
GJ
6cbf960dea Use the right value here. 2013-04-30 08:24:16 -04:00
TfT_02
374d34f76d Fixed that for you 2013-04-30 14:20:16 +02:00
GJ
cc486c2dc7 Update the localization files. 2013-04-29 16:27:25 -04:00
GJ
724dce07a9 Back to regular development. 2013-04-29 15:59:56 -04:00
GJ
1486e2063b Beta time! 2013-04-29 15:59:35 -04:00
GJ
50c9649b23 mcMMO - Now with 100% more scoreboards!
mcMMO now allows for the use of scoreboards to display information in
several instances. By default, all scoreboards are enabled in the config,
and will only display for 10 seconds. After 10 seconds, the scoreboard
will go away and revert to the previously displayed scoreboard, if one
exists.

A global scoreboard now exists for tracking all player stats, and will be
displayed when /mctop is used. Your name will be highlighted in gold when
looking through the scoreboard. Additionally, the scoreboard will display
players in groups of 15, rather than groups of 10 like in chat.
Unfortunately, due to the limitations of scoreboards, the player's rank
will not be displayed in front of their name.

The scoreboard area is now also used for displaying data for /mcrank,
/inspect. and /mcstats. Due to the way scoreboards are handled, the power
level is not guarenteed to show up at any given location in the
scoreboard, but is instead displayed in gold so that it can be easily
found.

Lastly, the scoreboard area is also now used for displaying current data
on skills when the relevant /<skillname> command is used. The effects and
ability stats will still be shown in chat, but the current level, xp, and
remaining xp will be shown in the scoreboard.
2013-04-29 15:45:07 -04:00
GJ
339a54b0ac Replace SkillMonitorTask with 3 unique timers instead. This should greatly
optimize our tool and ability cooldown tracking and hopefully reduce
server load.
2013-04-29 15:33:55 -04:00
GJ
b97afb85a1 Only check names if CombatTag is enabled. 2013-04-29 00:29:38 -04:00
GJ
15da9d580b The previous CombatTag fix should take care of these. 2013-04-28 16:52:14 -04:00
GJ
62aed496cc Fix issue with CombatTag NPC errors. Fixes #1012
NOTE: Do NOT change the default NPC name for CombatTag in your config,
or this fix won't work.
2013-04-28 16:50:41 -04:00
GJ
fba131936a Fix issue with tab-completing /party commands. 2013-04-28 01:11:51 -04:00
t00thpick1
70601a4560 Debug code - Why you be in main branch 2013-04-28 01:08:07 -03:00
t00thpick1
83604ecb6d Syntax fixes 2013-04-27 14:18:10 -03:00
TfT_02
b912f7072c Actually use float experience 2013-04-26 17:28:18 +02:00
GJ
7e7e468408 Fix /mcrank showing everything as unranked... 2013-04-26 10:51:17 -04:00
T00thpick1
748c97f6c1 Expand AbilityAPI capabilities 2013-04-25 21:47:41 -04:00
GJ
a3aab57cf8 I am bad at SQL. 2013-04-25 20:08:27 -04:00
GJ
5548e26dd9 Fixed bug where players could remain in party chat after leaving or
being kicked from a party.
2013-04-25 19:52:25 -04:00
GJ
89d2f07c03 Because the block is null if they click air. 2013-04-25 19:36:34 -04:00
GJ
f42a28f34f Use defaults in case these are null. 2013-04-25 19:26:50 -04:00
TfT_02
bdc753f03c Also add the cancel feature for the Salvage Anvil 2013-04-25 23:40:21 +02:00
TfT_02
68a7b540c5 Ask a confirmation when a player tries to repair an enchanted item 2013-04-25 23:29:49 +02:00
GJ
b2dd820507 Clean up a few more things. 2013-04-25 09:27:48 -04:00
GJ
612308eb9a No reason to have those variables. 2013-04-25 09:20:03 -04:00
GJ
98dc7b853a Protect our managers. 2013-04-25 09:16:42 -04:00
GJ
a2fefd6fb6 Oops. 2013-04-25 07:48:14 -04:00
TfT_02
17a0382283 Changed experience storage from integers to floats
This will make sure no experience is lost when the server has high
skill modifiers configured, or when low amounts of experience are being
shared.
2013-04-25 07:42:38 -04:00
GJ
eea5784527 Abstract our database operations into a single class.
This allows the logic between SQL and Flatfile to remain more hidden in
most cases and makes the code easier to read.
2013-04-25 07:41:23 -04:00
GJ
1aff2cf9eb Cleaning out some crap from our PlayerListener. 2013-04-24 21:18:31 -04:00
GJ
4fc6349824 Move healthbar stuff to it own class. 2013-04-24 11:40:34 -04:00
GJ
7a3921eace Make these actually random. 2013-04-24 11:05:40 -04:00
GJ
e99599c377 Fixed Smelting returning ink sacs instead of Lapis when double-dropping.
Fixes #986
2013-04-24 07:08:24 -04:00
GJ
e1f6366a00 Don't make a new File every time. 2013-04-23 09:32:28 -04:00
GJ
182b01ac2f Redundant check is redundant 2013-04-23 09:10:22 -04:00
GJ
18f3914428 Use the path we already have. 2013-04-23 09:10:03 -04:00
GJ
bd0a045da3 No need to handle the load ourselves. 2013-04-23 09:00:42 -04:00
t00thpick1
9a4bed8c67 Already set to config default in constructor 2013-04-23 01:25:54 -03:00
t00thpick1
ae0cf692cd Use defaults when using defaults. 2013-04-23 01:22:01 -03:00
GJ
2ca7d139fe Fix NPEs relating combat checks and world changing. Fixes #976, #979 2013-04-22 23:19:26 -04:00
TfT_02
7e67505dfb Remove redundant ChimaeraWing check
Also indent the code
2013-04-21 21:50:08 +02:00
TfT_02
21100de85d Move the ChimaeraWing permission check and add feedback 2013-04-21 21:48:42 +02:00
TfT_02
d8f799f8b4 Add a few missing items to the Shareables list 2013-04-20 16:11:07 +02:00
TfT_02
cb03a98113 Add pickup sounds to cancelled PlayerPickupItemEvents
This will make the player aware that he has picked up an item.
2013-04-20 13:24:50 +02:00
GJ
4b36a11dda Make sure the target is online.
This ensures that the McMMOPlayer object *should* be valid.
2013-04-18 22:18:06 -04:00
GJ
8099490213 Minor DB tweaks. 2013-04-18 22:18:05 -04:00
GJ
6cb2843707 Remove a stupid line. 2013-04-18 22:18:05 -04:00
TfT_02
e831f0561a Changed Call of the Wild, newly summoned pet's will have a custom name
Closes #972
2013-04-18 23:04:27 +02:00
GJ
d57c253b19 Returns in finally are bad. 2013-04-18 11:28:07 -04:00
GJ
c8c68ea7d9 A little file cleanup. 2013-04-18 11:23:45 -04:00
GJ
150fe730bd No point in having a class & method for one line of code. 2013-04-18 09:19:48 -04:00
GJ
8af425d067 Make this a bit more sane. 2013-04-18 09:09:12 -04:00
GJ
c3845abd2a Clean up a bit, and make the /party itemshare command recognize the new
"misc" option
2013-04-18 08:11:47 -04:00
GJ
eba6820ec6 Clean this up a bit. 2013-04-18 07:51:53 -04:00
TfT_02
822e40bc1f Added a new Party item share category "Misc" which contains a list of configurable items. 2013-04-17 16:03:34 +02:00
TfT_02
3ffcaae122 Track items dropped by a player, prevent them from being party shared 2013-04-17 15:20:09 +02:00
GJ
42a30b4521 Fixed Fishing treasures always having the same enchants. 2013-04-17 07:47:43 -04:00
GJ
377ed9e8e5 Fix not being able to change party owners. 2013-04-17 07:07:54 -04:00
GJ
be76fe61d8 Fixed being unable to kick party members. 2013-04-17 07:05:28 -04:00
GJ
07ba7a8d9e Nerf fishing again... AGAIN 2013-04-16 23:48:36 -04:00
GJ
2be3e3b43c Changed Berserk to add items to inventory rather than denying pickup 2013-04-16 23:44:41 -04:00
GJ
49bf190895 Update changelog. 2013-04-16 07:00:39 -04:00
GJ
c9a53bdaca Fixed NPE when trying to tab-complete /mctop 2013-04-15 12:52:11 -04:00
GJ
3a76a111d3 Use the mob name when we have it. 2013-04-14 02:10:48 -04:00
TfT_02
e59c7ac34a Reduced the amount of info messages in the console when enabling/disabling 2013-04-13 21:53:00 +02:00
TfT_02
f05b9ae365 Use LinkedHashSet instead of List 2013-04-13 18:43:22 +02:00
GJ
c60e5a65d6 Fixed shake drops not working.
NOTE: You need to delete your treasures.yml and allow it to regenerate.
2013-04-13 11:34:38 -04:00
TfT_02
1b4eda713f Moar magical fixes!
This will automagically fix bugged players who have joined multiple
parties.
2013-04-13 01:17:07 +02:00
TfT_02
cb133ced80 No longer needed! 2013-04-13 01:16:17 +02:00
TfT_02
062a3028f4 This makes it easier to read 2013-04-13 01:11:26 +02:00
TfT_02
682c2631f0 Fixed bug where players were able to join the same party multiple times
This change should automagically fix broken parties which have multiple
instances of the same player in it.

This will not fix bugged players who have joined multiple parties.
2013-04-13 00:41:36 +02:00
NuclearW
faecb9a439 Fix players not having ptp.send by default. 2013-04-12 18:25:52 -04:00
GJ
5dc40f3c03 Nerf fishing... again. 2013-04-12 17:48:04 -04:00
GJ
569e87847f Fixed fishing chance display values. 2013-04-12 10:25:00 -04:00
GJ
b448315f20 And now, back to your regularly scheduled development. 2013-04-11 23:55:13 -04:00
GJ
2c87ce06eb Weekly beta releases are back! 2013-04-11 23:54:10 -04:00
GJ
875091a1ce Added ability to configure drops from Shake in treasures.yml 2013-04-11 21:40:09 -04:00
GJ
5ad7716137 Don't need to store that. 2013-04-11 10:24:22 -04:00
GJ
8c97399cec This is important. 2013-04-11 10:02:08 -04:00
GJ
27e0a9d3b6 Fixed experience commands affecting all skills. Fixes #951 2013-04-11 09:55:39 -04:00
GJ
07f9b287e7 Move exceptions to their own package.
This will break plugins that directly catch these exceptions.
2013-04-10 20:21:55 -04:00
GJ
fbee4f1b37 Remove debug messages. 2013-04-10 19:41:55 -04:00
GJ
26542f3d6e Because otherwise you can't fish at low levels. 2013-04-10 19:32:26 -04:00
GJ
14630fe956 Nerfin' it. 2013-04-10 18:44:11 -04:00
GJ
30f5c761d9 Because some plugins do stupid things. 2013-04-10 17:04:32 -04:00
GJ
365abaaa8f Reverse the order to avoid NPE 2013-04-10 14:04:46 -04:00
GJ
f4681a282c Better handling of picking up items with unarmed. 2013-04-10 13:20:44 -04:00
TfT_02
8a14d9ac26 Update the changelog 2013-04-10 17:19:34 +02:00
TfT_02
0ab1986202 Set a seperate cooldowns between getting hurt and teleportations
Closes #880
2013-04-10 17:19:14 +02:00
TfT_02
e11dc680de Add configurable warmup and cooldown timers for party teleportation
Closes #348
2013-04-10 17:18:06 +02:00
TfT_02
71249334c3 Change the ChimaeraWing timestamp into a general teleportation timestamp 2013-04-10 17:15:48 +02:00
NuclearW
fa41dbce16 Regex used mean look, could not escape! 2013-04-10 00:00:57 -04:00
GJ
4246e6c900 Use char codes instead of symbols, just to be safe. 2013-04-09 23:41:02 -04:00
GJ
1b421a24b0 Remove the drop. 2013-04-09 21:44:27 -04:00
GJ
9cc9eead52 Unbreak the API 2013-04-09 21:09:47 -04:00
GJ
8b21aea9c7 Check Fisherman's Diet permission when checking for display headers. 2013-04-09 20:53:55 -04:00
GJ
4f87cb6446 Added "Master Angler" ability to Fishing.
This ability increases the chance that a fish will bite the line while
fishing.
2013-04-09 20:53:54 -04:00
GJ
7525de1a72 ExperienceAPI methods will now throw InvalidSkillException if the skill
name passed in is invalid
2013-04-09 20:52:58 -04:00
GJ
78d2fa7520 Only care if it was unarmed. 2013-04-09 16:52:41 -04:00
GJ
7fe8122499 Avoid picking up items to the hotbar while using unarmed. Fixes #939 2013-04-09 16:52:38 -04:00
GJ
532c2e7450 Remove unused import 2013-04-09 16:52:35 -04:00
GJ
b391a53c6b Make our commands support tab-complete. 2013-04-08 17:34:23 -04:00
GJ
f3c6346b95 Clear mob health display if it gets stuck. Fixes #933 2013-04-08 00:34:54 -04:00
GJ
dd8984314f Validate here instead. 2013-04-08 00:26:12 -04:00
GJ
b82c3f41d3 Remove metadata, validation checks. 2013-04-08 00:24:38 -04:00
GJ
7d6eb65776 No need to reset. 2013-04-08 00:11:09 -04:00
GJ
dc0800e7e1 Even better regex. 2013-04-08 00:07:07 -04:00
GJ
c151366952 Better regex for this. 2013-04-07 23:58:53 -04:00
GJ
212137ec3e Fix issues with mob healthbars being used in death messages. Fixes #934 2013-04-07 23:22:59 -04:00
GJ
31f36935d3 Avoid NPE when using experience commands on offline players. 2013-04-07 09:01:31 -04:00
TfT_02
a14fc3e3c9 Fixed broken /party chat command
Closes #931
2013-04-06 12:20:20 +02:00
GJ
158b3c43f8 Fixed wolves from Call of the Wild only having 8 health. 2013-04-05 16:17:59 -04:00
GJ
e31c1e33d9 Don't handle removing the name if the entity is dead. 2013-04-05 16:15:24 -04:00
GJ
25dfa6d34d Better way to get the HUD type. 2013-04-04 23:15:37 -04:00
GJ
431429a29c Broken config files are bad. 2013-04-04 23:03:54 -04:00
GJ
d4c8cc28a1 Use new hasConflictingEnchant method. 2013-04-04 22:26:48 -04:00
GJ
ce08405c00 Use new NetherWartState values. 2013-04-04 22:24:02 -04:00
GJ
da29185b7d Added health display for mobs during combat.
During combat, players will now see a healthbar appear over the head of
hostile mobs when they are damaged. This healthbar will have two display
options - HEARTS and BAR - which can be changed via the /mobhealth
command.

New Permissions:
mcmmo.mobhealthdisplay - Allows viewing of mob health display
mcmmo.commands.mobhealth - Allows access to the /mobhealth command

New Config Options (config.yml):
Mob_Healthbar.Display_Type - the default health display type
Mob_Healthbar.Display_Time - the amount of time to show health display
2013-04-04 22:11:11 -04:00
TfT_02
87feb8c250 Added new API method to McMMOPlayerLevelUpEvent to set levels gained
Closes #352
2013-04-04 23:00:21 +02:00
TfT_02
12797893df Update the changelog 2013-04-04 22:50:32 +02:00
TfT_02
6d47e43ba9 Display partial names when trying to use the ptp command 2013-04-04 22:50:22 +02:00
TfT_02
f6b1643378 Minor formatting, added a missing white space 2013-04-04 22:21:13 +02:00
TfT_02
f1c16df63b Added new permission node for party teleportation.
`mcmmo.commands.ptp.send`
This permission node will be check before sending a teleport request
(or teleporting the sender if no request is required), this allows
admins to grant certain groups of users permissions to accept incoming
party teleport request without being able to send ptp requests
themselves.

Closes #927
2013-04-04 22:20:19 +02:00
TfT_02
c16e5231f4 Changed Chimaera Wing's recipe result to use the ingredient Material 2013-04-04 21:35:09 +02:00
GJ
2365c253dd Back to active development. 2013-04-04 10:23:06 -04:00
GJ
c4e7f2597e 1.4.05 bugfix release. 2013-04-04 10:22:09 -04:00
GJ
13fd522bd4 Updated localization files. Adds Thai (Thailand) and Lithuanian support. 2013-04-04 10:17:55 -04:00
GJ
b74f6e92dc Fixed party & admin chat errors when not aysnc 2013-04-04 10:14:52 -04:00
GJ
630c3e81e6 Fixed Chimera Wing displaying warmup message if warmup was set to 0 2013-04-04 09:59:10 -04:00
GJ
0f77cf8066 Fixed Chimera Wing spamming console if Metrics was disabled 2013-04-04 09:48:48 -04:00
GJ
52746fca76 Speed up our BlockBreakEvent checks a bit. 2013-04-04 09:29:07 -04:00
GJ
dae25c2f2d Don't check if we don't watch. 2013-04-04 08:10:24 -04:00
GJ
a272316301 Don't even bother running these checks if we don't watch the block. 2013-04-04 08:05:48 -04:00
GJ
6772f4f169 Track these IF they're somehow full-grown when placed. 2013-04-04 08:02:45 -04:00
GJ
9463e210b8 Compact our checks. 2013-04-04 07:42:33 -04:00
GJ
4c44b72f78 50 != 100 2013-04-04 07:06:07 -04:00
GJ
c849f751bb Fixed potion buff option not using the appropriate # of ticks 2013-04-03 11:41:43 -04:00
GJ
1cde45599e Fixed huge mushroom blocks not being properly tracked 2013-04-03 11:16:24 -04:00
GJ
f1a22f5f6b Shouldn't track this either, just to be safe. 2013-04-02 21:30:18 -04:00
GJ
90d6fbde48 Fix ClassCastException with Taming. Fixes #924 2013-04-02 21:24:02 -04:00
GJ
802ad84613 Fixed Berserk getting "stuck" when /mcrefresh is used. 2013-04-02 17:38:33 -04:00
GJ
c4aa9396fd Update changelog. 2013-04-02 13:48:05 -04:00
GJ
f0c937ad47 Fixed parties and /reload not playing nice together. 2013-04-02 13:47:52 -04:00
GJ
fcc36ee5d7 Trying to fix reload more. 2013-04-02 11:17:40 -04:00
GJ
0f023f627c Metadata > Hashmap 2013-04-02 08:41:51 -04:00
GJ
fa645b5e00 Clear after saving, save before clearing. 2013-04-02 08:29:38 -04:00
GJ
1fb28eeee0 Because reload is evil. 2013-04-02 08:20:55 -04:00
TfT_02
d7f67d43b3 I quite liked the fireworks display! 2013-04-02 13:08:07 +02:00
TfT_02
5a1ec745ce Update the changelog 2013-04-01 22:55:19 +02:00
TfT_02
6fd599bd31 Fixed bug where /addxp was not processessing level-ups for online players
Fixes #918
2013-04-01 22:54:36 +02:00
GJ
afd706bed8 Fix NPE with smelting & /mctop. Fixes #917 2013-04-01 16:41:58 -04:00
TfT_02
6c3820c747 Because some people really wanted to disable this,
mostly due to clientside lag.
2013-04-01 16:38:22 +02:00
TfT_02
0ebc555136 Fixed bug with ChimaeraWings not taking Wings from a players inventory properly
Fixes #914
2013-04-01 11:32:28 +02:00
TfT_02
4992c50098 Sharing with the dead is bad, they have nothing to gain. 2013-04-01 00:22:24 +02:00
NuclearW
4e9322485a Flush write buffer for saving PlayerProfile before closing it. 2013-03-31 17:12:45 -04:00
TfT_02
fc8ad40b00 Fixed bug where /addxp was setting instead of adding experience
Fixes #898
2013-03-30 10:50:05 +01:00
TfT_02
f62e053a84 Update the changelog 2013-03-30 10:42:50 +01:00
T00thpick1
0af3c7ab7d Just in case. 2013-03-29 22:35:55 -04:00
NuclearW
7f4efe1775 Added option to allow refreshing of chunks after block-breaking abilities.
This, if enabled, should fix the problem of clients believing they have broken more blocks than they really have when the enchanced enchantment is removed.
If testing proves it to be useful, could be enabled by default.  This currently send a 3x3 set of chunks centered around the player, so some servers may wish to disable it in that case.
2013-03-29 18:29:31 -04:00
GJ
80a5c2f9c4 Back to active development 2013-03-28 12:49:57 -04:00
GJ
90e13c9562 1.4.04 bugfix release 2013-03-28 12:49:14 -04:00
GJ
fe89c19969 Passing events is bad. 2013-03-28 09:30:49 -04:00
GJ
0b6dfad7e5 Changelog update. 2013-03-28 08:03:26 -04:00
GJ
f2b1758439 Fix players not being able to pick up items. 2013-03-28 07:52:12 -04:00
GJ
86eaa3b091 These aren't the drops you're looking for. 2013-03-28 07:46:22 -04:00
GJ
24153c2fb1 Dumb ternary statement was dumb. 2013-03-28 07:45:35 -04:00
GJ
5e36683ff2 Fixed Potatoes and Carrots not awarding XP. 2013-03-28 07:45:15 -04:00
NuclearW
c53563e7d1 More work GJ didn't ask me to do 2013-03-28 02:18:36 -04:00
TfT_02
d778293531 Use full player names instead of partial names 2013-03-27 21:25:59 +01:00
GJ
7d8888d47d Even simpler. 2013-03-27 15:56:03 -04:00
TfT_02
6fbfec48b0 Revert "Deal with the ConcurrentModification issue. Fixes #873"
This reverts commit ca51b2f.
2013-03-27 20:44:44 +01:00
TfT_02
1f25b0b00b Use positive page numbers when a player uses /mctop -1 2013-03-27 20:37:03 +01:00
GJ
0118346aaf ACTUALLY fix our CME. 2013-03-27 15:34:34 -04:00
TfT_02
287842c675 Fixed bug which causes a NPE when trying to use /mcrefresh from the console 2013-03-27 20:17:54 +01:00
GJ
61dc77559b Updated to EMetrics 0.0.4-SNAPSHOT 2013-03-27 07:24:05 -04:00
TfT_02
ca51b2f70f Deal with the ConcurrentModification issue. Fixes #873 2013-03-26 15:18:14 +01:00
NuclearW
3cf01cb6f3 Expand ChatAPI 2013-03-26 01:55:24 -04:00
NuclearW
16a4b78580 Slight change to ChatAPI implementation 2013-03-26 01:54:47 -04:00
TfT_02
94b560ba01 Don't activate abilities when a player is in creative mode. 2013-03-25 23:15:09 +01:00
TfT_02
3ae9956df9 Actually fix partial name matching when using /mcrank
Fixes #878
2013-03-24 16:53:01 +01:00
TfT_02
78109eb499 Revert "Fixes partial name matching with /mcrank"
This reverts commit f9a823e4b0.
2013-03-24 16:30:27 +01:00
NuclearW
da5238878d Remove Ender Dragon, Wither, and Witch from granting combat experience and related configuration options 2013-03-24 01:31:50 -04:00
TfT_02
f9a823e4b0 Fixes partial name matching with /mcrank 2013-03-23 16:22:48 +01:00
TfT_02
eb20da021d Correctly format the config.yml comments 2013-03-23 15:19:40 +01:00
TfT_02
596f2fa78a Changed config node name for the skill experience modifiers from "Multiplier" to "Modifier"
Because the name was confusing.
This will break config settings, check your config.yml if you have
changed the skill experience modifiers.
2013-03-23 15:18:21 +01:00
TfT_02
fa99ebb391 Check if it's an mcMMO item instead.
For when we add more items than just ChimaeraWings
2013-03-22 19:15:29 +01:00
TfT_02
9b685be84e More inverted checkPlayerExistence() checks 2013-03-22 19:08:10 +01:00
TfT_02
96f9d2a030 Fixed broken /party invite command 2013-03-22 19:06:21 +01:00
TfT_02
2b7178fb00 Fixed broken /party join command
Fixes #863
2013-03-22 19:02:51 +01:00
TfT_02
c47bf84493 Fix an IndexOutOfBoundsException when using /mctop
Fixed #861
2013-03-22 17:38:52 +01:00
TfT_02
8cf16d4a1c Update player inventory after crafting multiple ChimaeraWings
Fixes #864
2013-03-22 11:22:03 +01:00
TfT_02
5b5b73cde0 Improving Chimaera Wing - part 2
* Added a warmup before using a Chimaera Wing
 * Closes #740
2013-03-22 00:38:21 +01:00
Glitchfinder
9f55c25775 Actually adding Nether Quartz to Mining for double drops. 2013-03-21 16:05:34 -07:00
TfT_02
92c6a7bfcf Added partial name matching
Works with commands such as /party kick <name>, /ptp <name>
2013-03-21 23:45:10 +01:00
TfT_02
145a47c890 Fixed a NPE when trying to ptp to a non-existing player 2013-03-21 23:09:44 +01:00
TfT_02
70160468c0 Fix a NPE when trying to join a non-existing player
Fixes #860
2013-03-21 22:04:52 +01:00
TfT_02
9730cdb880 Normalize line endings 2013-03-21 20:46:23 +01:00
GJ
399bf8e3b9 Use BukkitRunnable. 2013-03-20 03:11:16 -04:00
GJ
c3a69c8c55 Change to the newer, shorter scheduler methods. 2013-03-20 02:15:15 -04:00
GJ
db2bf9ee51 Updated localization files. 2013-03-18 14:28:04 -04:00
GJ
255dece550 Move Arcane Forging to it's own class to match the structure we used
with Blast Mining.
2013-03-18 14:02:53 -04:00
GJ
d004361836 Removed functions for getting the PlayerProfile - using API classes is
preferred, but if not the McMMOPlayer should be used instead
2013-03-18 14:02:52 -04:00
GJ
5453b0511d Update changelog. 2013-03-18 00:09:22 -04:00
GJ
42bc5065df Add support for new 1.5 inventory blocks. 2013-03-17 23:58:20 -04:00
GJ
b0d609e9a3 Add Quartz Ore to Mining. 2013-03-17 23:58:19 -04:00
GJ
814ffbe800 Fixed by Bukkit in CB #2654 2013-03-17 23:58:19 -04:00
GJ
e7ee23b871 Fixes NPE with FurnaceExtractEvent. Fixes #847 2013-03-17 21:47:45 -04:00
GJ
c14ceab24d Remove unused import. 2013-03-17 11:01:30 -04:00
GJ
70e8e534fe Fixed bug with retrieving a player's party members 2013-03-17 10:46:29 -04:00
GJ
c4504de1da Update changelog. 2013-03-17 10:41:53 -04:00
GJ
685f901e09 Removed deprecated functions from PartyAPI 2013-03-17 10:41:34 -04:00
GJ
d196710a87 Removed deprecated methods from ChatAPI 2013-03-17 10:40:32 -04:00
GJ
050f97e088 Remove deprecated functions from ExperienceAPI 2013-03-17 10:38:43 -04:00
GJ
c2fea660e7 Added functions to ExperienceAPI for use with offline players.
Fixes #836
2013-03-17 10:34:46 -04:00
GJ
b2cdf21de5 Fixed bug where the API would fail if the name of a player's current
party is requested when the player isn't in one (Thanks @dualspiral!)

Closes #843
2013-03-17 09:02:15 -04:00
GJ
ed09d1b390 Fixed bug where Shake wouldn't damage mobs whose max health was less
than 4.

Fixes #845
2013-03-17 08:11:20 -04:00
GJ
171026ba23 Fixed bug where Mining wasn't awarding double drops 2013-03-17 00:36:40 -04:00
GJ
dafa690a09 Make /mcnotify match the process of the other commands for getting the
mcMMOPlayer object.
2013-03-16 16:16:22 -04:00
GJ
4cd4223ee0 Fixed /skillreset being broken. 2013-03-16 16:16:22 -04:00
GJ
3ac5ac385d Fix issue with double drop display values. 2013-03-16 16:16:21 -04:00
bm01
0ae5421d10 So apparently we're no longer on 1.4.03 2013-03-16 16:59:01 +01:00
bm01
3f56c8e690 Fixed Treefeller trying to cut too many leaves 2013-03-16 16:49:32 +01:00
TfT_02
c14f3777c0 Fixed bug where trying to activate a Chimaera Wing would require one item too much 2013-03-16 11:42:38 +01:00
GJ
2838a52e0c Clean up on all of our commands. Abstracted experience commands and
hardcore commands. Moved lots of duplicated code to functions in
CommandUtils.java. Split /ptp into individual commands, just like /party.
Used ternary logic to simplify some of our /skillname stat displays. Fixed
skill guide to not allow for negative pages. Simplified logic for many
/skillname data calculations. Use permission checks to prevent calculating
data that will never be displayed. Made the skill guide into its own
command.
2013-03-16 03:17:00 -04:00
GJ
dcfdfa0e62 Back to active development. 2013-03-14 22:28:05 -04:00
GJ
23719ace47 1.4.03 Bugfix Release 2013-03-14 22:27:24 -04:00
TfT_02
33882983e9 Update the changelog 2013-03-14 22:32:35 +01:00
TfT_02
5aecedc074 Damage the player when ChimaeraWing use failed 2013-03-14 22:31:44 +01:00
TfT_02
69bf17a619 Added Bat takeoff sound when using a Chimaera Wing 2013-03-14 22:26:02 +01:00
TfT_02
0292d3eefb Cleanup ChimaeraWing 2013-03-14 22:24:38 +01:00
TfT_02
0cd3e4ed84 Teleport to save spawn locations
Changed underground usage check.
2013-03-14 22:13:23 +01:00
GJ
3a26194a71 Optimized a few things with our FFS leaderboards. 2013-03-14 10:25:54 -04:00
GJ
1313e3fe4b Fix CraftBukkit / Bukkit bug regarding event.getCurrentItem() throwing
an ArrayIndexOutOfBounds error.
2013-03-13 15:44:26 -04:00
TfT_02
b2f400f61a "Splinter the axe into dozens of pieces" 2013-03-12 23:31:44 +01:00
GJ
9aa676cee1 We don't need to have two different executors for these commands. 2013-03-11 22:51:44 -04:00
GJ
eabf0f7f82 No need to use an empty locale string for this. 2013-03-11 21:06:56 -04:00
GJ
d0171809ec Fixed bug with '/party chat (on|off)' and '/partychat (on|off)' not
working
2013-03-11 21:06:26 -04:00
GJ
410c946faf Tidying up Permission checks for /mcrank and /mctop 2013-03-11 12:48:00 -04:00
GJ
3a7d88db4f Fixed bug with Blast Mining increasing TNT damage. 2013-03-10 21:30:35 -04:00
GJ
9eba2c683b Use equalsIgnoreCase() instead of equals(), and use == for compaing
worlds.

Fixes #815
2013-03-10 18:06:10 -04:00
T00thpick1
8059636b62 Permissions for stat displays 2013-03-10 15:50:10 -04:00
GJ
d78a1efbf6 Fixed bug with Repair not decreasing enchanting levels properly.
Fixes #817
2013-03-10 15:48:16 -04:00
GJ
c0b4a33346 Importing Bukkit is usually bad. 2013-03-10 15:07:07 -04:00
GJ
2cef6700c7 Just to be 100% sure this gets processed correctly.
The blockstate DOES current store the metadata of the block, but I'd
rather stick with using the Block every time to be absolutely certain
that things are handled correctly.
2013-03-10 14:53:51 -04:00
t00thpick1
df67bd6720 Message player only when enchants actually exist 2013-03-09 20:05:15 -05:00
TfT_02
655dcb1c9b Add Cooldown setting for Chimaera Wing to default config.yml 2013-03-09 21:43:06 +01:00
TfT_02
ce32792668 Fixed bug where Deflect was calculated based on the attacker, not the defender
Closes #794
2013-03-09 14:44:29 +01:00
TfT_02
4b384abc51 Adding comments to config.yml and itemweights.yml 2013-03-09 10:26:57 +01:00
TfT_02
82bccd357b Removed trailing whitespace 2013-03-09 10:21:05 +01:00
NuclearW
12709bcd7f Check hasItemMeta 2013-03-08 22:20:26 -05:00
NuclearW
0b53f8266a Squashed commit of the following:
commit ba0ba3d2881dc672ef3dc40010278a0fbe158436
Author: NuclearW <incongruency@gmail.com>
Date:   Fri Mar 8 16:27:19 2013 -0500

    Line endings, yo

commit b93f0f54f5
Author: md-5 <md_5@live.com.au>
Date:   Sat Mar 9 08:18:49 2013 +1100

    Use correct state, not block refrence to fix compile.

commit 1063ad5c68
Author: md-5 <md_5@live.com.au>
Date:   Sat Mar 9 08:12:34 2013 +1100

    Fix errors in furnace listener.

    Bad GJ!
2013-03-08 16:32:44 -05:00
TfT_02
a07f14e326 Improving Chimaera Wing - part 1
* Added cooldown between using Chimaera Wings
 * Added shapeless recipe to craft a Chimaera Wing (by default 5
feathers)
2013-03-08 21:46:05 +01:00
TfT_02
3349e9cb05 Normalize line endings 2013-03-08 21:42:26 +01:00
bm01
0e2746622d Fixed the Cacti & Sugar Cane fix! 2013-03-08 19:33:03 +01:00
GJ
d9bd0ace9a Fixed bug with Smelting not properly tracking furnaces. Fixes #806 2013-03-08 10:23:21 -05:00
GJ
e31b7d5c48 Cacti & Sugar Cane are an exception, because the bottom block is
normally player-placed but the top two are grown naturally.
2013-03-08 08:53:54 -05:00
GJ
4bddbbf56e This must be handled first, else no XP is awarded if double-drops are
disabled.
2013-03-08 08:49:07 -05:00
GJ
0654f27599 Fixed bug where Blast Mining was awarding too much XP 2013-03-08 08:45:16 -05:00
GJ
3f71dab0b1 Improved stats display for child skills 2013-03-08 08:39:28 -05:00
GJ
bd45fff1b4 Fixed bug relating to "empty" ItemStacks. Fixes #807 2013-03-08 07:40:25 -05:00
GJ
9618e45a11 That was bothering me. 2013-03-08 07:26:43 -05:00
bm01
3839373f5a Forgot this one 2013-03-08 10:35:52 +01:00
bm01
1633617006 Minor cleanup 2013-03-08 10:33:20 +01:00
bm01
57e33bbf39 Fixed triple drop awarding experience twice in mining
The previous commit also fixed this for Herbalism
2013-03-08 10:31:32 +01:00
bm01
cddcf36016 Reworked some methods related to Herbalism
Fixes double seed consumption for Green Terra when used on crops
Fixes wheat consumption instead of seed for Green Thumb
Fixes XP and double drop exploit with some blocks (flowers...)
2013-03-08 10:11:33 +01:00
bm01
dff03109a3 Parties should only be saved once per call 2013-03-08 05:28:40 +01:00
bm01
c0986a1f89 Removed unneeded null checks 2013-03-08 02:09:43 +01:00
bm01
cd4c328320 Improved SkillMonitorTask 2013-03-08 02:03:25 +01:00
NuclearW
03d0ecd450 text=auto 2013-03-07 14:43:03 -05:00
GJ
3a809dab32 Fix downgrade chances all being calculated from Rank4. 2013-03-07 12:52:43 -05:00
GJ
ade9e20cdd Fixed bug where Beast Lore wouldn't work on friendly pets.
Fixes #805
2013-03-07 09:18:27 -05:00
GJ
29520dc95c Get the mcMMOPlayer outside of the loop so it doesn't have to be
recreated every time.
2013-03-07 08:53:13 -05:00
GJ
d40d89f29a Fixed bug where the 'mcmmo.commands.ptp.world.all' was registered twice.
Fixes #787
2013-03-07 08:07:55 -05:00
GJ
9377de930f Fixed bug with using Salvage on stacked items. Stacked items will now
return the appropriate amount of materials. Fixes #802
2013-03-07 08:03:18 -05:00
GJ
3219674678 Added option to advanced.yml to determine the # of enchant levels used
when buffing Super Breaker & Giga Drill Breaker
2013-03-06 23:00:37 -05:00
GJ
a9438ed52b Move BlockCracker into the UnarmedManager 2013-03-06 19:19:26 -05:00
GJ
09169bd019 Fixed bug where Fishing was becoming less successful at higher levels 2013-03-06 18:17:54 -05:00
GJ
c30fdef615 Removed the option to use Woodcutting without an axe from the config
file.
2013-03-06 16:27:10 -05:00
GJ
109e9725a9 No need to create our mcMMOPlayer again. 2013-03-06 16:25:46 -05:00
GJ
44ede5c3f8 Create a WoodcuttingManager 2013-03-06 16:23:41 -05:00
GJ
c1161da6de We don't use this function anymore. 2013-03-06 16:23:41 -05:00
TfT_02
80927417f2 Fix the update checker
Now it's able to parse x.x.x-type-bxxx and x.x.x-bxxx
2013-03-06 22:20:11 +01:00
GJ
91d8cd5da8 Reorganize our imports after Repair refactoring. 2013-03-06 12:21:02 -05:00
GJ
869d731b81 We now have a RepairManager. 2013-03-06 12:19:57 -05:00
GJ
f6a18ef777 Move Salvage functions into Repair 2013-03-06 11:31:51 -05:00
GJ
3e084b3b5d Unlock levels go in advanced.yml, not config.yml 2013-03-06 11:13:25 -05:00
GJ
2c7f931c4d Removed option to disable Salvage via the config file. This should be
handled via permissions instead.
2013-03-06 10:50:59 -05:00
GJ
6b18cec7fb Combine our placedAnvil checks into one function. 2013-03-06 10:47:56 -05:00
GJ
08960a2dbc Move Salvage checks into our RepairManager 2013-03-06 10:02:34 -05:00
GJ
5f4e269efa Fixed bug with repairing using materials with byte metadata 2013-03-06 09:43:09 -05:00
GJ
e5f6da01ec Create a proper RepairManager to match the others, rename our old
RepairManager to RepairableManager.
2013-03-06 09:37:09 -05:00
TfT_02
ae741a1b99 Fixed bug where players were unable to salvage leather armor. Closes #788 2013-03-05 14:39:39 +01:00
GJ
78a3ea4765 Back to active development 2013-03-04 22:50:25 -05:00
209 changed files with 12347 additions and 7035 deletions

2
.gitattributes vendored
View File

@@ -1,4 +1,4 @@
* text
* text=auto
*.png binary
*.wav binary

82
.gitignore vendored
View File

@@ -1,42 +1,42 @@
# Eclipse stuff
/.classpath
/.project
/.settings
# netbeans
/nbproject
# we use maven!
/build.xml
# maven
/target
# vim
.*.sw[a-p]
# various other potential build files
/build
/bin
/dist
/manifest.mf
/world
# Mac filesystem dust
*.DS_Store
# intellij
*.iml
*.ipr
*.iws
.idea/
# Project Stuff
/src/main/resources/mcMMO
# Other Libraries
*.jar
# Atlassian Stuff
# Eclipse stuff
/.classpath
/.project
/.settings
# netbeans
/nbproject
# we use maven!
/build.xml
# maven
/target
# vim
.*.sw[a-p]
# various other potential build files
/build
/bin
/dist
/manifest.mf
/world
# Mac filesystem dust
*.DS_Store
# intellij
*.iml
*.ipr
*.iws
.idea/
# Project Stuff
/src/main/resources/mcMMO
# Other Libraries
*.jar
# Atlassian Stuff
/atlassian-ide-plugin.xml

View File

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

10
pom.xml
View File

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

View File

@@ -1,14 +1,14 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>bin</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}.jar</source>
<outputDirectory>/</outputDirectory>
<destName>mcMMO.jar</destName>
</file>
</files>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>bin</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}.jar</source>
<outputDirectory>/</outputDirectory>
<destName>mcMMO.jar</destName>
</file>
</files>
</assembly>

View File

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

View File

@@ -39,22 +39,6 @@ public final class ChatAPI {
ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, sender, message);
}
/**
* Send a message to all members of a party
* </br>
* This function is designed for API usage.
*
* @deprecated Replaced by sendPartyChat(Plugin, String, String, String)
*
* @param sender The name of the sender to display in the chat
* @param party The name of the party to send to
* @param message The message to send
*/
@Deprecated
public static void sendPartyChat(String sender, String party, String message) {
sendPartyChat(null, party, sender, sender, message);
}
/**
* Send a message to administrators
* </br>
@@ -82,21 +66,6 @@ public final class ChatAPI {
ChatManager.handleAdminChat(plugin, sender, sender, message);
}
/**
* Send a message to administrators
* </br>
* This function is designed for API usage.
*
* @deprecated Replaced by sendAdminChat(Plugin, String, String)
*
* @param sender The name of the sender to display in the chat
* @param message The message to send
*/
@Deprecated
public static void sendAdminChat(String sender, String message) {
sendAdminChat(null, sender, sender, message);
}
/**
* Check if a player is currently talking in party chat.
*
@@ -104,7 +73,7 @@ public final class ChatAPI {
* @return true if the player is using party chat, false otherwise
*/
public static boolean isUsingPartyChat(Player player) {
return UserManager.getPlayer(player).getPartyChatMode();
return isUsingPartyChat(player.getName());
}
/**
@@ -124,7 +93,7 @@ public final class ChatAPI {
* @return true if the player is using admin chat, false otherwise
*/
public static boolean isUsingAdminChat(Player player) {
return UserManager.getPlayer(player).getAdminChatMode();
return isUsingAdminChat(player.getName());
}
/**
@@ -136,4 +105,40 @@ public final class ChatAPI {
public static boolean isUsingAdminChat(String playerName) {
return UserManager.getPlayer(playerName).getAdminChatMode();
}
/**
* Toggle the party chat mode of a player.
*
* @param player The player to toggle party chat on.
*/
public static void togglePartyChat(Player player) {
togglePartyChat(player.getName());
}
/**
* Toggle the party chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void togglePartyChat(String playerName) {
UserManager.getPlayer(playerName).setPartyChat(!isUsingPartyChat(playerName));
}
/**
* Toggle the admin chat mode of a player.
*
* @param player The player to toggle admin chat on.
*/
public static void toggleAdminChat(Player player) {
toggleAdminChat(player.getName());
}
/**
* Toggle the admin chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void toggleAdminChat(String playerName){
UserManager.getPlayer(playerName).setAdminChat(!isUsingAdminChat(playerName));
}
}

View File

@@ -1,11 +1,16 @@
package com.gmail.nossr50.api;
import java.util.Set;
import org.bukkit.entity.Player;
import com.gmail.nossr50.api.exceptions.InvalidPlayerException;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class ExperienceAPI {
private ExperienceAPI() {}
@@ -18,39 +23,39 @@ public final class ExperienceAPI {
* @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
* @deprecated Use {@link #addRawXP(Player, String, int)} instead
*/
@Deprecated
public static void addRawXP(Player player, SkillType skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(skillType, XP);
}
/**
* Adds raw XP to the player.
* </br>
* This function is designed for API usage.
*
* @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
* @throws InvalidSkillException if the given skill is not valid
*/
public static void addRawXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(SkillType.getSkill(skillType), XP);
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, XP);
}
/**
* Adds XP to the player, calculates for XP Rate only.
* Adds raw XP to an offline player.
* </br>
* This function is designed for API usage.
*
* @param player The player to add XP to
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
* @deprecated Use {@link #addMultipliedXP(Player, String, int)} instead
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
@Deprecated
public static void addMultipliedXP(Player player, SkillType skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(skillType, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
public static void addRawXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, XP);
}
/**
@@ -61,24 +66,82 @@ public final class ExperienceAPI {
* @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static void addMultipliedXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).applyXpGain(SkillType.getSkill(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP * 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 an offline player, calculates for XP Rate only.
* </br>
* This function is designed for API usage.
*
* @param player The player to add XP to
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
* @deprecated Use {@link #addXP(Player, String, int)} instead
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
@Deprecated
public static void addXP(Player player, SkillType skillType, int XP) {
UserManager.getPlayer(player).beginXpGain(skillType, XP);
public static void addMultipliedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
* Adds XP to the player, calculates for XP Rate and skill modifier.
* </br>
* This function is designed for API usage.
*
* @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static void addModifiedXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
* Adds XP to an offline player, calculates for XP Rate and skill modifier.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static void addModifiedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
}
/**
@@ -89,9 +152,17 @@ public final class ExperienceAPI {
* @param player The player to add XP to
* @param skillType The skill to add XP to
* @param XP The amount of XP to add
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static void addXP(Player player, String skillType, int XP) {
UserManager.getPlayer(player).beginXpGain(SkillType.getSkill(skillType), XP);
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).beginXpGain(skill, XP);
}
/**
@@ -102,86 +173,212 @@ public final class ExperienceAPI {
* @param player The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
* @deprecated Use {@link #getXP(Player, String)} instead
*/
@Deprecated
public static int getXP(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(skillType);
}
/**
* Get the amount of XP a player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param player The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getXP(Player player, String skillType) {
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(SkillType.getSkill(skillType));
SkillType skill = SkillType.getSkill(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);
}
/**
* Get the amount of XP left before leveling up.
* Get the amount of XP an offline player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for
* @return the amount of XP left before leveling up a specifc skill
* @deprecated Use {@link #getXPToNextLevel(Player, String)} instead
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
@Deprecated
public static int getXPToNextLevel(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getXpToLevel(skillType);
public static int getOfflineXP(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getSkillXpLevel(skill);
}
/**
* Get the amount of XP left before leveling up.
* Get the raw amount of XP a player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param player The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static float getXPRaw(Player player, String skillType) {
SkillType skill = SkillType.getSkill(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);
}
/**
* Get the raw amount of XP an offline player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP in a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static float getOfflineXPRaw(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getSkillXpLevelRaw(skill);
}
/**
* Get the total amount of XP needed to reach the next level.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for
* @return the amount of XP left before leveling up a specifc skill
* @return the total amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getXPToNextLevel(Player player, String skillType) {
return UserManager.getPlayer(player).getProfile().getXpToLevel(SkillType.getSkill(skillType));
}
SkillType skill = SkillType.getSkill(skillType);
/**
* Add levels to a skill.
* </br>
* This function is designed for API usage.
*
* @param player The player to add levels to
* @param skillType Type of skill to add levels to
* @param levels Number of levels to add
* @param notify Unused argument
* @deprecated Use addLevel(Player, SKillType, int) instead
*/
public static void addLevel(Player player, SkillType skillType, int levels, boolean notify) {
UserManager.getProfile(player).addLevels(skillType, levels);
if (notify) {
checkXP(player, 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);
}
/**
* Add levels to a skill.
* Get the total amount of XP an offline player needs to reach the next level.
* </br>
* This function is designed for API usage.
*
* @param player The player to add levels to
* @param skillType Type of skill to add levels to
* @param levels Number of levels to add
* @deprecated Use {@link #addLevel(Player, String, int)} instead
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the total amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
@Deprecated
public static void addLevel(Player player, SkillType skillType, int levels) {
UserManager.getPlayer(player).getProfile().addLevels(skillType, levels);
public static int getOfflineXPToNextLevel(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return getOfflineProfile(playerName).getXpToLevel(skill);
}
/**
* Get the amount of XP remaining until the next level.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for
* @return the amount of XP remaining until the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getXPRemaining(Player player, String skillType) {
SkillType skill = SkillType.getSkill(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();
return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
}
/**
* Get the amount of XP an offline player has left before leveling up.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getOfflineXPRemaining(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
PlayerProfile profile = getOfflineProfile(playerName);
return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
}
/**
@@ -192,24 +389,52 @@ public final class ExperienceAPI {
* @param player The player to add levels to
* @param skillType Type of skill to add levels to
* @param levels Number of levels to add
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static void addLevel(Player player, String skillType, int levels) {
UserManager.getPlayer(player).getProfile().addLevels(SkillType.getSkill(skillType), levels);
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().addLevels(skill, levels);
}
/**
* Get the level a player has in a specific skill.
* Add levels to a skill for an offline player.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the level for
* @param skillType The skill to get the level for
* @return the level of a given skill
* @deprecated Use {@link #getLevel(Player, String)} instead
* @param playerName The player to add levels to
* @param skillType Type of skill to add levels to
* @param levels Number of levels to add
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
@Deprecated
public static int getLevel(Player player, SkillType skillType) {
return UserManager.getPlayer(player).getProfile().getSkillLevel(skillType);
public static void addLevelOffline(String playerName, String skillType, int levels) {
PlayerProfile profile = getOfflineProfile(playerName);
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skill);
for (SkillType parentSkill : parentSkills) {
profile.addLevels(parentSkill, (levels / parentSkills.size()));
}
profile.save();
return;
}
profile.addLevels(skill, levels);
profile.save();
}
/**
@@ -220,9 +445,39 @@ public final class ExperienceAPI {
* @param player The player to get the level for
* @param skillType The skill to get the level for
* @return the level of a given skill
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static int getLevel(Player player, String skillType) {
return UserManager.getPlayer(player).getProfile().getSkillLevel(SkillType.getSkill(skillType));
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
return UserManager.getPlayer(player).getProfile().getSkillLevel(skill);
}
/**
* Get the level an offline player has in a specific skill.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get the level for
* @param skillType The skill to get the level for
* @return the level of a given skill
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static int getLevelOffline(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getSkillLevel(skill);
}
/**
@@ -237,6 +492,31 @@ public final class ExperienceAPI {
return UserManager.getPlayer(player).getPowerLevel();
}
/**
* Gets the power level of an offline player.
* </br>
* This function is designed for API usage.
*
* @param playerName The player to get the power level for
* @return the power level of the player
*
* @throws InvalidPlayerException if the given player does not exist in the database
*/
public static int getPowerLevelOffline(String playerName) {
int powerLevel = 0;
PlayerProfile profile = getOfflineProfile(playerName);
for (SkillType type : SkillType.values()) {
if (type.isChildSkill()) {
continue;
}
powerLevel += profile.getSkillLevel(type);
}
return powerLevel;
}
/**
* Get the level cap of a specific skill.
* </br>
@@ -244,9 +524,17 @@ public final class ExperienceAPI {
*
* @param skillType The skill to get the level cap for
* @return the level cap of a given skill
*
* @throws InvalidSkillException if the given skill is not valid
*/
public static int getLevelCap(String skillType) {
return Config.getInstance().getLevelCap(SkillType.getSkill(skillType));
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
return Config.getInstance().getLevelCap(skill);
}
/**
@@ -254,7 +542,7 @@ public final class ExperienceAPI {
* </br>
* This function is designed for API usage.
*
* @return the power level cap of a given skill
* @return the overall power level cap
*/
public static int getPowerLevelCap() {
return Config.getInstance().getPowerLevelCap();
@@ -268,39 +556,39 @@ public final class ExperienceAPI {
* @param player The player to set the level of
* @param skillType The skill to set the level for
* @param skillLevel The value to set the level to
* @deprecated Use {@link #setLevel(Player, String, int)} instead
*/
@Deprecated
public static void setLevel(Player player, SkillType skillType, int skillLevel) {
UserManager.getPlayer(player).getProfile().modifySkill(skillType, skillLevel);
}
/**
* Sets the level of a player in a specific skill type.
* </br>
* This function is designed for API usage.
*
* @param player The player to set the level of
* @param skillType The skill to set the level for
* @param skillLevel The value to set the level to
* @throws InvalidSkillException if the given skill is not valid
*/
public static void setLevel(Player player, String skillType, int skillLevel) {
UserManager.getPlayer(player).getProfile().modifySkill(SkillType.getSkill(skillType), skillLevel);
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().modifySkill(skill, skillLevel);
}
/**
* Sets the XP of a player in a specific skill type.
* Sets the level of an offline player in a specific skill type.
* </br>
* This function is designed for API usage.
*
* @param player The player to set the XP of
* @param skillType The skill to set the XP for
* @param newValue The value to set the XP to
* @deprecated Use {@link #setXP(Player, String, int)} instead
* @param playerName The player to set the level of
* @param skillType The skill to set the level for
* @param skillLevel The value to set the level to
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
*/
@Deprecated
public static void setXP(Player player, SkillType skillType, int newValue) {
UserManager.getPlayer(player).getProfile().setSkillXpLevel(skillType, newValue);
public static void setLevelOffline(String playerName, String skillType, int skillLevel) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
getOfflineProfile(playerName).modifySkill(skill, skillLevel);
}
/**
@@ -311,24 +599,49 @@ public final class ExperienceAPI {
* @param player The player to set the XP of
* @param skillType The skill to set the XP for
* @param newValue The value to set the XP to
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static void setXP(Player player, String skillType, int newValue) {
UserManager.getPlayer(player).getProfile().setSkillXpLevel(SkillType.getSkill(skillType), newValue);
SkillType skill = SkillType.getSkill(skillType);
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);
}
/**
* Removes XP from a player in a specific skill type.
* Sets the XP of an offline player in a specific skill type.
* </br>
* This function is designed for API usage.
*
* @param player The player to change the XP of
* @param skillType The skill to change the XP for
* @param xp The amount of XP to remove
* @deprecated Use {@link #removeXP(Player, String, int)} instead
* @param playerName The player to set the XP of
* @param skillType The skill to set the XP for
* @param newValue The value to set the XP to
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
@Deprecated
public static void removeXP(Player player, SkillType skillType, int xp) {
UserManager.getPlayer(player).getProfile().removeXp(skillType, xp);
public static void setXPOffline(String playerName, String skillType, int newValue) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
getOfflineProfile(playerName).setSkillXpLevel(skill, newValue);
}
/**
@@ -339,20 +652,83 @@ public final class ExperienceAPI {
* @param player The player to change the XP of
* @param skillType The skill to change the XP for
* @param xp The amount of XP to remove
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static void removeXP(Player player, String skillType, int xp) {
UserManager.getPlayer(player).getProfile().removeXp(SkillType.getSkill(skillType), xp);
SkillType skill = SkillType.getSkill(skillType);
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);
}
/**
* Check the XP of a player. This should be called after giving XP to process level-ups.
* Removes XP from an offline player in a specific skill type.
* </br>
* This function is designed for API usage.
*
* @param player The player to check
* @param skillType The skill to check
* @deprecated Calling this function is no longer needed and should be avoided
* @param playerName The player to change the XP of
* @param skillType The skill to change the XP for
* @param xp The amount of XP to remove
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
@Deprecated
private static void checkXP(Player player, SkillType skillType) {
SkillUtils.xpCheckSkill(skillType, player, UserManager.getProfile(player));
public static void removeXPOffline(String playerName, String skillType, int xp) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) {
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) {
PlayerProfile profile = getOfflineProfile(playerName);
if (skill.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skill);
for (SkillType parentSkill : parentSkills) {
profile.setSkillXpLevel(parentSkill, profile.getSkillLevel(parentSkill) + (XP / parentSkills.size()));
}
profile.save();
return;
}
profile.setSkillXpLevel(skill, profile.getSkillXpLevel(skill) + XP);
profile.save();
}
private static PlayerProfile getOfflineProfile(String playerName) {
PlayerProfile profile = new PlayerProfile(playerName, false);
if (!profile.isLoaded()) {
throw new InvalidPlayerException();
}
return profile;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,17 +1,17 @@
package com.gmail.nossr50.commands;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.getspout.spoutapi.player.SpoutPlayer;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.party.PartySubcommandType;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.spout.SpoutUtils;
public class McmmoCommand implements CommandExecutor {
@Override
@@ -28,13 +28,13 @@ public class McmmoCommand implements CommandExecutor {
sender.sendMessage(mcSplit);
if (Config.getInstance().getDonateMessageEnabled()) {
if (mcMMO.spoutEnabled && sender instanceof SpoutPlayer) {
SpoutPlayer spoutPlayer = (SpoutPlayer) sender;
spoutPlayer.sendNotification(LocaleLoader.getString("Spout.Donate"), ChatColor.GREEN + "gjmcferrin@gmail.com", Material.DIAMOND);
if (mcMMO.isSpoutEnabled() && sender instanceof Player) {
SpoutUtils.sendDonationNotification((Player) sender);
}
else {
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
}
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
}
sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion()));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,30 +1,34 @@
package com.gmail.nossr50.commands.database;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.database.SQLConversionTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class MmoupdateCommand implements CommandExecutor {
import com.google.common.collect.ImmutableList;
public class MmoupdateCommand implements TabExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mmoupdate(sender)) {
sender.sendMessage(command.getPermissionMessage());
if (!Config.getInstance().getUseMySQL()) {
sender.sendMessage("SQL Mode is not enabled."); // TODO: Localize
return true;
}
switch (args.length) {
case 0:
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Start"));
UserManager.saveAll();
UserManager.clearAll();
convertToMySQL();
new SQLConversionTask().runTaskLaterAsynchronously(mcMMO.p, 1);
for (Player player : mcMMO.p.getServer().getOnlinePlayers()) {
UserManager.addUser(player);
@@ -38,14 +42,8 @@ public class MmoupdateCommand implements CommandExecutor {
}
}
/**
* Convert FlatFile data to MySQL data.
*/
private void convertToMySQL() {
if (!Config.getInstance().getUseMySQL()) {
return;
}
mcMMO.p.getServer().getScheduler().runTaskLaterAsynchronously(mcMMO.p, new SQLConversionTask(), 1);
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,9 +3,7 @@ package com.gmail.nossr50.commands.party;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
@@ -16,9 +14,9 @@ public class PartyChangeOwnerCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 2:
Party playerParty = UserManager.getPlayer((Player) sender).getParty();
Party playerParty = UserManager.getPlayer(sender.getName()).getParty();
if (!playerParty.getMembers().contains(mcMMO.p.getServer().getOfflinePlayer(args[1]))) {
if (!playerParty.getMembers().contains(args[1])) {
sender.sendMessage(LocaleLoader.getString("Party.NotInYourParty", args[1]));
return true;
}

View File

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

View File

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

View File

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

View File

@@ -16,10 +16,11 @@ public class PartyDisbandCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 1:
Party playerParty = UserManager.getPlayer((Player) sender).getParty();
Party playerParty = UserManager.getPlayer(sender.getName()).getParty();
String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, playerParty.getName(), null, EventReason.KICKED_FROM_PARTY)) {
if (!PartyManager.handlePartyChangeEvent(member, partyName, null, EventReason.KICKED_FROM_PARTY)) {
return true;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,70 +1,62 @@
package com.gmail.nossr50.commands.player;
import org.bukkit.Bukkit;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.database.FlatfileDatabaseManager;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.google.common.collect.ImmutableList;
public class MctopCommand implements TabExecutor {
private SkillType skill;
public class MctopCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean useMySQL = Config.getInstance().getUseMySQL();
switch (args.length) {
case 0:
display(1, "ALL", sender, useMySQL, command);
display(1, "ALL", sender, command);
return true;
case 1:
if (StringUtils.isInt(args[0])) {
display(Integer.parseInt(args[0]), "ALL", sender, useMySQL, command);
}
else if (SkillUtils.isSkill(args[0])) {
SkillType skill = SkillType.getSkill(args[0]);
if (skill.isChildSkill()) {
sender.sendMessage("Child skills are not yet supported by this command."); // TODO: Localize this
return true;
}
display(1, skill.toString(), sender, useMySQL, command);
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
display(Math.abs(Integer.parseInt(args[0])), "ALL", sender, command);
return true;
}
if (!extractSkill(sender, args[0])) {
return true;
}
display(1, skill.toString(), sender, command);
return true;
case 2:
if (!StringUtils.isInt(args[1])) {
return false;
if (CommandUtils.isInvalidInteger(sender, args[1])) {
return true;
}
if (SkillUtils.isSkill(args[0])) {
SkillType skill = SkillType.getSkill(args[0]);
if (skill.isChildSkill()) {
sender.sendMessage("Child skills are not yet supported by this command."); // TODO: Localize this
return true;
}
display(Integer.parseInt(args[1]), skill.toString(), sender, useMySQL, command);
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
if (!extractSkill(sender, args[0])) {
return true;
}
display(Math.abs(Integer.parseInt(args[1])), skill.toString(), sender, command);
return true;
default:
@@ -72,29 +64,37 @@ public class MctopCommand implements CommandExecutor {
}
}
private void display(int page, String skill, CommandSender sender, boolean sql, Command command) {
if (sql) {
if (skill.equalsIgnoreCase("all")) {
sqlDisplay(page, "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing", sender, command);
}
else {
sqlDisplay(page, skill, sender, command);
}
}
else {
flatfileDisplay(page, skill, sender, command);
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], SkillType.SKILL_NAMES, new ArrayList<String>(SkillType.SKILL_NAMES.size()));
default:
return ImmutableList.of();
}
}
private void flatfileDisplay(int page, String skill, CommandSender sender, Command command) {
if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, SkillType.getSkill(skill))) {
private void display(int page, String skill, CommandSender sender, Command command) {
if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, this.skill)) {
sender.sendMessage(command.getPermissionMessage());
return;
}
LeaderboardManager.updateLeaderboards(); // Make sure we have the latest information
if (sender instanceof Player && Config.getInstance().getMctopScoreboardEnabled()) {
ScoreboardManager.enableGlobalStatsScoreboard((Player) sender, skill, page);
}
else {
if (Config.getInstance().getUseMySQL()) {
sqlDisplay(page, skill, sender);
}
else {
flatfileDisplay(page, skill, sender);
}
}
}
String[] info = LeaderboardManager.retrieveInfo(skill, page);
private void flatfileDisplay(int page, String skill, CommandSender sender) {
FlatfileDatabaseManager.updateLeaderboards(); // Make sure we have the latest information
if (skill.equalsIgnoreCase("all")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
@@ -103,27 +103,34 @@ public class MctopCommand implements CommandExecutor {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(skill)));
}
int n = (page * 10) - 9; // Position
for (String x : info) {
if (x != null) {
String digit = String.valueOf(n);
int position = (page * 10) - 9;
if (n < 10) {
digit = "0" + digit;
}
for (PlayerStat stat : FlatfileDatabaseManager.retrieveInfo(skill, page, 10)) {
String digit = (position < 10) ? "0" : "" + String.valueOf(position);
String[] splitx = x.split(":");
// Format: 1. Playername - skill value
sender.sendMessage(digit + ". " + ChatColor.GREEN + splitx[1] + " - " + ChatColor.WHITE + splitx[0]);
n++;
}
// 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, Command command) {
Bukkit.getScheduler().runTaskAsynchronously(mcMMO.p, new MctopCommandAsyncTask(page, query, sender, command));
private void sqlDisplay(int page, String query, CommandSender sender) {
new MctopCommandAsyncTask(page, query, sender).runTaskAsynchronously(mcMMO.p);
}
private boolean extractSkill(CommandSender sender, String skillName) {
if (CommandUtils.isInvalidSkill(sender, skillName)) {
return false;
}
skill = SkillType.getSkill(skillName);
if (CommandUtils.isChildSkill(sender, skill)) {
return false;
}
return true;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -20,6 +20,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/* GENERAL */
public int getAbilityLength() { return config.getInt("Skills.General.Ability_IncreaseLevel", 50); }
public int getEnchantBuff() { return config.getInt("Skills.General.Ability_EnchantBuff", 5); }
/* ACROBATICS */
public double getDodgeChanceMax() { return config.getDouble("Skills.Acrobatics.Dodge_ChanceMax", 20.0D); }
@@ -51,6 +52,8 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getRetrieveChanceMax() { return config.getDouble("Skills.Archery.Retrieve_MaxBonus", 100.0D); }
public int getRetrieveMaxBonusLevel() { return config.getInt("Skills.Archery.Retrieve_MaxBonusLevel", 1000); }
public double getForceMultiplier() { return config.getDouble("Skills.Archery.Force_Multiplier", 2.0D); }
/* AXES */
public int getBonusDamageAxesBonusMax() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonus", 4); }
public int getBonusDamageAxesMaxBonusLevel() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonusLevel", 200); }
@@ -84,6 +87,8 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.Fisherman_Diet_RankChange", 200); }
public int getIceFishingUnlockLevel() { return config.getInt("Skills.Fishing.Ice_Fishing_UnlockLevel", 50); }
/* Shake */
public int getShakeUnlockLevel() { return config.getInt("Skills.Fishing.Shake_UnlockLevel", 150); }
public int getShakeChanceRank1() { return config.getInt("Skills.Fishing.Shake_Chance.Rank_1", 25); }
@@ -178,6 +183,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public int getRepairMasteryMaxLevel() { return config.getInt("Skills.Repair.RepairMastery_MaxBonusLevel", 1000); }
public double getSuperRepairChanceMax() { return config.getDouble("Skills.Repair.SuperRepair_ChanceMax", 100.0D); }
public int getSuperRepairMaxLevel() { return config.getInt("Skills.Repair.SuperRepair_MaxBonusLevel", 1000); }
public int getSalvageUnlockLevel() { return config.getInt("Skills.Repair.Salvage_UnlockLevel", 600); }
/* Arcane Forging */
public boolean getArcaneForgingDowngradeEnabled() { return config.getBoolean("Skills.Repair.Arcane_Forging.Downgrades.Enabled", true); }
@@ -271,9 +277,17 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getWoodcuttingDoubleDropChance() { return config.getDouble("Skills.Woodcutting.DoubleDrops_ChanceMax", 100.0D); }
public int getWoodcuttingDoubleDropMaxLevel() { return config.getInt("Skills.Woodcutting.DoubleDrops_MaxBonusLevel", 1000); }
/* SPOUT STUFF*/
public int getSpoutNotificationTier1() { return config.getInt("Spout.Notifications.Tier1", 200); }
public int getSpoutNotificationTier2() { return config.getInt("Spout.Notifications.Tier2", 400); }
public int getSpoutNotificationTier3() { return config.getInt("Spout.Notifications.Tier3", 600); }
public int getSpoutNotificationTier4() { return config.getInt("Spout.Notifications.Tier4", 800); }
/* KRAKEN STUFF */
public boolean getKrakenEnabled() { return config.getBoolean("Kraken.Enabled", true); }
public boolean getKrakenGlobalSoundsEnabled() { return config.getBoolean("Kraken.Global_Sounds", true); }
public boolean getKrakenEscapeAllowed() { return config.getBoolean("Kraken.Allow_Escaping", false); }
public int getKrakenTriesBeforeRelease() { return config.getInt("Kraken.Tries_Before_Release", 50); }
public int getKrakenHealth() { return config.getInt("Kraken.Health", 50); }
public String getKrakenName() { return config.getString("Kraken.Name", "The Kraken"); }
public String getServerUnleashMessage() { return config.getString("Kraken.Unleashed_Message.Server", "(PLAYER) has unleashed the kraken!"); }
public String getPlayerUnleashMessage() { return config.getString("Kraken.Unleashed_Message.Player", "THE KRAKEN HAS BEEN UNLEASHED!"); }
public String getPlayerDefeatMessage() { return config.getString("Kraken.Defeated_Message.Killed", "You have slain the kraken!"); }
public String getPlayerEscapeMessage() { return config.getString("Kraken.Defeated_Message.Escape", "You have escaped from the kraken!"); }
public int getKrakenAttackInterval() { return config.getInt("Kraken.Attack_Interval_Seconds", 1); }
public int getKrakenAttackDamage() { return config.getInt("Kraken.Attack_Damage", 1); }
}

View File

@@ -6,6 +6,7 @@ import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils;
@@ -45,9 +46,42 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getVerboseLoggingEnabled() { return config.getBoolean("General.Verbose_Logging", false); }
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 getAdminDisplayNames() { return config.getBoolean("Commands.a.Use_Display_Names", true); }
/* Mob Healthbar */
public MobHealthbarType getMobHealthbarDefault() {
try {
return MobHealthbarType.valueOf(config.getString("Mob_Healthbar.Display_Type", "HEARTS").toUpperCase().trim());
}
catch (IllegalArgumentException ex) {
return MobHealthbarType.HEARTS;
}
}
public int getMobHealthbarTime() { return config.getInt("Mob_Healthbar.Display_Time", 3); }
/* Scoreboards */
public boolean getMcrankScoreboardEnabled() { return config.getBoolean("Scoreboards.Mcrank.Use", true); }
public int getMcrankScoreboardTime() { return config.getInt("Scoreboards.Mcrank.Display_Time", 10); }
public boolean getMcstatsScoreboardsEnabled() { return config.getBoolean("Scoreboards.Mcstats.Use", true); }
public int getMcstatsScoreboardTime() { return config.getInt("Scoreboards.Mcstats.Display_Time", 10); }
public boolean getMctopScoreboardEnabled() { return config.getBoolean("Scoreboards.Mctop.Use", true); }
public int getMctopScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); }
public boolean getInspectScoreboardEnabled() { return config.getBoolean("Scoreboards.Inspect.Use", true); }
public int getInspectScoreboardTime() { return config.getInt("Scoreboards.Inspect.Display_Time", 10); }
public boolean getSkillScoreboardEnabled() { return config.getBoolean("Scoreboards.Skillname.Use", true); }
public int getSkillScoreboardTime() { return config.getInt("Scoreboards.Skillname.Display_Time", 10); }
public boolean getPowerLevelsEnabled() { return config.getBoolean("Scoreboards.Power_Level.Use", true); }
/* Database Purging */
public int getPurgeInterval() { return config.getInt("Database_Purging.Purge_Interval", -1); }
public int getOldUsersCutoff() { return config.getInt("Database_Purging.Old_User_Cutoff", 6); }
@@ -101,9 +135,14 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getEntityModsEnabled() { return config.getBoolean("Mods.Entity_Mods_Enabled", false); }
/* Items */
public int getChimaeraCost() { return config.getInt("Items.Chimaera_Wing.Feather_Cost", 10); }
public int getChimaeraUseCost() { return config.getInt("Items.Chimaera_Wing.Use_Cost", 1); }
public int getChimaeraRecipeCost() { return config.getInt("Items.Chimaera_Wing.Recipe_Cost", 5); }
public int getChimaeraItemId() { return config.getInt("Items.Chimaera_Wing.Item_ID", 288); }
public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); }
public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); }
public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); }
public int getChimaeraWarmup() { return config.getInt("Items.Chimaera_Wing.Warmup", 5); }
public int getChimaeraRecentlyHurtCooldown() { return config.getInt("Items.Chimaera_Wing.RecentlyHurt_Cooldown", 60); }
/* Particles */
public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); }
@@ -111,6 +150,9 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); }
public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); }
public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); }
public boolean getLevelUpEffectsEnabled() { return config.getBoolean("Particles.LevelUp_Enabled", true); }
public int getLevelUpEffectsTier() { return config.getInt("Particles.LevelUp_Tier", 100); }
public boolean getLargeFireworks() { return config.getBoolean("Particles.LargeFireworks", true); }
/* PARTY SETTINGS */
public int getAutoPartyKickInterval() { return config.getInt("Party.AutoKick_Interval", 12); }
@@ -123,7 +165,9 @@ public class Config extends AutoUpdateConfigLoader {
public double getPartyShareRange() { return config.getDouble("Party.Sharing.Range", 75.0); }
/* Party Teleport Settings */
public int getPTPCommandCooldown() { return config.getInt("Commands.ptp.Cooldown", 30); }
public int getPTPCommandCooldown() { return config.getInt("Commands.ptp.Cooldown", 120); }
public int getPTPCommandWarmup() { return config.getInt("Commands.ptp.Warmup", 5); }
public int getPTPCommandRecentlyHurtCooldown() { return config.getInt("Commands.ptp.RecentlyHurt_Cooldown", 60); }
public int getPTPCommandTimeout() { return config.getInt("Commands.ptp.Request_Timeout", 300); }
public boolean getPTPCommandConfirmRequired() { return config.getBoolean("Commands.ptp.Confirm_Required", true); }
public boolean getPTPCommandWorldPermissions() { return config.getBoolean("Commands.ptp.World_Based_Permissions", false); }
@@ -183,11 +227,10 @@ public class Config extends AutoUpdateConfigLoader {
/* Repair */
public boolean getRepairAnvilMessagesEnabled() { return config.getBoolean("Skills.Repair.Anvil_Messages", true); }
public int getRepairAnvilId() { return config.getInt("Skills.Repair.Anvil_ID", 42); }
public boolean getSalvageEnabled() { return config.getBoolean("Skills.Repair.Salvage_enabled", true); }
public int getSalvageAnvilId() { return config.getInt("Skills.Repair.Salvage_Anvil_ID", 41); }
public int getSalvageUnlockLevel() { return config.getInt("Skills.Repair.Salvage_UnlockLevel", 600); }
public boolean getSalvageTools() { return config.getBoolean("Skills.Repair.Salvage_tools", true); }
public boolean getSalvageArmor() { return config.getBoolean("Skills.Repair.Salvage_armor", true); }
public boolean getRepairConfirmRequired() { return config.getBoolean("Skills.Repair.Confirm_Required", true); }
/* Unarmed */
public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); }
@@ -199,8 +242,6 @@ public class Config extends AutoUpdateConfigLoader {
public int getTamingCOTWOcelotCost() { return config.getInt("Skills.Taming.Call_Of_The_Wild.Fish_Required", 10); }
/* Woodcutting */
public boolean getWoodcuttingRequiresTool() { return config.getBoolean("Skills.Woodcutting.Requires_Axe", true); }
public int getWoodcuttingXPOak() { return config.getInt("Experience.Woodcutting.Oak", 70); }
public int getWoodcuttingXPBirch() { return config.getInt("Experience.Woodcutting.Birch", 90); }
public int getWoodcuttingXPSpruce() { return config.getInt("Experience.Woodcutting.Spruce", 80); }
@@ -237,7 +278,6 @@ public class Config extends AutoUpdateConfigLoader {
*/
/* General Settings */
public boolean getExperienceGainsMobspawnersEnabled() { return config.getBoolean("Experience.Gains.Mobspawners.Enabled", false); }
public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience.PVP.Rewards", true); }
public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience.Gains.Multiplier.Global", 1.0); }
@@ -250,8 +290,9 @@ public class Config extends AutoUpdateConfigLoader {
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 getSpawnedMobXpMultiplier() { return config.getDouble("Experience.Gains.MobSpawners.Multiplier", 0.0); }
/* XP Formula Multiplier */
public int getFormulaMultiplierCurve() { return config.getInt("Experience.Formula.Curve_Modifier", 20); }
public double getForumulaMultiplier(SkillType skill) { return config.getDouble("Experience.Formula.Multiplier." + StringUtils.getCapitalized(skill.toString())); }
public double getForumulaMultiplier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,6 +9,7 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
@@ -16,7 +17,7 @@ import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils;
public final class LeaderboardManager {
public final class FlatfileDatabaseManager {
private static HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>();
private static List<PlayerStat> powerLevels = new ArrayList<PlayerStat>();
private static long lastUpdate = 0;
@@ -24,7 +25,7 @@ public final class LeaderboardManager {
private static final long UPDATE_WAIT_TIME = 600000L; // 10 minutes
private static final long ONE_MONTH = 2630000000L;
private LeaderboardManager() {}
private FlatfileDatabaseManager() {}
/**
* Update the leader boards.
@@ -35,6 +36,7 @@ public final class LeaderboardManager {
return;
}
String usersFilePath = mcMMO.getUsersFilePath();
lastUpdate = System.currentTimeMillis(); // Log when the last update was run
powerLevels.clear(); // Clear old values from the power levels
@@ -54,90 +56,42 @@ public final class LeaderboardManager {
// Read from the FlatFile database and fill our arrays with information
try {
FileReader file = new FileReader(mcMMO.getUsersFilePath());
BufferedReader in = new BufferedReader(file);
BufferedReader in = new BufferedReader(new FileReader(usersFilePath));
String line = "";
ArrayList<String> players = new ArrayList<String>();
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
String[] data = line.split(":");
String p = character[0];
String playerName = data[0];
int powerLevel = 0;
// Prevent the same player from being added multiple times (I'd like to note that this shouldn't happen...)
if (players.contains(p)) {
if (players.contains(playerName)) {
continue;
}
players.add(p);
players.add(playerName);
if (character.length > 1 && StringUtils.isInt(character[1])) {
mining.add(new PlayerStat(p, Integer.parseInt(character[1])));
powerLevel += Integer.parseInt(character[1]);
}
powerLevel += loadStat(mining, playerName, data, 1);
powerLevel += loadStat(woodcutting, playerName, data, 5);
powerLevel += loadStat(repair, playerName, data, 7);
powerLevel += loadStat(unarmed, playerName, data, 8);
powerLevel += loadStat(herbalism, playerName, data, 9);
powerLevel += loadStat(excavation, playerName, data, 10);
powerLevel += loadStat(archery, playerName, data, 11);
powerLevel += loadStat(swords, playerName, data, 12);
powerLevel += loadStat(axes, playerName, data, 13);
powerLevel += loadStat(acrobatics, playerName, data, 14);
powerLevel += loadStat(taming, playerName, data, 24);
powerLevel += loadStat(fishing, playerName, data, 34);
if (character.length > 5 && StringUtils.isInt(character[5])) {
woodcutting.add(new PlayerStat(p, Integer.parseInt(character[5])));
powerLevel += Integer.parseInt(character[5]);
}
if (character.length > 7 && StringUtils.isInt(character[7])) {
repair.add(new PlayerStat(p, Integer.parseInt(character[7])));
powerLevel += Integer.parseInt(character[7]);
}
if (character.length > 8 && StringUtils.isInt(character[8])) {
unarmed.add(new PlayerStat(p, Integer.parseInt(character[8])));
powerLevel += Integer.parseInt(character[8]);
}
if (character.length > 9 && StringUtils.isInt(character[9])) {
herbalism.add(new PlayerStat(p, Integer.parseInt(character[9])));
powerLevel += Integer.parseInt(character[9]);
}
if (character.length > 10 && StringUtils.isInt(character[10])) {
excavation.add(new PlayerStat(p, Integer.parseInt(character[10])));
powerLevel += Integer.parseInt(character[10]);
}
if (character.length > 11 && StringUtils.isInt(character[11])) {
archery.add(new PlayerStat(p, Integer.parseInt(character[11])));
powerLevel += Integer.parseInt(character[11]);
}
if (character.length > 12 && StringUtils.isInt(character[12])) {
swords.add(new PlayerStat(p, Integer.parseInt(character[12])));
powerLevel += Integer.parseInt(character[12]);
}
if (character.length > 13 && StringUtils.isInt(character[13])) {
axes.add(new PlayerStat(p, Integer.parseInt(character[13])));
powerLevel += Integer.parseInt(character[13]);
}
if (character.length > 14 && StringUtils.isInt(character[14])) {
acrobatics.add(new PlayerStat(p, Integer.parseInt(character[14])));
powerLevel += Integer.parseInt(character[14]);
}
if (character.length > 24 && StringUtils.isInt(character[24])) {
taming.add(new PlayerStat(p, Integer.parseInt(character[24])));
powerLevel += Integer.parseInt(character[24]);
}
if (character.length > 34 && StringUtils.isInt(character[34])) {
fishing.add(new PlayerStat(p, Integer.parseInt(character[34])));
powerLevel += Integer.parseInt(character[34]);
}
powerLevels.add(new PlayerStat(p, powerLevel));
powerLevels.add(new PlayerStat(playerName, powerLevel));
}
in.close();
}
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + mcMMO.getUsersFilePath() + " (Are you sure you formatted it correctly?)" + e.toString());
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
SkillComparator c = new SkillComparator();
@@ -177,83 +131,11 @@ public final class LeaderboardManager {
* @param pageNumber Which page in the leaderboards to retrieve
* @return the requested leaderboard information
*/
public static String[] retrieveInfo(String skillType, int pageNumber) {
String[] info = new String[10];
List<PlayerStat> statsList;
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;
if (skillType.equalsIgnoreCase("all")) {
statsList = powerLevels;
}
else {
statsList = playerStatHash.get(SkillType.getSkill(skillType));
}
int destination;
// How many lines to skip through
if (pageNumber == 1) {
destination = 0;
}
else {
destination = (pageNumber * 10) - 9;
}
int currentPos = 0;
for (PlayerStat ps : statsList) {
if (currentPos == 10) {
break;
}
if (destination > 1) {
destination--;
continue;
}
info[currentPos] = ps.name + ":" + ps.statVal;
currentPos++;
}
return info;
}
public static int[] getPlayerRank(String playerName) {
int currentPos = 1;
if (powerLevels != null) {
for (PlayerStat stat : powerLevels) {
if (stat.name.equalsIgnoreCase(playerName)) {
return new int[] {currentPos, stat.statVal};
}
currentPos++;
continue;
}
return new int[] {0, 0};
}
return new int[] {0, 0};
}
public static int[] getPlayerRank(String playerName, SkillType skillType) {
int currentPos = 1;
List<PlayerStat> statsList = playerStatHash.get(skillType);
if (statsList != null) {
for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) {
return new int[] {currentPos, stat.statVal};
}
currentPos++;
continue;
}
return new int[] {0, 0};
}
return new int[] {0, 0};
return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size()));
}
public static boolean removeFlatFileUser(String playerName) {
@@ -311,26 +193,21 @@ public final class LeaderboardManager {
return worked;
}
public static void purgePowerlessFlatfile() {
public static int purgePowerlessFlatfile() {
mcMMO.p.getLogger().info("Purging powerless users...");
int purgedUsers = 0;
for (PlayerStat stat : powerLevels) {
if (stat.statVal == 0 && removeFlatFileUser(stat.name) && !mcMMO.p.getServer().getOfflinePlayer(stat.name).isOnline()) {
if (stat.statVal == 0 && !mcMMO.p.getServer().getOfflinePlayer(stat.name).isOnline() && removeFlatFileUser(stat.name)) {
purgedUsers++;
}
}
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
return purgedUsers;
}
public static void purgeOldFlatfile() {
mcMMO.p.getLogger().info("Purging old users...");
int purgedUsers = removeOldFlatfileUsers();
mcMMO.p.getLogger().info("Purged " + purgedUsers + " users from the database.");
}
private static int removeOldFlatfileUsers() {
public static int removeOldFlatfileUsers() {
int removedPlayers = 0;
long currentTime = System.currentTimeMillis();
long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
@@ -394,6 +271,57 @@ public final class LeaderboardManager {
return removedPlayers;
}
private static Integer getPlayerRank(String playerName, List<PlayerStat> statsList) {
int currentPos = 1;
if (statsList == null) {
return null;
}
for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) {
return currentPos;
}
currentPos++;
}
return null;
}
public static Map<String, Integer> getPlayerRanks(String playerName) {
updateLeaderboards();
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;
}
private static class SkillComparator implements Comparator<PlayerStat> {
@Override
public int compare(PlayerStat o1, PlayerStat o2) {

View File

@@ -0,0 +1,638 @@
package com.gmail.nossr50.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.DatabaseUpdateType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.runnables.database.SQLReconnectTask;
import com.gmail.nossr50.util.Misc;
public final class SQLDatabaseManager {
private static String connectionString;
private static String tablePrefix = Config.getInstance().getMySQLTablePrefix();
private static Connection connection = null;
// Scale waiting time by this much per failed attempt
private static final double SCALING_FACTOR = 40;
// Minimum wait in nanoseconds (default 500ms)
private static final long MIN_WAIT = 500L * 1000000L;
// Maximum time to wait between reconnects (default 5 minutes)
private static final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
// How long to wait when checking if connection is valid (default 3 seconds)
private static final int VALID_TIMEOUT = 3;
// When next to try connecting to Database in nanoseconds
private static long nextReconnectTimestamp = 0L;
// How many connection attempts have failed
private static int reconnectAttempt = 0;
private static final long ONE_MONTH = 2630000000L;
private SQLDatabaseManager() {}
/**
* Attempt to connect to the mySQL database.
*/
public static void connect() {
Config configInstance = Config.getInstance();
connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName();
try {
mcMMO.p.getLogger().info("Attempting connection to MySQL...");
// Force driver to load if not yet loaded
Class.forName("com.mysql.jdbc.Driver");
Properties connectionProperties = new Properties();
connectionProperties.put("user", configInstance.getMySQLUserName());
connectionProperties.put("password", configInstance.getMySQLUserPassword());
connectionProperties.put("autoReconnect", "false");
connectionProperties.put("maxReconnects", "0");
connection = DriverManager.getConnection(connectionString, connectionProperties);
mcMMO.p.getLogger().info("Connection to MySQL was a success!");
}
catch (SQLException ex) {
connection = null;
if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
mcMMO.p.getLogger().info("Connection to MySQL failed!");
}
}
catch (ClassNotFoundException ex) {
connection = null;
if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
mcMMO.p.getLogger().info("MySQL database driver not found!");
}
}
}
/**
* Attempt to create the database structure.
*/
public static void createStructure() {
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
+ "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`user` varchar(40) NOT NULL,"
+ "`lastlogin` int(32) unsigned NOT NULL,"
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY `user` (`user`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
+ "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
checkDatabaseStructure(DatabaseUpdateType.FISHING);
checkDatabaseStructure(DatabaseUpdateType.BLAST_MINING);
checkDatabaseStructure(DatabaseUpdateType.INDEX);
checkDatabaseStructure(DatabaseUpdateType.MOB_HEALTHBARS);
checkDatabaseStructure(DatabaseUpdateType.PARTY_NAMES);
}
/**
* Attempt to write the SQL query.
*
* @param sql Query to write.
* @return true if the query was successfully written, false otherwise.
*/
public static boolean write(String sql) {
if (!checkConnected()) {
return false;
}
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
statement.executeUpdate();
return true;
}
catch (SQLException ex) {
if (!sql.equalsIgnoreCase("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party` ;")) {
printErrors(ex);
}
return false;
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
}
public static boolean removeUserSQL(String playerName) {
return SQLDatabaseManager.update("DELETE FROM u, e, h, s, c " +
"USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE u.user = '" + playerName + "'") != 0;
}
/**
* Returns the number of rows affected by either a DELETE or UPDATE query
*
* @param sql SQL query to execute
* @return the number of rows affected
*/
public static int update(String sql) {
if (!checkConnected()) {
return 0;
}
int rows = 0;
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
rows = statement.executeUpdate();
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
return rows;
}
/**
* Get the Integer. Only return first row / first field.
*
* @param sql SQL query to execute
* @return the value in the first row / first field
*/
public static int getInt(String sql) {
if (!checkConnected()) {
return 0;
}
int result = 0;
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
result = resultSet.getInt(1);
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
return result;
}
/**
* Check connection status and re-establish if dead or stale.
*
* If the very first immediate attempt fails, further attempts
* will be made in progressively larger intervals up to MAX_WAIT
* intervals.
*
* This allows for MySQL to time out idle connections as needed by
* server operator, without affecting McMMO, while still providing
* protection against a database outage taking down Bukkit's tick
* processing loop due to attemping a database connection each
* time McMMO needs the database.
*
* @return the boolean value for whether or not we are connected
*/
public static boolean checkConnected() {
boolean isClosed = true;
boolean isValid = false;
boolean exists = (connection != null);
// If we're waiting for server to recover then leave early
if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
return false;
}
if (exists) {
try {
isClosed = connection.isClosed();
}
catch (SQLException e) {
isClosed = true;
e.printStackTrace();
printErrors(e);
}
if (!isClosed) {
try {
isValid = connection.isValid(VALID_TIMEOUT);
}
catch (SQLException e) {
// Don't print stack trace because it's valid to lose idle connections to the server and have to restart them.
isValid = false;
}
}
}
// Leave if all ok
if (exists && !isClosed && isValid) {
// Housekeeping
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
// Cleanup after ourselves for GC and MySQL's sake
if (exists && !isClosed) {
try {
connection.close();
}
catch (SQLException ex) {
// This is a housekeeping exercise, ignore errors
}
}
// Try to connect again
connect();
// Leave if connection is good
try {
if (connection != null && !connection.isClosed()) {
// Schedule a database save if we really had an outage
if (reconnectAttempt > 1) {
new SQLReconnectTask().runTaskLater(mcMMO.p, 5);
}
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
}
catch (SQLException e) {
// Failed to check isClosed, so presume connection is bad and attempt later
e.printStackTrace();
printErrors(e);
}
reconnectAttempt++;
nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt * SCALING_FACTOR * MIN_WAIT)));
return false;
}
/**
* Read SQL query.
*
* @param sql SQL query to read
* @return the rows in this SQL query
*/
public static HashMap<Integer, ArrayList<String>> read(String sql) {
ResultSet resultSet;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
if (checkConnected()) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
}
rows.put(resultSet.getRow(), column);
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
printErrors(e);
}
}
}
}
return rows;
}
public static Map<String, Integer> readSQLRank(String playerName) {
ResultSet resultSet;
Map<String, Integer> skills = new HashMap<String, Integer>();
if (checkConnected()) {
try {
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
String skillName = skillType.name().toLowerCase();
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = '" + playerName + "') ORDER BY user";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put(skillType.name(), rank + resultSet.getRow());
break;
}
}
statement.close();
}
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
"AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > " +
"(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
"AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing = " +
"(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?) ORDER BY user";
statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put("ALL", rank + resultSet.getRow());
break;
}
}
statement.close();
}
catch (SQLException ex) {
printErrors(ex);
}
}
return skills;
}
public static int purgePowerlessSQL() {
HashMap<Integer, ArrayList<String>> usernames = read("SELECT u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u WHERE s.user_id = u.id AND (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0");
write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0");
return processPurge(usernames.values());
}
public static int purgeOldSQL() {
long currentTime = System.currentTimeMillis();
long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
HashMap<Integer, ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")");
write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")");
return processPurge(usernames.values());
}
private static int processPurge(Collection<ArrayList<String>> usernames) {
int purgedUsers = 0;
for (ArrayList<String> user : usernames) {
Misc.profileCleanup(user.get(0));
purgedUsers++;
}
return purgedUsers;
}
/**
* Check database structure for missing values.
*
* @param update Type of data to check updates for
*/
private static void checkDatabaseStructure(DatabaseUpdateType update) {
String sql = null;
ResultSet resultSet = null;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
switch (update) {
case BLAST_MINING:
sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
break;
case FISHING:
sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
break;
case INDEX:
if (read("SHOW INDEX FROM " + tablePrefix + "skills").size() != 13 && checkConnected()) {
mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
write("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_taming` (`taming`) USING BTREE, "
+ "ADD INDEX `idx_mining` (`mining`) USING BTREE, "
+ "ADD INDEX `idx_woodcutting` (`woodcutting`) USING BTREE, "
+ "ADD INDEX `idx_repair` (`repair`) USING BTREE, "
+ "ADD INDEX `idx_unarmed` (`unarmed`) USING BTREE, "
+ "ADD INDEX `idx_herbalism` (`herbalism`) USING BTREE, "
+ "ADD INDEX `idx_excavation` (`excavation`) USING BTREE, "
+ "ADD INDEX `idx_archery` (`archery`) USING BTREE, "
+ "ADD INDEX `idx_swords` (`swords`) USING BTREE, "
+ "ADD INDEX `idx_axes` (`axes`) USING BTREE, "
+ "ADD INDEX `idx_acrobatics` (`acrobatics`) USING BTREE, "
+ "ADD INDEX `idx_fishing` (`fishing`) USING BTREE;");
}
break;
case MOB_HEALTHBARS:
sql = "SELECT * FROM `" + tablePrefix + "huds` ORDER BY `" + tablePrefix + "huds`.`mobhealthbar` ASC LIMIT 0 , 30";
break;
case PARTY_NAMES:
write("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party` ;");
break;
default:
break;
}
PreparedStatement statement = null;
try {
if (!checkConnected()) {
return;
}
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
}
rows.put(resultSet.getRow(), column);
}
}
catch (SQLException ex) {
switch (update) {
case BLAST_MINING:
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
break;
case FISHING:
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
break;
case MOB_HEALTHBARS:
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
write("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "' ;");
break;
default:
break;
}
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore the error, we're leaving
}
}
}
}
private static void printErrors(SQLException ex) {
mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
}
}

View File

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

View File

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

View File

@@ -0,0 +1,33 @@
package com.gmail.nossr50.datatypes.party;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.util.ItemUtils;
public enum ItemShareType {
LOOT,
MINING,
HERBALISM,
WOODCUTTING,
MISC;
public static ItemShareType getShareType(ItemStack itemStack) {
if (ItemUtils.isMobDrop(itemStack)) {
return LOOT;
}
else if (ItemUtils.isMiningDrop(itemStack)) {
return MINING;
}
else if (ItemUtils.isHerbalismDrop(itemStack)) {
return HERBALISM;
}
else if (ItemUtils.isWoodcuttingDrop(itemStack)) {
return WOODCUTTING;
}
else if (ItemUtils.isMiscDrop(itemStack)) {
return MISC;
}
return null;
}
}

View File

@@ -1,36 +1,41 @@
package com.gmail.nossr50.datatypes.party;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler.ShareMode;
public class Party {
private List<OfflinePlayer> members = new ArrayList<OfflinePlayer>();
private LinkedHashSet<String> members = new LinkedHashSet<String>();
private String leader;
private String name;
private String password;
private boolean locked;
private ShareHandler.ShareMode xpShareMode = ShareHandler.ShareMode.NONE;
private ShareHandler.ShareMode itemShareMode = ShareHandler.ShareMode.NONE;
private ShareMode xpShareMode = ShareMode.NONE;
private ShareMode itemShareMode = ShareMode.NONE;
private boolean shareLootDrops = true;
private boolean shareMiningDrops = true;
private boolean shareHerbalismDrops = true;
private boolean shareWoodcuttingDrops = true;
private boolean shareMiscDrops = true;
public List<OfflinePlayer> getMembers() {
public LinkedHashSet<String> getMembers() {
return members;
}
public List<Player> getOnlineMembers() {
List<Player> onlineMembers = new ArrayList<Player>();
for (OfflinePlayer member : members) {
for (String memberName : members) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName);
if (member.isOnline()) {
onlineMembers.add(member.getPlayer());
}
@@ -55,40 +60,27 @@ public class Party {
return locked;
}
public boolean sharingLootDrops() {
return shareLootDrops;
}
public boolean sharingMiningDrops() {
return shareMiningDrops;
}
public boolean sharingHerbalismDrops() {
return shareHerbalismDrops;
}
public boolean sharingWoodcuttingDrops() {
return shareWoodcuttingDrops;
}
public List<String> getItemShareCategories() {
List<String> shareCategories = new ArrayList<String>();
// TODO Locale the category names!
if (sharingLootDrops()) {
shareCategories.add("Loot");
if (shareLootDrops) {
shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Loot"));
}
if (sharingMiningDrops()) {
shareCategories.add("Mining");
if (shareMiningDrops) {
shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Mining"));
}
if (sharingHerbalismDrops()) {
shareCategories.add("Herbalism");
if (shareHerbalismDrops) {
shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Herbalism"));
}
if (sharingWoodcuttingDrops()) {
shareCategories.add("Woodcutting");
if (shareWoodcuttingDrops) {
shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Woodcutting"));
}
if (shareMiscDrops) {
shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Misc"));
}
return shareCategories;
@@ -110,35 +102,68 @@ public class Party {
this.locked = locked;
}
public void setXpShareMode(ShareHandler.ShareMode xpShareMode) {
public void setXpShareMode(ShareMode xpShareMode) {
this.xpShareMode = xpShareMode;
}
public ShareHandler.ShareMode getXpShareMode() {
public ShareMode getXpShareMode() {
return xpShareMode;
}
public void setItemShareMode(ShareHandler.ShareMode itemShareMode) {
public void setItemShareMode(ShareMode itemShareMode) {
this.itemShareMode = itemShareMode;
}
public ShareHandler.ShareMode getItemShareMode() {
public ShareMode getItemShareMode() {
return itemShareMode;
}
public void setSharingLootDrops(boolean enabled) {
shareLootDrops = enabled;
public boolean sharingDrops(ItemShareType shareType) {
switch (shareType) {
case HERBALISM:
return shareHerbalismDrops;
case LOOT:
return shareLootDrops;
case MINING:
return shareMiningDrops;
case MISC:
return shareMiscDrops;
case WOODCUTTING:
return shareWoodcuttingDrops;
default:
return false;
}
}
public void setSharingMiningDrops(boolean enabled) {
shareMiningDrops = enabled;
}
public void setSharingDrops(ItemShareType shareType, boolean enabled) {
switch (shareType) {
case HERBALISM:
shareHerbalismDrops = enabled;
break;
public void setSharingHerbalismDrops(boolean enabled) {
shareHerbalismDrops = enabled;
}
case LOOT:
shareLootDrops = enabled;
break;
public void setSharingWoodcuttingDrops(boolean enabled) {
shareWoodcuttingDrops = enabled;
case MINING:
shareMiningDrops = enabled;
break;
case MISC:
shareMiscDrops = enabled;
break;
case WOODCUTTING:
shareWoodcuttingDrops = enabled;
break;
default:
return;
}
}
}

View File

@@ -5,6 +5,7 @@ import java.util.Map;
import java.util.Set;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -19,6 +20,7 @@ import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.events.experience.McMMOPlayerXpGainEvent;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.skills.AbilityDisableTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
import com.gmail.nossr50.skills.archery.ArcheryManager;
@@ -28,10 +30,13 @@ import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.fishing.FishingManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.repair.RepairManager;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.swords.SwordsManager;
import com.gmail.nossr50.skills.taming.TamingManager;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.ModUtils;
import com.gmail.nossr50.util.Permissions;
@@ -65,8 +70,10 @@ public class McMMOPlayer {
private boolean displaySkillNotifications = true;
private boolean abilityUse = true;
private boolean placedAnvil;
private boolean placedRepairAnvil;
private int lastRepairClick;
private boolean placedSalvageAnvil;
private int lastSalvageClick;
private boolean godMode;
private Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>();
@@ -77,6 +84,10 @@ public class McMMOPlayer {
private int recentlyHurt;
private int respawnATS;
private int teleportLastUse;
private Location teleportCommence;
private boolean isUsingUnarmed;
public McMMOPlayer(Player player) {
String playerName = player.getName();
@@ -92,12 +103,7 @@ public class McMMOPlayer {
*/
try {
for (SkillType skillType : SkillType.values()) {
Class<? extends SkillManager> skillManagerClass = skillType.getManagerClass();
// TODO: The null check is needed only because currently some SkillType doesn't have a valid skillManagerClass
if (skillManagerClass != null) {
skillManagers.put(skillType, skillManagerClass.getConstructor(McMMOPlayer.class).newInstance(this));
}
skillManagers.put(skillType, skillType.getManagerClass().getConstructor(McMMOPlayer.class).newInstance(this));
}
}
catch (Exception e) {
@@ -144,6 +150,10 @@ public class McMMOPlayer {
return (MiningManager) skillManagers.get(SkillType.MINING);
}
public RepairManager getRepairManager() {
return (RepairManager) skillManagers.get(SkillType.REPAIR);
}
public SmeltingManager getSmeltingManager() {
return (SmeltingManager) skillManagers.get(SkillType.SMELTING);
}
@@ -160,6 +170,10 @@ public class McMMOPlayer {
return (UnarmedManager) skillManagers.get(SkillType.UNARMED);
}
public WoodcuttingManager getWoodcuttingManager() {
return (WoodcuttingManager) skillManagers.get(SkillType.WOODCUTTING);
}
/*
* Abilities
*/
@@ -169,7 +183,8 @@ public class McMMOPlayer {
*/
public void resetAbilityMode() {
for (AbilityType ability : AbilityType.values()) {
setAbilityMode(ability, false);
// Correctly disable and handle any special deactivate code
new AbilityDisableTask(this, ability).run();
}
}
@@ -292,6 +307,34 @@ public class McMMOPlayer {
recentlyHurt = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
/*
* Teleportation cooldown & warmup
*/
public int getLastTeleport() {
return teleportLastUse;
}
public void setLastTeleport(int value) {
teleportLastUse = value;
}
public void actualizeLastTeleport() {
teleportLastUse = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
public Location getTeleportCommenceLocation() {
return teleportCommence;
}
public void setTeleportCommenceLocation(Location location) {
teleportCommence = location;
}
public void actualizeTeleportCommenceLocation(Player player) {
setTeleportCommenceLocation(player.getLocation());
}
/*
* Exploit Prevention
*/
@@ -308,24 +351,62 @@ public class McMMOPlayer {
* Repair Anvil Placement
*/
public void togglePlacedAnvil() {
placedAnvil = !placedAnvil;
public boolean getPlacedAnvil(int anvilId) {
if (anvilId == Repair.repairAnvilId) {
return placedRepairAnvil;
}
if (anvilId == Repair.salvageAnvilId) {
return placedSalvageAnvil;
}
return true;
}
public Boolean getPlacedAnvil() {
return placedAnvil;
public void togglePlacedAnvil(int anvilId) {
if (anvilId == Repair.repairAnvilId) {
placedRepairAnvil = !placedRepairAnvil;
}
if (anvilId == Repair.salvageAnvilId) {
placedSalvageAnvil = !placedSalvageAnvil;
}
}
/*
* Salvage Anvil Placement
* Repair Anvil Usage
*/
public void togglePlacedSalvageAnvil() {
placedSalvageAnvil = !placedSalvageAnvil;
public int getLastAnvilUse(int anvilId) {
if (anvilId == Repair.repairAnvilId) {
return lastRepairClick;
}
if (anvilId == Repair.salvageAnvilId) {
return lastSalvageClick;
}
return 0;
}
public Boolean getPlacedSalvageAnvil() {
return placedSalvageAnvil;
public void setLastAnvilUse(int anvilId, int value) {
if (anvilId == Repair.repairAnvilId) {
lastRepairClick = value;
}
if (anvilId == Repair.salvageAnvilId) {
lastSalvageClick = value;
}
}
public void actualizeLastAnvilUse(int anvilId) {
if (anvilId == Repair.repairAnvilId) {
lastRepairClick = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
if (anvilId == Repair.salvageAnvilId) {
lastSalvageClick = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
}
/*
@@ -379,7 +460,7 @@ public class McMMOPlayer {
* @param skillType Skill being used
* @param xp Experience amount to process
*/
public void beginXpGain(SkillType skillType, int xp) {
public void beginXpGain(SkillType skillType, float xp) {
if (xp == 0) {
return;
}
@@ -410,7 +491,7 @@ public class McMMOPlayer {
* @param skillType Skill being used
* @param xp Experience amount to process
*/
public void beginUnsharedXpGain(SkillType skillType, int xp) {
public void beginUnsharedXpGain(SkillType skillType, float xp) {
xp = modifyXpGain(skillType, xp);
applyXpGain(skillType, xp);
@@ -422,7 +503,21 @@ public class McMMOPlayer {
* @param skillType Skill being used
* @param xp Experience amount to add
*/
public void applyXpGain(SkillType skillType, int xp) {
public void applyXpGain(SkillType skillType, float xp) {
if (skillType.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skillType);
for (SkillType parentSkill : parentSkills) {
applyXpGain(parentSkill, xp / parentSkills.size());
}
return;
}
if (!Permissions.skillEnabled(player, skillType)) {
return;
}
McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skillType, xp);
mcMMO.p.getServer().getPluginManager().callEvent(event);
@@ -430,7 +525,7 @@ public class McMMOPlayer {
return;
}
profile.setSkillXpLevel(skillType, profile.getSkillXpLevel(skillType) + event.getXpGained());
profile.setSkillXpLevel(skillType, profile.getSkillXpLevelRaw(skillType) + event.getRawXpGained());
McMMOHud spoutHud = profile.getSpoutHud();
@@ -438,6 +533,7 @@ public class McMMOPlayer {
spoutHud.setLastGained(skillType);
}
isUsingUnarmed = skillType == SkillType.UNARMED;
SkillUtils.xpCheckSkill(skillType, player, profile);
}
@@ -589,6 +685,10 @@ public class McMMOPlayer {
partyChatMode = !partyChatMode;
}
public boolean isUsingUnarmed() {
return isUsingUnarmed;
}
/**
* Modifies an experience gain using skill modifiers, global rate and perks
*
@@ -596,16 +696,12 @@ public class McMMOPlayer {
* @param xp Experience amount to process
* @return Modified experience
*/
private int modifyXpGain(SkillType skillType, int xp) {
if (player.getGameMode() == GameMode.CREATIVE) {
private float modifyXpGain(SkillType skillType, float xp) {
if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() < profile.getSkillLevel(skillType) + 1) || (Config.getInstance().getPowerLevelCap() < getPowerLevel() + 1)) {
return 0;
}
if ((skillType.getMaxLevel() < profile.getSkillLevel(skillType) + 1) || (Config.getInstance().getPowerLevelCap() < getPowerLevel() + 1)) {
return 0;
}
xp = (int) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
if (Config.getInstance().getToolModsEnabled()) {
ItemStack item = player.getItemInHand();

View File

@@ -1,5 +1,11 @@
package com.gmail.nossr50.datatypes.skills;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.Color;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader;
@@ -11,39 +17,59 @@ import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.fishing.FishingManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.skills.repair.RepairManager;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.swords.SwordsManager;
import com.gmail.nossr50.skills.taming.TamingManager;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.google.common.collect.ImmutableList;
public enum SkillType {
ACROBATICS(AcrobaticsManager.class),
ARCHERY(ArcheryManager.class),
AXES(AxesManager.class, AbilityType.SKULL_SPLITTER, ToolType.AXE),
EXCAVATION(ExcavationManager.class, AbilityType.GIGA_DRILL_BREAKER, ToolType.SHOVEL),
FISHING(FishingManager.class),
HERBALISM(HerbalismManager.class, AbilityType.GREEN_TERRA, ToolType.HOE),
MINING(MiningManager.class, AbilityType.SUPER_BREAKER, ToolType.PICKAXE),
REPAIR(null), // TODO: Create a proper RepairManager class
SMELTING(SmeltingManager.class),
SWORDS(SwordsManager.class, AbilityType.SERRATED_STRIKES, ToolType.SWORD),
TAMING(TamingManager.class),
UNARMED(UnarmedManager.class, AbilityType.BERSERK, ToolType.FISTS),
WOODCUTTING(null, AbilityType.TREE_FELLER, ToolType.AXE); // TODO: Create a proper WoodcuttingManager class
ACROBATICS(AcrobaticsManager.class, Color.WHITE),
ARCHERY(ArcheryManager.class, Color.MAROON),
AXES(AxesManager.class, Color.AQUA, AbilityType.SKULL_SPLITTER, ToolType.AXE),
EXCAVATION(ExcavationManager.class, Color.fromRGB(139, 69, 19), AbilityType.GIGA_DRILL_BREAKER, ToolType.SHOVEL),
FISHING(FishingManager.class, Color.NAVY),
HERBALISM(HerbalismManager.class, Color.GREEN, AbilityType.GREEN_TERRA, ToolType.HOE),
MINING(MiningManager.class, Color.GRAY, AbilityType.SUPER_BREAKER, ToolType.PICKAXE),
REPAIR(RepairManager.class, Color.SILVER),
SMELTING(SmeltingManager.class, Color.YELLOW),
SWORDS(SwordsManager.class, Color.fromRGB(178, 34, 34), AbilityType.SERRATED_STRIKES, ToolType.SWORD),
TAMING(TamingManager.class, Color.PURPLE),
UNARMED(UnarmedManager.class, Color.BLACK, AbilityType.BERSERK, ToolType.FISTS),
WOODCUTTING(WoodcuttingManager.class, Color.OLIVE, AbilityType.TREE_FELLER, ToolType.AXE);
private Class<? extends SkillManager> managerClass;
private Color runescapeColor;
private AbilityType ability;
private ToolType tool;
private SkillType(Class<? extends SkillManager> managerClass) {
public static final List<String> SKILL_NAMES;
static {
ArrayList<String> names = new ArrayList<String>();
for (SkillType skill : values()) {
names.add(SkillUtils.getSkillName(skill));
}
Collections.sort(names);
SKILL_NAMES = ImmutableList.copyOf(names);
}
private SkillType(Class<? extends SkillManager> managerClass, Color runescapeColor) {
this.managerClass = managerClass;
this.runescapeColor = runescapeColor;
ability = null;
tool = null;
}
private SkillType(Class<? extends SkillManager> managerClass, AbilityType ability, ToolType tool) {
private SkillType(Class<? extends SkillManager> managerClass, Color runescapeColor, AbilityType ability, ToolType tool) {
this.managerClass = managerClass;
this.runescapeColor = runescapeColor;
this.ability = ability;
this.tool = tool;
}
@@ -114,4 +140,18 @@ public enum SkillType {
return false;
}
}
public Color getRunescapeModeColor() {
return runescapeColor;
}
public static SkillType byAbility(AbilityType ability) {
for (SkillType type : values()) {
if (type.getAbility() == ability) {
return type;
}
}
return null;
}
}

View File

@@ -0,0 +1,21 @@
package com.gmail.nossr50.datatypes.treasure;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
public class ShakeTreasure extends Treasure {
private EntityType mob;
public ShakeTreasure(ItemStack drop, int xp, double dropChance, int dropLevel, EntityType mob) {
super(drop, xp, dropChance, dropLevel);
this.mob = mob;
}
public EntityType getMob() {
return mob;
}
public void setMob(EntityType mob) {
this.mob = mob;
}
}

View File

@@ -17,6 +17,14 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
public McMMOPlayerLevelUpEvent(Player player, SkillType skill, int levelsGained) {
super(player, skill);
this.setLevelsGained(levelsGained);
}
/**
* @param levelsGained
* @return Set the number of levels gained in this event
*/
public void setLevelsGained(int levelsGained) {
this.levelsGained = levelsGained;
}

View File

@@ -8,9 +8,9 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
* Called when a player gains XP in a skill
*/
public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent {
private int xpGained;
private float xpGained;
public McMMOPlayerXpGainEvent(Player player, SkillType skill, int xpGained) {
public McMMOPlayerXpGainEvent(Player player, SkillType skill, float xpGained) {
super(player, skill);
this.xpGained = xpGained;
}
@@ -18,13 +18,29 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent {
/**
* @return The amount of experience gained in this event
*/
public int getXpGained() {
public float getRawXpGained() {
return xpGained;
}
/**
* @param xpGained int amount of experience gained in this event
*/
@Deprecated
public int getXpGained() {
return (int) xpGained;
}
/**
* @param xpGained int amount of experience gained in this event
*/
public void setRawXpGained(float xpGained) {
this.xpGained = xpGained;
}
/**
* @param xpGained int amount of experience gained in this event
*/
@Deprecated
public void setXpGained(int xpGained) {
this.xpGained = xpGained;
}

View File

@@ -0,0 +1,12 @@
package com.gmail.nossr50.events.fake;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fish;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerFishEvent;
public class FakePlayerFishEvent extends PlayerFishEvent {
public FakePlayerFishEvent(Player player, Entity entity, Fish hookEntity, State state) {
super(player, entity, hookEntity, state);
}
}

View File

@@ -0,0 +1,35 @@
package com.gmail.nossr50.events.skills.abilities;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
public class McMMOPlayerAbilityActivateEvent extends McMMOPlayerSkillEvent implements Cancellable {
private AbilityType abilityType;
private boolean cancelled;
public McMMOPlayerAbilityActivateEvent(Player player, SkillType skill) {
super(player, skill);
abilityType = skill.getAbility();
cancelled = false;
}
/**
* @return The ability type involved in this event
*/
public AbilityType getAbilityType() {
return abilityType;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean value) {
this.cancelled = value;
}
}

View File

@@ -0,0 +1,22 @@
package com.gmail.nossr50.events.skills.abilities;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
public class McMMOPlayerAbilityDeactivateEvent extends McMMOPlayerSkillEvent {
private AbilityType ability;
public McMMOPlayerAbilityDeactivateEvent(Player player, SkillType skill) {
super(player, skill);
this.ability = skill.getAbility();
}
public AbilityType getAbility() {
return ability;
}
}

View File

@@ -2,6 +2,7 @@ package com.gmail.nossr50.listeners;
import java.util.List;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
@@ -20,8 +21,6 @@ import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType;
@@ -35,10 +34,9 @@ import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager;
import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.repair.Salvage;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.unarmed.Unarmed;
import com.gmail.nossr50.skills.woodcutting.Woodcutting;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
@@ -60,23 +58,22 @@ public class BlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
List<Block> blocks = event.getBlocks();
BlockFace direction = event.getDirection();
Block futureEmptyBlock = event.getBlock().getRelative(direction); // Block that would be air after piston is finished
for (Block b : blocks) {
if (mcMMO.placeStore.isTrue(b)) {
if (BlockUtils.shouldBeWatched(b.getState()) && mcMMO.getPlaceStore().isTrue(b)) {
b.getRelative(direction).setMetadata(mcMMO.blockMetadataKey, mcMMO.metadataValue);
if (b.equals(futureEmptyBlock)) {
mcMMO.placeStore.setFalse(b);
mcMMO.getPlaceStore().setFalse(b);
}
}
}
for (Block b : blocks) {
if (b.getRelative(direction).hasMetadata(mcMMO.blockMetadataKey)) {
mcMMO.placeStore.setTrue(b.getRelative(direction));
mcMMO.getPlaceStore().setTrue(b.getRelative(direction));
b.getRelative(direction).removeMetadata(mcMMO.blockMetadataKey, plugin);
}
}
@@ -91,7 +88,7 @@ public class BlockListener implements Listener {
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isSticky()) {
// Needed only because under some circumstances Minecraft doesn't move the block
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new StickyPistonTrackerTask(event), 2);
new StickyPistonTrackerTask(event.getDirection(), event.getBlock()).runTaskLater(plugin, 2);
}
}
@@ -109,21 +106,15 @@ public class BlockListener implements Listener {
}
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 */
if (BlockUtils.shouldBeWatched(blockState)) {
mcMMO.placeStore.setTrue(blockState);
mcMMO.getPlaceStore().setTrue(blockState);
}
if (Repair.anvilMessagesEnabled) {
int blockID = blockState.getTypeId();
if (blockID == Repair.anvilID) {
Repair.placedAnvilCheck(player, blockID);
}
else if (blockID == Salvage.anvilID) {
Salvage.placedAnvilCheck(player, blockID);
}
if (Repair.anvilMessagesEnabled && (blockId == Repair.repairAnvilId || blockId == Repair.salvageAnvilId)) {
UserManager.getPlayer(player).getRepairManager().placedAnvilCheck(blockId);
}
}
@@ -138,20 +129,24 @@ public class BlockListener implements Listener {
return;
}
BlockState blockState = event.getBlock().getState();
if (!BlockUtils.shouldBeWatched(blockState)) {
return;
}
Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) {
return;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
BlockState blockState = event.getBlock().getState();
ItemStack heldItem = player.getItemInHand();
/* HERBALISM */
if (BlockUtils.affectedByGreenTerra(blockState)) {
HerbalismManager herbalismManager = UserManager.getPlayer(player).getHerbalismManager();
HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager();
/* Green Terra */
if (herbalismManager.canActivateAbility()) {
@@ -163,47 +158,31 @@ public class BlockListener implements Listener {
* Instead, we check it inside the drops handler.
*/
if (Permissions.skillEnabled(player, SkillType.HERBALISM)) {
// Double drops
herbalismManager.herbalismBlockCheck(blockState);
// Triple drops
if (herbalismManager.canGreenTerraPlant()) {
herbalismManager.herbalismBlockCheck(blockState);
}
}
}
/* MINING */
else if (BlockUtils.affectedBySuperBreaker(blockState) && ItemUtils.isPickaxe(heldItem) && Permissions.skillEnabled(player, SkillType.MINING) && !mcMMO.placeStore.isTrue(blockState)) {
MiningManager miningManager = UserManager.getPlayer(player).getMiningManager();
else if (BlockUtils.affectedBySuperBreaker(blockState) && ItemUtils.isPickaxe(heldItem) && Permissions.skillEnabled(player, SkillType.MINING) && !mcMMO.getPlaceStore().isTrue(blockState)) {
MiningManager miningManager = mcMMOPlayer.getMiningManager();
miningManager.miningBlockCheck(blockState);
if (mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER)) {
miningManager.miningBlockCheck(blockState);
}
}
/* WOOD CUTTING */
else if (BlockUtils.isLog(blockState) && Permissions.skillEnabled(player, SkillType.WOODCUTTING) && !mcMMO.placeStore.isTrue(blockState)) {
if (mcMMOPlayer.getAbilityMode(AbilityType.TREE_FELLER) && Permissions.treeFeller(player) && ItemUtils.isAxe(heldItem)) {
Woodcutting.beginTreeFeller(blockState, player);
else if (BlockUtils.isLog(blockState) && Permissions.skillEnabled(player, SkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isTrue(blockState)) {
WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager();
if (woodcuttingManager.canUseTreeFeller(heldItem)) {
woodcuttingManager.processTreeFeller(blockState);
}
else {
if (Config.getInstance().getWoodcuttingRequiresTool()) {
if (ItemUtils.isAxe(heldItem)) {
Woodcutting.beginWoodcutting(player, blockState);
}
}
else {
Woodcutting.beginWoodcutting(player, blockState);
}
woodcuttingManager.woodcuttingBlockCheck(blockState);
}
}
/* EXCAVATION */
else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && Permissions.skillEnabled(player, SkillType.EXCAVATION) && !mcMMO.placeStore.isTrue(blockState)) {
ExcavationManager excavationManager = UserManager.getPlayer(player).getExcavationManager();
else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && Permissions.skillEnabled(player, SkillType.EXCAVATION) && !mcMMO.getPlaceStore().isTrue(blockState)) {
ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager();
excavationManager.excavationBlockCheck(blockState);
if (mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER)) {
@@ -212,9 +191,7 @@ public class BlockListener implements Listener {
}
/* Remove metadata from placed watched blocks */
if (BlockUtils.shouldBeWatched(blockState) && mcMMO.placeStore.isTrue(blockState)) {
mcMMO.placeStore.setFalse(blockState);
}
mcMMO.getPlaceStore().setFalse(blockState);
}
/**
@@ -230,7 +207,7 @@ public class BlockListener implements Listener {
Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) {
return;
}
@@ -321,7 +298,7 @@ public class BlockListener implements Listener {
* We don't need to check permissions here because they've already been checked for the ability to even activate.
*/
if (mcMMOPlayer.getAbilityMode(AbilityType.TREE_FELLER) && BlockUtils.isLog(blockState)) {
player.playSound(blockState.getLocation(), Sound.FIZZ, Misc.FIZZ_VOLUME, Misc.FIZZ_PITCH);
player.playSound(blockState.getLocation(), Sound.FIZZ, Misc.FIZZ_VOLUME, Misc.getFizzPitch());
}
}
@@ -364,28 +341,22 @@ public class BlockListener implements Listener {
plugin.getServer().getPluginManager().callEvent(new FakePlayerAnimationEvent(player));
event.setInstaBreak(true);
player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.POP_PITCH);
player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
}
}
// Another perm check for the cracked blocks activation
else if (BlockUtils.affectedByBlockCracker(blockState) && Permissions.blockCracker(player)) {
if (Unarmed.blockCracker(player, blockState)) {
else if (BlockUtils.affectedByBlockCracker(blockState)) {
UnarmedManager unarmedManager = mcMMOPlayer.getUnarmedManager();
if (unarmedManager.canUseBlockCracker() && SkillUtils.blockBreakSimulate(block, player, false) && unarmedManager.blockCrackerCheck(blockState)) {
blockState.update();
}
}
}
else if ((mcMMOPlayer.getProfile().getSkillLevel(SkillType.WOODCUTTING) >= AdvancedConfig.getInstance().getLeafBlowUnlockLevel()) && BlockUtils.isLeaves(blockState)) {
if (SkillUtils.triggerCheck(player, block, AbilityType.LEAF_BLOWER)) {
if (Config.getInstance().getWoodcuttingRequiresTool()) {
if (ItemUtils.isAxe(heldItem)) {
event.setInstaBreak(true);
Woodcutting.beginLeafBlower(player, blockState);
}
}
else if (!(heldItem.getType() == Material.SHEARS)) {
event.setInstaBreak(true);
Woodcutting.beginLeafBlower(player, blockState);
}
else if (BlockUtils.isLeaves(blockState)) {
if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && SkillUtils.blockBreakSimulate(block, player, true)) {
event.setInstaBreak(true);
player.playSound(blockState.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
}
}
}

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