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

Compare commits

...

443 Commits

Author SHA1 Message Date
GJ
4a5307f47b New 1.4.06 release before work starts on adding new features from 1.6 2013-07-11 12:09:24 -04:00
GJ
69aead58a7 Using getPlayerExact is faster. 2013-07-08 19:15:44 -04:00
T00thpick1
f0dcfb0346 Temporary for building for old peoples 2013-07-02 12:48:35 -04:00
T00thpick1
c85d52e594 Make Riking's stuff work 2013-07-02 12:42:09 -04:00
Travis Ralston
4342abca3d Update EMetrics version to use 0.0.5-SNAPSHOT (MCStats R7) 2013-07-01 17:11:58 +02:00
T00thpick1
11e4ff34d6 Flatfile repair 2013-07-01 02:36:21 -04:00
Kane York
f118ac14ca Specify returning of generated keys before using them
This is a herp derp fix
2013-07-01 00:35:07 -04:00
T00thpick1
f5eb7a10de Only set custom class when valid class 2013-07-01 00:34:54 -04:00
T00thpick1
36b09421e8 These should all be 0 too, for consistancy 2013-06-29 23:42:28 -04:00
T00thpick1
d6b39a11e7 0 is nonexistant, not -1 2013-06-29 23:41:08 -04:00
riking
23729f45ee Pull changes from dev-dbman (commit f63c5e3) 2013-06-28 15:02:58 -07:00
T00thpick1
27d7b73e57 Pretty sure this should be Fake 2013-06-28 16:22:55 -04:00
TfT_02
af60f08a8b Localize the ScoreboardManager
Closes #1232
2013-06-28 19:17:39 +02:00
TfT_02
c19d3fd068 Fixed bug with Ice Fishing which allowed players to break protected blocks
Fixes #2074
2013-06-28 14:06:54 +02:00
TfT_02
0f8312dd5e Minor cleanup 2013-06-28 14:06:13 +02:00
TfT_02
1edb11cedf Disable mob healthbars for boss mobs!
Fixes #1210
2013-06-28 13:36:48 +02:00
TfT_02
6fea7c8d74 Update the changelog: Fixed update check 2013-06-27 22:23:09 +02:00
riking
a4a1ba4331 Make UpdateChecker run asynchronously and not block startup
Closes #1049
2013-06-27 09:48:39 -07:00
TfT_02
de46277bea Realized that it wasn't only happening in the Nether 2013-06-24 17:10:39 +02:00
TfT_02
6d7d811814 Fixed bug with Ice Fishing in the Nether
Fixes  #1218
2013-06-24 16:25:49 +02:00
GJ
98b98256b7 Make our oldUserRemover actually work... 2013-06-13 12:23:58 -04:00
GJ
abd389f4de Try to speed up our PartyKickTask a bit. 2013-06-13 12:18:18 -04:00
GJ
602956a555 Fix duplicate prefix sending with party chat & logging. 2013-06-13 11:10:46 -04:00
GJ
8d0601babc Fix bug where all ranks less than 10 show as 0 with /mctop. 2013-06-13 10:56:46 -04:00
GJ
050be563bf Less magic numbers. 2013-06-12 19:26:09 -04:00
GJ
965dbda101 Clean up some stuff with our DATS. 2013-06-12 19:20:05 -04:00
GJ
f2b2cd9cc0 Oops. 2013-06-12 15:59:51 -04:00
GJ
3a78e1b487 More code duplication removal. 2013-06-12 15:56:42 -04:00
GJ
db637f0bc9 Remove more code duplication. 2013-06-12 15:41:26 -04:00
GJ
b15f1dde28 We don't need that potato. 2013-06-12 15:15:56 -04:00
GJ
28a78d820a Tidy up our InventoryListener. 2013-06-12 15:10:43 -04:00
GJ
a1792fe125 We were calling deflect twice. Also made individual functions for each
type of combat.
2013-06-07 15:47:00 -04:00
T00thpick1
3f7b17961f Reset mob healthbars on death to avoid conflicting with loot plugins 2013-06-07 15:46:59 -04:00
GJ
0ea07d4bc7 Fixed bug where spawned arrows could throw
ArrayIndexOutOfBoundsException. Fixes #1171
2013-06-07 15:46:59 -04:00
GJ
190b7ee1f5 ChatManagers... 2013-06-07 15:46:58 -04:00
GJ
4ff4271da2 These should be protected. 2013-06-07 15:46:57 -04:00
T00thpick1
8705974e08 Use a single manager to handle our databases. 2013-06-07 15:46:57 -04:00
TfT_02
de0487d16f This should make it work properly 2013-06-07 15:46:56 -04:00
TfT_02
fc0c386ecb Fixing this as pointed out by Riking 2013-06-07 15:46:55 -04:00
TfT_02
86db4251a2 Check visibility before range 2013-06-07 15:46:55 -04:00
TfT_02
effe5ec305 We were deprecating these kind of permission nodes 2013-06-07 15:46:54 -04:00
TfT_02
8fb92292bd Move adding users to UserManager from onLogin to onJoin 2013-06-07 15:46:54 -04:00
TfT_02
375fa4f75c Added permission node to prevent inspecting hidden players 2013-06-07 15:46:53 -04:00
TfT_02
da25b02e0a Only set the item in hand null if it's actually a fishing rod 2013-06-07 15:46:53 -04:00
GJ
d43ae17bd2 Tweak a few things on the UpdateChecker. 2013-06-07 15:46:52 -04:00
Kane York
f81a763d6c Use finally to close the update checker stream 2013-06-07 15:46:52 -04:00
Kane York
385f8ca0b3 Reduce code duplication in ExperienceAPI 2013-06-07 15:46:46 -04:00
GJ
0ba4bc25c7 Use player objects instead of names - should be more efficient and less
buggy.
2013-05-28 13:33:20 -04:00
GJ
b0eb4b93a8 Cleaner way to avoid salvaging chainmail. 2013-05-28 12:59:10 -04:00
GJ
54f135aebd We're checking this twice and shouldn't be. 2013-05-28 12:53:12 -04:00
GJ
10e369f9c5 Increased auto-fishing detection. 2013-05-28 12:42:39 -04:00
TfT_02
1ae9b0f4d2 Animals can also have the "Spawned Entity" tag 2013-05-26 17:55:24 +02:00
T00thpick1
198ee6a7ed I think this is case sensitive 2013-05-26 11:51:42 -04:00
TfT_02
2414ddf485 Fix broken Tree Feller
Fixes #1139
2013-05-25 14:45:24 +02:00
GJ
2cd52db8c9 The ; is important. 2013-05-22 22:30:40 -04:00
GJ
5e00636761 And a little more... 2013-05-22 22:30:09 -04:00
GJ
a82cc9609b Cleaning up a bit. 2013-05-22 22:13:40 -04:00
T00thpick1
45c6c20ccd Null parties! Hurray! 2013-05-22 21:20:35 -04:00
GJ
7a61f55e49 Remove some code duplication in our ShareHandler. 2013-05-22 17:22:06 -04:00
GJ
aa0b77a64c Updates to our parties. 2013-05-22 13:02:26 -04:00
GJ
030c8e59d7 The other way leaks memory like a sieve. 2013-05-22 00:01:19 -04:00
GJ
f21fbe2d40 Make repair & salvage respect the sneaking settings. Fixes #1108 2013-05-21 22:34:06 -04:00
GJ
9a5f4b638f Little more cleaning. 2013-05-21 14:15:28 -04:00
GJ
9aa49a09da Little more cleanup. 2013-05-21 14:03:00 -04:00
GJ
bf8945ac59 Try to clean CombatUtils a bit... 2013-05-21 13:36:44 -04:00
GJ
d9926bab4e Try to clean up our poor EntityListener... 2013-05-21 13:27:52 -04:00
GJ
38ba2c21e5 Back to normal development. 2013-05-21 12:22:11 -04:00
GJ
a48fb30edf New beta! 2013-05-21 12:20:50 -04:00
GJ
92ec04bd46 Better boolean handling. 2013-05-21 11:44:16 -04:00
GJ
0b6372a6ea Don't run these calculations twice. Also, pretty sure one of these was
bugged.
2013-05-21 11:41:39 -04:00
GJ
4f8b66f94d Clean up our block listener some. 2013-05-21 11:11:55 -04:00
GJ
0c52b3016c We've got these functions, might as well use them. 2013-05-21 10:02:09 -04:00
GJ
a2f80569e3 Fire McMMOPlayerLevelUp events for our experience commands, when
applicable. Fixes #921
2013-05-21 09:31:25 -04:00
GJ
87df536a1f Only check for kraken if you're actually fishing. 2013-05-21 09:14:54 -04:00
T00thpick1
12e70490d8 Cooldowns messages need to be affected by perks too 2013-05-20 22:35:34 -04:00
TfT_02
23b1518dc0 More formatting :) 2013-05-20 17:28:02 -04:00
T00thpick1
6dbf2e0d95 FishingTreasureEvent, FishingShakeEvent and MagicHunterEvent 2013-05-20 17:27:59 -04:00
GJ
60304e9643 Because Minecraft does stupid things with "/" in the chat.
Fixes #994
2013-05-20 08:56:02 -04:00
GJ
614557e2fa It'd be nice if Ice Fishing actually worked. 2013-05-20 08:07:39 -04:00
TfT_02
e312e95aed Refactor to a more descriptive name,
also fixes a small typo.
2013-05-20 10:55:17 +02:00
t00thpick1
2ee919b51f Update gravatar 2013-05-19 18:18:55 -03:00
T00thpick1
22f6ae858b Update inventories after chimera wing 2013-05-19 16:13:19 -04:00
T00thpick1
3c3b4af2c4 No salvaging chainmail - FIXES 1118 2013-05-19 12:55:18 -04:00
T00thpick1
feb0d1fe5d Things that should never happen, but are. 2013-05-18 22:15:32 -04:00
TfT_02
2d66b8ed12 Cleanup - fixing various formatting issues 2013-05-18 22:41:42 +02:00
TfT_02
483f348403 Fixed bug with Blast Mining where the Ability refreshed message was being send too early 2013-05-18 22:27:17 +02:00
TfT_02
a8a5100f58 Update the changelog
Also made a minor edit to a comment about the powerlevel display
2013-05-18 14:27:14 +02:00
TfT_02
1f9dc70bb1 I forgot to remove the setting from advanced.yml 2013-05-18 14:12:45 +02:00
TfT_02
7f1ef61657 Get rid of the SuccessModifier
There's no need for this modifier, because the user can define the
exact chance for Rolls and Gracefull Rolls in the config file. This
means that the ratio between the two is already configurable.
2013-05-18 14:12:07 +02:00
TfT_02
2e74c079b0 Set the enchant buff level to 1 if it's lower than 0
Prevents issue #1006 from happening again.

If a user wants to disable SuperBreaker, they should do this using
permissions and not by setting the Enchant Buff level to zero.
2013-05-18 11:37:40 +02:00
TfT_02
ce4295289a Changed powerlevel display setting to disabled by default.
Because scoreboards are being cached by Minecraft in scoreboard.dat it
is no user friendly to enabled this by default. Users will have to
manually delete this file in order to actually disable this.
Described in #1105
2013-05-18 11:27:17 +02:00
T00thpick1
7fde04851d Typo 2013-05-17 18:44:23 -04:00
riking
71d030e5ad Change rounding strategy to ceiling for mob healthbars 2013-05-17 00:19:59 -04:00
T00thpick1
b08649d0a4 Not much help if not static 2013-05-16 23:58:49 -04:00
T00thpick1
0a11a9a2c8 More methods for SkillType 2013-05-16 22:00:40 -04:00
T00thpick1
068f47b523 Option for any distance 2013-05-16 19:53:58 -04:00
T00thpick1
79aab57abc Configure the inspect distance 2013-05-16 19:31:12 -04:00
T00thpick1
2cf58f1b5b Why break when we can return? 2013-05-16 18:04:14 -04:00
T00thpick1
9678875b4b We do enjoy killing off orphans 2013-05-16 17:26:16 -04:00
GJ
d1a7ce827a Back to active development. Again. 2013-05-16 16:24:19 -04:00
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
217 changed files with 13140 additions and 7153 deletions

View File

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

View File

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

12
pom.xml
View File

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

View File

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

View File

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

View File

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

View File

@@ -1,11 +1,13 @@
package com.gmail.nossr50.api; package com.gmail.nossr50.api;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@@ -19,9 +21,13 @@ public final class PartyAPI {
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to check the party name of * @param player The player to check the party name of
* @return the name of the player's party * @return the name of the player's party, or null if not in a party
*/ */
public static String getPartyName(Player player) { public static String getPartyName(Player player) {
if (!inParty(player)) {
return null;
}
return UserManager.getPlayer(player).getParty().getName(); return UserManager.getPlayer(player).getParty().getName();
} }
@@ -71,14 +77,13 @@ public final class PartyAPI {
*/ */
public static void addToParty(Player player, String partyName) { public static void addToParty(Player player, String partyName) {
Party party = PartyManager.getParty(partyName); Party party = PartyManager.getParty(partyName);
String playerName = player.getName();
if (party == null) { if (party == null) {
party = new Party(); party = new Party(playerName, partyName);
party.setName(partyName);
party.setLeader(player.getName());
} }
PartyManager.addToParty(player, UserManager.getPlayer(player), party); PartyManager.addToParty(playerName, UserManager.getPlayer(player), party);
} }
/** /**
@@ -123,28 +128,27 @@ public final class PartyAPI {
* *
* @param player The player to check * @param player The player to check
* @return all the players in the player's party * @return all the players in the player's party
* @deprecated
*/ */
@Deprecated @Deprecated
public static List<String> getAllMembers(Player player) { public static List<OfflinePlayer> getOnlineAndOfflineMembers(Player player) {
List<String> memberNames = new ArrayList<String>(); List<OfflinePlayer> members = new ArrayList<OfflinePlayer>();
for (OfflinePlayer member : PartyManager.getAllMembers(player)) { for (String memberName : PartyManager.getAllMembers(player)) {
memberNames.add(member.getName()); OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName);
members.add(member);
} }
return members;
return memberNames;
} }
/** /**
* Get a list of all players in this player's party. * Get a list of all player names in this player's party.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
* @param player The player to check * @param player The player to check
* @return all the 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); 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,22 @@
package com.gmail.nossr50.chat;
import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.events.chat.McMMOAdminChatEvent;
public class AdminChatManager extends ChatManager {
protected AdminChatManager(Plugin plugin) {
super(plugin, Config.getInstance().getAdminDisplayNames(), "Commands.AdminChat.Prefix");
}
@Override
public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
handleChat(new McMMOAdminChatEvent(plugin, senderName, displayName, message, isAsync));
}
@Override
protected void sendMessage() {
plugin.getServer().broadcast(message, "mcmmo.chat.adminchat");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,28 +1,26 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class McnotifyCommand implements CommandExecutor { import com.google.common.collect.ImmutableList;
public class McnotifyCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 0: case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
if (mcMMOPlayer.useChatNotifications()) { sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On")));
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
}
mcMMOPlayer.toggleChatNotifications(); mcMMOPlayer.toggleChatNotifications();
return true; return true;
@@ -30,4 +28,9 @@ public class McnotifyCommand implements CommandExecutor {
return false; 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; package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class McrefreshCommand implements CommandExecutor { public class McrefreshCommand extends ToggleCommand {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { protected boolean hasOtherPermission(CommandSender sender) {
McMMOPlayer mcMMOPlayer; return Permissions.mcrefreshOthers(sender);
switch (args.length) {
case 0:
if (!Permissions.mcrefresh(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
} }
if (!(sender instanceof Player)) { @Override
return false; protected boolean hasSelfPermission(CommandSender sender) {
} return Permissions.mcrefresh(sender);
mcMMOPlayer = UserManager.getPlayer(sender.getName());
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;
} }
@Override
protected void applyCommandAction() {
mcMMOPlayer.setRecentlyHurt(0); mcMMOPlayer.setRecentlyHurt(0);
mcMMOPlayer.getProfile().resetCooldowns(); mcMMOPlayer.getProfile().resetCooldowns();
mcMMOPlayer.resetToolPrepMode(); mcMMOPlayer.resetToolPrepMode();
mcMMOPlayer.resetAbilityMode(); mcMMOPlayer.resetAbilityMode();
player.sendMessage(LocaleLoader.getString("Ability.Generic.Refresh")); player.sendMessage(LocaleLoader.getString("Ability.Generic.Refresh"));
sender.sendMessage(LocaleLoader.getString("Commands.mcrefresh.Success", args[0])); }
return true;
default: @Override
return false; 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,69 @@
package com.gmail.nossr50.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class MobhealthCommand implements TabExecutor {
private static final List<String> MOB_HEALTHBAR_TYPES;
static {
ArrayList<String> types = new ArrayList<String>();
for (MobHealthbarType type : MobHealthbarType.values()) {
types.add(type.toString());
}
Collections.sort(types);
MOB_HEALTHBAR_TYPES = ImmutableList.copyOf(types);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
switch (args.length) {
case 1:
PlayerProfile playerProfile = UserManager.getPlayer((Player) sender).getProfile();
try {
MobHealthbarType type = MobHealthbarType.valueOf(args[0].toUpperCase().trim());
playerProfile.setMobHealthbarType(type);
sender.sendMessage("Display type changed to: " + type); //TODO: Localize
return true;
}
catch (IllegalArgumentException ex) {
sender.sendMessage("Invalid type!"); //TODO: Localize
return true;
}
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
return StringUtil.copyPartialMatches(args[0], MOB_HEALTHBAR_TYPES, new ArrayList<String>(MOB_HEALTHBAR_TYPES.size()));
default:
return ImmutableList.of();
}
}
}

View File

@@ -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;
}
player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player);
applyCommandAction();
return true;
case 1:
if (!hasOtherPermission(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
mcMMOPlayer = UserManager.getPlayer(args[0]);
if (!CommandUtils.checkPlayerExistence(sender, args[0], mcMMOPlayer)) {
return true;
}
player = mcMMOPlayer.getPlayer();
if (CommandUtils.isOffline(sender, player)) {
return true;
}
applyCommandAction();
sendSuccessMessage(sender);
return true;
default:
return false;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
switch (args.length) {
case 1:
Set<String> playerNames = UserManager.getPlayers().keySet();
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<String>(playerNames.size()));
default:
return ImmutableList.of();
}
}
protected abstract boolean hasOtherPermission(CommandSender sender);
protected abstract boolean hasSelfPermission(CommandSender sender);
protected abstract void applyCommandAction();
protected abstract void sendSuccessMessage(CommandSender sender);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,154 +1,41 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AddlevelsCommand implements CommandExecutor { public class AddlevelsCommand extends ExperienceCommand {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { protected boolean permissionsCheckSelf(CommandSender sender) {
PlayerProfile profile; return Permissions.addlevels(sender);
int levels;
boolean allSkills = false;
SkillType skill = null;
switch (args.length) {
case 2:
if (!Permissions.addlevels(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
} }
if (!(sender instanceof Player)) { @Override
return false; protected boolean permissionsCheckOthers(CommandSender sender) {
return Permissions.addlevelsOthers(sender);
} }
if (args[0].equalsIgnoreCase("all")) { @Override
allSkills = true; protected void handleCommand(SkillType skill) {
} profile.addLevels(skill, value);
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[1])) { if (player != null) {
return false; mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value));
}
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) { @Override
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0])); protected void handlePlayerMessageAll() {
} player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", value));
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", SkillUtils.getSkillName(skill), args[0]));
} }
return true; @Override
protected void handlePlayerMessageSkill() {
default: player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, SkillUtils.getSkillName(skill)));
return false;
}
} }
} }

View File

@@ -1,152 +1,40 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AddxpCommand implements CommandExecutor { public class AddxpCommand extends ExperienceCommand {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { protected boolean permissionsCheckSelf(CommandSender sender) {
int xp; return Permissions.addxp(sender);
McMMOPlayer mcMMOPlayer;
PlayerProfile profile;
boolean allSkills = false;
SkillType skill = null;
switch (args.length) {
case 2:
if (!Permissions.addxp(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
} }
if (!(sender instanceof Player)) { @Override
return false; protected boolean permissionsCheckOthers(CommandSender sender) {
return Permissions.addxpOthers(sender);
} }
if (args[0].equalsIgnoreCase("all")) { @Override
allSkills = true; protected void handleCommand(SkillType skill) {
} if (player != null) {
else if (!SkillUtils.isSkill(args[0])) { mcMMOPlayer.applyXpGain(skill, value);
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 { else {
skill = SkillType.getSkill(args[0]); profile.addExperience(skill, value);
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) { @Override
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0])); protected void handlePlayerMessageAll() {
} player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", value));
else {
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", SkillUtils.getSkillName(skill), args[0]));
} }
return true; @Override
protected void handlePlayerMessageSkill() {
default: player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, SkillUtils.getSkillName(skill)));
return false;
}
} }
} }

View File

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

View File

@@ -1,150 +1,41 @@
package com.gmail.nossr50.commands.experience; package com.gmail.nossr50.commands.experience;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class MmoeditCommand implements CommandExecutor { public class MmoeditCommand extends ExperienceCommand {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { protected boolean permissionsCheckSelf(CommandSender sender) {
PlayerProfile profile; return Permissions.mmoedit(sender);
int newValue;
boolean allSkills = false;
SkillType skill = null;
switch (args.length) {
case 2:
if (!Permissions.mmoedit(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
} }
if (!(sender instanceof Player)) { @Override
return false; protected boolean permissionsCheckOthers(CommandSender sender) {
return Permissions.mmoeditOthers(sender);
} }
if (args[0].equalsIgnoreCase("all")) { @Override
allSkills = true; protected void handleCommand(SkillType skill) {
} profile.modifySkill(skill, value);
else if (!SkillUtils.isSkill(args[0])) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
return true;
}
if (!StringUtils.isInt(args[1])) { if (player != null) {
return false; mcMMO.p.getServer().getPluginManager().callEvent(new McMMOPlayerLevelUpEvent(player, skill, value - profile.getSkillLevel(skill)));
}
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) { @Override
sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", args[0])); protected void handlePlayerMessageAll() {
} player.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", value));
else {
sender.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.2", SkillUtils.getSkillName(skill), args[0]));
} }
return true; @Override
protected void handlePlayerMessageSkill() {
default: player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", SkillUtils.getSkillName(skill), value));
return false;
}
} }
} }

View File

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

View File

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

View File

@@ -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; package com.gmail.nossr50.commands.hardcore;
import java.text.DecimalFormat;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
public class VampirismCommand implements CommandExecutor { public class VampirismCommand extends HardcoreModeCommand {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { protected boolean checkTogglePermissions() {
if (!Config.getInstance().getHardcoreEnabled()) { return Permissions.vampirismToggle(sender);
sender.sendMessage(LocaleLoader.getString("Hardcore.Disabled"));
return true;
} }
switch (args.length) { @Override
case 0: protected boolean checkModifyPermissions() {
if (!Permissions.vampirismToggle(sender)) { return Permissions.vampirismModify(sender);
sender.sendMessage(command.getPermissionMessage());
return true;
} }
if (Config.getInstance().getHardcoreVampirismEnabled()) { @Override
disableVampirism(); protected boolean checkEnabled() {
} return Config.getInstance().getHardcoreVampirismEnabled();
else {
enableVampirism();
} }
return true; @Override
protected void enable() {
case 1: Config.getInstance().setHardcoreVampirismEnabled(true);
if (args[0].equalsIgnoreCase("on") || args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("enabled")) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Enabled"));
if (!Permissions.vampirismToggle(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
} }
enableVampirism(); @Override
return true; protected void disable() {
}
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;
}
}
private void disableVampirism() {
Config.getInstance().setHardcoreVampirismEnabled(false); Config.getInstance().setHardcoreVampirismEnabled(false);
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Disabled")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Disabled"));
} }
private void enableVampirism() { @Override
Config.getInstance().setHardcoreVampirismEnabled(true); protected void modify() {
mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Vampirism.Enabled")); 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; import com.gmail.nossr50.util.player.UserManager;
public class PartyAcceptCommand implements CommandExecutor { public class PartyAcceptCommand implements CommandExecutor {
private McMMOPlayer mcMMOPlayer;
private Player player;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 1: case 1:
player = (Player) sender; Player player = (Player) sender;
mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPartyInvite()) { if (!mcMMOPlayer.hasPartyInvite()) {
sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites")); sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites"));

View File

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

View File

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

View File

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

View File

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

View File

@@ -17,9 +17,10 @@ public class PartyDisbandCommand implements CommandExecutor {
switch (args.length) { switch (args.length) {
case 1: case 1:
Party playerParty = UserManager.getPlayer((Player) sender).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, playerParty.getName(), null, EventReason.KICKED_FROM_PARTY)) { if (!PartyManager.handlePartyChangeEvent(member, partyName, null, EventReason.KICKED_FROM_PARTY)) {
return true; 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;
import com.gmail.nossr50.party.ShareHandler.ShareMode; import com.gmail.nossr50.party.ShareHandler.ShareMode;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyExpShareCommand implements CommandExecutor { public class PartyExpShareCommand implements CommandExecutor {
@@ -27,14 +28,14 @@ public class PartyExpShareCommand implements CommandExecutor {
case 2: case 2:
playerParty = UserManager.getPlayer((Player) sender).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
if (args[1].equalsIgnoreCase("none") || args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) { if (args[1].equalsIgnoreCase("none") || CommandUtils.shouldDisableToggle(args[1])) {
handleChangingShareMode(ShareMode.NONE); 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); handleChangingShareMode(ShareMode.EQUAL);
} }
else { else {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "expshare", "[NONE | EQUAL]")); sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "expshare", "<NONE | EQUAL>"));
} }
return true; return true;
@@ -48,8 +49,10 @@ public class PartyExpShareCommand implements CommandExecutor {
private void handleChangingShareMode(ShareHandler.ShareMode mode) { private void handleChangingShareMode(ShareHandler.ShareMode mode) {
playerParty.setXpShareMode(mode); playerParty.setXpShareMode(mode);
String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Exp"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString())));
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {
member.sendMessage(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.6", "/party kick"));
sender.sendMessage(LocaleLoader.getString("Party.Help.7", "/party leader")); sender.sendMessage(LocaleLoader.getString("Party.Help.7", "/party leader"));
sender.sendMessage(LocaleLoader.getString("Party.Help.8", "/party disband")); sender.sendMessage(LocaleLoader.getString("Party.Help.8", "/party disband"));
sender.sendMessage(LocaleLoader.getString("Party.Help.9", "/party itemshare"));
sender.sendMessage(LocaleLoader.getString("Party.Help.10", "/party expshare"));
return true; return true;
default: default:
@@ -26,5 +28,4 @@ public class PartyHelpCommand implements CommandExecutor {
return true; return true;
} }
} }
} }

View File

@@ -1,12 +1,12 @@
package com.gmail.nossr50.commands.party; package com.gmail.nossr50.commands.party;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -21,6 +21,9 @@ public class PartyInfoCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
case 1:
player = (Player) sender; player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty(); playerParty = mcMMOPlayer.getParty();
@@ -29,21 +32,29 @@ public class PartyInfoCommand implements CommandExecutor {
displayShareModeInfo(); displayShareModeInfo();
displayMemberInfo(); displayMemberInfo();
return true; return true;
default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "info"));
return true;
}
} }
private String createMembersList() { private String createMembersList() {
StringBuilder memberList = new StringBuilder(); StringBuilder memberList = new StringBuilder();
for (OfflinePlayer member : playerParty.getMembers()) { for (String memberName : playerParty.getMembers()) {
if (playerParty.getLeader().equalsIgnoreCase(member.getName())) { Player member = mcMMO.p.getServer().getPlayerExact(memberName);
memberList.append(ChatColor.GOLD).append(member.getName()).append(" ");
if (playerParty.getLeader().equalsIgnoreCase(memberName)) {
memberList.append(ChatColor.GOLD);
} }
else if (member.isOnline()) { else if (member != null) {
memberList.append(ChatColor.WHITE).append(member.getName()).append(" "); memberList.append(ChatColor.WHITE);
} }
else { else {
memberList.append(ChatColor.GRAY).append(member.getName()).append(" "); memberList.append(ChatColor.GRAY);
} }
memberList.append(memberName).append(" ");
} }
return memberList.toString(); return memberList.toString();
@@ -52,7 +63,7 @@ public class PartyInfoCommand implements CommandExecutor {
private void displayShareModeInfo() { private void displayShareModeInfo() {
boolean xpShareEnabled = Config.getInstance().getExpShareEnabled(); boolean xpShareEnabled = Config.getInstance().getExpShareEnabled();
boolean itemShareEnabled = Config.getInstance().getItemShareEnabled(); boolean itemShareEnabled = Config.getInstance().getItemShareEnabled();
boolean itemSharingActive = playerParty.getItemShareMode() != ShareHandler.ShareMode.NONE; boolean itemSharingActive = (playerParty.getItemShareMode() != ShareHandler.ShareMode.NONE);
if (!xpShareEnabled && !itemShareEnabled) { if (!xpShareEnabled && !itemShareEnabled) {
return; return;
@@ -97,6 +108,6 @@ public class PartyInfoCommand implements CommandExecutor {
player.sendMessage(LocaleLoader.getString("Commands.Party.Members.Header")); player.sendMessage(LocaleLoader.getString("Commands.Party.Members.Header"));
player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", membersNear, membersOnline)); player.sendMessage(LocaleLoader.getString("Commands.Party.MembersNear", membersNear, membersOnline));
player.sendMessage(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.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
public class PartyInviteCommand implements CommandExecutor { public class PartyInviteCommand implements CommandExecutor {
private McMMOPlayer mcMMOTarget;
private Player target;
private McMMOPlayer mcMMOPlayer;
private Player player;
private Party playerParty;
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 2: case 2:
if (!mcMMO.p.getServer().getOfflinePlayer(args[1]).isOnline()) { McMMOPlayer mcMMOTarget = UserManager.getPlayer(args[1]);
sender.sendMessage(LocaleLoader.getString("Party.NotOnline", args[1]));
return true; if (!CommandUtils.checkPlayerExistence(sender, args[1], mcMMOTarget)) {
return false;
} }
mcMMOTarget = UserManager.getPlayer(args[1]); Player target = mcMMOTarget.getPlayer();
Player player = (Player) sender;
if (mcMMOTarget == null) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
sender.sendMessage(LocaleLoader.getString("Party.Player.Invalid"));
return true;
}
target = mcMMOTarget.getPlayer();
mcMMOPlayer = UserManager.getPlayer((Player) sender);
player = mcMMOPlayer.getPlayer();
if (player.equals(target)) { if (player.equals(target)) {
sender.sendMessage(LocaleLoader.getString("Party.Invite.Self")); sender.sendMessage(LocaleLoader.getString("Party.Invite.Self"));
@@ -50,7 +37,7 @@ public class PartyInviteCommand implements CommandExecutor {
return true; return true;
} }
playerParty = mcMMOPlayer.getParty(); Party playerParty = mcMMOPlayer.getParty();
if (!PartyManager.canInvite(player, playerParty)) { if (!PartyManager.canInvite(player, playerParty)) {
player.sendMessage(LocaleLoader.getString("Party.Locked")); player.sendMessage(LocaleLoader.getString("Party.Locked"));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpConfirmRequired()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled"));
}
mcMMOPlayer.togglePtpConfirmRequired();
return true;
}
}

View File

@@ -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;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPtpRequest()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.NoRequests"));
return true;
}
if ((mcMMOPlayer.getPtpTimeout() + Config.getInstance().getPTPCommandTimeout()) * Misc.TIME_CONVERSION_FACTOR < System.currentTimeMillis()) {
mcMMOPlayer.removePtpRequest();
player.sendMessage(LocaleLoader.getString("Commands.ptp.RequestExpired"));
return true;
}
Player target = mcMMOPlayer.getPtpRequest();
mcMMOPlayer.removePtpRequest();
if (!PtpCommand.canTeleport(sender, player, target.getName())) {
return true;
}
if (Config.getInstance().getPTPCommandWorldPermissions()) {
World targetWorld = target.getWorld();
World playerWorld = player.getWorld();
if (!Permissions.partyTeleportAllWorlds(target)) {
if (!Permissions.partyTeleportWorld(target, targetWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName()));
return true;
}
else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) {
target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName()));
return true;
}
}
}
PtpCommand.handleTeleportWarmup(target, player);
return true;
}
}

View File

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

View File

@@ -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;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer.getPtpEnabled()) {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled"));
}
else {
player.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled"));
}
mcMMOPlayer.togglePtpUse();
return true;
}
}

View File

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

View File

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

View File

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

View File

@@ -1,69 +1,58 @@
package com.gmail.nossr50.commands.player; package com.gmail.nossr50.commands.player;
import org.bukkit.ChatColor; import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.LeaderboardManager;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask; import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
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 @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean useMySQL = Config.getInstance().getUseMySQL();
switch (args.length) { switch (args.length) {
case 0: case 0:
display(1, "ALL", sender, useMySQL, command); display(1, "ALL", sender, command);
return true; return true;
case 1: case 1:
if (StringUtils.isInt(args[0])) { if (StringUtils.isInt(args[0])) {
display(Integer.parseInt(args[0]), "ALL", sender, useMySQL, command); display(Math.abs(Integer.parseInt(args[0])), "ALL", sender, 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; return true;
} }
display(1, skill.toString(), sender, useMySQL, command); if (!extractSkill(sender, args[0])) {
} return true;
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
} }
display(1, skill.toString(), sender, command);
return true; return true;
case 2: case 2:
if (!StringUtils.isInt(args[1])) { if (CommandUtils.isInvalidInteger(sender, args[1])) {
return false;
}
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; return true;
} }
display(Integer.parseInt(args[1]), skill.toString(), sender, useMySQL, command); if (!extractSkill(sender, args[0])) {
} return true;
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Invalid"));
} }
display(Math.abs(Integer.parseInt(args[1])), skill.toString(), sender, command);
return true; return true;
default: default:
@@ -71,58 +60,45 @@ public class MctopCommand implements CommandExecutor {
} }
} }
private void display(int page, String skill, CommandSender sender, boolean sql, Command command) { @Override
if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, SkillType.getSkill(skill))) { 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 display(int page, String skill, CommandSender sender, Command command) {
if (!skill.equalsIgnoreCase("all") && !Permissions.mctop(sender, this.skill)) {
sender.sendMessage(command.getPermissionMessage()); sender.sendMessage(command.getPermissionMessage());
return; return;
} }
if (sql) { if (sender instanceof Player && Config.getInstance().getMctopScoreboardEnabled()) {
if (skill.equalsIgnoreCase("all")) { ScoreboardManager.enableGlobalStatsScoreboard((Player) sender, skill, page);
sqlDisplay(page, "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing", sender, command);
} }
else { else {
sqlDisplay(page, skill, sender, command); display(page, skill, sender);
}
}
else {
flatfileDisplay(page, skill, sender, command);
} }
} }
private void flatfileDisplay(int page, String skill, CommandSender sender, Command command) { private void display(int page, String query, CommandSender sender) {
LeaderboardManager.updateLeaderboards(); // Make sure we have the latest information new MctopCommandAsyncTask(page, query, sender).runTaskAsynchronously(mcMMO.p);
String[] info = LeaderboardManager.retrieveInfo(skill, page);
if (skill.equalsIgnoreCase("all")) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", StringUtils.getCapitalized(skill)));
} }
int n = (page * 10) - 9; // Position private boolean extractSkill(CommandSender sender, String skillName) {
for (String x : info) { if (CommandUtils.isInvalidSkill(sender, skillName)) {
if (x != null) { return false;
String digit = String.valueOf(n);
if (n < 10) {
digit = "0" + digit;
} }
String[] splitx = x.split(":"); skill = SkillType.getSkill(skillName);
// Format: 1. Playername - skill value if (CommandUtils.isChildSkill(sender, skill)) {
sender.sendMessage(digit + ". " + ChatColor.GREEN + splitx[1] + " - " + ChatColor.WHITE + splitx[0]); return false;
n++;
}
} }
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip")); return true;
}
private void sqlDisplay(int page, String query, CommandSender sender, Command command) {
mcMMO.p.getServer().getScheduler().runTaskAsynchronously(mcMMO.p, new MctopCommandAsyncTask(page, query, sender, command));
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,14 +1,18 @@
package com.gmail.nossr50.commands.skills; package com.gmail.nossr50.commands.skills;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.config.AdvancedConfig; import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -17,15 +21,20 @@ import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.PerksUtils; import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public abstract class SkillCommand implements CommandExecutor { import com.google.common.collect.ImmutableList;
public abstract class SkillCommand implements TabExecutor {
protected SkillType skill; protected SkillType skill;
private String skillString; protected String skillName;
protected Player player; protected Player player;
protected PlayerProfile profile; protected PlayerProfile profile;
protected McMMOPlayer mcMMOPlayer;
protected float skillValue; protected float skillValue;
protected boolean isLucky; protected boolean isLucky;
protected boolean hasEndurance; protected boolean hasEndurance;
@@ -33,9 +42,12 @@ public abstract class SkillCommand implements CommandExecutor {
protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat percent = new DecimalFormat("##0.00%");
protected DecimalFormat decimal = new DecimalFormat("##0.00"); protected DecimalFormat decimal = new DecimalFormat("##0.00");
private CommandExecutor skillGuideCommand;
public SkillCommand(SkillType skill) { public SkillCommand(SkillType skill) {
this.skill = skill; this.skill = skill;
this.skillString = StringUtils.getCapitalized(skill.toString()); skillName = SkillUtils.getSkillName(skill);
skillGuideCommand = new SkillGuideCommand(skill);
} }
@Override @Override
@@ -45,29 +57,35 @@ public abstract class SkillCommand implements CommandExecutor {
} }
player = (Player) sender; player = (Player) sender;
profile = UserManager.getPlayer(player).getProfile(); mcMMOPlayer = UserManager.getPlayer(player);
if (profile == null) { switch (args.length) {
sender.sendMessage(LocaleLoader.getString("Commands.DoesNotExist")); case 0:
return true; profile = mcMMOPlayer.getProfile();
}
skillValue = profile.getSkillLevel(skill); skillValue = profile.getSkillLevel(skill);
isLucky = Permissions.lucky(sender, skill); isLucky = Permissions.lucky(sender, skill);
hasEndurance = (Permissions.twelveSecondActivationBoost(sender) || Permissions.eightSecondActivationBoost(sender) || Permissions.fourSecondActivationBoost(sender)); hasEndurance = (PerksUtils.handleActivationPerks(player, 0, 0) != 0);
dataCalculations();
permissionsCheck(); permissionsCheck();
dataCalculations();
if (!skill.isChildSkill()) { if (!skill.isChildSkill()) {
player.sendMessage(LocaleLoader.getString("Skills.Header", SkillUtils.getSkillName(skill))); player.sendMessage(LocaleLoader.getString("Skills.Header", skillName));
player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + skillString))); player.sendMessage(LocaleLoader.getString("Commands.XPGain", LocaleLoader.getString("Commands.XPGain." + StringUtils.getCapitalized(skill.toString()))));
player.sendMessage(LocaleLoader.getString("Effects.Level", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), profile.getXpToLevel(skill)));
if (Config.getInstance().getSkillScoreboardEnabled()) {
ScoreboardManager.setupPlayerScoreboard(player.getName());
ScoreboardManager.enablePlayerSkillScoreboard(mcMMOPlayer, skill);
} }
else { else {
player.sendMessage(LocaleLoader.getString("Skills.Header", SkillUtils.getSkillName(skill) + " " + LocaleLoader.getString("Skills.Child"))); 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("Commands.XPGain", LocaleLoader.getString("Commands.XPGain.Child")));
player.sendMessage(LocaleLoader.getString("Effects.Child", profile.getSkillLevel(skill))); player.sendMessage(LocaleLoader.getString("Effects.Child", (int) skillValue));
player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Skills.Parents"))); player.sendMessage(LocaleLoader.getString("Skills.Header", LocaleLoader.getString("Skills.Parents")));
Set<SkillType> parents = FamilyTree.getParents(skill); Set<SkillType> parents = FamilyTree.getParents(skill);
@@ -89,52 +107,39 @@ public abstract class SkillCommand implements CommandExecutor {
statsDisplay(); statsDisplay();
return SkillGuideCommand.grabGuidePageForSkill(skill, player, args); player.sendMessage(LocaleLoader.getString("Guides.Available", skillName, skillName.toLowerCase()));
return true;
default:
return skillGuideCommand.onCommand(sender, command, label, args);
}
} }
protected String calculateRank(int maxLevel, int rankChangeLevel) { @Override
if (skillValue >= maxLevel) { public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return String.valueOf(maxLevel / rankChangeLevel); 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) { protected String[] calculateAbilityDisplayValues(double chance) {
if (isLucky) { String[] displayValues = new String[2];
double luckyChance = chance * 1.3333D;
if (luckyChance >= 100D) { displayValues[0] = percent.format(Math.min(chance, 100.0D) / 100.0D);
return new String[] { percent.format(chance / 100.0D), percent.format(1.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 displayValues;
}
return new String[] { percent.format(chance / 100.0D), null };
} }
protected String[] calculateAbilityDisplayValues(int maxBonusLevel, double maxChance) { protected String[] calculateAbilityDisplayValues(int maxBonusLevel, double maxChance) {
double abilityChance; return calculateAbilityDisplayValues((maxChance / maxBonusLevel) * Math.min(skillValue, maxBonusLevel));
if (skillValue >= maxBonusLevel) {
abilityChance = maxChance;
}
else {
abilityChance = (maxChance / maxBonusLevel) * skillValue;
}
if (isLucky) {
double luckyChance = abilityChance * 1.3333D;
if (luckyChance >= 100D) {
return new String[] { percent.format(abilityChance / 100.0D), percent.format(1.0D) };
}
return new String[] { percent.format(abilityChance / 100.0D), percent.format(luckyChance / 100.0D) };
}
return new String[] { percent.format(abilityChance / 100.0D), null };
} }
protected String[] calculateLengthDisplayValues() { protected String[] calculateLengthDisplayValues() {
@@ -143,9 +148,7 @@ public abstract class SkillCommand implements CommandExecutor {
int enduranceLength = PerksUtils.handleActivationPerks(player, length, maxLength); int enduranceLength = PerksUtils.handleActivationPerks(player, length, maxLength);
if (maxLength != 0) { if (maxLength != 0) {
if (length > maxLength) { length = Math.min(length, maxLength);
length = maxLength;
}
} }
return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; return new String[] { String.valueOf(length), String.valueOf(enduranceLength) };
@@ -154,7 +157,7 @@ public abstract class SkillCommand implements CommandExecutor {
protected void luckyEffectsDisplay() { protected void luckyEffectsDisplay() {
if (isLucky) { if (isLucky) {
String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix"); String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix");
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc", 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 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.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public final class SkillGuideCommand { public class SkillGuideCommand implements CommandExecutor {
private SkillGuideCommand() {} private String header;
private String[] guide;
public static int getTotalPageNumber(String address) { private String invalidPage;
String[] addressSplit = LocaleLoader.getString(address).split("\n");
if (addressSplit.length <= 8) { public SkillGuideCommand(SkillType skillType) {
return 1; header = LocaleLoader.getString("Guides.Header", SkillUtils.getSkillName(skillType));
guide = LocaleLoader.getString("Guides." + StringUtils.getCapitalized(skillType.toString())).split("\n");
invalidPage = LocaleLoader.getString("Guides.Page.Invalid");
} }
return (addressSplit.length / 8) + 1; @Override
} public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
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;
switch (args.length) { switch (args.length) {
case 0:
// We have to specify this, otherwise we get the usage string every time we call /skillname...
return true;
case 1: case 1:
if (!args[0].equals("?")) { if (!args[0].equals("?")) {
return false; return false;
} }
SkillGuideCommand.clearChat(player); sendGuide(sender, 1);
for (String target : SkillGuideCommand.grabPageContents(localized, address, 1)) {
player.sendMessage(target);
}
return true; return true;
case 2: case 2:
int totalPages = SkillGuideCommand.getTotalPageNumber(address); int totalPages = getTotalPageNumber();
if (!StringUtils.isInt(args[1])) { if (!StringUtils.isInt(args[1])) {
player.sendMessage(LocaleLoader.getString("Guides.Page.Invalid")); sender.sendMessage(invalidPage);
return true; return true;
} }
if (Integer.parseInt(args[1]) > totalPages) { int pageNumber = Integer.parseInt(args[1]);
player.sendMessage(LocaleLoader.getString("Guides.Page.OutOfRange", totalPages));
if (pageNumber > totalPages || pageNumber <= 0) {
sender.sendMessage(LocaleLoader.getString("Guides.Page.OutOfRange", totalPages));
return true; return true;
} }
SkillGuideCommand.clearChat(player); sendGuide(sender, pageNumber);
for (String target : SkillGuideCommand.grabPageContents(localized, address, Integer.parseInt(args[1]))) {
player.sendMessage(target);
}
return true; return true;
default: default:
return false; return false;
} }
} }
private int getTotalPageNumber() {
return (int) Math.ceil(guide.length / 8.0);
}
private void sendGuide(CommandSender sender, int pageNumber) {
for (String target : grabPageContents(pageNumber)) {
sender.sendMessage(target);
}
}
private ArrayList<String> grabPageContents(int pagenum) {
int pageIndexStart = 8 * (pagenum - 1); // Determine what string to start at
ArrayList<String> allStrings = new ArrayList<String>();
allStrings.add(header);
// Add targeted strings
while (allStrings.size() < 9) {
if (pageIndexStart + allStrings.size() > guide.length) {
allStrings.add("");
}
else {
allStrings.add(guide[pageIndexStart + (allStrings.size() - 1)]);
}
}
allStrings.add("Page " + pagenum + " of " + getTotalPageNumber());
return allStrings;
}
} }

View File

@@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.smelting.Smelting; import com.gmail.nossr50.skills.smelting.Smelting;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public class SmeltingCommand extends SkillCommand { public class SmeltingCommand extends SkillCommand {
private String burnTimeModifier; private String burnTimeModifier;
@@ -14,8 +13,6 @@ public class SmeltingCommand extends SkillCommand {
private String fluxMiningChance; private String fluxMiningChance;
private String fluxMiningChanceLucky; private String fluxMiningChanceLucky;
private int vanillaXPModifier;
private boolean canFuelEfficiency; private boolean canFuelEfficiency;
private boolean canSecondSmelt; private boolean canSecondSmelt;
private boolean canFluxMine; private boolean canFluxMine;
@@ -28,20 +25,23 @@ public class SmeltingCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// FUEL EFFICIENCY // FUEL EFFICIENCY
if (canFuelEfficiency) {
burnTimeModifier = decimal.format(1 + ((skillValue / Smelting.burnModifierMaxLevel) * Smelting.burnTimeMultiplier)); burnTimeModifier = decimal.format(1 + ((skillValue / Smelting.burnModifierMaxLevel) * Smelting.burnTimeMultiplier));
}
// SECOND SMELT // SECOND SMELT
if (canSecondSmelt) {
String[] secondSmeltStrings = calculateAbilityDisplayValues(Smelting.secondSmeltMaxLevel, Smelting.secondSmeltMaxChance); String[] secondSmeltStrings = calculateAbilityDisplayValues(Smelting.secondSmeltMaxLevel, Smelting.secondSmeltMaxChance);
secondSmeltChance = secondSmeltStrings[0]; secondSmeltChance = secondSmeltStrings[0];
secondSmeltChanceLucky = secondSmeltStrings[1]; secondSmeltChanceLucky = secondSmeltStrings[1];
}
// FLUX MINING // FLUX MINING
if (canFluxMine) {
String[] fluxMiningStrings = calculateAbilityDisplayValues(Smelting.fluxMiningChance); String[] fluxMiningStrings = calculateAbilityDisplayValues(Smelting.fluxMiningChance);
fluxMiningChance = fluxMiningStrings[0]; fluxMiningChance = fluxMiningStrings[0];
fluxMiningChanceLucky = fluxMiningStrings[1]; fluxMiningChanceLucky = fluxMiningStrings[1];
}
// VANILLA XP BOOST
vanillaXPModifier = UserManager.getPlayer(player).getSmeltingManager().getVanillaXpMultiplier();
} }
@Override @Override
@@ -90,20 +90,17 @@ public class SmeltingCommand extends SkillCommand {
} }
if (canSecondSmelt) { if (canSecondSmelt) {
if (isLucky) { player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", secondSmeltChanceLucky) : ""));
player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance) + LocaleLoader.getString("Perks.lucky.bonus", secondSmeltChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.SecondSmelt", secondSmeltChance));
}
} }
if (canVanillaXPBoost) { if (canVanillaXPBoost) {
if (skillValue < AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level()) { int unlockLevel = AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level();
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.0", AdvancedConfig.getInstance().getSmeltingVanillaXPBoostRank1Level())));
if (skillValue < unlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.0", unlockLevel)));
} }
else { else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.VanillaXPBoost", vanillaXPModifier)); player.sendMessage(LocaleLoader.getString("Smelting.Ability.VanillaXPBoost", mcMMOPlayer.getSmeltingManager().getVanillaXpMultiplier()));
} }
} }
@@ -111,11 +108,8 @@ public class SmeltingCommand extends SkillCommand {
if (skillValue < Smelting.fluxMiningUnlockLevel) { if (skillValue < Smelting.fluxMiningUnlockLevel) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.1", Smelting.fluxMiningUnlockLevel))); player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", LocaleLoader.getString("Smelting.Ability.Locked.1", Smelting.fluxMiningUnlockLevel)));
} }
else if (isLucky) {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.FluxMining", fluxMiningChance) + LocaleLoader.getString("Perks.lucky.bonus", fluxMiningChanceLucky));
}
else { else {
player.sendMessage(LocaleLoader.getString("Smelting.Ability.FluxMining", fluxMiningChance)); 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 { public class SwordsCommand extends SkillCommand {
private String counterAttackChance; private String counterAttackChance;
private String counterAttackChanceLucky; private String counterAttackChanceLucky;
private String bleedLength; private int bleedLength;
private String bleedChance; private String bleedChance;
private String bleedChanceLucky; private String bleedChanceLucky;
private String serratedStrikesLength; private String serratedStrikesLength;
@@ -25,27 +25,28 @@ public class SwordsCommand extends SkillCommand {
@Override @Override
protected void dataCalculations() { protected void dataCalculations() {
// SERRATED STRIKES // SERRATED STRIKES
if (canSerratedStrike) {
String[] serratedStrikesStrings = calculateLengthDisplayValues(); String[] serratedStrikesStrings = calculateLengthDisplayValues();
serratedStrikesLength = serratedStrikesStrings[0]; serratedStrikesLength = serratedStrikesStrings[0];
serratedStrikesLengthEndurance = serratedStrikesStrings[1]; serratedStrikesLengthEndurance = serratedStrikesStrings[1];
}
// BLEED // BLEED
if (skillValue >= Swords.bleedMaxBonusLevel) { if (canBleed) {
bleedLength = String.valueOf(Swords.bleedMaxTicks); bleedLength = (skillValue >= Swords.bleedMaxBonusLevel) ? Swords.bleedMaxTicks : Swords.bleedBaseTicks;
}
else {
bleedLength = String.valueOf(Swords.bleedBaseTicks);
}
String[] bleedStrings = calculateAbilityDisplayValues(Swords.bleedMaxBonusLevel, Swords.bleedMaxChance); String[] bleedStrings = calculateAbilityDisplayValues(Swords.bleedMaxBonusLevel, Swords.bleedMaxChance);
bleedChance = bleedStrings[0]; bleedChance = bleedStrings[0];
bleedChanceLucky = bleedStrings[1]; bleedChanceLucky = bleedStrings[1];
}
// COUNTER ATTACK // COUNTER ATTACK
if (canCounter) {
String[] counterAttackStrings = calculateAbilityDisplayValues(Swords.counterAttackMaxBonusLevel, Swords.counterAttackMaxChance); String[] counterAttackStrings = calculateAbilityDisplayValues(Swords.counterAttackMaxBonusLevel, Swords.counterAttackMaxChance);
counterAttackChance = counterAttackStrings[0]; counterAttackChance = counterAttackStrings[0];
counterAttackChanceLucky = counterAttackStrings[1]; counterAttackChanceLucky = counterAttackStrings[1];
} }
}
@Override @Override
protected void permissionsCheck() { protected void permissionsCheck() {
@@ -85,33 +86,17 @@ public class SwordsCommand extends SkillCommand {
@Override @Override
protected void statsDisplay() { protected void statsDisplay() {
if (canCounter) { if (canCounter) {
if (isLucky) { player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", counterAttackChanceLucky) : ""));
player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance) + LocaleLoader.getString("Perks.lucky.bonus", counterAttackChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Counter.Chance", counterAttackChance));
}
} }
if (canBleed) { if (canBleed) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Length", bleedLength)); player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Length", bleedLength));
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Note")); player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Note"));
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance) + (isLucky ? LocaleLoader.getString("Perks.lucky.bonus", bleedChanceLucky) : ""));
if (isLucky) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance) + LocaleLoader.getString("Perks.lucky.bonus", bleedChanceLucky));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleed.Chance", bleedChance));
}
} }
if (canSerratedStrike) { if (canSerratedStrike) {
if (hasEndurance) { player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength) + (hasEndurance ? LocaleLoader.getString("Perks.activationtime.bonus", serratedStrikesLengthEndurance) : ""));
player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength) + LocaleLoader.getString("Perks.activationtime.bonus", serratedStrikesLengthEndurance));
}
else {
player.sendMessage(LocaleLoader.getString("Swords.SS.Length", serratedStrikesLength));
}
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,10 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/* GENERAL */ /* GENERAL */
public int getAbilityLength() { return config.getInt("Skills.General.Ability_IncreaseLevel", 50); } public int getAbilityLength() { return config.getInt("Skills.General.Ability_IncreaseLevel", 50); }
public int getEnchantBuff() { return config.getInt("Skills.General.Ability_EnchantBuff", 5); } public int getEnchantBuff() {
int buff = config.getInt("Skills.General.Ability_EnchantBuff", 5);
return (buff <= 0) ? 1 : buff;
}
/* ACROBATICS */ /* ACROBATICS */
public double getDodgeChanceMax() { return config.getDouble("Skills.Acrobatics.Dodge_ChanceMax", 20.0D); } public double getDodgeChanceMax() { return config.getDouble("Skills.Acrobatics.Dodge_ChanceMax", 20.0D); }
@@ -34,7 +37,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getGracefulRollChanceMax() { return config.getDouble("Skills.Acrobatics.GracefulRoll_ChanceMax", 100.0D); } public double getGracefulRollChanceMax() { return config.getDouble("Skills.Acrobatics.GracefulRoll_ChanceMax", 100.0D); }
public int getGracefulRollMaxBonusLevel() { return config.getInt("Skills.Acrobatics.GracefulRoll_MaxBonusLevel", 500); } public int getGracefulRollMaxBonusLevel() { return config.getInt("Skills.Acrobatics.GracefulRoll_MaxBonusLevel", 500); }
public int getGracefulRollDamageThreshold() { return config.getInt("Skills.Acrobatics.GracefulRoll_DamageThreshold", 14); } public int getGracefulRollDamageThreshold() { return config.getInt("Skills.Acrobatics.GracefulRoll_DamageThreshold", 14); }
public int getGracefulRollSuccessModifer() { return config.getInt("Skills.Acrobatics.GracefulRoll_SuccessModifier", 2); }
public int getDodgeXPModifier() { return config.getInt("Skills.Acrobatics.Dodge_XP_Modifier", 120); } public int getDodgeXPModifier() { return config.getInt("Skills.Acrobatics.Dodge_XP_Modifier", 120); }
public int getRollXPModifier() { return config.getInt("Skills.Acrobatics.Roll_XP_Modifier", 80); } public int getRollXPModifier() { return config.getInt("Skills.Acrobatics.Roll_XP_Modifier", 80); }
@@ -52,6 +54,8 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getRetrieveChanceMax() { return config.getDouble("Skills.Archery.Retrieve_MaxBonus", 100.0D); } public double getRetrieveChanceMax() { return config.getDouble("Skills.Archery.Retrieve_MaxBonus", 100.0D); }
public int getRetrieveMaxBonusLevel() { return config.getInt("Skills.Archery.Retrieve_MaxBonusLevel", 1000); } public int getRetrieveMaxBonusLevel() { return config.getInt("Skills.Archery.Retrieve_MaxBonusLevel", 1000); }
public double getForceMultiplier() { return config.getDouble("Skills.Archery.Force_Multiplier", 2.0D); }
/* AXES */ /* AXES */
public int getBonusDamageAxesBonusMax() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonus", 4); } public int getBonusDamageAxesBonusMax() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonus", 4); }
public int getBonusDamageAxesMaxBonusLevel() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonusLevel", 200); } public int getBonusDamageAxesMaxBonusLevel() { return config.getInt("Skills.Axes.DamageIncrease_MaxBonusLevel", 200); }
@@ -85,6 +89,8 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.Fisherman_Diet_RankChange", 200); } public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.Fisherman_Diet_RankChange", 200); }
public int getIceFishingUnlockLevel() { return config.getInt("Skills.Fishing.Ice_Fishing_UnlockLevel", 50); }
/* Shake */ /* Shake */
public int getShakeUnlockLevel() { return config.getInt("Skills.Fishing.Shake_UnlockLevel", 150); } public int getShakeUnlockLevel() { return config.getInt("Skills.Fishing.Shake_UnlockLevel", 150); }
public int getShakeChanceRank1() { return config.getInt("Skills.Fishing.Shake_Chance.Rank_1", 25); } public int getShakeChanceRank1() { return config.getInt("Skills.Fishing.Shake_Chance.Rank_1", 25); }
@@ -273,9 +279,17 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getWoodcuttingDoubleDropChance() { return config.getDouble("Skills.Woodcutting.DoubleDrops_ChanceMax", 100.0D); } public double getWoodcuttingDoubleDropChance() { return config.getDouble("Skills.Woodcutting.DoubleDrops_ChanceMax", 100.0D); }
public int getWoodcuttingDoubleDropMaxLevel() { return config.getInt("Skills.Woodcutting.DoubleDrops_MaxBonusLevel", 1000); } public int getWoodcuttingDoubleDropMaxLevel() { return config.getInt("Skills.Woodcutting.DoubleDrops_MaxBonusLevel", 1000); }
/* SPOUT STUFF*/ /* KRAKEN STUFF */
public int getSpoutNotificationTier1() { return config.getInt("Spout.Notifications.Tier1", 200); } public boolean getKrakenEnabled() { return config.getBoolean("Kraken.Enabled", true); }
public int getSpoutNotificationTier2() { return config.getInt("Spout.Notifications.Tier2", 400); } public boolean getKrakenGlobalSoundsEnabled() { return config.getBoolean("Kraken.Global_Sounds", true); }
public int getSpoutNotificationTier3() { return config.getInt("Spout.Notifications.Tier3", 600); } public boolean getKrakenEscapeAllowed() { return config.getBoolean("Kraken.Allow_Escaping", false); }
public int getSpoutNotificationTier4() { return config.getInt("Spout.Notifications.Tier4", 800); } 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.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
@@ -48,6 +49,36 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getPartyDisplayNames() { return config.getBoolean("Commands.p.Use_Display_Names", true); } public boolean getPartyDisplayNames() { return config.getBoolean("Commands.p.Use_Display_Names", true); }
public boolean getAdminDisplayNames() { return config.getBoolean("Commands.a.Use_Display_Names", true); } public boolean getAdminDisplayNames() { return config.getBoolean("Commands.a.Use_Display_Names", true); }
/* Mob Healthbar */
public MobHealthbarType getMobHealthbarDefault() {
try {
return MobHealthbarType.valueOf(config.getString("Mob_Healthbar.Display_Type", "HEARTS").toUpperCase().trim());
}
catch (IllegalArgumentException ex) {
return MobHealthbarType.HEARTS;
}
}
public int getMobHealthbarTime() { return config.getInt("Mob_Healthbar.Display_Time", 3); }
/* Scoreboards */
public boolean getMcrankScoreboardEnabled() { return config.getBoolean("Scoreboards.Mcrank.Use", true); }
public int getMcrankScoreboardTime() { return config.getInt("Scoreboards.Mcrank.Display_Time", 10); }
public boolean getMcstatsScoreboardsEnabled() { return config.getBoolean("Scoreboards.Mcstats.Use", true); }
public int getMcstatsScoreboardTime() { return config.getInt("Scoreboards.Mcstats.Display_Time", 10); }
public boolean getMctopScoreboardEnabled() { return config.getBoolean("Scoreboards.Mctop.Use", true); }
public int getMctopScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); }
public boolean getInspectScoreboardEnabled() { return config.getBoolean("Scoreboards.Inspect.Use", true); }
public int getInspectScoreboardTime() { return config.getInt("Scoreboards.Inspect.Display_Time", 10); }
public boolean getSkillScoreboardEnabled() { return config.getBoolean("Scoreboards.Skillname.Use", true); }
public int getSkillScoreboardTime() { return config.getInt("Scoreboards.Skillname.Display_Time", 10); }
public boolean getPowerLevelsEnabled() { return config.getBoolean("Scoreboards.Power_Level.Use", false); }
/* Database Purging */ /* Database Purging */
public int getPurgeInterval() { return config.getInt("Database_Purging.Purge_Interval", -1); } public int getPurgeInterval() { return config.getInt("Database_Purging.Purge_Interval", -1); }
public int getOldUsersCutoff() { return config.getInt("Database_Purging.Old_User_Cutoff", 6); } public int getOldUsersCutoff() { return config.getInt("Database_Purging.Old_User_Cutoff", 6); }
@@ -107,6 +138,8 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); } public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); }
public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); } public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); }
public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); } public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); }
public int getChimaeraWarmup() { return config.getInt("Items.Chimaera_Wing.Warmup", 5); }
public int getChimaeraRecentlyHurtCooldown() { return config.getInt("Items.Chimaera_Wing.RecentlyHurt_Cooldown", 60); }
/* Particles */ /* Particles */
public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); } public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); }
@@ -114,6 +147,9 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); } public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); }
public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); } public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); }
public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); } public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); }
public boolean getLevelUpEffectsEnabled() { return config.getBoolean("Particles.LevelUp_Enabled", true); }
public int getLevelUpEffectsTier() { return config.getInt("Particles.LevelUp_Tier", 100); }
public boolean getLargeFireworks() { return config.getBoolean("Particles.LargeFireworks", true); }
/* PARTY SETTINGS */ /* PARTY SETTINGS */
public int getAutoPartyKickInterval() { return config.getInt("Party.AutoKick_Interval", 12); } public int getAutoPartyKickInterval() { return config.getInt("Party.AutoKick_Interval", 12); }
@@ -126,11 +162,16 @@ public class Config extends AutoUpdateConfigLoader {
public double getPartyShareRange() { return config.getDouble("Party.Sharing.Range", 75.0); } public double getPartyShareRange() { return config.getDouble("Party.Sharing.Range", 75.0); }
/* Party Teleport Settings */ /* Party Teleport Settings */
public int getPTPCommandCooldown() { return config.getInt("Commands.ptp.Cooldown", 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 int getPTPCommandTimeout() { return config.getInt("Commands.ptp.Request_Timeout", 300); }
public boolean getPTPCommandConfirmRequired() { return config.getBoolean("Commands.ptp.Confirm_Required", true); } public boolean getPTPCommandConfirmRequired() { return config.getBoolean("Commands.ptp.Confirm_Required", true); }
public boolean getPTPCommandWorldPermissions() { return config.getBoolean("Commands.ptp.World_Based_Permissions", false); } public boolean getPTPCommandWorldPermissions() { return config.getBoolean("Commands.ptp.World_Based_Permissions", false); }
/* Inspect command distance */
public double getInspectDistance() { return config.getDouble("Commands.inspect.Max_Distance", 30); }
/* /*
* ABILITY SETTINGS * ABILITY SETTINGS
*/ */
@@ -189,6 +230,7 @@ public class Config extends AutoUpdateConfigLoader {
public int getSalvageAnvilId() { return config.getInt("Skills.Repair.Salvage_Anvil_ID", 41); } public int getSalvageAnvilId() { return config.getInt("Skills.Repair.Salvage_Anvil_ID", 41); }
public boolean getSalvageTools() { return config.getBoolean("Skills.Repair.Salvage_tools", true); } public boolean getSalvageTools() { return config.getBoolean("Skills.Repair.Salvage_tools", true); }
public boolean getSalvageArmor() { return config.getBoolean("Skills.Repair.Salvage_armor", true); } public boolean getSalvageArmor() { return config.getBoolean("Skills.Repair.Salvage_armor", true); }
public boolean getRepairConfirmRequired() { return config.getBoolean("Skills.Repair.Confirm_Required", true); }
/* Unarmed */ /* Unarmed */
public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); } public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); }
@@ -236,7 +278,6 @@ public class Config extends AutoUpdateConfigLoader {
*/ */
/* General Settings */ /* General Settings */
public boolean getExperienceGainsMobspawnersEnabled() { return config.getBoolean("Experience.Gains.Mobspawners.Enabled", false); }
public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience.PVP.Rewards", true); } public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience.PVP.Rewards", true); }
public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience.Gains.Multiplier.Global", 1.0); } public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience.Gains.Multiplier.Global", 1.0); }
@@ -249,8 +290,9 @@ public class Config extends AutoUpdateConfigLoader {
public double getAnimalsXP() { return config.getDouble("Experience.Combat.Multiplier.Animals", 1.0); } public double getAnimalsXP() { return config.getDouble("Experience.Combat.Multiplier.Animals", 1.0); }
public double getWitherSkeletonXP() { return config.getDouble("Experience.Combat.Multiplier.Wither_Skeleton", 4.0); } public double getWitherSkeletonXP() { return config.getDouble("Experience.Combat.Multiplier.Wither_Skeleton", 4.0); }
public double getSpawnedMobXpMultiplier() { return config.getDouble("Experience.Gains.Mobspawners.Multiplier", 0.0); }
/* XP Formula Multiplier */ /* XP Formula Multiplier */
public int getFormulaMultiplierCurve() { return config.getInt("Experience.Formula.Curve_Modifier", 20); } public int getFormulaMultiplierCurve() { return config.getInt("Experience.Formula.Curve_Modifier", 20); }
public double getForumulaMultiplier(SkillType skill) { return config.getDouble("Experience.Formula.Multiplier." + StringUtils.getCapitalized(skill.toString())); } public double getFormulaSkillModifier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
} }

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
package com.gmail.nossr50.config.party; package com.gmail.nossr50.config.party;
import java.util.HashSet;
import org.bukkit.Material; import org.bukkit.Material;
import com.gmail.nossr50.config.ConfigLoader; import com.gmail.nossr50.config.ConfigLoader;
@@ -21,13 +23,20 @@ public class ItemWeightConfig extends ConfigLoader {
} }
public int getItemWeight(Material material) { public int getItemWeight(Material material) {
String materialName = StringUtils.getPrettyItemString(material).replace(" ", "_"); return config.getInt("Item_Weights." + StringUtils.getPrettyItemString(material).replace(" ", "_"), config.getInt("Item_Weights.Default"));
int itemWeight = config.getInt("Item_Weights.Default");
if (config.getInt("Item_Weights." + materialName) > 0) {
itemWeight = config.getInt("Item_Weights." + materialName);
} }
return itemWeight;
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 miscItems;
} }
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

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

View File

@@ -5,8 +5,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
@@ -19,6 +19,7 @@ import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.events.experience.McMMOPlayerXpGainEvent; import com.gmail.nossr50.events.experience.McMMOPlayerXpGainEvent;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.party.ShareHandler; import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.skills.AbilityDisableTask;
import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
import com.gmail.nossr50.skills.archery.ArcheryManager; import com.gmail.nossr50.skills.archery.ArcheryManager;
@@ -52,7 +53,7 @@ public class McMMOPlayer {
* we make sure that all class inheriting from SkillManager are instanced. * we make sure that all class inheriting from SkillManager are instanced.
* Which solution is better, I let you decide. - bm01 * Which solution is better, I let you decide. - bm01
*/ */
private Map<SkillType, SkillManager> skillManagers = new HashMap<SkillType, SkillManager>(); private final Map<SkillType, SkillManager> skillManagers = new HashMap<SkillType, SkillManager>();
private Party party; private Party party;
private Party invite; private Party invite;
@@ -69,24 +70,29 @@ public class McMMOPlayer {
private boolean abilityUse = true; private boolean abilityUse = true;
private boolean placedRepairAnvil; private boolean placedRepairAnvil;
private int lastRepairClick;
private boolean placedSalvageAnvil; private boolean placedSalvageAnvil;
private int lastSalvageClick;
private boolean godMode; private boolean godMode;
private Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>();
private Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>();
private Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>(); private final Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>();
private Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>(); private final Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>();
private int recentlyHurt; private int recentlyHurt;
private int chimaeraWing;
private int respawnATS; private int respawnATS;
private int teleportLastUse;
private Location teleportCommence;
private boolean isUsingUnarmed;
public McMMOPlayer(Player player) { public McMMOPlayer(Player player) {
String playerName = player.getName(); String playerName = player.getName();
this.player = player; this.player = player;
profile = new PlayerProfile(playerName, true); profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, true);
party = PartyManager.getPlayerParty(playerName); party = PartyManager.getPlayerParty(playerName);
/* /*
@@ -176,7 +182,8 @@ public class McMMOPlayer {
*/ */
public void resetAbilityMode() { public void resetAbilityMode() {
for (AbilityType ability : AbilityType.values()) { for (AbilityType ability : AbilityType.values()) {
setAbilityMode(ability, false); // Correctly disable and handle any special deactivate code
new AbilityDisableTask(this, ability).run();
} }
} }
@@ -194,10 +201,10 @@ public class McMMOPlayer {
* Set the mode of an ability. * Set the mode of an ability.
* *
* @param ability The ability to check * @param ability The ability to check
* @param bool True if the ability is active, false otherwise * @param isActive True if the ability is active, false otherwise
*/ */
public void setAbilityMode(AbilityType ability, boolean bool) { public void setAbilityMode(AbilityType ability, boolean isActive) {
abilityMode.put(ability, bool); abilityMode.put(ability, isActive);
} }
/** /**
@@ -214,10 +221,10 @@ public class McMMOPlayer {
* Set the informed state of an ability. * Set the informed state of an ability.
* *
* @param ability The ability to check * @param ability The ability to check
* @param bool True if the ability is informed, false otherwise * @param isInformed True if the ability is informed, false otherwise
*/ */
public void setAbilityInformed(AbilityType ability, boolean bool) { public void setAbilityInformed(AbilityType ability, boolean isInformed) {
abilityInformed.put(ability, bool); abilityInformed.put(ability, isInformed);
} }
/** /**
@@ -255,10 +262,10 @@ public class McMMOPlayer {
* Set the current prep mode of a tool. * Set the current prep mode of a tool.
* *
* @param tool Tool to set the mode for * @param tool Tool to set the mode for
* @param bool true if the tool should be prepped, false otherwise * @param isPrepared true if the tool should be prepped, false otherwise
*/ */
public void setToolPreparationMode(ToolType tool, boolean bool) { public void setToolPreparationMode(ToolType tool, boolean isPrepared) {
toolMode.put(tool, bool); toolMode.put(tool, isPrepared);
} }
/** /**
@@ -300,21 +307,32 @@ public class McMMOPlayer {
} }
/* /*
* Chimaera Wing * Teleportation cooldown & warmup
*/ */
public int getLastChimaeraTeleport() { public int getLastTeleport() {
return chimaeraWing; return teleportLastUse;
} }
public void setLastChimaeraTeleport(int value) { public void setLastTeleport(int value) {
chimaeraWing = value; teleportLastUse = value;
} }
public void actualizeLastChimaeraTeleport() { public void actualizeLastTeleport() {
chimaeraWing = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR); 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) {
teleportCommence = player.getLocation();
}
/* /*
* Exploit Prevention * Exploit Prevention
@@ -354,6 +372,42 @@ public class McMMOPlayer {
} }
} }
/*
* Repair Anvil Usage
*/
public int getLastAnvilUse(int anvilId) {
if (anvilId == Repair.repairAnvilId) {
return lastRepairClick;
}
if (anvilId == Repair.salvageAnvilId) {
return lastSalvageClick;
}
return 0;
}
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);
}
}
/* /*
* God Mode * God Mode
*/ */
@@ -386,11 +440,7 @@ public class McMMOPlayer {
public int getPowerLevel() { public int getPowerLevel() {
int powerLevel = 0; int powerLevel = 0;
for (SkillType type : SkillType.values()) { for (SkillType type : SkillType.nonChildSkills()) {
if (type.isChildSkill()) {
continue;
}
if (Permissions.skillEnabled(player, type)) { if (Permissions.skillEnabled(player, type)) {
powerLevel += profile.getSkillLevel(type); powerLevel += profile.getSkillLevel(type);
} }
@@ -405,7 +455,7 @@ public class McMMOPlayer {
* @param skillType Skill being used * @param skillType Skill being used
* @param xp Experience amount to process * @param xp Experience amount to process
*/ */
public void beginXpGain(SkillType skillType, int xp) { public void beginXpGain(SkillType skillType, float xp) {
if (xp == 0) { if (xp == 0) {
return; return;
} }
@@ -436,7 +486,7 @@ public class McMMOPlayer {
* @param skillType Skill being used * @param skillType Skill being used
* @param xp Experience amount to process * @param xp Experience amount to process
*/ */
public void beginUnsharedXpGain(SkillType skillType, int xp) { public void beginUnsharedXpGain(SkillType skillType, float xp) {
xp = modifyXpGain(skillType, xp); xp = modifyXpGain(skillType, xp);
applyXpGain(skillType, xp); applyXpGain(skillType, xp);
@@ -448,7 +498,21 @@ public class McMMOPlayer {
* @param skillType Skill being used * @param skillType Skill being used
* @param xp Experience amount to add * @param xp Experience amount to add
*/ */
public void applyXpGain(SkillType skillType, int xp) { public void applyXpGain(SkillType skillType, float xp) {
if (!Permissions.skillEnabled(player, skillType)) {
return;
}
if (skillType.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skillType);
for (SkillType parentSkill : parentSkills) {
applyXpGain(parentSkill, xp / parentSkills.size());
}
return;
}
McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skillType, xp); McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skillType, xp);
mcMMO.p.getServer().getPluginManager().callEvent(event); mcMMO.p.getServer().getPluginManager().callEvent(event);
@@ -456,7 +520,7 @@ public class McMMOPlayer {
return; return;
} }
profile.setSkillXpLevel(skillType, profile.getSkillXpLevel(skillType) + event.getXpGained()); profile.setSkillXpLevel(skillType, profile.getSkillXpLevelRaw(skillType) + event.getRawXpGained());
McMMOHud spoutHud = profile.getSpoutHud(); McMMOHud spoutHud = profile.getSpoutHud();
@@ -464,6 +528,7 @@ public class McMMOPlayer {
spoutHud.setLastGained(skillType); spoutHud.setLastGained(skillType);
} }
isUsingUnarmed = (skillType == SkillType.UNARMED);
SkillUtils.xpCheckSkill(skillType, player, profile); SkillUtils.xpCheckSkill(skillType, player, profile);
} }
@@ -496,11 +561,7 @@ public class McMMOPlayer {
} }
public boolean hasPartyInvite() { public boolean hasPartyInvite() {
if (invite != null) { return (invite != null);
return true;
}
return false;
} }
public void setParty(Party party) { public void setParty(Party party) {
@@ -512,11 +573,7 @@ public class McMMOPlayer {
} }
public boolean inParty() { public boolean inParty() {
if (party != null) { return (party != null);
return true;
}
return false;
} }
public void removeParty() { public void removeParty() {
@@ -544,11 +601,7 @@ public class McMMOPlayer {
} }
public boolean hasPtpRequest() { public boolean hasPtpRequest() {
if (ptpRequest != null) { return (ptpRequest != null);
return true;
}
return false;
} }
public void removePtpRequest() { public void removePtpRequest() {
@@ -580,11 +633,7 @@ public class McMMOPlayer {
} }
public void setItemShareModifier(int modifier) { public void setItemShareModifier(int modifier) {
if (modifier < 10) { itemShareModifier = Math.max(10, modifier);
modifier = 10;
}
itemShareModifier = modifier;
} }
/* /*
@@ -615,6 +664,10 @@ public class McMMOPlayer {
partyChatMode = !partyChatMode; partyChatMode = !partyChatMode;
} }
public boolean isUsingUnarmed() {
return isUsingUnarmed;
}
/** /**
* Modifies an experience gain using skill modifiers, global rate and perks * Modifies an experience gain using skill modifiers, global rate and perks
* *
@@ -622,20 +675,15 @@ public class McMMOPlayer {
* @param xp Experience amount to process * @param xp Experience amount to process
* @return Modified experience * @return Modified experience
*/ */
private int modifyXpGain(SkillType skillType, int xp) { private float modifyXpGain(SkillType skillType, float xp) {
if (player.getGameMode() == GameMode.CREATIVE) { if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() <= profile.getSkillLevel(skillType)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) {
return 0; return 0;
} }
if ((skillType.getMaxLevel() < profile.getSkillLevel(skillType) + 1) || (Config.getInstance().getPowerLevelCap() < getPowerLevel() + 1)) { xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
return 0;
}
xp = (int) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
if (Config.getInstance().getToolModsEnabled()) { if (Config.getInstance().getToolModsEnabled()) {
ItemStack item = player.getItemInHand(); CustomTool tool = ModUtils.getToolFromItemStack(player.getItemInHand());
CustomTool tool = ModUtils.getToolFromItemStack(item);
if (tool != null) { if (tool != null) {
xp *= tool.getXpMultiplier(); xp *= tool.getXpMultiplier();

View File

@@ -1,529 +1,81 @@
package com.gmail.nossr50.datatypes.player; package com.gmail.nossr50.datatypes.player;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.bukkit.scoreboard.Scoreboard;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.database.DatabaseManager; import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.spout.huds.HudType; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.datatypes.spout.huds.McMMOHud; import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.skills.child.FamilyTree; import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.StringUtils;
public class PlayerProfile { public class PlayerProfile {
private String playerName; private final String playerName;
// HUD
private McMMOHud spoutHud;
private HudType hudType;
// mySQL Stuff
private int userId;
private boolean loaded; private boolean loaded;
private Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skills and Levels /* HUDs */
private Map<SkillType, Integer> skillsXp = new HashMap<SkillType, Integer>(); // Skills and Xp private HudType hudType;
private Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); private MobHealthbarType mobHealthbarType;
private McMMOHud spoutHud;
private Scoreboard playerStatsScoreboard;
private final static String location = mcMMO.getUsersFilePath(); /* Skill Data */
private final Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level
private final Map<SkillType, Float> skillsXp = new HashMap<SkillType, Float>(); // Skill & XP
private final Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); // Ability & Cooldown
public PlayerProfile(String playerName, boolean addNew) { public PlayerProfile(String playerName) {
this.playerName = playerName; this.playerName = playerName;
if (mcMMO.spoutEnabled) { hudType = mcMMO.isSpoutEnabled() ? SpoutConfig.getInstance().getDefaultHudType() : HudType.DISABLED;
hudType = SpoutConfig.getInstance().defaultHudType; mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
}
else {
hudType = HudType.DISABLED;
}
for (AbilityType abilityType : AbilityType.values()) { for (AbilityType abilityType : AbilityType.values()) {
skillsDATS.put(abilityType, 0); skillsDATS.put(abilityType, 0);
} }
for (SkillType skillType : SkillType.values()) { for (SkillType skillType : SkillType.nonChildSkills()) {
if (!skillType.isChildSkill()) {
skills.put(skillType, 0); skills.put(skillType, 0);
skillsXp.put(skillType, 0); skillsXp.put(skillType, 0F);
} }
} }
if (Config.getInstance().getUseMySQL()) { public PlayerProfile(String playerName, boolean isLoaded) {
if (!loadMySQL() && addNew) { this(playerName);
addMySQLPlayer(); this.loaded = isLoaded;
loaded = true; }
}
} /**
else if (!load() && addNew) { * Calling this constructor is considered loading the profile.
addPlayer(); */
public PlayerProfile(String playerName, Map<SkillType, Integer> argSkills, Map<SkillType, Float> argSkillsXp, Map<AbilityType, Integer> argSkillsDats, HudType hudType, MobHealthbarType mobHealthbarType) {
this(playerName, true);
this.hudType = hudType;
this.mobHealthbarType = mobHealthbarType;
this.skills.putAll(argSkills);
this.skillsXp.putAll(argSkillsXp);
this.skillsDATS.putAll(argSkillsDats);
loaded = true; loaded = true;
} }
public void save() {
mcMMO.getDatabaseManager().saveUser(this);
} }
public String getPlayerName() { public String getPlayerName() {
return playerName; return playerName;
} }
public boolean loadMySQL() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
userId = DatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
if (userId == 0) {
return false;
}
HashMap<Integer, ArrayList<String>> huds = DatabaseManager.read("SELECT hudtype FROM " + tablePrefix + "huds WHERE user_id = " + userId);
if (huds.get(1) == null) {
DatabaseManager.write("INSERT INTO " + tablePrefix + "huds (user_id) VALUES (" + userId + ")");
}
else {
for (HudType type : HudType.values()) {
if (type.toString().equalsIgnoreCase(huds.get(1).get(0))) {
hudType = type;
}
}
}
HashMap<Integer, ArrayList<String>> cooldowns = DatabaseManager.read("SELECT mining, woodcutting, unarmed, herbalism, excavation, swords, axes, blast_mining FROM " + tablePrefix + "cooldowns WHERE user_id = " + userId);
ArrayList<String> cooldownValues = cooldowns.get(1);
if (cooldownValues == null) {
DatabaseManager.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the cooldown table. Their cooldowns will be reset.");
}
else {
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(cooldownValues.get(0)));
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(cooldownValues.get(1)));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(cooldownValues.get(2)));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(cooldownValues.get(3)));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(cooldownValues.get(4)));
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(cooldownValues.get(5)));
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(cooldownValues.get(6)));
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(cooldownValues.get(7)));
}
HashMap<Integer, ArrayList<String>> stats = DatabaseManager.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "skills WHERE user_id = " + userId);
ArrayList<String> statValues = stats.get(1);
if (statValues == null) {
DatabaseManager.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the skills table. Their stats will be reset.");
}
else {
skills.put(SkillType.TAMING, Integer.valueOf(statValues.get(0)));
skills.put(SkillType.MINING, Integer.valueOf(statValues.get(1)));
skills.put(SkillType.REPAIR, Integer.valueOf(statValues.get(2)));
skills.put(SkillType.WOODCUTTING, Integer.valueOf(statValues.get(3)));
skills.put(SkillType.UNARMED, Integer.valueOf(statValues.get(4)));
skills.put(SkillType.HERBALISM, Integer.valueOf(statValues.get(5)));
skills.put(SkillType.EXCAVATION, Integer.valueOf(statValues.get(6)));
skills.put(SkillType.ARCHERY, Integer.valueOf(statValues.get(7)));
skills.put(SkillType.SWORDS, Integer.valueOf(statValues.get(8)));
skills.put(SkillType.AXES, Integer.valueOf(statValues.get(9)));
skills.put(SkillType.ACROBATICS, Integer.valueOf(statValues.get(10)));
skills.put(SkillType.FISHING, Integer.valueOf(statValues.get(11)));
}
HashMap<Integer, ArrayList<String>> experience = DatabaseManager.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "experience WHERE user_id = " + userId);
ArrayList<String> experienceValues = experience.get(1);
if (experienceValues == null) {
DatabaseManager.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the experience table. Their experience will be reset.");
}
else {
skillsXp.put(SkillType.TAMING, Integer.valueOf(experienceValues.get(0)));
skillsXp.put(SkillType.MINING, Integer.valueOf(experienceValues.get(1)));
skillsXp.put(SkillType.REPAIR, Integer.valueOf(experienceValues.get(2)));
skillsXp.put(SkillType.WOODCUTTING, Integer.valueOf(experienceValues.get(3)));
skillsXp.put(SkillType.UNARMED, Integer.valueOf(experienceValues.get(4)));
skillsXp.put(SkillType.HERBALISM, Integer.valueOf(experienceValues.get(5)));
skillsXp.put(SkillType.EXCAVATION, Integer.valueOf(experienceValues.get(6)));
skillsXp.put(SkillType.ARCHERY, Integer.valueOf(experienceValues.get(7)));
skillsXp.put(SkillType.SWORDS, Integer.valueOf(experienceValues.get(8)));
skillsXp.put(SkillType.AXES, Integer.valueOf(experienceValues.get(9)));
skillsXp.put(SkillType.ACROBATICS, Integer.valueOf(experienceValues.get(10)));
skillsXp.put(SkillType.FISHING, Integer.valueOf(experienceValues.get(11)));
}
loaded = true;
return true;
}
public void addMySQLPlayer() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
DatabaseManager.write("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES ('" + playerName + "'," + System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR + ")");
userId = DatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
DatabaseManager.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
DatabaseManager.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
DatabaseManager.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
}
public boolean load() {
try {
// Open the user file
FileReader file = new FileReader(location);
BufferedReader in = new BufferedReader(file);
String line;
while ((line = in.readLine()) != null) {
// Find if the line contains the player we want.
String[] character = line.split(":");
if (!character[0].equalsIgnoreCase(playerName)) {
continue;
}
if (character.length > 1 && StringUtils.isInt(character[1])) {
skills.put(SkillType.MINING, Integer.valueOf(character[1]));
}
if (character.length > 4 && StringUtils.isInt(character[4])) {
skillsXp.put(SkillType.MINING, Integer.valueOf(character[4]));
}
if (character.length > 5 && StringUtils.isInt(character[5])) {
skills.put(SkillType.WOODCUTTING, Integer.valueOf(character[5]));
}
if (character.length > 6 && StringUtils.isInt(character[6])) {
skillsXp.put(SkillType.WOODCUTTING, Integer.valueOf(character[6]));
}
if (character.length > 7 && StringUtils.isInt(character[7])) {
skills.put(SkillType.REPAIR, Integer.valueOf(character[7]));
}
if (character.length > 8 && StringUtils.isInt(character[8])) {
skills.put(SkillType.UNARMED, Integer.valueOf(character[8]));
}
if (character.length > 9 && StringUtils.isInt(character[9])) {
skills.put(SkillType.HERBALISM, Integer.valueOf(character[9]));
}
if (character.length > 10 && StringUtils.isInt(character[10])) {
skills.put(SkillType.EXCAVATION, Integer.valueOf(character[10]));
}
if (character.length > 11 && StringUtils.isInt(character[11])) {
skills.put(SkillType.ARCHERY, Integer.valueOf(character[11]));
}
if (character.length > 12 && StringUtils.isInt(character[12])) {
skills.put(SkillType.SWORDS, Integer.valueOf(character[12]));
}
if (character.length > 13 && StringUtils.isInt(character[13])) {
skills.put(SkillType.AXES, Integer.valueOf(character[13]));
}
if (character.length > 14 && StringUtils.isInt(character[14])) {
skills.put(SkillType.ACROBATICS, Integer.valueOf(character[14]));
}
if (character.length > 15 && StringUtils.isInt(character[15])) {
skillsXp.put(SkillType.REPAIR, Integer.valueOf(character[15]));
}
if (character.length > 16 && StringUtils.isInt(character[16])) {
skillsXp.put(SkillType.UNARMED, Integer.valueOf(character[16]));
}
if (character.length > 17 && StringUtils.isInt(character[17])) {
skillsXp.put(SkillType.HERBALISM, Integer.valueOf(character[17]));
}
if (character.length > 18 && StringUtils.isInt(character[18])) {
skillsXp.put(SkillType.EXCAVATION, Integer.valueOf(character[18]));
}
if (character.length > 19 && StringUtils.isInt(character[19])) {
skillsXp.put(SkillType.ARCHERY, Integer.valueOf(character[19]));
}
if (character.length > 20 && StringUtils.isInt(character[20])) {
skillsXp.put(SkillType.SWORDS, Integer.valueOf(character[20]));
}
if (character.length > 21 && StringUtils.isInt(character[21])) {
skillsXp.put(SkillType.AXES, Integer.valueOf(character[21]));
}
if (character.length > 22 && StringUtils.isInt(character[22])) {
skillsXp.put(SkillType.ACROBATICS, Integer.valueOf(character[22]));
}
if (character.length > 24 && StringUtils.isInt(character[24])) {
skills.put(SkillType.TAMING, Integer.valueOf(character[24]));
}
if (character.length > 25 && StringUtils.isInt(character[25])) {
skillsXp.put(SkillType.TAMING, Integer.valueOf(character[25]));
}
if (character.length > 26) {
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(character[26]));
}
if (character.length > 27) {
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(character[27]));
}
if (character.length > 28) {
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(character[28]));
}
if (character.length > 29) {
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(character[29]));
}
if (character.length > 30) {
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(character[30]));
}
if (character.length > 31) {
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(character[31]));
}
if (character.length > 32) {
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(character[32]));
}
if (character.length > 33) {
for (HudType type : HudType.values()) {
if (type.toString().equalsIgnoreCase(character[33])) {
hudType = type;
}
}
}
if (character.length > 34) {
skills.put(SkillType.FISHING, Integer.valueOf(character[34]));
}
if (character.length > 35) {
skillsXp.put(SkillType.FISHING, Integer.valueOf(character[35]));
}
if (character.length > 36) {
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(character[36]));
}
loaded = true;
in.close();
return true;
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void save() {
Long timestamp = System.currentTimeMillis();
// If we are using mysql save to database
if (Config.getInstance().getUseMySQL()) {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
DatabaseManager.write("UPDATE " + tablePrefix + "huds SET hudtype = '" + hudType.toString() + "' WHERE user_id = " + userId);
DatabaseManager.write("UPDATE " + tablePrefix + "users SET lastlogin = " + ((int) (timestamp / Misc.TIME_CONVERSION_FACTOR)) + " WHERE id = " + userId);
DatabaseManager.write("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = " + skillsDATS.get(AbilityType.SUPER_BREAKER)
+ ", woodcutting = " + skillsDATS.get(AbilityType.TREE_FELLER)
+ ", unarmed = " + skillsDATS.get(AbilityType.BERSERK)
+ ", herbalism = " + skillsDATS.get(AbilityType.GREEN_TERRA)
+ ", excavation = " + skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)
+ ", swords = " + skillsDATS.get(AbilityType.SERRATED_STRIKES)
+ ", axes = " + skillsDATS.get(AbilityType.SKULL_SPLITTER)
+ ", blast_mining = " + skillsDATS.get(AbilityType.BLAST_MINING)
+ " WHERE user_id = " + userId);
DatabaseManager.write("UPDATE " + tablePrefix + "skills SET "
+ " taming = " + skills.get(SkillType.TAMING)
+ ", mining = " + skills.get(SkillType.MINING)
+ ", repair = " + skills.get(SkillType.REPAIR)
+ ", woodcutting = " + skills.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skills.get(SkillType.UNARMED)
+ ", herbalism = " + skills.get(SkillType.HERBALISM)
+ ", excavation = " + skills.get(SkillType.EXCAVATION)
+ ", archery = " + skills.get(SkillType.ARCHERY)
+ ", swords = " + skills.get(SkillType.SWORDS)
+ ", axes = " + skills.get(SkillType.AXES)
+ ", acrobatics = " + skills.get(SkillType.ACROBATICS)
+ ", fishing = " + skills.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
DatabaseManager.write("UPDATE " + tablePrefix + "experience SET "
+ " taming = " + skillsXp.get(SkillType.TAMING)
+ ", mining = " + skillsXp.get(SkillType.MINING)
+ ", repair = " + skillsXp.get(SkillType.REPAIR)
+ ", woodcutting = " + skillsXp.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skillsXp.get(SkillType.UNARMED)
+ ", herbalism = " + skillsXp.get(SkillType.HERBALISM)
+ ", excavation = " + skillsXp.get(SkillType.EXCAVATION)
+ ", archery = " + skillsXp.get(SkillType.ARCHERY)
+ ", swords = " + skillsXp.get(SkillType.SWORDS)
+ ", axes = " + skillsXp.get(SkillType.AXES)
+ ", acrobatics = " + skillsXp.get(SkillType.ACROBATICS)
+ ", fishing = " + skillsXp.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
}
else {
// Otherwise save to flatfile
try {
// Open the file
FileReader file = new FileReader(location);
BufferedReader in = new BufferedReader(file);
StringBuilder writer = new StringBuilder();
String line;
// While not at the end of the file
while ((line = in.readLine()) != null) {
// Read the line in and copy it to the output it's not the player we want to edit
if (!line.split(":")[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
// Otherwise write the new player information
writer.append(playerName).append(":");
writer.append(skills.get(SkillType.MINING)).append(":");
writer.append(":");
writer.append(":");
writer.append(skillsXp.get(SkillType.MINING)).append(":");
writer.append(skills.get(SkillType.WOODCUTTING)).append(":");
writer.append(skillsXp.get(SkillType.WOODCUTTING)).append(":");
writer.append(skills.get(SkillType.REPAIR)).append(":");
writer.append(skills.get(SkillType.UNARMED)).append(":");
writer.append(skills.get(SkillType.HERBALISM)).append(":");
writer.append(skills.get(SkillType.EXCAVATION)).append(":");
writer.append(skills.get(SkillType.ARCHERY)).append(":");
writer.append(skills.get(SkillType.SWORDS)).append(":");
writer.append(skills.get(SkillType.AXES)).append(":");
writer.append(skills.get(SkillType.ACROBATICS)).append(":");
writer.append(skillsXp.get(SkillType.REPAIR)).append(":");
writer.append(skillsXp.get(SkillType.UNARMED)).append(":");
writer.append(skillsXp.get(SkillType.HERBALISM)).append(":");
writer.append(skillsXp.get(SkillType.EXCAVATION)).append(":");
writer.append(skillsXp.get(SkillType.ARCHERY)).append(":");
writer.append(skillsXp.get(SkillType.SWORDS)).append(":");
writer.append(skillsXp.get(SkillType.AXES)).append(":");
writer.append(skillsXp.get(SkillType.ACROBATICS)).append(":");
writer.append(":");
writer.append(skills.get(SkillType.TAMING)).append(":");
writer.append(skillsXp.get(SkillType.TAMING)).append(":");
writer.append(skillsDATS.get(AbilityType.BERSERK)).append(":");
writer.append(skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)).append(":");
writer.append(skillsDATS.get(AbilityType.TREE_FELLER)).append(":");
writer.append(skillsDATS.get(AbilityType.GREEN_TERRA)).append(":");
writer.append(skillsDATS.get(AbilityType.SERRATED_STRIKES)).append(":");
writer.append(skillsDATS.get(AbilityType.SKULL_SPLITTER)).append(":");
writer.append(skillsDATS.get(AbilityType.SUPER_BREAKER)).append(":");
writer.append(hudType.toString()).append(":");
writer.append(skills.get(SkillType.FISHING)).append(":");
writer.append(skillsXp.get(SkillType.FISHING)).append(":");
writer.append(skillsDATS.get(AbilityType.BLAST_MINING)).append(":");
writer.append(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR).append(":");
writer.append("\r\n");
}
}
in.close();
// Write the new file
FileWriter out = new FileWriter(location);
out.write(writer.toString());
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void addPlayer() {
try {
// Open the file to write the player
FileWriter file = new FileWriter(location, true);
BufferedWriter out = new BufferedWriter(file);
// Add the player to the end
out.append(playerName).append(":");
out.append("0:"); // Mining
out.append(":");
out.append(":");
out.append("0:"); // Xp
out.append("0:"); // Woodcutting
out.append("0:"); // WoodCuttingXp
out.append("0:"); // Repair
out.append("0:"); // Unarmed
out.append("0:"); // Herbalism
out.append("0:"); // Excavation
out.append("0:"); // Archery
out.append("0:"); // Swords
out.append("0:"); // Axes
out.append("0:"); // Acrobatics
out.append("0:"); // RepairXp
out.append("0:"); // UnarmedXp
out.append("0:"); // HerbalismXp
out.append("0:"); // ExcavationXp
out.append("0:"); // ArcheryXp
out.append("0:"); // SwordsXp
out.append("0:"); // AxesXp
out.append("0:"); // AcrobaticsXp
out.append(":");
out.append("0:"); // Taming
out.append("0:"); // TamingXp
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append(hudType.toString()).append(":"); // HUD
out.append("0:"); // Fishing
out.append("0:"); // FishingXp
out.append("0:"); // Blast Mining
out.append(String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)).append(":"); // LastLogin
// Add more in the same format as the line above
out.newLine();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
* mySQL Stuff
*/
public int getMySQLuserId() {
return userId;
}
public boolean isLoaded() { public boolean isLoaded() {
return loaded; return loaded;
} }
@@ -548,6 +100,30 @@ public class PlayerProfile {
this.hudType = hudType; this.hudType = hudType;
} }
/*
* Mob Healthbars
*/
public MobHealthbarType getMobHealthbarType() {
return mobHealthbarType;
}
public void setMobHealthbarType(MobHealthbarType mobHealthbarType) {
this.mobHealthbarType = mobHealthbarType;
}
/*
* Scoreboards
*/
public Scoreboard getPlayerStatsScoreboard() {
return playerStatsScoreboard;
}
public void setPlayerStatsScoreboard(Scoreboard statsScoreboard) {
this.playerStatsScoreboard = statsScoreboard;
}
/* /*
* Cooldowns * Cooldowns
*/ */
@@ -578,8 +154,8 @@ public class PlayerProfile {
* Reset all skill cooldowns. * Reset all skill cooldowns.
*/ */
public void resetCooldowns() { public void resetCooldowns() {
for (AbilityType x : skillsDATS.keySet()) { for (AbilityType ability : skillsDATS.keySet()) {
skillsDATS.put(x, 0); skillsDATS.put(ability, 0);
} }
} }
@@ -595,22 +171,19 @@ public class PlayerProfile {
return skills.get(skillType); return skills.get(skillType);
} }
public int getChildSkillLevel(SkillType skillType) { public float getSkillXpLevelRaw(SkillType skillType) {
Set<SkillType> parents = FamilyTree.getParents(skillType);
int sum = 0;
for (SkillType parent : parents) {
sum += Math.min(getSkillLevel(parent), 1000);
}
return sum / parents.size();
}
public int getSkillXpLevel(SkillType skillType) {
return skillsXp.get(skillType); return skillsXp.get(skillType);
} }
public void setSkillXpLevel(SkillType skillType, int newValue) { public int getSkillXpLevel(SkillType skillType) {
return (int) Math.floor(getSkillXpLevelRaw(skillType));
}
public void setSkillXpLevel(SkillType skillType, float newValue) {
if (skillType.isChildSkill()) {
return;
}
skillsXp.put(skillType, newValue); skillsXp.put(skillType, newValue);
} }
@@ -644,7 +217,7 @@ public class PlayerProfile {
} }
skills.put(skillType, newValue); skills.put(skillType, newValue);
skillsXp.put(skillType, 0); skillsXp.put(skillType, 0F);
} }
/** /**
@@ -659,7 +232,21 @@ public class PlayerProfile {
} }
skills.put(skillType, skills.get(skillType) + levels); skills.put(skillType, skills.get(skillType) + levels);
skillsXp.put(skillType, 0); skillsXp.put(skillType, 0F);
}
/**
* Add Experience to a skill.
*
* @param skillType Type of skill to add experience to
* @param experience Number of experience to add
*/
public void addExperience(SkillType skillType, int experience) {
if (skillType.isChildSkill()) {
return;
}
skillsXp.put(skillType, skillsXp.get(skillType) + experience);
} }
/** /**
@@ -671,4 +258,15 @@ public class PlayerProfile {
public int getXpToLevel(SkillType skillType) { public int getXpToLevel(SkillType skillType) {
return 1020 + (skills.get(skillType) * Config.getInstance().getFormulaMultiplierCurve()); return 1020 + (skills.get(skillType) * Config.getInstance().getFormulaMultiplierCurve());
} }
private int getChildSkillLevel(SkillType skillType) {
Set<SkillType> parents = FamilyTree.getParents(skillType);
int sum = 0;
for (SkillType parent : parents) {
sum += Math.min(getSkillLevel(parent), 1000);
}
return sum / parents.size();
}
} }

View File

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

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