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

Compare commits

..

211 Commits

Author SHA1 Message Date
riking
ffd11f6e0e Use PlayerLoginEvent instead to alleviate ban concerns
Research indicates that there is still enough time from login to join for this to be a good idea.
2013-07-03 22:16:32 -07:00
riking
f1f9ffc10b Prefetch profile information from the database.
Note that this implementation may open us to a denial-of-service attack by a banned user - AsyncPlayerPreLoginEvent is called before the ban lists are checked.

Look into the consequences of recieving an InterruptedException in the middle of loadPlayerProfile on the integrity of the database. If possible, we would prefer to interrupt the profile fetching task when the player stops logging in, to mitigate any possible denial-of-service attacks.
2013-07-03 21:52:19 -07:00
riking
8fe18be79b Move that PlayerProfile up another level! 2013-07-03 21:12:23 -07: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
153 changed files with 6572 additions and 3919 deletions

View File

@@ -8,6 +8,7 @@ Key:
- Removal - Removal
Version 1.4.06-dev Version 1.4.06-dev
+ Added "Ice Fishing" ability to Fishing
+ Added global scoreboards to track skill rankings (display using /mctop) + Added global scoreboards to track skill rankings (display using /mctop)
+ Added per-player scoreboard displays for the /inspect, /mcrank, /mcstats, and /<skillname> commands + Added per-player scoreboard displays for the /inspect, /mcrank, /mcstats, and /<skillname> commands
+ Added tab-complete support for all commands + Added tab-complete support for all commands
@@ -18,6 +19,22 @@ Version 1.4.06-dev
+ Added new permission node for /ptp; mcmmo.commands.ptp.send (enabled by default) + Added new permission node for /ptp; mcmmo.commands.ptp.send (enabled by default)
+ Added configurable cooldown and warmup times when using /ptp + 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 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 bug where players were able to join the same party multiple times
= Fixed displaying partial names when trying to use /ptp = Fixed displaying partial names when trying to use /ptp
= Fixed wolves from Call of the Wild only having 8 health = Fixed wolves from Call of the Wild only having 8 health
@@ -28,6 +45,19 @@ Version 1.4.06-dev
= Fixed Fishing treasures always having the same enchants = Fixed Fishing treasures always having the same enchants
= Fixed Smelting returning ink sacs instead of Lapis when double-dropping = 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 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 Berserk to add items to inventory rather than denying pickup
! Changed Call of the Wild, newly summoned pet's will have a custom name. (added permission node to disable this) ! Changed Call of the Wild, newly summoned pet's will have a custom name. (added permission node to disable this)
! Changed Chimaera Wing's recipe result to use the ingredient Material ! Changed Chimaera Wing's recipe result to use the ingredient Material
@@ -38,6 +68,7 @@ Version 1.4.06-dev
! Changed the amount of info messages in the console when enabling/disabling, enable Verbose_Logging to enable them again ! 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 ! Items dropped by players are now being tracked and are not being shared with party members
! Optimized tracking of tool & ability cooldowns. ! Optimized tracking of tool & ability cooldowns.
! Updated the localization files
Version 1.4.05 Version 1.4.05
+ Added option to allow refreshing of chunks after block-breaking abilities. (Disabled by default) + Added option to allow refreshing of chunks after block-breaking abilities. (Disabled by default)

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

View File

@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.nossr50.mcMMO</groupId> <groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId> <artifactId>mcMMO</artifactId>
<version>1.4.06-beta2</version> <version>1.4.06-dev6</version>
<name>mcMMO</name> <name>mcMMO</name>
<url>https://github.com/mcMMO-Dev/mcMMO</url> <url>https://github.com/mcMMO-Dev/mcMMO</url>
<issueManagement> <issueManagement>
@@ -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,7 +165,7 @@
<dependency> <dependency>
<groupId>com.turt2live.metrics</groupId> <groupId>com.turt2live.metrics</groupId>
<artifactId>MetricsExtension</artifactId> <artifactId>MetricsExtension</artifactId>
<version>0.0.4-SNAPSHOT</version> <version>0.0.5-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
<distributionManagement> <distributionManagement>

View File

@@ -4,6 +4,9 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.chat.ChatManager; import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.chat.PartyChatManager;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@@ -22,7 +25,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) { public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) {
ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, displayName, message); getPartyChatManager(plugin, party).handleChat(sender, displayName, message);
} }
/** /**
@@ -36,7 +39,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendPartyChat(Plugin plugin, String sender, String party, String message) { public static void sendPartyChat(Plugin plugin, String sender, String party, String message) {
ChatManager.handlePartyChat(plugin, PartyManager.getParty(party), sender, sender, message); getPartyChatManager(plugin, party).handleChat(sender, message);
} }
/** /**
@@ -50,7 +53,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) { public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) {
ChatManager.handleAdminChat(plugin, sender, displayName, message); ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, displayName, message);
} }
/** /**
@@ -63,7 +66,7 @@ public final class ChatAPI {
* @param message The message to send * @param message The message to send
*/ */
public static void sendAdminChat(Plugin plugin, String sender, String message) { public static void sendAdminChat(Plugin plugin, String sender, String message) {
ChatManager.handleAdminChat(plugin, sender, sender, message); ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN).handleChat(sender, message);
} }
/** /**
@@ -73,7 +76,7 @@ public final class ChatAPI {
* @return true if the player is using party chat, false otherwise * @return true if the player is using party chat, false otherwise
*/ */
public static boolean isUsingPartyChat(Player player) { public static boolean isUsingPartyChat(Player player) {
return isUsingPartyChat(player.getName()); return UserManager.getPlayer(player).getPartyChatMode();
} }
/** /**
@@ -93,7 +96,7 @@ public final class ChatAPI {
* @return true if the player is using admin chat, false otherwise * @return true if the player is using admin chat, false otherwise
*/ */
public static boolean isUsingAdminChat(Player player) { public static boolean isUsingAdminChat(Player player) {
return isUsingAdminChat(player.getName()); return UserManager.getPlayer(player).getAdminChatMode();
} }
/** /**
@@ -112,7 +115,7 @@ public final class ChatAPI {
* @param player The player to toggle party chat on. * @param player The player to toggle party chat on.
*/ */
public static void togglePartyChat(Player player) { public static void togglePartyChat(Player player) {
togglePartyChat(player.getName()); UserManager.getPlayer(player).togglePartyChat();
} }
/** /**
@@ -121,7 +124,7 @@ public final class ChatAPI {
* @param playerName The name of the player to toggle party chat on. * @param playerName The name of the player to toggle party chat on.
*/ */
public static void togglePartyChat(String playerName) { public static void togglePartyChat(String playerName) {
UserManager.getPlayer(playerName).setPartyChat(!isUsingPartyChat(playerName)); UserManager.getPlayer(playerName).togglePartyChat();
} }
/** /**
@@ -130,7 +133,7 @@ public final class ChatAPI {
* @param player The player to toggle admin chat on. * @param player The player to toggle admin chat on.
*/ */
public static void toggleAdminChat(Player player) { public static void toggleAdminChat(Player player) {
toggleAdminChat(player.getName()); UserManager.getPlayer(player).toggleAdminChat();
} }
/** /**
@@ -138,7 +141,14 @@ public final class ChatAPI {
* *
* @param playerName The name of the player to toggle party chat on. * @param playerName The name of the player to toggle party chat on.
*/ */
public static void toggleAdminChat(String playerName){ public static void toggleAdminChat(String playerName) {
UserManager.getPlayer(playerName).setAdminChat(!isUsingAdminChat(playerName)); UserManager.getPlayer(playerName).toggleAdminChat();
}
private static ChatManager getPartyChatManager(Plugin plugin, String party) {
ChatManager chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.PARTY);
((PartyChatManager) chatManager).setParty(PartyManager.getParty(party));
return chatManager;
} }
} }

View File

@@ -4,6 +4,7 @@ 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.InvalidPlayerException;
import com.gmail.nossr50.api.exceptions.InvalidSkillException; import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
@@ -15,6 +16,37 @@ import com.gmail.nossr50.util.player.UserManager;
public final class ExperienceAPI { public final class ExperienceAPI {
private ExperienceAPI() {} private ExperienceAPI() {}
/**
* Returns whether given string is a valid type of skill suitable for the
* other API calls in this class.
* </br>
* This function is designed for API usage.
*
* @param skillType A string that may or may not be a skill
* @return true if this is a valid mcMMO skill
*/
public static boolean isValidSkillType(String skillType) {
return SkillType.getSkill(skillType) != null;
}
/**
* Returns whether the given skill type string is both valid and not a
* child skill. (Child skills have no XP of their own, and their level is
* derived from the parent(s).)
* </br>
* This function is designed for API usage.
*
* @param skillType the skill to check
* @return true if this is a valid, non-child mcMMO skill
*/
public static boolean isNonChildSkill(String skillType) {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) return false;
return !skill.isChildSkill();
}
/** /**
* Adds raw XP to the player. * Adds raw XP to the player.
* </br> * </br>
@@ -27,13 +59,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addRawXP(Player player, String skillType, int XP) { public static void addRawXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, XP);
} }
/** /**
@@ -49,13 +75,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addRawXPOffline(String playerName, String skillType, int XP) { public static void addRawXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); addOfflineXP(playerName, getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, XP);
} }
/** /**
@@ -70,13 +90,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addMultipliedXP(Player player, String skillType, int XP) { public static void addMultipliedXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).applyXpGain(getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
@@ -92,13 +106,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addMultipliedXPOffline(String playerName, String skillType, int XP) { public static void addMultipliedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); addOfflineXP(playerName, getSkillType(skillType), (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
@@ -113,13 +121,9 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addModifiedXP(Player player, String skillType, int XP) { public static void addModifiedXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) { UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
throw new InvalidSkillException();
}
UserManager.getPlayer(player).applyXpGain(skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
@@ -135,17 +139,14 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void addModifiedXPOffline(String playerName, String skillType, int XP) { public static void addModifiedXPOffline(String playerName, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier())); addOfflineXP(playerName, skill, (int) (XP / skill.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()));
} }
/** /**
* Adds XP to the player, calculates for XP Rate, skill modifiers and perks. May be shared with the party. * Adds XP to the player, calculates for XP Rate, skill modifiers, perks, child skills,
* and party sharing.
* </br> * </br>
* This function is designed for API usage. * This function is designed for API usage.
* *
@@ -156,13 +157,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addXP(Player player, String skillType, int XP) { public static void addXP(Player player, String skillType, int XP) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).beginXpGain(getSkillType(skillType), XP);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).beginXpGain(skill, XP);
} }
/** /**
@@ -175,15 +170,10 @@ public final class ExperienceAPI {
* @return the amount of XP in a given skill * @return the amount of XP in a given skill
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getXP(Player player, String skillType) { public static int getXP(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillXpLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return UserManager.getPlayer(player).getProfile().getSkillXpLevel(skill);
} }
/** /**
@@ -197,15 +187,10 @@ public final class ExperienceAPI {
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getOfflineXP(String playerName, String skillType) { public static int getOfflineXP(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillXpLevel(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getSkillXpLevel(skill);
} }
/** /**
@@ -218,15 +203,10 @@ public final class ExperienceAPI {
* @return the amount of XP in a given skill * @return the amount of XP in a given skill
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static float getXPRaw(Player player, String skillType) { public static float getXPRaw(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillXpLevelRaw(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return UserManager.getPlayer(player).getProfile().getSkillXpLevelRaw(skill);
} }
/** /**
@@ -240,36 +220,63 @@ public final class ExperienceAPI {
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database * @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) { public static float getOfflineXPRaw(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillXpLevelRaw(getNonChildSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getSkillXpLevelRaw(skill);
} }
/** /**
* Get the amount of XP left before leveling up. * 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 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) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getXpToLevel(getNonChildSkillType(skillType));
}
if (skill == null) { /**
throw new InvalidSkillException(); * Get the total amount of XP an offline player needs to reach the next level.
} * </br>
* This function is designed for API usage.
*
* @param playerName The player to get XP for
* @param skillType The skill to get XP for
* @return the total amount of XP needed to reach the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getOfflineXPToNextLevel(String playerName, String skillType) {
return getOfflineProfile(playerName).getXpToLevel(getNonChildSkillType(skillType));
}
return UserManager.getPlayer(player).getProfile().getXpToLevel(skill); /**
* Get the amount of XP remaining until the next level.
* </br>
* This function is designed for API usage.
*
* @param player The player to get the XP amount for
* @param skillType The skill to get the XP amount for
* @return the amount of XP remaining until the next level
*
* @throws InvalidSkillException if the given skill is not valid
* @throws UnsupportedOperationException if the given skill is a child skill
*/
public static int getXPRemaining(Player player, String skillType) {
SkillType skill = getNonChildSkillType(skillType);
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
} }
/** /**
@@ -279,19 +286,18 @@ public final class ExperienceAPI {
* *
* @param playerName The player to get XP for * @param playerName 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 needed to reach the next level
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static int getOfflineXPToNextLevel(String playerName, String skillType) { public static int getOfflineXPRemaining(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getNonChildSkillType(skillType);
if (skill == null) { PlayerProfile profile = getOfflineProfile(playerName);
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getXpToLevel(skill); return profile.getXpToLevel(skill) - profile.getSkillXpLevel(skill);
} }
/** /**
@@ -306,13 +312,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void addLevel(Player player, String skillType, int levels) { public static void addLevel(Player player, String skillType, int levels) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().addLevels(getSkillType(skillType), levels);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().addLevels(skill, levels);
} }
/** /**
@@ -329,11 +329,7 @@ public final class ExperienceAPI {
*/ */
public static void addLevelOffline(String playerName, String skillType, int levels) { public static void addLevelOffline(String playerName, String skillType, int levels) {
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
SkillType skill = SkillType.getSkill(skillType); SkillType skill = getSkillType(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
if (skill.isChildSkill()) { if (skill.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skill); Set<SkillType> parentSkills = FamilyTree.getParents(skill);
@@ -362,13 +358,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevel(Player player, String skillType) { public static int getLevel(Player player, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return UserManager.getPlayer(player).getProfile().getSkillLevel(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return UserManager.getPlayer(player).getProfile().getSkillLevel(skill);
} }
/** /**
@@ -384,13 +374,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static int getLevelOffline(String playerName, String skillType) { public static int getLevelOffline(String playerName, String skillType) {
SkillType skill = SkillType.getSkill(skillType); return getOfflineProfile(playerName).getSkillLevel(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return getOfflineProfile(playerName).getSkillLevel(skill);
} }
/** /**
@@ -419,11 +403,7 @@ public final class ExperienceAPI {
int powerLevel = 0; int powerLevel = 0;
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
for (SkillType type : SkillType.values()) { for (SkillType type : SkillType.nonChildSkills()) {
if (type.isChildSkill()) {
continue;
}
powerLevel += profile.getSkillLevel(type); powerLevel += profile.getSkillLevel(type);
} }
@@ -441,13 +421,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static int getLevelCap(String skillType) { public static int getLevelCap(String skillType) {
SkillType skill = SkillType.getSkill(skillType); return Config.getInstance().getLevelCap(getSkillType(skillType));
if (skill == null) {
throw new InvalidSkillException();
}
return Config.getInstance().getLevelCap(skill);
} }
/** /**
@@ -473,13 +447,7 @@ public final class ExperienceAPI {
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
*/ */
public static void setLevel(Player player, String skillType, int skillLevel) { public static void setLevel(Player player, String skillType, int skillLevel) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().modifySkill(getSkillType(skillType), skillLevel);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().modifySkill(skill, skillLevel);
} }
/** /**
@@ -495,13 +463,7 @@ public final class ExperienceAPI {
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
*/ */
public static void setLevelOffline(String playerName, String skillType, int skillLevel) { public static void setLevelOffline(String playerName, String skillType, int skillLevel) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).modifySkill(getSkillType(skillType), skillLevel);
if (skill == null) {
throw new InvalidSkillException();
}
getOfflineProfile(playerName).modifySkill(skill, skillLevel);
} }
/** /**
@@ -514,15 +476,10 @@ public final class ExperienceAPI {
* @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 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) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().setSkillXpLevel(getNonChildSkillType(skillType), newValue);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().setSkillXpLevel(skill, newValue);
} }
/** /**
@@ -536,15 +493,10 @@ public final class ExperienceAPI {
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void setXPOffline(String playerName, String skillType, int newValue) { public static void setXPOffline(String playerName, String skillType, int newValue) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).setSkillXpLevel(getNonChildSkillType(skillType), newValue);
if (skill == null) {
throw new InvalidSkillException();
}
getOfflineProfile(playerName).setSkillXpLevel(skill, newValue);
} }
/** /**
@@ -557,15 +509,10 @@ public final class ExperienceAPI {
* @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 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) {
SkillType skill = SkillType.getSkill(skillType); UserManager.getPlayer(player).getProfile().removeXp(getNonChildSkillType(skillType), xp);
if (skill == null) {
throw new InvalidSkillException();
}
UserManager.getPlayer(player).getProfile().removeXp(skill, xp);
} }
/** /**
@@ -579,24 +526,14 @@ public final class ExperienceAPI {
* *
* @throws InvalidSkillException if the given skill is not valid * @throws InvalidSkillException if the given skill is not valid
* @throws InvalidPlayerException if the given player does not exist in the database * @throws InvalidPlayerException if the given player does not exist in the database
* @throws UnsupportedOperationException if the given skill is a child skill
*/ */
public static void removeXPOffline(String playerName, String skillType, int xp) { public static void removeXPOffline(String playerName, String skillType, int xp) {
SkillType skill = SkillType.getSkill(skillType); getOfflineProfile(playerName).removeXp(getNonChildSkillType(skillType), xp);
if (skill == null) {
throw new InvalidSkillException();
}
getOfflineProfile(playerName).removeXp(skill, xp);
} }
/** // Utility methods follow.
* Add XP to an offline player.
*
* @param playerName The player to check
* @param skillType The skill to check
* @param XP The amount of XP to award.
*/
private static void addOfflineXP(String playerName, SkillType skill, int XP) { private static void addOfflineXP(String playerName, SkillType skill, int XP) {
PlayerProfile profile = getOfflineProfile(playerName); PlayerProfile profile = getOfflineProfile(playerName);
@@ -616,7 +553,7 @@ public final class ExperienceAPI {
} }
private static PlayerProfile getOfflineProfile(String playerName) { private static PlayerProfile getOfflineProfile(String playerName) {
PlayerProfile profile = new PlayerProfile(playerName, false); PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false);
if (!profile.isLoaded()) { if (!profile.isLoaded()) {
throw new InvalidPlayerException(); throw new InvalidPlayerException();
@@ -624,4 +561,24 @@ public final class ExperienceAPI {
return profile; return profile;
} }
private static SkillType getSkillType(String skillType) throws InvalidSkillException {
SkillType skill = SkillType.getSkill(skillType);
if (skill == null) {
throw new InvalidSkillException();
}
return skill;
}
private static SkillType getNonChildSkillType(String skillType) throws InvalidSkillException, UnsupportedOperationException {
SkillType skill = getSkillType(skillType);
if (skill.isChildSkill()) {
throw new UnsupportedOperationException("Child skills do not have XP");
}
return skill;
}
} }

View File

@@ -77,14 +77,13 @@ public final class PartyAPI {
*/ */
public static void addToParty(Player player, String partyName) { public static void addToParty(Player player, String partyName) {
Party party = PartyManager.getParty(partyName); Party party = PartyManager.getParty(partyName);
String playerName = player.getName();
if (party == null) { if (party == null) {
party = new Party(); party = new Party(playerName, partyName);
party.setName(partyName);
party.setLeader(player.getName());
} }
PartyManager.addToParty(player, UserManager.getPlayer(player), party); PartyManager.addToParty(playerName, UserManager.getPlayer(player), party);
} }
/** /**

View File

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

View File

@@ -1,78 +1,51 @@
package com.gmail.nossr50.chat; package com.gmail.nossr50.chat;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.events.chat.McMMOChatEvent;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOAdminChatEvent;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
public final class ChatManager { public abstract class ChatManager {
public ChatManager () {} protected Plugin plugin;
protected boolean useDisplayNames;
protected String chatPrefix;
public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message, boolean isAsync) { protected String displayName;
McMMOAdminChatEvent chatEvent = new McMMOAdminChatEvent(plugin, playerName, displayName, message, isAsync); protected String message;
mcMMO.p.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) { protected ChatManager(Plugin plugin, boolean useDisplayNames, String chatPrefix) {
this.plugin = plugin;
this.useDisplayNames = useDisplayNames;
this.chatPrefix = chatPrefix;
}
protected void handleChat(McMMOChatEvent event) {
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return; return;
} }
if (Config.getInstance().getAdminDisplayNames()) { displayName = useDisplayNames ? event.getDisplayName() : event.getSender();
displayName = chatEvent.getDisplayName(); message = LocaleLoader.getString(chatPrefix, displayName) + event.getMessage();
}
else {
displayName = chatEvent.getSender();
}
String adminMessage = chatEvent.getMessage(); sendMessage();
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(String senderName, String message) {
handleAdminChat(plugin, senderName, senderName, message); handleChat(senderName, senderName, message, false);
} }
public static void handleAdminChat(Plugin plugin, String playerName, String displayName, String message) { public void handleChat(Player player, String message, boolean isAsync) {
handleAdminChat(plugin, playerName, displayName, message, false); handleChat(player.getName(), player.getDisplayName(), message, isAsync);
} }
public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message, boolean isAsync) { public void handleChat(String senderName, String displayName, String message) {
String partyName = party.getName(); handleChat(senderName, displayName, message, false);
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(plugin, playerName, displayName, partyName, message, isAsync);
mcMMO.p.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return;
}
if (Config.getInstance().getPartyDisplayNames()) {
displayName = chatEvent.getDisplayName();
}
else {
displayName = chatEvent.getSender();
}
String partyMessage = chatEvent.getMessage();
for (Player member : party.getOnlineMembers()) {
member.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Prefix", displayName) + partyMessage);
}
mcMMO.p.getLogger().info("[P](" + partyName + ")" + "<" + ChatColor.stripColor(displayName) + "> " + partyMessage);
} }
public static void handlePartyChat(Plugin plugin, Party party, String senderName, String message) { public abstract void handleChat(String senderName, String displayName, String message, boolean isAsync);
handlePartyChat(plugin, party, senderName, senderName, message);
}
public static void handlePartyChat(Plugin plugin, Party party, String playerName, String displayName, String message) { protected abstract void sendMessage();
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,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,13 +28,13 @@ 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(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
} }
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "gjmcferrin@gmail.com" + ChatColor.GOLD + " Paypal");
} }
sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion())); sender.sendMessage(LocaleLoader.getString("MOTD.Version", mcMMO.p.getDescription().getVersion()));
@@ -62,52 +62,52 @@ public class McmmoCommand implements CommandExecutor {
private void displayPartyCommands(CommandSender sender) { private void displayPartyCommands(CommandSender sender) {
if (Permissions.party(sender)) { if (Permissions.party(sender)) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Commands")); sender.sendMessage(LocaleLoader.getString("Commands.Party.Commands"));
sender.sendMessage("/party create <" + LocaleLoader.getString("Commands.Usage.PartyName") + "> " + LocaleLoader.getString("Commands.Party1")); sender.sendMessage(" /party create <" + LocaleLoader.getString("Commands.Usage.PartyName") + "> " + LocaleLoader.getString("Commands.Party1"));
sender.sendMessage("/party join <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party2")); sender.sendMessage(" /party join <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party2"));
sender.sendMessage("/party quit " + LocaleLoader.getString("Commands.Party.Quit")); sender.sendMessage(" /party quit " + LocaleLoader.getString("Commands.Party.Quit"));
if (Permissions.partyChat(sender)) { if (Permissions.partyChat(sender)) {
sender.sendMessage("/party chat " + LocaleLoader.getString("Commands.Party.Toggle")); sender.sendMessage(" /party chat " + LocaleLoader.getString("Commands.Party.Toggle"));
} }
sender.sendMessage("/party invite <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party.Invite")); sender.sendMessage(" /party invite <" + LocaleLoader.getString("Commands.Usage.Player") + "> " + LocaleLoader.getString("Commands.Party.Invite"));
sender.sendMessage("/party accept " + LocaleLoader.getString("Commands.Party.Accept")); sender.sendMessage(" /party accept " + LocaleLoader.getString("Commands.Party.Accept"));
if (Permissions.partySubcommand(sender, PartySubcommandType.TELEPORT)) { if (Permissions.partySubcommand(sender, PartySubcommandType.TELEPORT)) {
sender.sendMessage("/party teleport " + LocaleLoader.getString("Commands.Party.Teleport")); sender.sendMessage(" /party teleport " + LocaleLoader.getString("Commands.Party.Teleport"));
} }
} }
} }
private void displayOtherCommands(CommandSender sender) { private void displayOtherCommands(CommandSender sender) {
sender.sendMessage(LocaleLoader.getString("Commands.Other")); sender.sendMessage(LocaleLoader.getString("Commands.Other"));
sender.sendMessage("/mcstats " + LocaleLoader.getString("Commands.Stats")); sender.sendMessage(" /mcstats " + LocaleLoader.getString("Commands.Stats"));
sender.sendMessage("/mctop " + LocaleLoader.getString("Commands.Leaderboards")); sender.sendMessage(" /mctop " + LocaleLoader.getString("Commands.Leaderboards"));
if (Permissions.skillreset(sender)) { if (Permissions.skillreset(sender)) {
sender.sendMessage("/skillreset <skill|all> " + LocaleLoader.getString("Commands.Reset")); sender.sendMessage(" /skillreset <skill|all> " + LocaleLoader.getString("Commands.Reset"));
} }
if (Permissions.mcability(sender)) { if (Permissions.mcability(sender)) {
sender.sendMessage("/mcability " + LocaleLoader.getString("Commands.ToggleAbility")); sender.sendMessage(" /mcability " + LocaleLoader.getString("Commands.ToggleAbility"));
} }
if (Permissions.adminChat(sender)) { if (Permissions.adminChat(sender)) {
sender.sendMessage("/adminchat " + LocaleLoader.getString("Commands.AdminToggle")); sender.sendMessage(" /adminchat " + LocaleLoader.getString("Commands.AdminToggle"));
} }
if (Permissions.inspect(sender)) { if (Permissions.inspect(sender)) {
sender.sendMessage("/inspect " + LocaleLoader.getString("Commands.Inspect")); sender.sendMessage(" /inspect " + LocaleLoader.getString("Commands.Inspect"));
} }
if (Permissions.mmoedit(sender)) { if (Permissions.mmoedit(sender)) {
sender.sendMessage("/mmoedit " + LocaleLoader.getString("Commands.mmoedit")); sender.sendMessage(" /mmoedit " + LocaleLoader.getString("Commands.mmoedit"));
} }
if (Permissions.mcgod(sender)) { if (Permissions.mcgod(sender)) {
sender.sendMessage("/mcgod " + LocaleLoader.getString("Commands.mcgod")); sender.sendMessage(" /mcgod " + LocaleLoader.getString("Commands.mcgod"));
} }
sender.sendMessage(LocaleLoader.getString("Commands.SkillInfo")); sender.sendMessage(" /<skill>" + LocaleLoader.getString("Commands.SkillInfo"));
} }
} }

View File

@@ -5,6 +5,7 @@ import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -17,7 +18,7 @@ public class McnotifyCommand implements TabExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 0: case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On"))); sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On")));
mcMMOPlayer.toggleChatNotifications(); mcMMOPlayer.toggleChatNotifications();

View File

@@ -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

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

View File

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

View File

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

View File

@@ -6,8 +6,12 @@ import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.ChatMode; import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -18,10 +22,12 @@ import com.google.common.collect.ImmutableList;
public abstract class ChatCommand implements TabExecutor { public abstract class ChatCommand implements TabExecutor {
protected ChatMode chatMode; protected ChatMode chatMode;
protected ChatManager chatManager;
private McMMOPlayer mcMMOPlayer; private McMMOPlayer mcMMOPlayer;
public ChatCommand(ChatMode chatMode) { public ChatCommand(ChatMode chatMode) {
this.chatMode = chatMode; this.chatMode = chatMode;
this.chatManager = ChatManagerFactory.getChatManager(mcMMO.p, chatMode);
} }
@Override @Override
@@ -32,7 +38,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
if (chatMode.isEnabled(mcMMOPlayer)) { if (chatMode.isEnabled(mcMMOPlayer)) {
disableChatMode(sender); disableChatMode(sender);
@@ -49,7 +55,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
enableChatMode(sender); enableChatMode(sender);
return true; return true;
@@ -60,7 +66,7 @@ public abstract class ChatCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); mcMMOPlayer = UserManager.getPlayer((Player) sender);
disableChatMode(sender); disableChatMode(sender);
return true; return true;
@@ -96,6 +102,10 @@ public abstract class ChatCommand implements TabExecutor {
return builder.toString(); return builder.toString();
} }
protected String getDisplayName(CommandSender sender) {
return (sender instanceof Player) ? ((Player) sender).getDisplayName() : LocaleLoader.getString("Commands.Chat.Console");
}
protected abstract void handleChatSending(CommandSender sender, String[] args); protected abstract void handleChatSending(CommandSender sender, String[] args);
private void enableChatMode(CommandSender sender) { private void enableChatMode(CommandSender sender) {

View File

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

View File

@@ -9,18 +9,12 @@ import org.bukkit.command.TabExecutor;
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.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
public class McpurgeCommand implements TabExecutor { public class McpurgeCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mcpurge(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
switch (args.length) { switch (args.length) {
case 0: case 0:
mcMMO.getDatabaseManager().purgePowerlessUsers(); mcMMO.getDatabaseManager().purgePowerlessUsers();

View File

@@ -10,9 +10,7 @@ import org.bukkit.command.TabExecutor;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
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.commands.CommandUtils; import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
@@ -21,14 +19,9 @@ import com.google.common.collect.ImmutableList;
public class McremoveCommand implements TabExecutor { public class McremoveCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mcremove(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
switch (args.length) { switch (args.length) {
case 1: case 1:
if (UserManager.getPlayer(args[0]) == null && CommandUtils.unloadedProfile(sender, new PlayerProfile(args[0], false))) { if (UserManager.getPlayer(args[0]) == null && CommandUtils.unloadedProfile(sender, mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false))) {
return true; return true;
} }

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

@@ -9,47 +9,130 @@ 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;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
public class MmoupdateCommand implements TabExecutor { public class MmoupdateCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!Permissions.mmoupdate(sender)) {
sender.sendMessage(command.getPermissionMessage());
return true;
}
if (!Config.getInstance().getUseMySQL()) {
sender.sendMessage("SQL Mode is not enabled."); // TODO: Localize
return true;
}
switch (args.length) { switch (args.length) {
case 0: case 1:
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Start")); String argType = args[0];
String oldType = validateName(sender, args[0]);
if (oldType == null) {
return true;
}
String newType = getCurrentDb();
if (newType.equals(oldType)) {
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Same", argType));
return true;
}
DatabaseManager oldDb;
if (oldType == "sql") {
oldDb = DatabaseManagerFactory.createSQLDatabaseManager();
}
else if (oldType == "flatfile") {
oldDb = DatabaseManagerFactory.createFlatfileDatabaseManager();
}
else try {
@SuppressWarnings("unchecked")
Class<? extends DatabaseManager> clazz = (Class<? extends DatabaseManager>) Class.forName(oldType);
oldDb = DatabaseManagerFactory.createCustomDatabaseManager((Class<? extends DatabaseManager>) clazz);
oldType = clazz.getSimpleName(); // For pretty-printing; we have the database now
}
catch (Throwable e) {
return false;
}
sender.sendMessage(LocaleLoader.getString("Commands.mmoupdate.Start", oldType, newType));
// Convert the online players right away, without waiting
// first, flush out the current data
UserManager.saveAll(); UserManager.saveAll();
UserManager.clearAll(); UserManager.clearAll();
new SQLConversionTask().runTaskLaterAsynchronously(mcMMO.p, 1);
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;
}
/**
* @return null - if type not recognized / class not found
* empty string - if type is same as current
* normalized string - if type is recognized
*/
private String validateName(CommandSender sender, String type) {
if (type.equalsIgnoreCase("sql") || type.equalsIgnoreCase("mysql")) {
return "sql";
}
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 @Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of(); Class<?> clazz = DatabaseManagerFactory.getCustomDatabaseManagerClass();
if (clazz != null) {
return ImmutableList.of("flatfile", "sql", clazz.getName());
}
return ImmutableList.of("flatfile", "sql");
} }
} }

View File

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

View File

@@ -10,6 +10,7 @@ import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
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;
@@ -46,8 +47,8 @@ public abstract class ExperienceCommand implements TabExecutor {
return true; return true;
} }
mcMMOPlayer = UserManager.getPlayer(sender.getName()); player = (Player) sender;
player = mcMMOPlayer.getPlayer(); mcMMOPlayer = UserManager.getPlayer(player);
profile = mcMMOPlayer.getProfile(); profile = mcMMOPlayer.getProfile();
editValues(); editValues();
@@ -68,7 +69,7 @@ public abstract class ExperienceCommand implements TabExecutor {
// 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 (CommandUtils.unloadedProfile(sender, profile)) { if (CommandUtils.unloadedProfile(sender, profile)) {
return true; return true;

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.party;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -13,7 +14,7 @@ public class PartyChangePasswordCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
switch (args.length) { switch (args.length) {
case 1: case 1:

View File

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

View File

@@ -19,8 +19,8 @@ public class PartyCreateCommand implements CommandExecutor {
case 3: case 3:
Party newParty = PartyManager.getParty(args[1]); Party newParty = PartyManager.getParty(args[1]);
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
// Check to see if the party exists, and if it does cancel creating a new party // Check to see if the party exists, and if it does cancel creating a new party
if (PartyManager.checkPartyExistence(player, newParty, args[1])) { if (PartyManager.checkPartyExistence(player, newParty, args[1])) {

View File

@@ -16,7 +16,7 @@ public class PartyDisbandCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 1: case 1:
Party playerParty = UserManager.getPlayer(sender.getName()).getParty(); Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String partyName = playerParty.getName(); String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) { for (Player member : playerParty.getOnlineMembers()) {

View File

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

View File

@@ -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:

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.party;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
@@ -15,7 +16,7 @@ public class PartyLockCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
playerParty = UserManager.getPlayer(sender.getName()).getParty(); playerParty = UserManager.getPlayer((Player) sender).getParty();
switch (args.length) { switch (args.length) {
case 1: case 1:

View File

@@ -17,7 +17,7 @@ public class PartyRenameCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) { switch (args.length) {
case 2: case 2:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
Party playerParty = mcMMOPlayer.getParty(); Party playerParty = mcMMOPlayer.getParty();
String oldPartyName = playerParty.getName(); String oldPartyName = playerParty.getName();

View File

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

View File

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

View File

@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.bukkit.ChatColor;
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;
@@ -52,15 +51,19 @@ public class PtpCommand implements TabExecutor {
return ptpAcceptAnyCommand.onCommand(sender, command, label, args); return ptpAcceptAnyCommand.onCommand(sender, command, label, args);
} }
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); Player player = (Player) sender;
Player player = mcMMOPlayer.getPlayer(); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
long recentlyHurt = mcMMOPlayer.getRecentlyHurt(); long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int recentlyhurt_cooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown(); int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)) { if (hurtCooldown > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
return true;
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return true;
}
} }
if (args[0].equalsIgnoreCase("accept")) { if (args[0].equalsIgnoreCase("accept")) {
@@ -75,9 +78,13 @@ public class PtpCommand implements TabExecutor {
int ptpCooldown = Config.getInstance().getPTPCommandCooldown(); int ptpCooldown = Config.getInstance().getPTPCommandCooldown();
long lastTeleport = mcMMOPlayer.getLastTeleport(); long lastTeleport = mcMMOPlayer.getLastTeleport();
if (!SkillUtils.cooldownOver(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player)) { if (ptpCooldown > 0) {
player.sendMessage(ChatColor.RED + "You need to wait before you can use this again! " + ChatColor.YELLOW + "(" + SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player) + ")"); //TODO Locale! int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, ptpCooldown, player);
return true;
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Generic.Wait", timeRemaining));
return true;
}
} }
sendTeleportRequest(sender, player, args[0]); sendTeleportRequest(sender, player, args[0]);
@@ -166,7 +173,7 @@ public class PtpCommand implements TabExecutor {
mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer); mcMMOPlayer.actualizeTeleportCommenceLocation(teleportingPlayer);
if (warmup > 0) { if (warmup > 0) {
teleportingPlayer.sendMessage(ChatColor.GRAY + "Commencing teleport in " + ChatColor.GOLD + "(" + warmup + ")" + ChatColor.GRAY + " seconds, please stand still..."); //TODO Locale! teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup));
new TeleportationWarmup(mcMMOPlayer, mcMMOTarget).runTaskLater(mcMMO.p, 20 * warmup); new TeleportationWarmup(mcMMOPlayer, mcMMOTarget).runTaskLater(mcMMO.p, 20 * warmup);
} }
else { else {

View File

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

View File

@@ -10,6 +10,7 @@ import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil; import org.bukkit.util.StringUtil;
import com.gmail.nossr50.mcMMO;
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.datatypes.player.PlayerProfile;
@@ -35,7 +36,7 @@ public class InspectCommand implements TabExecutor {
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process. // If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) { if (mcMMOPlayer == null) {
PlayerProfile profile = new PlayerProfile(args[0], false); // Temporary Profile PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(args[0], false); // Temporary Profile
if (CommandUtils.inspectOffline(sender, profile, Permissions.inspectOffline(sender))) { if (CommandUtils.inspectOffline(sender, profile, Permissions.inspectOffline(sender))) {
return true; return true;
@@ -69,7 +70,13 @@ public class InspectCommand implements TabExecutor {
else { else {
Player target = mcMMOPlayer.getPlayer(); Player target = mcMMOPlayer.getPlayer();
if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) { if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) {
if (!Permissions.inspectOffline(sender)) {
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
return true;
}
}
else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) {
return true; return true;
} }

View File

@@ -13,7 +13,6 @@ 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.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask; import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask;
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;
@@ -61,7 +60,7 @@ public class McrankCommand implements TabExecutor {
return true; return true;
} }
} }
else if (CommandUtils.inspectOffline(sender, new PlayerProfile(playerName, false), Permissions.mcrankOffline(sender))) { else if (CommandUtils.inspectOffline(sender, mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false), Permissions.mcrankOffline(sender))) {
return true; return true;
} }

View File

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

View File

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

View File

@@ -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;
@@ -22,6 +25,7 @@ public class FishingCommand extends SkillCommand {
private boolean canShake; private boolean canShake;
private boolean canFishermansDiet; private boolean canFishermansDiet;
private boolean canMasterAngler; private boolean canMasterAngler;
private boolean canIceFish;
public FishingCommand() { public FishingCommand() {
super(SkillType.FISHING); super(SkillType.FISHING);
@@ -60,7 +64,18 @@ public class FishingCommand extends SkillCommand {
// MASTER ANGLER // MASTER ANGLER
if (canMasterAngler) { if (canMasterAngler) {
biteChance = calculateAbilityDisplayValues(((Math.max((skillValue / 200.0), 1.0)) / (isStorming ? 300 : 500)) * 100.0)[0]; 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];
} }
} }
@@ -71,11 +86,12 @@ public class FishingCommand extends SkillCommand {
canShake = Permissions.shake(player); canShake = Permissions.shake(player);
canFishermansDiet = Permissions.fishermansDiet(player); canFishermansDiet = Permissions.fishermansDiet(player);
canMasterAngler = Permissions.masterAngler(player); canMasterAngler = Permissions.masterAngler(player);
canIceFish = Permissions.iceFishing(player);
} }
@Override @Override
protected boolean effectsHeaderPermissions() { protected boolean effectsHeaderPermissions() {
return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet; return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet || canIceFish;
} }
@Override @Override
@@ -101,11 +117,15 @@ public class FishingCommand extends SkillCommand {
if (canMasterAngler) { if (canMasterAngler) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.8"), LocaleLoader.getString("Fishing.Effect.9"))); player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.8"), LocaleLoader.getString("Fishing.Effect.9")));
} }
if (canIceFish) {
player.sendMessage(LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Fishing.Effect.10"), LocaleLoader.getString("Fishing.Effect.11")));
}
} }
@Override @Override
protected boolean statsHeaderPermissions() { protected boolean statsHeaderPermissions() {
return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet; return canTreasureHunt || canMagicHunt || canShake || canMasterAngler || canFishermansDiet || canIceFish;
} }
@Override @Override
@@ -136,5 +156,16 @@ public class FishingCommand extends SkillCommand {
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

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

View File

@@ -3,6 +3,7 @@ package com.gmail.nossr50.commands.spout;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor; import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
@@ -22,12 +23,12 @@ public abstract class SpoutCommand implements TabExecutor {
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;
} }
playerProfile = UserManager.getPlayer(sender.getName()).getProfile(); playerProfile = UserManager.getPlayer((Player) sender).getProfile();
spoutHud = playerProfile.getSpoutHud(); spoutHud = playerProfile.getSpoutHud();
if (spoutHud == null) { if (spoutHud == null) {

View File

@@ -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

@@ -66,7 +66,7 @@ public class Config extends AutoUpdateConfigLoader {
public int getMcrankScoreboardTime() { return config.getInt("Scoreboards.Mcrank.Display_Time", 10); } public int getMcrankScoreboardTime() { return config.getInt("Scoreboards.Mcrank.Display_Time", 10); }
public boolean getMcstatsScoreboardsEnabled() { return config.getBoolean("Scoreboards.Mcstats.Use", true); } public boolean getMcstatsScoreboardsEnabled() { return config.getBoolean("Scoreboards.Mcstats.Use", true); }
public int getMcstatsScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); } public int getMcstatsScoreboardTime() { return config.getInt("Scoreboards.Mcstats.Display_Time", 10); }
public boolean getMctopScoreboardEnabled() { return config.getBoolean("Scoreboards.Mctop.Use", true); } public boolean getMctopScoreboardEnabled() { return config.getBoolean("Scoreboards.Mctop.Use", true); }
public int getMctopScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); } public int getMctopScoreboardTime() { return config.getInt("Scoreboards.Mctop.Display_Time", 10); }
@@ -77,6 +77,8 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getSkillScoreboardEnabled() { return config.getBoolean("Scoreboards.Skillname.Use", true); } public boolean getSkillScoreboardEnabled() { return config.getBoolean("Scoreboards.Skillname.Use", true); }
public int getSkillScoreboardTime() { return config.getInt("Scoreboards.Skillname.Display_Time", 10); } 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); }
@@ -147,6 +149,7 @@ public class Config extends AutoUpdateConfigLoader {
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 boolean getLevelUpEffectsEnabled() { return config.getBoolean("Particles.LevelUp_Enabled", true); }
public int getLevelUpEffectsTier() { return config.getInt("Particles.LevelUp_Tier", 100); } 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); }
@@ -166,6 +169,9 @@ public class Config extends AutoUpdateConfigLoader {
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
*/ */
@@ -272,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); }
@@ -285,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.Modifier." + StringUtils.getCapitalized(skill.toString())); } public double getFormulaSkillModifier(SkillType skill) { return config.getDouble("Experience.Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
} }

View File

@@ -57,7 +57,7 @@ public abstract class ConfigLoader {
OutputStream outputStream = null; OutputStream outputStream = null;
try { try {
outputStream = new FileOutputStream(configFile); outputStream = new FileOutputStream(configFile);
int read; int read;
byte[] bytes = new byte[1024]; byte[] bytes = new byte[1024];

View File

@@ -1,5 +1,7 @@
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;
@@ -34,7 +36,14 @@ public class SpoutConfig extends ConfigLoader {
} }
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); }
@@ -57,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

@@ -117,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);
} }
@@ -442,13 +442,10 @@ public class TreasureConfig extends ConfigLoader {
} }
private boolean noErrorsInTreasure(List<String> issues) { private boolean noErrorsInTreasure(List<String> issues) {
if (issues.isEmpty()) {
return true;
}
for (String issue : issues) { for (String issue : issues) {
plugin.getLogger().warning(issue); plugin.getLogger().warning(issue);
} }
return false;
return issues.isEmpty();
} }
} }

View File

@@ -1,63 +1,89 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import java.io.File; import java.util.List;
import java.io.IOException; import java.util.Map;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
public class DatabaseManager { public interface DatabaseManager {
private final mcMMO plugin; // One month in milliseconds
private final boolean isUsingSQL; public final long PURGE_TIME = 2630000000L * Config.getInstance().getOldUsersCutoff();
private File usersFile;
public DatabaseManager(final mcMMO plugin, final boolean isUsingSQL) { /**
this.plugin = plugin; * Purge users with 0 power level from the database.
this.isUsingSQL = isUsingSQL; */
public void purgePowerlessUsers();
if (isUsingSQL) { /**
SQLDatabaseManager.checkConnected(); * Purge users who haven't logged on in over a certain time frame from the database.
SQLDatabaseManager.createStructure(); */
} public void purgeOldUsers();
else {
usersFile = new File(mcMMO.getUsersFilePath());
createFlatfileDatabase();
FlatfileDatabaseManager.updateLeaderboards();
}
}
public void purgePowerlessUsers() { /**
plugin.getLogger().info("Purging powerless users..."); * Remove a user from the database.
plugin.getLogger().info("Purged " + (isUsingSQL ? SQLDatabaseManager.purgePowerlessSQL() : FlatfileDatabaseManager.purgePowerlessFlatfile()) + " users from the database."); *
} * @param playerName The name of the user to remove
* @return true if the user was successfully removed, false otherwise
*/
public boolean removeUser(String playerName);
public void purgeOldUsers() { /**
plugin.getLogger().info("Purging old users..."); * Save a user to the database.
plugin.getLogger().info("Purged " + (isUsingSQL ? SQLDatabaseManager.purgeOldSQL() : FlatfileDatabaseManager.removeOldFlatfileUsers()) + " users from the database."); *
} * @param profile The profile of the player to save
*/
public void saveUser(PlayerProfile profile);
public boolean removeUser(String playerName) { /**
if (isUsingSQL ? SQLDatabaseManager.removeUserSQL(playerName) : FlatfileDatabaseManager.removeFlatFileUser(playerName)) { * Retrieve leaderboard info.
Misc.profileCleanup(playerName); *
return true; * @param skillName The skill to retrieve info on
} * @param pageNumber Which page in the leaderboards to retrieve
* @param statsPerPage The number of stats per page
* @return the requested leaderboard information
*/
public List<PlayerStat> readLeaderboard(String skillName, int pageNumber, int statsPerPage);
return false; /**
} * Retrieve rank info.
*
* @param playerName The name of the user to retrieve the rankings for
* @return the requested rank information
*/
public Map<String, Integer> readRank(String playerName);
private void createFlatfileDatabase() { /**
if (usersFile.exists()) { * Add a new user to the database.
return; *
} * @param playerName The name of the player to be added to the database
*/
public void newUser(String playerName);
usersFile.getParentFile().mkdir(); /**
* Load a player from the database.
*
* @param playerName The name of the player to load from the database
* @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
*/
public PlayerProfile loadPlayerProfile(String playerName, boolean createNew);
try { /**
plugin.debug("Creating mcmmo.users file..."); * Get all users currently stored in the database.
new File(mcMMO.getUsersFilePath()).createNewFile(); *
} * @return list of playernames
catch (IOException e) { */
e.printStackTrace(); public List<String> getStoredUsers();
}
} /**
* Convert all users from this database to the provided database using
* {@link #saveUser(PlayerProfile)}.
*
* @param the DatabaseManager to save to
*/
public void convertUsers(DatabaseManager destination);
} }

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

@@ -1,6 +1,9 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
@@ -11,26 +14,448 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.util.Misc;
public final class FlatfileDatabaseManager { public final class FlatfileDatabaseManager implements DatabaseManager {
private static HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>(); private final HashMap<SkillType, List<PlayerStat>> playerStatHash = new HashMap<SkillType, List<PlayerStat>>();
private static List<PlayerStat> powerLevels = new ArrayList<PlayerStat>(); private final List<PlayerStat> powerLevels = new ArrayList<PlayerStat>();
private static long lastUpdate = 0; private long lastUpdate = 0;
private static final long UPDATE_WAIT_TIME = 600000L; // 10 minutes private final long UPDATE_WAIT_TIME = 600000L; // 10 minutes
private static final long ONE_MONTH = 2630000000L; private final File usersFile;
private static final Object fileWritingLock = new Object();
private FlatfileDatabaseManager() {} 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. * Update the leader boards.
*/ */
public static void updateLeaderboards() { private void updateLeaderboards() {
// Only update FFS leaderboards every 10 minutes.. this puts a lot of strain on the server (depending on the size of the database) and should not be done frequently // Only update FFS leaderboards every 10 minutes.. this puts a lot of strain on the server (depending on the size of the database) and should not be done frequently
if (System.currentTimeMillis() < lastUpdate + UPDATE_WAIT_TIME) { if (System.currentTimeMillis() < lastUpdate + UPDATE_WAIT_TIME) {
return; return;
@@ -41,57 +466,63 @@ public final class FlatfileDatabaseManager {
powerLevels.clear(); // Clear old values from the power levels powerLevels.clear(); // Clear old values from the power levels
// Initialize lists // Initialize lists
List<PlayerStat> mining = new ArrayList<PlayerStat>(); List<PlayerStat> mining = new ArrayList<PlayerStat>();
List<PlayerStat> woodcutting = new ArrayList<PlayerStat>(); List<PlayerStat> woodcutting = new ArrayList<PlayerStat>();
List<PlayerStat> herbalism = new ArrayList<PlayerStat>(); List<PlayerStat> herbalism = new ArrayList<PlayerStat>();
List<PlayerStat> excavation = new ArrayList<PlayerStat>(); List<PlayerStat> excavation = new ArrayList<PlayerStat>();
List<PlayerStat> acrobatics = new ArrayList<PlayerStat>(); List<PlayerStat> acrobatics = new ArrayList<PlayerStat>();
List<PlayerStat> repair = new ArrayList<PlayerStat>(); List<PlayerStat> repair = new ArrayList<PlayerStat>();
List<PlayerStat> swords = new ArrayList<PlayerStat>(); List<PlayerStat> swords = new ArrayList<PlayerStat>();
List<PlayerStat> axes = new ArrayList<PlayerStat>(); List<PlayerStat> axes = new ArrayList<PlayerStat>();
List<PlayerStat> archery = new ArrayList<PlayerStat>(); List<PlayerStat> archery = new ArrayList<PlayerStat>();
List<PlayerStat> unarmed = new ArrayList<PlayerStat>(); List<PlayerStat> unarmed = new ArrayList<PlayerStat>();
List<PlayerStat> taming = new ArrayList<PlayerStat>(); List<PlayerStat> taming = new ArrayList<PlayerStat>();
List<PlayerStat> fishing = new ArrayList<PlayerStat>(); List<PlayerStat> fishing = new ArrayList<PlayerStat>();
BufferedReader in = null;
// Read from the FlatFile database and fill our arrays with information // Read from the FlatFile database and fill our arrays with information
try { synchronized (fileWritingLock) {
BufferedReader in = new BufferedReader(new FileReader(usersFilePath)); try {
String line = ""; in = new BufferedReader(new FileReader(usersFilePath));
ArrayList<String> players = new ArrayList<String>(); String line = "";
ArrayList<String> players = new ArrayList<String>();
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
String[] data = line.split(":"); String[] data = line.split(":");
String playerName = data[0];
int powerLevel = 0;
String playerName = data[0]; // Prevent the same player from being added multiple times (I'd like to note that this shouldn't happen...)
int powerLevel = 0; if (players.contains(playerName)) {
continue;
}
// Prevent the same player from being added multiple times (I'd like to note that this shouldn't happen...) players.add(playerName);
if (players.contains(playerName)) {
continue; 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);
} }
players.add(playerName);
powerLevel += loadStat(mining, playerName, data, 1);
powerLevel += loadStat(woodcutting, playerName, data, 5);
powerLevel += loadStat(repair, playerName, data, 7);
powerLevel += loadStat(unarmed, playerName, data, 8);
powerLevel += loadStat(herbalism, playerName, data, 9);
powerLevel += loadStat(excavation, playerName, data, 10);
powerLevel += loadStat(archery, playerName, data, 11);
powerLevel += loadStat(swords, playerName, data, 12);
powerLevel += loadStat(axes, playerName, data, 13);
powerLevel += loadStat(acrobatics, playerName, data, 14);
powerLevel += loadStat(taming, playerName, data, 24);
powerLevel += loadStat(fishing, playerName, data, 34);
powerLevels.add(new PlayerStat(playerName, powerLevel));
} }
in.close(); catch (Exception e) {
} mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
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(); SkillComparator c = new SkillComparator();
@@ -125,159 +556,73 @@ public final class FlatfileDatabaseManager {
} }
/** /**
* Retrieve leaderboard info. * Checks that the file is present and valid
*
* @param skillType Skill to retrieve info on.
* @param pageNumber Which page in the leaderboards to retrieve
* @return the requested leaderboard information
*/ */
public static List<PlayerStat> retrieveInfo(String skillType, int pageNumber, int statsPerPage) { private void checkStructure() {
List<PlayerStat> statsList = skillType.equalsIgnoreCase("all") ? powerLevels : playerStatHash.get(SkillType.getSkill(skillType)); if (usersFile.exists()) {
int fromIndex = (Math.max(pageNumber, 1) - 1) * statsPerPage; BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size())); synchronized (fileWritingLock) {
} try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line = "";
public static boolean removeFlatFileUser(String playerName) { while ((line = in.readLine()) != null) {
boolean worked = false; String[] character = line.split(":");
BufferedReader in = null; // If they're valid, rewrite them to the file.
FileWriter out = null; if (character.length >= 37) {
String usersFilePath = mcMMO.getUsersFilePath(); 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 { try {
FileReader file = new FileReader(usersFilePath); mcMMO.p.debug("Creating mcmmo.users file...");
in = new BufferedReader(file); new File(mcMMO.getUsersFilePath()).createNewFile();
StringBuilder writer = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
if (!line.split(":")[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
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) { catch (IOException e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); e.printStackTrace();
} }
finally {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
return worked;
} }
public static int purgePowerlessFlatfile() { private void tryClose(Closeable c) {
mcMMO.p.getLogger().info("Purging powerless users..."); if (c == null) return;
int purgedUsers = 0;
for (PlayerStat stat : powerLevels) {
if (stat.statVal == 0 && !mcMMO.p.getServer().getOfflinePlayer(stat.name).isOnline() && removeFlatFileUser(stat.name)) {
purgedUsers++;
}
}
return purgedUsers;
}
public static int removeOldFlatfileUsers() {
int removedPlayers = 0;
long currentTime = System.currentTimeMillis();
long purgeTime = ONE_MONTH * Config.getInstance().getOldUsersCutoff();
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
try { try {
FileReader file = new FileReader(usersFilePath); c.close();
in = new BufferedReader(file); } catch (IOException e) {
StringBuilder writer = new StringBuilder(); e.printStackTrace();
String line = "";
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
String[] splitLine = line.split(":");
if (splitLine.length > 37) {
if (currentTime - (StringUtils.getLong(line.split(":")[37]) * 1000) <= purgeTime) {
writer.append(line).append("\r\n");
}
else {
mcMMO.p.getLogger().info("User found, removing...");
removedPlayers++;
continue; // Skip the player
}
}
else {
writer.append(line).append("\r\n");
}
}
out = new FileWriter(usersFilePath); // Write out the new file
out.write(writer.toString());
} }
catch (Exception e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
return removedPlayers;
} }
private static Integer getPlayerRank(String playerName, List<PlayerStat> statsList) { private Integer getPlayerRank(String playerName, List<PlayerStat> statsList) {
int currentPos = 1;
if (statsList == null) { if (statsList == null) {
return null; return null;
} }
int currentPos = 1;
for (PlayerStat stat : statsList) { for (PlayerStat stat : statsList) {
if (stat.name.equalsIgnoreCase(playerName)) { if (stat.name.equalsIgnoreCase(playerName)) {
return currentPos; return currentPos;
@@ -289,43 +634,86 @@ public final class FlatfileDatabaseManager {
return null; return null;
} }
public static Map<String, Integer> getPlayerRanks(String playerName) { private int putStat(List<PlayerStat> statList, String playerName, int statValue) {
updateLeaderboards(); statList.add(new PlayerStat(playerName, statValue));
return statValue;
Map<String, Integer> skills = new HashMap<String, Integer>();
for (SkillType skill : SkillType.values()) {
if (skill.isChildSkill()) {
continue;
}
skills.put(skill.name(), getPlayerRank(playerName, playerStatHash.get(skill)));
}
skills.put("ALL", getPlayerRank(playerName, powerLevels));
return skills;
} }
public static List<PlayerStat> getPlayerStats(String skillName) { private class SkillComparator implements Comparator<PlayerStat> {
return (skillName.equalsIgnoreCase("all")) ? powerLevels : playerStatHash.get(SkillType.getSkill(skillName));
}
private static int loadStat(List<PlayerStat> statList, String playerName, String[] data, int dataIndex) {
if (data.length > dataIndex) {
int statValue = Integer.parseInt(data[dataIndex]);
statList.add(new PlayerStat(playerName, statValue));
return statValue;
}
return 0;
}
private static class SkillComparator implements Comparator<PlayerStat> {
@Override @Override
public int compare(PlayerStat o1, PlayerStat o2) { public int compare(PlayerStat o1, PlayerStat o2) {
return (o2.statVal - o1.statVal); return (o2.statVal - o1.statVal);
} }
} }
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

@@ -3,7 +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; MOB_HEALTHBARS,
PARTY_NAMES,
KILL_ORPHANS,
;
} }

View File

@@ -4,14 +4,15 @@ import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler.ShareMode; import com.gmail.nossr50.party.ShareHandler.ShareMode;
public class Party { public class Party {
private LinkedHashSet<String> members = new LinkedHashSet<String>(); private final LinkedHashSet<String> members = new LinkedHashSet<String>();
private String leader; private String leader;
private String name; private String name;
private String password; private String password;
@@ -26,6 +27,30 @@ public class Party {
private boolean shareWoodcuttingDrops = true; private boolean shareWoodcuttingDrops = true;
private boolean shareMiscDrops = true; private boolean shareMiscDrops = true;
public Party(String name) {
this.name = name;
}
public Party(String leader, String name) {
this.leader = leader;
this.name = name;
this.locked = true;
}
public Party(String leader, String name, String password) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = true;
}
public Party(String leader, String name, String password, boolean locked) {
this.leader = leader;
this.name = name;
this.password = password;
this.locked = locked;
}
public LinkedHashSet<String> getMembers() { public LinkedHashSet<String> getMembers() {
return members; return members;
} }
@@ -34,9 +59,10 @@ public class Party {
List<Player> onlineMembers = new ArrayList<Player>(); List<Player> onlineMembers = new ArrayList<Player>();
for (String memberName : members) { for (String memberName : members) {
OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName); Player member = mcMMO.p.getServer().getPlayerExact(memberName);
if (member.isOnline()) {
onlineMembers.add(member.getPlayer()); if (member != null) {
onlineMembers.add(member);
} }
} }
@@ -62,25 +88,24 @@ public class Party {
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 (shareLootDrops) {
shareCategories.add("Loot"); shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Loot"));
} }
if (shareMiningDrops) { if (shareMiningDrops) {
shareCategories.add("Mining"); shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Mining"));
} }
if (shareHerbalismDrops) { if (shareHerbalismDrops) {
shareCategories.add("Herbalism"); shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Herbalism"));
} }
if (shareWoodcuttingDrops) { if (shareWoodcuttingDrops) {
shareCategories.add("Woodcutting"); shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Woodcutting"));
} }
if (shareMiscDrops) { if (shareMiscDrops) {
shareCategories.add("Misc"); shareCategories.add(LocaleLoader.getString("Party.ItemShare.Category.Misc"));
} }
return shareCategories; return shareCategories;
@@ -166,4 +191,28 @@ public class Party {
return; return;
} }
} }
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Party)) {
return false;
}
Party other = (Party) obj;
if ((this.getName() == null) || (other.getName() == null)) {
return false;
}
return this.getName().equals(other.getName());
}
@Override
public int hashCode() {
return super.hashCode();
}
} }

View File

@@ -7,7 +7,6 @@ import java.util.Set;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
@@ -20,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;
@@ -53,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;
@@ -75,11 +75,11 @@ public class McMMOPlayer {
private int lastSalvageClick; private int lastSalvageClick;
private boolean godMode; private boolean godMode;
private Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityMode = new HashMap<AbilityType, Boolean>();
private Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>(); private final Map<AbilityType, Boolean> abilityInformed = new HashMap<AbilityType, Boolean>();
private Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>(); private final Map<ToolType, Boolean> toolMode = new HashMap<ToolType, Boolean>();
private Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>(); private final Map<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>();
private int recentlyHurt; private int recentlyHurt;
private int respawnATS; private int respawnATS;
@@ -89,10 +89,14 @@ public class McMMOPlayer {
private boolean isUsingUnarmed; private boolean isUsingUnarmed;
public McMMOPlayer(Player player) { public McMMOPlayer(Player player) {
this(player, mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), true));
}
public McMMOPlayer(Player player, PlayerProfile profile) {
String playerName = player.getName(); String playerName = player.getName();
this.player = player; this.player = player;
profile = new PlayerProfile(playerName, true); this.profile = profile;
party = PartyManager.getPlayerParty(playerName); party = PartyManager.getPlayerParty(playerName);
/* /*
@@ -182,7 +186,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();
} }
} }
@@ -200,10 +205,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);
} }
/** /**
@@ -220,10 +225,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);
} }
/** /**
@@ -261,10 +266,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);
} }
/** /**
@@ -330,7 +335,7 @@ public class McMMOPlayer {
} }
public void actualizeTeleportCommenceLocation(Player player) { public void actualizeTeleportCommenceLocation(Player player) {
setTeleportCommenceLocation(player.getLocation()); teleportCommence = player.getLocation();
} }
/* /*
@@ -439,11 +444,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);
} }
@@ -502,19 +503,20 @@ public class McMMOPlayer {
* @param xp Experience amount to add * @param xp Experience amount to add
*/ */
public void applyXpGain(SkillType skillType, float xp) { public void applyXpGain(SkillType skillType, float xp) {
if (!Permissions.skillEnabled(player, skillType)) {
return;
}
if (skillType.isChildSkill()) { if (skillType.isChildSkill()) {
Set<SkillType> parentSkills = FamilyTree.getParents(skillType); Set<SkillType> parentSkills = FamilyTree.getParents(skillType);
for (SkillType parentSkill : parentSkills) { for (SkillType parentSkill : parentSkills) {
if (Permissions.skillEnabled(player, parentSkill)) { applyXpGain(parentSkill, xp / parentSkills.size());
applyXpGain(parentSkill, xp / parentSkills.size());
}
} }
return; 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);
@@ -530,7 +532,7 @@ public class McMMOPlayer {
spoutHud.setLastGained(skillType); spoutHud.setLastGained(skillType);
} }
isUsingUnarmed = skillType == SkillType.UNARMED; isUsingUnarmed = (skillType == SkillType.UNARMED);
SkillUtils.xpCheckSkill(skillType, player, profile); SkillUtils.xpCheckSkill(skillType, player, profile);
} }
@@ -563,11 +565,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) {
@@ -579,11 +577,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() {
@@ -611,11 +605,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() {
@@ -647,11 +637,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;
} }
/* /*
@@ -694,15 +680,14 @@ public class McMMOPlayer {
* @return Modified experience * @return Modified experience
*/ */
private float modifyXpGain(SkillType skillType, float xp) { private float modifyXpGain(SkillType skillType, float xp) {
if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() < profile.getSkillLevel(skillType) + 1) || (Config.getInstance().getPowerLevelCap() < getPowerLevel() + 1)) { if (player.getGameMode() == GameMode.CREATIVE || (skillType.getMaxLevel() <= profile.getSkillLevel(skillType)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) {
return 0; return 0;
} }
xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier()); xp = (float) (xp / skillType.getXpModifier() * Config.getInstance().getExperienceGainsGlobalMultiplier());
if (Config.getInstance().getToolModsEnabled()) { if (Config.getInstance().getToolModsEnabled()) {
ItemStack item = player.getItemInHand(); CustomTool tool = ModUtils.getToolFromItemStack(player.getItemInHand());
CustomTool tool = ModUtils.getToolFromItemStack(item);
if (tool != null) { if (tool != null) {
xp *= tool.getXpMultiplier(); xp *= tool.getXpMultiplier();

View File

@@ -1,10 +1,5 @@
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;
@@ -14,18 +9,15 @@ import org.bukkit.scoreboard.Scoreboard;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.MobHealthbarType; import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.skills.AbilityType; import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.spout.huds.HudType; import com.gmail.nossr50.datatypes.spout.huds.HudType;
import com.gmail.nossr50.datatypes.spout.huds.McMMOHud; import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.skills.child.FamilyTree; import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.Misc;
public class PlayerProfile { public class PlayerProfile {
private final String playerName; private final String playerName;
private int userId;
private boolean loaded; private boolean loaded;
/* HUDs */ /* HUDs */
@@ -36,41 +28,48 @@ public class PlayerProfile {
/* Skill Data */ /* Skill Data */
private final Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level 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<SkillType, Float> skillsXp = new HashMap<SkillType, Float>(); // Skill & XP
private final Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); // Ability & Cooldown 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;
hudType = mcMMO.spoutEnabled ? SpoutConfig.getInstance().getDefaultHudType() : HudType.DISABLED; hudType = mcMMO.isSpoutEnabled() ? SpoutConfig.getInstance().getDefaultHudType() : HudType.DISABLED;
mobHealthbarType = Config.getInstance().getMobHealthbarDefault(); mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
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()) {
continue;
}
skills.put(skillType, 0); skills.put(skillType, 0);
skillsXp.put(skillType, 0F); skillsXp.put(skillType, 0F);
} }
}
if (!loadPlayer() && addNew) { public PlayerProfile(String playerName, boolean isLoaded) {
addPlayer(); this(playerName);
loaded = true; this.loaded = isLoaded;
} }
/**
* Calling this constructor is considered loading the profile.
*/
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;
} }
public void save() { public void save() {
if (Config.getInstance().getUseMySQL()) { mcMMO.getDatabaseManager().saveUser(this);
saveMySQL();
}
else {
saveFlatfile();
}
} }
public String getPlayerName() { public String getPlayerName() {
@@ -142,7 +141,7 @@ public class PlayerProfile {
/** /**
* Set the current DATS of a skill. * Set the current DATS of a skill.
* *
* @param abilityType Ability to set the DATS for * @param abilityType Ability to set the DATS for
* @param DATS the DATS of the ability * @param DATS the DATS of the ability
*/ */
public void setSkillDATS(AbilityType abilityType, long DATS) { public void setSkillDATS(AbilityType abilityType, long DATS) {
@@ -257,7 +256,7 @@ public class PlayerProfile {
* @return the Xp remaining until next level * @return the Xp remaining until next level
*/ */
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) { private int getChildSkillLevel(SkillType skillType) {
@@ -270,373 +269,4 @@ public class PlayerProfile {
return sum / parents.size(); return sum / parents.size();
} }
private boolean loadPlayer() {
return Config.getInstance().getUseMySQL() ? loadMySQL() : loadFlatfile();
}
private void addPlayer() {
if (Config.getInstance().getUseMySQL()) {
addMySQLPlayer();
}
else {
addFlatfilePlayer();
}
}
private boolean loadMySQL() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
userId = SQLDatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
if (userId == 0) {
return false;
}
ArrayList<String> hudValues = SQLDatabaseManager.read("SELECT hudtype, mobhealthbar FROM " + tablePrefix + "huds WHERE user_id = " + userId).get(1);
if (hudValues == null) {
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (" + userId + ",'" + mobHealthbarType.name() + "')");
mcMMO.p.getLogger().warning(playerName + "does not exist in the HUD table. Their HUDs will be reset.");
}
else {
hudType = HudType.valueOf(hudValues.get(0));
mobHealthbarType = MobHealthbarType.valueOf(hudValues.get(1));
}
ArrayList<String> cooldownValues = SQLDatabaseManager.read("SELECT mining, woodcutting, unarmed, herbalism, excavation, swords, axes, blast_mining FROM " + tablePrefix + "cooldowns WHERE user_id = " + userId).get(1);
if (cooldownValues == null) {
SQLDatabaseManager.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)));
}
ArrayList<String> statValues = SQLDatabaseManager.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "skills WHERE user_id = " + userId).get(1);
if (statValues == null) {
SQLDatabaseManager.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)));
}
ArrayList<String> experienceValues = SQLDatabaseManager.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "experience WHERE user_id = " + userId).get(1);
if (experienceValues == null) {
SQLDatabaseManager.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, (float) Integer.valueOf(experienceValues.get(0)));
skillsXp.put(SkillType.MINING, (float) Integer.valueOf(experienceValues.get(1)));
skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(experienceValues.get(2)));
skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(experienceValues.get(3)));
skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(experienceValues.get(4)));
skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(experienceValues.get(5)));
skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(experienceValues.get(6)));
skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(experienceValues.get(7)));
skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(experienceValues.get(8)));
skillsXp.put(SkillType.AXES, (float) Integer.valueOf(experienceValues.get(9)));
skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(experienceValues.get(10)));
skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(experienceValues.get(11)));
}
loaded = true;
return true;
}
private void addMySQLPlayer() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES ('" + playerName + "'," + System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR + ")");
userId = SQLDatabaseManager.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (" + userId + ", '" + mobHealthbarType.name() + "')");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
SQLDatabaseManager.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
}
private void addFlatfilePlayer() {
try {
// Open the file to write the player
BufferedWriter out = new BufferedWriter(new FileWriter(mcMMO.getUsersFilePath(), true));
// Add the player to the end
out.append(playerName).append(":");
out.append("0:"); // Mining
out.append(":");
out.append(":");
out.append("0:"); // Xp
out.append("0:"); // Woodcutting
out.append("0:"); // WoodCuttingXp
out.append("0:"); // Repair
out.append("0:"); // Unarmed
out.append("0:"); // Herbalism
out.append("0:"); // Excavation
out.append("0:"); // Archery
out.append("0:"); // Swords
out.append("0:"); // Axes
out.append("0:"); // Acrobatics
out.append("0:"); // RepairXp
out.append("0:"); // UnarmedXp
out.append("0:"); // HerbalismXp
out.append("0:"); // ExcavationXp
out.append("0:"); // ArcheryXp
out.append("0:"); // SwordsXp
out.append("0:"); // AxesXp
out.append("0:"); // AcrobaticsXp
out.append(":");
out.append("0:"); // Taming
out.append("0:"); // TamingXp
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append(hudType == null ? "STANDARD" : hudType.toString()).append(":"); // HUD
out.append("0:"); // Fishing
out.append("0:"); // FishingXp
out.append("0:"); // Blast Mining
out.append(String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)).append(":"); // LastLogin
out.append(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":"); // Mob Healthbar HUD
// Add more in the same format as the line above
out.newLine();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private boolean loadFlatfile() {
try {
// Open the user file
FileReader file = new FileReader(mcMMO.getUsersFilePath());
BufferedReader in = new BufferedReader(file);
String line;
while ((line = in.readLine()) != null) {
// Find if the line contains the player we want.
String[] character = line.split(":");
if (!character[0].equalsIgnoreCase(playerName)) {
continue;
}
loadSkillData(SkillType.MINING, character, 1);
loadSkillData(SkillType.WOODCUTTING, character, 5);
loadSkillData(SkillType.REPAIR, character, 7);
loadSkillData(SkillType.UNARMED, character, 8);
loadSkillData(SkillType.HERBALISM, character, 9);
loadSkillData(SkillType.EXCAVATION, character, 10);
loadSkillData(SkillType.ARCHERY, character, 11);
loadSkillData(SkillType.SWORDS, character, 12);
loadSkillData(SkillType.AXES, character, 13);
loadSkillData(SkillType.ACROBATICS, character, 14);
loadSkillData(SkillType.TAMING, character, 24);
loadSkillData(SkillType.FISHING, character, 34);
loadSkillXpData(SkillType.MINING, character, 4);
loadSkillXpData(SkillType.WOODCUTTING, character, 6);
loadSkillXpData(SkillType.REPAIR, character, 15);
loadSkillXpData(SkillType.UNARMED, character, 16);
loadSkillXpData(SkillType.HERBALISM, character, 17);
loadSkillXpData(SkillType.EXCAVATION, character, 18);
loadSkillXpData(SkillType.ARCHERY, character, 19);
loadSkillXpData(SkillType.SWORDS, character, 20);
loadSkillXpData(SkillType.AXES, character, 21);
loadSkillXpData(SkillType.ACROBATICS, character, 22);
loadSkillXpData(SkillType.TAMING, character, 25);
loadSkillXpData(SkillType.FISHING, character, 35);
loadDATSData(AbilityType.BERSERK, character, 26);
loadDATSData(AbilityType.GIGA_DRILL_BREAKER, character, 27);
loadDATSData(AbilityType.TREE_FELLER, character, 28);
loadDATSData(AbilityType.GREEN_TERRA, character, 29);
loadDATSData(AbilityType.SERRATED_STRIKES, character, 30);
loadDATSData(AbilityType.SKULL_SPLITTER, character, 31);
loadDATSData(AbilityType.SUPER_BREAKER, character, 32);
loadDATSData(AbilityType.BLAST_MINING, character, 36);
hudType = character.length > 33 ? HudType.valueOf(character[33]) : null;
mobHealthbarType = character.length > 38 ? MobHealthbarType.valueOf(character[38]) : null;
loaded = true;
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return loaded;
}
private void saveMySQL() {
if (Config.getInstance().getUseMySQL()) {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
SQLDatabaseManager.write("UPDATE " + tablePrefix + "users SET lastlogin = " + ((int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)) + " WHERE id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "huds SET "
+ " hudtype = '" + (hudType == null ? "STANDARD" : hudType.toString() + "'")
+ ", mobhealthbar = '" + (mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString() + "'")
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = " + skillsDATS.get(AbilityType.SUPER_BREAKER)
+ ", woodcutting = " + skillsDATS.get(AbilityType.TREE_FELLER)
+ ", unarmed = " + skillsDATS.get(AbilityType.BERSERK)
+ ", herbalism = " + skillsDATS.get(AbilityType.GREEN_TERRA)
+ ", excavation = " + skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)
+ ", swords = " + skillsDATS.get(AbilityType.SERRATED_STRIKES)
+ ", axes = " + skillsDATS.get(AbilityType.SKULL_SPLITTER)
+ ", blast_mining = " + skillsDATS.get(AbilityType.BLAST_MINING)
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "skills SET "
+ " taming = " + skills.get(SkillType.TAMING)
+ ", mining = " + skills.get(SkillType.MINING)
+ ", repair = " + skills.get(SkillType.REPAIR)
+ ", woodcutting = " + skills.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skills.get(SkillType.UNARMED)
+ ", herbalism = " + skills.get(SkillType.HERBALISM)
+ ", excavation = " + skills.get(SkillType.EXCAVATION)
+ ", archery = " + skills.get(SkillType.ARCHERY)
+ ", swords = " + skills.get(SkillType.SWORDS)
+ ", axes = " + skills.get(SkillType.AXES)
+ ", acrobatics = " + skills.get(SkillType.ACROBATICS)
+ ", fishing = " + skills.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
SQLDatabaseManager.write("UPDATE " + tablePrefix + "experience SET "
+ " taming = " + getSkillXpLevel(SkillType.TAMING)
+ ", mining = " + getSkillXpLevel(SkillType.MINING)
+ ", repair = " + getSkillXpLevel(SkillType.REPAIR)
+ ", woodcutting = " + getSkillXpLevel(SkillType.WOODCUTTING)
+ ", unarmed = " + getSkillXpLevel(SkillType.UNARMED)
+ ", herbalism = " + getSkillXpLevel(SkillType.HERBALISM)
+ ", excavation = " + getSkillXpLevel(SkillType.EXCAVATION)
+ ", archery = " + getSkillXpLevel(SkillType.ARCHERY)
+ ", swords = " + getSkillXpLevel(SkillType.SWORDS)
+ ", axes = " + getSkillXpLevel(SkillType.AXES)
+ ", acrobatics = " + getSkillXpLevel(SkillType.ACROBATICS)
+ ", fishing = " + getSkillXpLevel(SkillType.FISHING)
+ " WHERE user_id = " + userId);
}
}
private void saveFlatfile() {
try {
// Open the file
BufferedReader in = new BufferedReader(new FileReader(mcMMO.getUsersFilePath()));
StringBuilder writer = new StringBuilder();
String line;
// While not at the end of the file
while ((line = in.readLine()) != null) {
// Read the line in and copy it to the output it's not the player we want to edit
if (!line.split(":")[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
// Otherwise write the new player information
writer.append(playerName).append(":");
writer.append(skills.get(SkillType.MINING)).append(":");
writer.append(":");
writer.append(":");
writer.append(getSkillXpLevel(SkillType.MINING)).append(":");
writer.append(skills.get(SkillType.WOODCUTTING)).append(":");
writer.append(getSkillXpLevel(SkillType.WOODCUTTING)).append(":");
writer.append(skills.get(SkillType.REPAIR)).append(":");
writer.append(skills.get(SkillType.UNARMED)).append(":");
writer.append(skills.get(SkillType.HERBALISM)).append(":");
writer.append(skills.get(SkillType.EXCAVATION)).append(":");
writer.append(skills.get(SkillType.ARCHERY)).append(":");
writer.append(skills.get(SkillType.SWORDS)).append(":");
writer.append(skills.get(SkillType.AXES)).append(":");
writer.append(skills.get(SkillType.ACROBATICS)).append(":");
writer.append(getSkillXpLevel(SkillType.REPAIR)).append(":");
writer.append(getSkillXpLevel(SkillType.UNARMED)).append(":");
writer.append(getSkillXpLevel(SkillType.HERBALISM)).append(":");
writer.append(getSkillXpLevel(SkillType.EXCAVATION)).append(":");
writer.append(getSkillXpLevel(SkillType.ARCHERY)).append(":");
writer.append(getSkillXpLevel(SkillType.SWORDS)).append(":");
writer.append(getSkillXpLevel(SkillType.AXES)).append(":");
writer.append(getSkillXpLevel(SkillType.ACROBATICS)).append(":");
writer.append(":");
writer.append(skills.get(SkillType.TAMING)).append(":");
writer.append(getSkillXpLevel(SkillType.TAMING)).append(":");
writer.append(skillsDATS.get(AbilityType.BERSERK)).append(":");
writer.append(skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)).append(":");
writer.append(skillsDATS.get(AbilityType.TREE_FELLER)).append(":");
writer.append(skillsDATS.get(AbilityType.GREEN_TERRA)).append(":");
writer.append(skillsDATS.get(AbilityType.SERRATED_STRIKES)).append(":");
writer.append(skillsDATS.get(AbilityType.SKULL_SPLITTER)).append(":");
writer.append(skillsDATS.get(AbilityType.SUPER_BREAKER)).append(":");
writer.append(hudType == null ? "STANDARD" : hudType.toString()).append(":");
writer.append(skills.get(SkillType.FISHING)).append(":");
writer.append(getSkillXpLevel(SkillType.FISHING)).append(":");
writer.append(skillsDATS.get(AbilityType.BLAST_MINING)).append(":");
writer.append(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR).append(":");
writer.append(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":");
writer.append("\r\n");
}
}
in.close();
// Write the new file
FileWriter out = new FileWriter(mcMMO.getUsersFilePath());
out.write(writer.toString());
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void loadSkillXpData(SkillType skill, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skillsXp.put(skill, (float) Integer.valueOf(data[dataIndex]));
}
}
private void loadSkillData(SkillType skill, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skills.put(skill, Integer.valueOf(data[dataIndex]));
}
}
private void loadDATSData(AbilityType ability, String[] data, int dataIndex) {
if (data.length > dataIndex) {
skillsDATS.put(ability, Integer.valueOf(data[dataIndex]));
}
}
} }

View File

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

View File

@@ -108,7 +108,7 @@ public enum SkillType {
} }
public double getXpModifier() { public double getXpModifier() {
return Config.getInstance().getForumulaMultiplier(this); return Config.getInstance().getFormulaSkillModifier(this);
} }
public static SkillType getSkill(String skillName) { public static SkillType getSkill(String skillName) {
@@ -141,7 +141,36 @@ public enum SkillType {
} }
} }
public static SkillType[] nonChildSkills() {
return new SkillType[] {SkillType.ACROBATICS,
SkillType.ARCHERY,
SkillType.AXES,
SkillType.EXCAVATION,
SkillType.FISHING,
SkillType.HERBALISM,
SkillType.MINING,
SkillType.REPAIR,
SkillType.SWORDS,
SkillType.TAMING,
SkillType.UNARMED,
SkillType.WOODCUTTING };
}
public static SkillType[] childSkills() {
return new SkillType[] { SkillType.SMELTING };
}
public Color getRunescapeModeColor() { public Color getRunescapeModeColor() {
return runescapeColor; return runescapeColor;
} }
public static SkillType byAbility(AbilityType ability) {
for (SkillType type : values()) {
if (type.getAbility() == ability) {
return type;
}
}
return null;
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,7 +2,9 @@ package com.gmail.nossr50.listeners;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock; import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
@@ -15,19 +17,23 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTameEvent; import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageEvent;
@@ -52,13 +58,43 @@ public class EntityListener implements Listener {
this.plugin = plugin; this.plugin = plugin;
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityShootBow(EntityShootBowEvent event) {
Entity projectile = event.getProjectile();
if (!(projectile instanceof Arrow)) {
return;
}
ItemStack bow = event.getBow();
if (bow != null && bow.containsEnchantment(Enchantment.ARROW_INFINITE)) {
projectile.setMetadata(mcMMO.infiniteArrowKey, mcMMO.metadataValue);
}
projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(plugin, Math.min(event.getForce() * AdvancedConfig.getInstance().getForceMultiplier(), 1.0)));
projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(plugin, Archery.locationToString(projectile.getLocation())));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile projectile = event.getEntity();
if (!(projectile instanceof Arrow) || projectile.hasMetadata(mcMMO.bowForceKey)) {
return;
}
projectile.setMetadata(mcMMO.bowForceKey, new FixedMetadataValue(plugin, 1.0));
projectile.setMetadata(mcMMO.arrowDistanceKey, new FixedMetadataValue(plugin, Archery.locationToString(projectile.getLocation())));
}
/** /**
* Monitor EntityChangeBlock events. * Monitor EntityChangeBlock events.
* *
* @param event The event to watch * @param event The event to watch
*/ */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (!(entity instanceof FallingBlock)) { if (!(entity instanceof FallingBlock)) {
@@ -84,7 +120,13 @@ public class EntityListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event instanceof FakeEntityDamageByEntityEvent || event.getDamage() <= 0) { if (event instanceof FakeEntityDamageByEntityEvent) {
return;
}
int damage = event.getDamage();
if (damage <= 0) {
return; return;
} }
@@ -94,13 +136,14 @@ public class EntityListener implements Listener {
return; return;
} }
Entity attacker = event.getDamager();
LivingEntity target = (LivingEntity) defender; LivingEntity target = (LivingEntity) defender;
if (CombatUtils.isInvincible(target, event.getDamage())) { if (CombatUtils.isInvincible(target, damage)) {
return; return;
} }
Entity attacker = event.getDamager();
if (attacker instanceof Projectile) { if (attacker instanceof Projectile) {
attacker = ((Projectile) attacker).getShooter(); attacker = ((Projectile) attacker).getShooter();
} }
@@ -127,7 +170,7 @@ public class EntityListener implements Listener {
} }
} }
CombatUtils.combatChecks(event, attacker, target); CombatUtils.processCombatAttack(event, attacker, target);
} }
/** /**
@@ -137,7 +180,13 @@ public class EntityListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof FakeEntityDamageEvent || event.getDamage() <= 0) { if (event instanceof FakeEntityDamageEvent) {
return;
}
int damage = event.getDamage();
if (damage <= 0) {
return; return;
} }
@@ -147,13 +196,14 @@ public class EntityListener implements Listener {
return; return;
} }
DamageCause cause = event.getCause();
LivingEntity livingEntity = (LivingEntity) entity; LivingEntity livingEntity = (LivingEntity) entity;
if (CombatUtils.isInvincible(livingEntity, event.getDamage())) { if (CombatUtils.isInvincible(livingEntity, damage)) {
return; return;
} }
DamageCause cause = event.getCause();
if (livingEntity instanceof Player) { if (livingEntity instanceof Player) {
Player player = (Player) entity; Player player = (Player) entity;
@@ -273,6 +323,30 @@ public class EntityListener implements Listener {
} }
} }
/**
* Monitor EntityDeath events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDeathLowest(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
if (Misc.isNPCEntity(entity)) {
return;
}
if (entity.hasMetadata(mcMMO.customNameKey)) {
entity.setCustomName(entity.getMetadata(mcMMO.customNameKey).get(0).asString());
entity.removeMetadata(mcMMO.customNameKey, mcMMO.p);
}
if (entity.hasMetadata(mcMMO.customVisibleKey)) {
entity.setCustomNameVisible(entity.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean());
entity.removeMetadata(mcMMO.customVisibleKey, mcMMO.p);
}
}
/** /**
* Monitor EntityDeath events. * Monitor EntityDeath events.
* *
@@ -286,7 +360,6 @@ public class EntityListener implements Listener {
return; return;
} }
entity.setFireTicks(0);
BleedTimerTask.remove(entity); BleedTimerTask.remove(entity);
Archery.arrowRetrievalCheck(entity); Archery.arrowRetrievalCheck(entity);
} }
@@ -298,14 +371,21 @@ public class EntityListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) { public void onCreatureSpawn(CreatureSpawnEvent event) {
if (Misc.isSpawnerXPEnabled) { switch (event.getSpawnReason()) {
return; case SPAWNER:
} case SPAWNER_EGG:
LivingEntity entity = event.getEntity();
Entity passenger = entity.getPassenger();
SpawnReason reason = event.getSpawnReason(); entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
if (reason == SpawnReason.SPAWNER || reason == SpawnReason.SPAWNER_EGG) { if (passenger != null) {
event.getEntity().setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue); passenger.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
}
return;
default:
return;
} }
} }
@@ -318,19 +398,21 @@ public class EntityListener implements Listener {
public void onExplosionPrime(ExplosionPrimeEvent event) { public void onExplosionPrime(ExplosionPrimeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof TNTPrimed && entity.hasMetadata(mcMMO.tntMetadataKey)) { if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(mcMMO.tntMetadataKey)) {
// We can make this assumption because we (should) be the only ones using this exact metadata return;
Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString()); }
if (Misc.isNPCEntity(player)) { // We can make this assumption because we (should) be the only ones using this exact metadata
return; Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
}
MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); if (Misc.isNPCEntity(player)) {
return;
}
if (miningManager.canUseBiggerBombs()) { MiningManager miningManager = UserManager.getPlayer(player).getMiningManager();
event.setRadius(miningManager.biggerBombs(event.getRadius()));
} if (miningManager.canUseBiggerBombs()) {
event.setRadius(miningManager.biggerBombs(event.getRadius()));
} }
} }
@@ -343,20 +425,22 @@ public class EntityListener implements Listener {
public void onEnitityExplode(EntityExplodeEvent event) { public void onEnitityExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof TNTPrimed && entity.hasMetadata(mcMMO.tntMetadataKey)) { if (!(entity instanceof TNTPrimed) || !entity.hasMetadata(mcMMO.tntMetadataKey)) {
// We can make this assumption because we (should) be the only ones using this exact metadata return;
Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString()); }
if (Misc.isNPCEntity(player)) { // We can make this assumption because we (should) be the only ones using this exact metadata
return; Player player = plugin.getServer().getPlayer(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
}
MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); if (Misc.isNPCEntity(player)) {
return;
}
if (miningManager.canUseBlastMining()) { MiningManager miningManager = UserManager.getPlayer(player).getMiningManager();
miningManager.blastMiningDropProcessing(event.getYield(), event.blockList());
event.setYield(0); if (miningManager.canUseBlastMining()) {
} miningManager.blastMiningDropProcessing(event.getYield(), event.blockList());
event.setYield(0);
} }
} }
@@ -369,63 +453,65 @@ public class EntityListener implements Listener {
public void onFoodLevelChange(FoodLevelChangeEvent event) { public void onFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
if (entity instanceof Player) { if (!(entity instanceof Player)) {
Player player = (Player) entity; return;
}
if (Misc.isNPCEntity(player)) { Player player = (Player) entity;
if (Misc.isNPCEntity(player)) {
return;
}
int currentFoodLevel = player.getFoodLevel();
int newFoodLevel = event.getFoodLevel();
int foodChange = newFoodLevel - currentFoodLevel;
if (foodChange <= 0) {
return;
}
/*
* Some foods have 3 ranks
* Some foods have 5 ranks
* The number of ranks is based on how 'common' the item is
* We can adjust this quite easily if we find something is giving too much of a bonus
*/
switch (player.getItemInHand().getType()) {
case BAKED_POTATO: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
case CARROT_ITEM: /* RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ 1000 */
case GOLDEN_CARROT: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case MUSHROOM_SOUP: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
case PUMPKIN_PIE: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
if (Permissions.farmersDiet(player)) {
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel1, newFoodLevel));
}
return; return;
}
int currentFoodLevel = player.getFoodLevel(); case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
int newFoodLevel = event.getFoodLevel(); case MELON: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
int foodChange = newFoodLevel - currentFoodLevel; case POISONOUS_POTATO: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case POTATO_ITEM: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
if (foodChange <= 0) { if (Permissions.farmersDiet(player)) {
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel2, newFoodLevel));
}
return; return;
}
/* case COOKED_FISH: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
* Some foods have 3 ranks if (Permissions.fishermansDiet(player)) {
* Some foods have 5 ranks event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel1, newFoodLevel));
* The number of ranks is based on how 'common' the item is }
* We can adjust this quite easily if we find something is giving too much of a bonus return;
*/
switch (player.getItemInHand().getType()) {
case BAKED_POTATO: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
case CARROT_ITEM: /* RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ 1000 */
case GOLDEN_CARROT: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case MUSHROOM_SOUP: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
case PUMPKIN_PIE: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
if (Permissions.farmersDiet(player)) {
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel1, newFoodLevel));
}
return;
case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ case RAW_FISH: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case MELON: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ if (Permissions.fishermansDiet(player)) {
case POISONOUS_POTATO: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel2, newFoodLevel));
case POTATO_ITEM: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ }
if (Permissions.farmersDiet(player)) { return;
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel2, newFoodLevel));
}
return;
case COOKED_FISH: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */ default:
if (Permissions.fishermansDiet(player)) { return;
event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel1, newFoodLevel));
}
return;
case RAW_FISH: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
if (Permissions.fishermansDiet(player)) {
event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel2, newFoodLevel));
}
return;
default:
return;
}
} }
} }
@@ -456,20 +542,21 @@ public class EntityListener implements Listener {
Entity entity = event.getEntity(); Entity entity = event.getEntity();
Entity target = event.getTarget(); Entity target = event.getTarget();
if (entity instanceof Tameable && target instanceof Player) { if (!(entity instanceof Tameable) || !(target instanceof Player)) {
Player player = (Player) target; return;
Tameable tameable = (Tameable) entity; }
if (!CombatUtils.isFriendlyPet(player, tameable)) { Player player = (Player) target;
return; Tameable tameable = (Tameable) entity;
}
// isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party if (!CombatUtils.isFriendlyPet(player, tameable)) {
// So we can make some assumptions here, about our casting and our check return;
if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) { }
event.setCancelled(true);
return; // isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party
} // So we can make some assumptions here, about our casting and our check
if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) {
event.setCancelled(true);
} }
} }
} }

View File

@@ -1,8 +1,6 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@@ -15,14 +13,12 @@ import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import 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.skills.smelting.SmeltingManager; import com.gmail.nossr50.runnables.PlayerUpdateInventoryTask;
import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
@@ -36,7 +32,7 @@ public class InventoryListener implements Listener {
this.plugin = plugin; this.plugin = plugin;
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
HumanEntity player = event.getPlayer(); HumanEntity player = event.getPlayer();
@@ -44,25 +40,14 @@ public class InventoryListener implements Listener {
return; return;
} }
Inventory inventory = event.getInventory(); Block furnaceBlock = Misc.processInventoryOpenorCloseEvent(event);
if (inventory instanceof FurnaceInventory) { if (furnaceBlock != null && !furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
Furnace furnace = (Furnace) inventory.getHolder(); furnaceBlock.setMetadata(mcMMO.furnaceMetadataKey, new FixedMetadataValue(plugin, player.getName()));
if (furnace == null) {
return;
}
if (furnace.getBurnTime() == 0) {
Block furnaceBlock = furnace.getBlock();
if (!furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
furnaceBlock.setMetadata(mcMMO.furnaceMetadataKey, new FixedMetadataValue(plugin, player.getName()));
}
}
} }
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
HumanEntity player = event.getPlayer(); HumanEntity player = event.getPlayer();
@@ -70,90 +55,65 @@ public class InventoryListener implements Listener {
return; return;
} }
Inventory inventory = event.getInventory(); Block furnaceBlock = Misc.processInventoryOpenorCloseEvent(event);
if (inventory instanceof FurnaceInventory) { if (furnaceBlock != null && furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
Furnace furnace = (Furnace) inventory.getHolder(); furnaceBlock.removeMetadata(mcMMO.furnaceMetadataKey, plugin);
if (furnace == null) {
return;
}
if (furnace.getBurnTime() == 0) {
Block furnaceBlock = furnace.getBlock();
if (furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey)) {
furnaceBlock.removeMetadata(mcMMO.furnaceMetadataKey, plugin);
}
}
} }
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceBurnEvent(FurnaceBurnEvent event) { public void onFurnaceBurnEvent(FurnaceBurnEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack smelting = Misc.getSmeltingFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmeltable(smelting)) {
ItemStack smelting = ((Furnace) furnaceState).getInventory().getSmelting(); return;
if (furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey) && smelting != null && ItemUtils.isSmeltable(smelting)) {
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).get(0).asString());
if (Misc.isNPCEntity(player) || !Permissions.fuelEfficiency(player)) {
return;
}
event.setBurnTime(UserManager.getPlayer(player).getSmeltingManager().fuelEfficiency(event.getBurnTime()));
}
} }
Player player = Misc.getPlayerFromFurnace(furnaceBlock);
if (Misc.isNPCEntity(player) || !Permissions.fuelEfficiency(player)) {
return;
}
event.setBurnTime(UserManager.getPlayer(player).getSmeltingManager().fuelEfficiency(event.getBurnTime()));
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) { public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack smelting = Misc.getSmeltingFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmeltable(smelting)) {
ItemStack smelting = ((Furnace) furnaceState).getInventory().getSmelting(); return;
if (furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey) && smelting != null && ItemUtils.isSmeltable(smelting)) {
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).get(0).asString());
if (Misc.isNPCEntity(player) || !Permissions.skillEnabled(player, SkillType.SMELTING)) {
return;
}
event.setResult(UserManager.getPlayer(player).getSmeltingManager().smeltProcessing(event.getSource().getType(), event.getResult()));
}
} }
Player player = Misc.getPlayerFromFurnace(furnaceBlock);
if (Misc.isNPCEntity(player) || !Permissions.skillEnabled(player, SkillType.SMELTING)) {
return;
}
event.setResult(UserManager.getPlayer(player).getSmeltingManager().smeltProcessing(smelting.getType(), event.getResult()));
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceExtractEvent(FurnaceExtractEvent event) { public void onFurnaceExtractEvent(FurnaceExtractEvent event) {
Block furnaceBlock = event.getBlock(); Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState(); ItemStack result = Misc.getResultFromFurnace(furnaceBlock);
if (furnaceState instanceof Furnace) { if (!ItemUtils.isSmelted(result)) {
ItemStack result = ((Furnace) furnaceState).getInventory().getResult(); return;
if (furnaceBlock.hasMetadata(mcMMO.furnaceMetadataKey) && result != null && ItemUtils.isSmelted(result)) {
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayer(furnaceBlock.getMetadata(mcMMO.furnaceMetadataKey).get(0).asString());
if (Misc.isNPCEntity(player)) {
return;
}
SmeltingManager smeltingManager = UserManager.getPlayer(player).getSmeltingManager();
if (smeltingManager.canUseVanillaXpBoost()) {
event.setExpToDrop(smeltingManager.vanillaXPBoost(event.getExpToDrop()));
}
}
} }
Player player = Misc.getPlayerFromFurnace(furnaceBlock);
if (Misc.isNPCEntity(player) || !Permissions.vanillaXpBoost(player, SkillType.SMELTING)) {
return;
}
event.setExpToDrop(UserManager.getPlayer(player).getSmeltingManager().vanillaXPBoost(event.getExpToDrop()));
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@@ -163,18 +123,18 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCraftItem(CraftItemEvent event) { public void onCraftItem(CraftItemEvent event) {
ItemStack result = event.getRecipe().getResult();
final HumanEntity whoClicked = event.getWhoClicked(); final HumanEntity whoClicked = event.getWhoClicked();
if (!ItemUtils.isMcMMOItem(result) || Misc.isNPCEntity(whoClicked) || !(whoClicked instanceof Player)) { if (Misc.isNPCEntity(whoClicked) || !(whoClicked instanceof Player)) {
return; return;
} }
mcMMO.p.getServer().getScheduler().runTaskLater(mcMMO.p, new Runnable() { ItemStack result = event.getRecipe().getResult();
@Override
public void run() { if (!ItemUtils.isMcMMOItem(result)) {
((Player) whoClicked).updateInventory(); return;
} }
}, 0);
new PlayerUpdateInventoryTask((Player) whoClicked).runTaskLater(plugin, 0);
} }
} }

View File

@@ -1,12 +1,12 @@
package com.gmail.nossr50.listeners; package com.gmail.nossr50.listeners;
import org.bukkit.ChatColor;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.Fish;
import org.bukkit.entity.Item; import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -15,6 +15,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerDropItemEvent;
@@ -22,7 +23,6 @@ import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerRespawnEvent;
@@ -30,11 +30,15 @@ import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager; import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.ChatMode;
import com.gmail.nossr50.chat.PartyChatManager;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party; import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
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.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.ShareHandler; import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.skills.BleedTimerTask; import com.gmail.nossr50.runnables.skills.BleedTimerTask;
@@ -54,6 +58,7 @@ import com.gmail.nossr50.util.MobHealthbarUtils;
import com.gmail.nossr50.util.Motd; import com.gmail.nossr50.util.Motd;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class PlayerListener implements Listener { public class PlayerListener implements Listener {
@@ -126,26 +131,6 @@ public class PlayerListener implements Listener {
} }
} }
/**
* Monitor PlayerLogin events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
if (event.getResult() != Result.ALLOWED) {
return;
}
Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
return;
}
UserManager.addUser(player).actualizeRespawnATS();
}
/** /**
* Handle PlayerDropItem events that involve modifying the event. * Handle PlayerDropItem events that involve modifying the event.
* *
@@ -176,6 +161,14 @@ public class PlayerListener implements Listener {
switch (event.getState()) { switch (event.getState()) {
case FISHING: case FISHING:
if (!Permissions.krakenBypass(player)) {
event.setCancelled(fishingManager.exploitPrevention());
if (event.isCancelled()) {
return;
}
}
if (fishingManager.canMasterAngler()) { if (fishingManager.canMasterAngler()) {
fishingManager.masterAngler(event.getHook()); fishingManager.masterAngler(event.getHook());
} }
@@ -191,11 +184,29 @@ public class PlayerListener implements Listener {
case CAUGHT_ENTITY: case CAUGHT_ENTITY:
Entity entity = event.getCaught(); Entity entity = event.getCaught();
if (fishingManager.canShake(entity)) { if (fishingManager.canShake(entity)) {
fishingManager.shakeCheck((LivingEntity) entity); fishingManager.shakeCheck((LivingEntity) entity);
} }
break; break;
case IN_GROUND:
Fish hook = event.getHook();
Block block = event.getPlayer().getTargetBlock(null, 100);
if (fishingManager.canIceFish(block)) {
FakeBlockBreakEvent blockBreakEvent = new FakeBlockBreakEvent(block, player);
mcMMO.p.getServer().getPluginManager().callEvent(blockBreakEvent);
if (blockBreakEvent.isCancelled()) {
return;
}
event.setCancelled(true);
fishingManager.iceFishing(hook, block);
}
break;
default: default:
break; break;
} }
@@ -255,6 +266,24 @@ public class PlayerListener implements Listener {
BleedTimerTask.bleedOut(player); // Bleed it out BleedTimerTask.bleedOut(player); // Bleed it out
} }
/**
* Start user data prefetch.
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onLoginStart(PlayerLoginEvent event) {
UserManager.prefetchUserData(event.getPlayer().getName());
}
/**
* Cancel user data prefetch if a plugin kicks them.
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onLoginComplete(PlayerLoginEvent event) {
if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) {
UserManager.discardPrefetch(event.getPlayer().getName());
}
}
/** /**
* Monitor PlayerJoin events. * Monitor PlayerJoin events.
* *
@@ -264,6 +293,13 @@ public class PlayerListener implements Listener {
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (Misc.isNPCEntity(player)) {
return;
}
UserManager.addUser(player).actualizeRespawnATS();
ScoreboardManager.enablePowerLevelDisplay(player);
if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) { if (Config.getInstance().getMOTDEnabled() && Permissions.motd(player)) {
Motd.displayAll(player); Motd.displayAll(player);
} }
@@ -303,38 +339,47 @@ public class PlayerListener implements Listener {
public void onPlayerInteractLowest(PlayerInteractEvent event) { public void onPlayerInteractLowest(PlayerInteractEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
ItemStack heldItem = player.getItemInHand();
if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) { if (Misc.isNPCEntity(player) || player.getGameMode() == GameMode.CREATIVE) {
return; return;
} }
MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); ItemStack heldItem = player.getItemInHand();
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
// This shouldn't be possible - this is probably a band-aid for a larger issue somewhere else.
if (mcMMOPlayer == null) {
return;
}
MiningManager miningManager = mcMMOPlayer.getMiningManager();
switch (event.getAction()) { switch (event.getAction()) {
case RIGHT_CLICK_BLOCK: case RIGHT_CLICK_BLOCK:
int blockID = block.getTypeId(); int blockID = block.getTypeId();
/* REPAIR CHECKS */ if ((Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && player.isSneaking()) || !Config.getInstance().getAbilitiesOnlyActivateWhenSneaking()) {
if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) { /* REPAIR CHECKS */
RepairManager repairManager = UserManager.getPlayer(player).getRepairManager(); if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
event.setCancelled(true); RepairManager repairManager = mcMMOPlayer.getRepairManager();
event.setCancelled(true);
// Make sure the player knows what he's doing when trying to repair an enchanted item // Make sure the player knows what he's doing when trying to repair an enchanted item
if (!(heldItem.getEnchantments().size() > 0) || repairManager.checkConfirmation(blockID, true)) { if (!(heldItem.getEnchantments().size() > 0) || repairManager.checkConfirmation(blockID, true)) {
repairManager.handleRepair(heldItem); repairManager.handleRepair(heldItem);
player.updateInventory(); player.updateInventory();
}
} }
} /* SALVAGE CHECKS */
/* SALVAGE CHECKS */ else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) {
else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) { RepairManager repairManager = mcMMOPlayer.getRepairManager();
RepairManager repairManager = UserManager.getPlayer(player).getRepairManager(); event.setCancelled(true);
event.setCancelled(true);
// Make sure the player knows what he's doing when trying to salvage an enchanted item // Make sure the player knows what he's doing when trying to salvage an enchanted item
if (!(heldItem.getEnchantments().size() > 0) || repairManager.checkConfirmation(blockID, true)) { if (!(heldItem.getEnchantments().size() > 0) || repairManager.checkConfirmation(blockID, true)) {
repairManager.handleSalvage(block.getLocation(), heldItem); repairManager.handleSalvage(block.getLocation(), heldItem);
player.updateInventory(); player.updateInventory();
}
} }
} }
/* BLAST MINING CHECK */ /* BLAST MINING CHECK */
@@ -352,24 +397,26 @@ public class PlayerListener implements Listener {
case LEFT_CLICK_BLOCK: case LEFT_CLICK_BLOCK:
blockID = block.getTypeId(); blockID = block.getTypeId();
/* REPAIR CHECKS */ if ((Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && player.isSneaking()) || !Config.getInstance().getAbilitiesOnlyActivateWhenSneaking()) {
if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) { /* REPAIR CHECKS */
RepairManager repairManager = UserManager.getPlayer(player).getRepairManager(); if (blockID == Repair.repairAnvilId && Permissions.skillEnabled(player, SkillType.REPAIR) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
RepairManager repairManager = mcMMOPlayer.getRepairManager();
// Cancel repairing an enchanted item // Cancel repairing an enchanted item
if (repairManager.checkConfirmation(blockID, false) && Config.getInstance().getRepairConfirmRequired()) { if (repairManager.checkConfirmation(blockID, false) && Config.getInstance().getRepairConfirmRequired()) {
UserManager.getPlayer(player).setLastAnvilUse(Repair.repairAnvilId, 0); mcMMOPlayer.setLastAnvilUse(Repair.repairAnvilId, 0);
player.sendMessage(ChatColor.RED + "Repair cancelled!"); //TODO Locale! player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Repair.Pretty.Name")));
}
} }
} /* SALVAGE CHECKS */
/* SALVAGE CHECKS */ else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) {
else if (blockID == Repair.salvageAnvilId && Permissions.salvage(player) && Repair.isSalvageable(heldItem)) { RepairManager repairManager = mcMMOPlayer.getRepairManager();
RepairManager repairManager = UserManager.getPlayer(player).getRepairManager();
// Cancel salvaging an enchanted item // Cancel salvaging an enchanted item
if (repairManager.checkConfirmation(blockID, false) && Config.getInstance().getRepairConfirmRequired()) { if (repairManager.checkConfirmation(blockID, false) && Config.getInstance().getRepairConfirmRequired()) {
UserManager.getPlayer(player).setLastAnvilUse(Repair.salvageAnvilId, 0); mcMMOPlayer.setLastAnvilUse(Repair.salvageAnvilId, 0);
player.sendMessage(ChatColor.RED + "Salvage cancelled!"); //TODO Locale! player.sendMessage(LocaleLoader.getString("Skills.Cancelled", LocaleLoader.getString("Salvage.Pretty.Name")));
}
} }
} }
@@ -404,6 +451,11 @@ public class PlayerListener implements Listener {
ItemStack heldItem = player.getItemInHand(); ItemStack heldItem = player.getItemInHand();
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
// This shouldn't be possible - this is probably a band-aid for a larger issue somewhere else.
if (mcMMOPlayer == null) {
return;
}
switch (event.getAction()) { switch (event.getAction()) {
case RIGHT_CLICK_BLOCK: case RIGHT_CLICK_BLOCK:
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
@@ -502,19 +554,31 @@ public class PlayerListener implements Listener {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer == null) {
mcMMO.p.debug(player.getName() + " is currently chatting, but has never logged on to the server.");
return;
}
ChatManager chatManager = null;
if (mcMMOPlayer.getPartyChatMode()) { if (mcMMOPlayer.getPartyChatMode()) {
Party party = mcMMOPlayer.getParty(); Party party = mcMMOPlayer.getParty();
if (party == null) { if (party == null) {
mcMMOPlayer.togglePartyChat();
player.sendMessage(LocaleLoader.getString("Commands.Party.None")); player.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return; return;
} }
ChatManager.handlePartyChat(plugin, party, player.getName(), player.getDisplayName(), event.getMessage(), event.isAsynchronous()); chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.PARTY);
event.setCancelled(true); ((PartyChatManager) chatManager).setParty(party);
} }
else if (mcMMOPlayer.getAdminChatMode()) { else if (mcMMOPlayer.getAdminChatMode()) {
ChatManager.handleAdminChat(plugin, player.getName(), player.getDisplayName(), event.getMessage(), event.isAsynchronous()); chatManager = ChatManagerFactory.getChatManager(plugin, ChatMode.ADMIN);
}
if (chatManager != null) {
chatManager.handleChat(player, event.getMessage(), event.isAsynchronous());
event.setCancelled(true); event.setCancelled(true);
} }
} }

View File

@@ -11,13 +11,13 @@ import org.getspout.spoutapi.gui.Button;
import org.getspout.spoutapi.gui.ScreenType; import org.getspout.spoutapi.gui.ScreenType;
import org.getspout.spoutapi.player.SpoutPlayer; import org.getspout.spoutapi.player.SpoutPlayer;
import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.spout.buttons.McMMOButton; import com.gmail.nossr50.datatypes.spout.buttons.McMMOButton;
import com.gmail.nossr50.datatypes.spout.huds.McMMOHud; import com.gmail.nossr50.datatypes.spout.huds.McMMOHud;
import com.gmail.nossr50.datatypes.spout.popups.McMMOMenu; import com.gmail.nossr50.datatypes.spout.popups.McMMOMenu;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.spout.SpoutUtils;
public class SpoutListener implements Listener { public class SpoutListener implements Listener {
@@ -32,8 +32,8 @@ public class SpoutListener implements Listener {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(spoutPlayer); McMMOPlayer mcMMOPlayer = UserManager.getPlayer(spoutPlayer);
// TODO: Add custom titles based on skills // TODO: Add custom titles based on skills
if (SpoutUtils.showPowerLevel) { if (SpoutConfig.getInstance().getShowPowerLevel()) {
spoutPlayer.setTitle(LocaleLoader.getString("Spout.Title", spoutPlayer.getName(), mcMMOPlayer.getPowerLevel())); spoutPlayer.setTitle(LocaleLoader.getString("Spout.Title", spoutPlayer.getTitle(), mcMMOPlayer.getPowerLevel()));
} }
mcMMOPlayer.getProfile().setSpoutHud(new McMMOHud(mcMMOPlayer)); // Setup Party HUD stuff mcMMOPlayer.getProfile().setSpoutHud(new McMMOHud(mcMMOPlayer)); // Setup Party HUD stuff
@@ -81,7 +81,7 @@ public class SpoutListener implements Listener {
return; return;
} }
if (event.getKey() == SpoutUtils.menuKey) { if (event.getKey() == SpoutConfig.getInstance().getMenuKey()) {
McMMOHud spoutHud = UserManager.getPlayer(spoutPlayer).getProfile().getSpoutHud(); McMMOHud spoutHud = UserManager.getPlayer(spoutPlayer).getProfile().getSpoutHud();
if (!spoutHud.isMenuOpened()) { if (!spoutHud.isMenuOpened()) {

View File

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

View File

@@ -23,18 +23,19 @@ import com.gmail.nossr50.config.mods.CustomToolConfig;
import com.gmail.nossr50.config.spout.SpoutConfig; import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.config.treasure.TreasureConfig; import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.database.DatabaseManager; import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.listeners.BlockListener; import com.gmail.nossr50.listeners.BlockListener;
import com.gmail.nossr50.listeners.EntityListener; import com.gmail.nossr50.listeners.EntityListener;
import com.gmail.nossr50.listeners.InventoryListener; import com.gmail.nossr50.listeners.InventoryListener;
import com.gmail.nossr50.listeners.PlayerListener; import com.gmail.nossr50.listeners.PlayerListener;
import com.gmail.nossr50.listeners.SelfListener; import com.gmail.nossr50.listeners.SelfListener;
import com.gmail.nossr50.listeners.SpoutListener;
import com.gmail.nossr50.listeners.WorldListener; import com.gmail.nossr50.listeners.WorldListener;
import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.metrics.MetricsManager; import com.gmail.nossr50.metrics.MetricsManager;
import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.SaveTimerTask; import com.gmail.nossr50.runnables.SaveTimerTask;
import com.gmail.nossr50.runnables.UpdateCheckerTask;
import com.gmail.nossr50.runnables.database.UserPurgeTask; import com.gmail.nossr50.runnables.database.UserPurgeTask;
import com.gmail.nossr50.runnables.party.PartyAutoKickTask; import com.gmail.nossr50.runnables.party.PartyAutoKickTask;
import com.gmail.nossr50.runnables.skills.BleedTimerTask; import com.gmail.nossr50.runnables.skills.BleedTimerTask;
@@ -45,8 +46,8 @@ import com.gmail.nossr50.skills.repair.RepairableManagerFactory;
import com.gmail.nossr50.skills.repair.config.RepairConfigManager; import com.gmail.nossr50.skills.repair.config.RepairConfigManager;
import com.gmail.nossr50.util.ChimaeraWing; import com.gmail.nossr50.util.ChimaeraWing;
import com.gmail.nossr50.util.LogFilter; import com.gmail.nossr50.util.LogFilter;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.UpdateChecker;
import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManager; import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManager;
import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManagerFactory; import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManagerFactory;
import com.gmail.nossr50.util.commands.CommandRegistrationManager; import com.gmail.nossr50.util.commands.CommandRegistrationManager;
@@ -54,18 +55,10 @@ import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.spout.SpoutUtils; import com.gmail.nossr50.util.spout.SpoutUtils;
public class mcMMO extends JavaPlugin { public class mcMMO extends JavaPlugin {
/* Listeners */
private final PlayerListener playerListener = new PlayerListener(this);
private final BlockListener blockListener = new BlockListener(this);
private final EntityListener entityListener = new EntityListener(this);
private final InventoryListener inventoryListener = new InventoryListener(this);
private final WorldListener worldListener = new WorldListener(this);
private final SelfListener selfListener = new SelfListener();
/* Managers */ /* Managers */
private static ChunkManager placeStore; private static ChunkManager placeStore;
private static RepairableManager repairableManager; private static RepairableManager repairableManager;
private static DatabaseManager databaseManager; private static DatabaseManager databaseManager;
/* File Paths */ /* File Paths */
private static String mainDirectory; private static String mainDirectory;
@@ -81,14 +74,14 @@ public class mcMMO extends JavaPlugin {
// Update Check // Update Check
private boolean updateAvailable; private boolean updateAvailable;
// Plugin Checks /* Plugin Checks */
public static boolean spoutEnabled; private static boolean spoutEnabled;
public static boolean combatTagEnabled; private static boolean combatTagEnabled;
// XP Event Check // XP Event Check
private boolean xpEventEnabled; private boolean xpEventEnabled;
// Metadata Values /* Metadata Values */
public final static String entityMetadataKey = "mcMMO: Spawned Entity"; public final static String entityMetadataKey = "mcMMO: Spawned Entity";
public final static String blockMetadataKey = "mcMMO: Piston Tracking"; public final static String blockMetadataKey = "mcMMO: Piston Tracking";
public final static String furnaceMetadataKey = "mcMMO: Tracked Furnace"; public final static String furnaceMetadataKey = "mcMMO: Tracked Furnace";
@@ -96,6 +89,9 @@ public class mcMMO extends JavaPlugin {
public final static String customNameKey = "mcMMO: Custom Name"; public final static String customNameKey = "mcMMO: Custom Name";
public final static String customVisibleKey = "mcMMO: Name Visibility"; public final static String customVisibleKey = "mcMMO: Name Visibility";
public final static String droppedItemKey = "mcMMO: Tracked Item"; public final static String droppedItemKey = "mcMMO: Tracked Item";
public final static String infiniteArrowKey = "mcMMO: Infinite Arrow";
public final static String bowForceKey = "mcMMO: Bow Force";
public final static String arrowDistanceKey = "mcMMO: Arrow Distance";
public static FixedMetadataValue metadataValue; public static FixedMetadataValue metadataValue;
@@ -113,9 +109,9 @@ public class mcMMO extends JavaPlugin {
setupSpout(); setupSpout();
loadConfigFiles(); loadConfigFiles();
combatTagEnabled = getServer().getPluginManager().isPluginEnabled("CombatTag"); combatTagEnabled = getServer().getPluginManager().getPlugin("CombatTag") != null;
databaseManager = new DatabaseManager(this, Config.getInstance().getUseMySQL()); databaseManager = DatabaseManagerFactory.getDatabaseManager();
registerEvents(); registerEvents();
registerCustomRecipes(); registerCustomRecipes();
@@ -129,7 +125,7 @@ public class mcMMO extends JavaPlugin {
debug("Version " + getDescription().getVersion() + " is enabled!"); debug("Version " + getDescription().getVersion() + " is enabled!");
scheduleTasks(); scheduleTasks();
registerCommands(); CommandRegistrationManager.registerCommands();
MetricsManager.setup(); MetricsManager.setup();
@@ -161,7 +157,6 @@ public class mcMMO extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
try { try {
reloadDisableHelper(); // Prevent Berserk from getting "stuck"
UserManager.saveAll(); // Make sure to save player information if the server shuts down UserManager.saveAll(); // Make sure to save player information if the server shuts down
PartyManager.saveParties(); // Save our parties PartyManager.saveParties(); // Save our parties
placeStore.saveAll(); // Save our metadata placeStore.saveAll(); // Save our metadata
@@ -234,12 +229,25 @@ public class mcMMO extends JavaPlugin {
return placeStore; return placeStore;
} }
public static RepairableManager getRepairableManager() {
return repairableManager;
}
public static DatabaseManager getDatabaseManager() { public static DatabaseManager getDatabaseManager() {
return databaseManager; return databaseManager;
} }
public static RepairableManager getRepairableManager() { @Deprecated
return repairableManager; public static void setDatabaseManager(DatabaseManager databaseManager) {
mcMMO.databaseManager = databaseManager;
}
public static boolean isSpoutEnabled() {
return spoutEnabled;
}
public static boolean isCombatTagEnabled() {
return combatTagEnabled;
} }
/** /**
@@ -254,24 +262,23 @@ public class mcMMO extends JavaPlugin {
} }
private void checkForUpdates() { private void checkForUpdates() {
if (Config.getInstance().getUpdateCheckEnabled()) { if (!Config.getInstance().getUpdateCheckEnabled()) {
try { return;
updateAvailable = UpdateChecker.updateAvailable(); }
}
catch (Exception e) {
updateAvailable = false;
}
if (updateAvailable) { getServer().getScheduler().runTaskAsynchronously(this, new UpdateCheckerTask());
getLogger().info(LocaleLoader.getString("UpdateChecker.outdated")); }
getLogger().info(LocaleLoader.getString("UpdateChecker.newavailable"));
} public void updateCheckerCallback(boolean updateAvailable) {
this.updateAvailable = updateAvailable;
if (updateAvailable) {
getLogger().info(LocaleLoader.getString("UpdateChecker.outdated"));
getLogger().info(LocaleLoader.getString("UpdateChecker.newavailable"));
} }
} }
private void loadConfigFiles() { private void loadConfigFiles() {
// Force the loading of config files // Force the loading of config files
Config configInstance = Config.getInstance();
TreasureConfig.getInstance(); TreasureConfig.getInstance();
HiddenConfig.getInstance(); HiddenConfig.getInstance();
AdvancedConfig.getInstance(); AdvancedConfig.getInstance();
@@ -279,19 +286,19 @@ public class mcMMO extends JavaPlugin {
List<Repairable> repairables = new ArrayList<Repairable>(); List<Repairable> repairables = new ArrayList<Repairable>();
if (configInstance.getToolModsEnabled()) { if (Config.getInstance().getToolModsEnabled()) {
repairables.addAll(CustomToolConfig.getInstance().getLoadedRepairables()); repairables.addAll(CustomToolConfig.getInstance().getLoadedRepairables());
} }
if (configInstance.getArmorModsEnabled()) { if (Config.getInstance().getArmorModsEnabled()) {
repairables.addAll(CustomArmorConfig.getInstance().getLoadedRepairables()); repairables.addAll(CustomArmorConfig.getInstance().getLoadedRepairables());
} }
if (configInstance.getBlockModsEnabled()) { if (Config.getInstance().getBlockModsEnabled()) {
CustomBlockConfig.getInstance(); CustomBlockConfig.getInstance();
} }
if (configInstance.getEntityModsEnabled()) { if (Config.getInstance().getEntityModsEnabled()) {
CustomEntityConfig.getInstance(); CustomEntityConfig.getInstance();
} }
@@ -302,75 +309,34 @@ public class mcMMO extends JavaPlugin {
repairableManager.registerRepairables(repairables); repairableManager.registerRepairables(repairables);
// Check if Repair Anvil and Salvage Anvil have different itemID's // Check if Repair Anvil and Salvage Anvil have different itemID's
if (configInstance.getSalvageAnvilId() == configInstance.getRepairAnvilId()) { if (Config.getInstance().getSalvageAnvilId() == Config.getInstance().getRepairAnvilId()) {
getLogger().warning("Can't use the same itemID for Repair/Salvage Anvils!"); getLogger().warning("Can't use the same itemID for Repair/Salvage Anvils!");
} }
} }
private void setupSpout() { private void setupSpout() {
// Check for Spout if (!getServer().getPluginManager().isPluginEnabled("Spout")) {
if (getServer().getPluginManager().isPluginEnabled("Spout")) { return;
spoutEnabled = true;
SpoutConfig.getInstance();
SpoutUtils.setupSpoutConfigs();
SpoutUtils.registerCustomEvent();
SpoutUtils.preCacheFiles();
SpoutUtils.reloadSpoutPlayers(); // Handle spout players after a /reload
} }
spoutEnabled = true;
SpoutConfig.getInstance();
getServer().getPluginManager().registerEvents(new SpoutListener(), this);
SpoutUtils.preCacheFiles();
SpoutUtils.reloadSpoutPlayers(); // Handle spout players after a /reload
} }
private void registerEvents() { private void registerEvents() {
PluginManager pluginManager = getServer().getPluginManager(); PluginManager pluginManager = getServer().getPluginManager();
// Register events // Register events
pluginManager.registerEvents(playerListener, this); pluginManager.registerEvents(new PlayerListener(this), this);
pluginManager.registerEvents(blockListener, this); pluginManager.registerEvents(new BlockListener(this), this);
pluginManager.registerEvents(entityListener, this); pluginManager.registerEvents(new EntityListener(this), this);
pluginManager.registerEvents(inventoryListener, this); pluginManager.registerEvents(new InventoryListener(this), this);
pluginManager.registerEvents(selfListener, this); pluginManager.registerEvents(new SelfListener(), this);
pluginManager.registerEvents(worldListener, this); pluginManager.registerEvents(new WorldListener(this), this);
}
/**
* Register the commands.
*/
private void registerCommands() {
CommandRegistrationManager.registerSkillCommands();
// mc* commands
CommandRegistrationManager.registerMcpurgeCommand();
CommandRegistrationManager.registerMcremoveCommand();
CommandRegistrationManager.registerMcabilityCommand();
CommandRegistrationManager.registerMcgodCommand();
CommandRegistrationManager.registerMcmmoCommand();
CommandRegistrationManager.registerMcrefreshCommand();
CommandRegistrationManager.registerMctopCommand();
CommandRegistrationManager.registerMcrankCommand();
CommandRegistrationManager.registerMcstatsCommand();
// Party commands
CommandRegistrationManager.registerAdminChatCommand();
CommandRegistrationManager.registerPartyCommand();
CommandRegistrationManager.registerPartyChatCommand();
CommandRegistrationManager.registerPtpCommand();
// Other commands
CommandRegistrationManager.registerAddxpCommand();
CommandRegistrationManager.registerAddlevelsCommand();
CommandRegistrationManager.registerMmoeditCommand();
CommandRegistrationManager.registerInspectCommand();
CommandRegistrationManager.registerXprateCommand();
CommandRegistrationManager.registerMmoupdateCommand();
CommandRegistrationManager.registerSkillresetCommand();
CommandRegistrationManager.registerHardcoreCommand();
CommandRegistrationManager.registerVampirismCommand();
CommandRegistrationManager.registerMcnotifyCommand();
CommandRegistrationManager.registerMobhealthCommand();
// Spout commands
CommandRegistrationManager.registerXplockCommand();
CommandRegistrationManager.registerMchudCommand();
} }
private void registerCustomRecipes() { private void registerCustomRecipes() {
@@ -382,49 +348,29 @@ public class mcMMO extends JavaPlugin {
private void scheduleTasks() { private void scheduleTasks() {
// Periodic save timer (Saves every 10 minutes by default) // Periodic save timer (Saves every 10 minutes by default)
long saveIntervalTicks = Config.getInstance().getSaveInterval() * 1200; long saveIntervalTicks = Config.getInstance().getSaveInterval() * 1200;
new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks); new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks);
// Bleed timer (Runs every two seconds) // Bleed timer (Runs every two seconds)
new BleedTimerTask().runTaskTimer(this, 40, 40); new BleedTimerTask().runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR);
// Old & Powerless User remover // Old & Powerless User remover
int purgeInterval = Config.getInstance().getPurgeInterval(); long purgeIntervalTicks = Config.getInstance().getPurgeInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;
UserPurgeTask userPurgeTask = new UserPurgeTask();
if (purgeInterval == 0) { if (purgeIntervalTicks == 0) {
userPurgeTask.runTaskLater(this, 40); new UserPurgeTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
} }
else if (purgeInterval > 0) { else if (purgeIntervalTicks > 0) {
long purgeIntervalTicks = purgeInterval * 60 * 60 * 20; new UserPurgeTask().runTaskTimer(this, purgeIntervalTicks, purgeIntervalTicks);
userPurgeTask.runTaskTimer(this, purgeIntervalTicks, purgeIntervalTicks);
} }
// Automatically remove old members from parties // Automatically remove old members from parties
long kickInterval = Config.getInstance().getAutoPartyKickInterval(); long kickIntervalTicks = Config.getInstance().getAutoPartyKickInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;
PartyAutoKickTask partyAutoKickTask = new PartyAutoKickTask();
if (kickInterval == 0) { if (kickIntervalTicks == 0) {
partyAutoKickTask.runTaskLater(this, 40); // Start 2 seconds after startup. new PartyAutoKickTask().runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
} }
else if (kickInterval > 0) { else if (kickIntervalTicks > 0) {
long kickIntervalTicks = kickInterval * 60 * 60 * 20; new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks);
partyAutoKickTask.runTaskTimer(this, kickIntervalTicks, kickIntervalTicks);
}
}
/**
* Because /reload is the biggest piece of garbage in existence,
* we have to do some special checks to keep it from breaking everything.
*/
private void reloadDisableHelper() {
for (McMMOPlayer mcMMOPlayer : UserManager.getPlayers().values()) {
if (mcMMOPlayer.getAbilityMode(AbilityType.BERSERK)) {
mcMMOPlayer.setAbilityMode(AbilityType.BERSERK, false);
mcMMOPlayer.getPlayer().setCanPickupItems(true);
}
} }
} }
} }

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
package com.gmail.nossr50.runnables;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.UpdateChecker;
/**
* Async task
*/
public class UpdateCheckerTask implements Runnable {
@Override
public void run() {
try {
mcMMO.p.updateCheckerCallback(UpdateChecker.updateAvailable());
}
catch (Exception e) {
mcMMO.p.updateCheckerCallback(false);
}
}
}

View File

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

View File

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

View File

@@ -1,31 +1,28 @@
package com.gmail.nossr50.runnables.commands; package com.gmail.nossr50.runnables.commands;
import java.util.ArrayList; import java.util.List;
import java.util.Collection;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.database.SQLDatabaseManager;
public class MctopCommandAsyncTask extends BukkitRunnable { public class MctopCommandAsyncTask extends BukkitRunnable {
private CommandSender sender; private CommandSender sender;
private String query; private String skill;
private int page; private int page;
public MctopCommandAsyncTask(int page, String query, CommandSender sender) { public MctopCommandAsyncTask(int page, String skill, CommandSender sender) {
this.page = page; this.page = page;
this.query = query.equalsIgnoreCase("ALL") ? "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing" : query; this.skill = skill;
this.sender = sender; this.sender = sender;
} }
@Override @Override
public void run() { public void run() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix(); final List<PlayerStat> userStats = mcMMO.getDatabaseManager().readLeaderboard(skill, page, 10);
final Collection<ArrayList<String>> userStats = SQLDatabaseManager.read("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT " + ((page * 10) - 10) + ",10").values();
new MctopCommandDisplayTask(userStats, page, tablePrefix, sender).runTaskLater(mcMMO.p, 1); new MctopCommandDisplayTask(userStats, page, skill, sender).runTaskLater(mcMMO.p, 1);
} }
} }

View File

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

View File

@@ -0,0 +1,41 @@
package com.gmail.nossr50.runnables.database;
import java.util.logging.Level;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.locale.LocaleLoader;
public class ConversionTask extends BukkitRunnable {
private final DatabaseManager sourceDb;
private final CommandSender sender;
private final String message;
public ConversionTask(DatabaseManager from, CommandSender sendback, String oldType, String newType) {
sourceDb = from;
sender = sendback;
message = LocaleLoader.getString("Commands.mmoupdate.Finish", oldType, newType);
}
@Override
public void run() {
sourceDb.convertUsers(mcMMO.getDatabaseManager());
// Announce completeness
mcMMO.p.getServer().getScheduler().runTask(mcMMO.p, new CompleteAnnouncement());
}
public class CompleteAnnouncement implements Runnable {
@Override
public void run() {
try {
sender.sendMessage(message);
} catch (Exception e) {
mcMMO.p.getLogger().log(Level.WARNING, "Exception sending database conversion completion message to " + sender.getName(), e);
}
}
}
}

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.runnables.items; package com.gmail.nossr50.runnables.items;
import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@@ -29,27 +28,31 @@ public class ChimaeraWingWarmup extends BukkitRunnable {
private void checkChimaeraWingTeleport() { private void checkChimaeraWingTeleport() {
Player player = mcMMOPlayer.getPlayer(); Player player = mcMMOPlayer.getPlayer();
Location previousLocation = mcMMOPlayer.getTeleportCommenceLocation(); Location previousLocation = mcMMOPlayer.getTeleportCommenceLocation();
Location newLocation = mcMMOPlayer.getPlayer().getLocation();
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
ItemStack inHand = player.getItemInHand();
mcMMOPlayer.setTeleportCommenceLocation(null); mcMMOPlayer.setTeleportCommenceLocation(null);
if (newLocation.distanceSquared(previousLocation) > 1.0 || !player.getInventory().containsAtLeast(ChimaeraWing.getChimaeraWing(0), 1)) { if (player.getLocation().distanceSquared(previousLocation) > 1.0 || !player.getInventory().containsAtLeast(ChimaeraWing.getChimaeraWing(0), 1)) {
player.sendMessage(ChatColor.DARK_RED + "Teleportation canceled!"); //TODO Locale! player.sendMessage(LocaleLoader.getString("Teleport.Cancelled"));
return; return;
} }
ItemStack inHand = player.getItemInHand();
if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) { if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", "Chimaera Wings")); //TODO Locale! player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name")));
return; return;
} }
int recentlyhurt_cooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown(); long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player)) { if (hurtCooldown > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, player))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
return;
if (timeRemaining > 0) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return;
}
} }
ChimaeraWing.chimaeraExecuteTeleport(); ChimaeraWing.chimaeraExecuteTeleport();

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.runnables.items; package com.gmail.nossr50.runnables.items;
import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@@ -44,15 +43,19 @@ public class TeleportationWarmup extends BukkitRunnable {
} }
if (newLocation.distanceSquared(previousLocation) > 1.0) { if (newLocation.distanceSquared(previousLocation) > 1.0) {
teleportingPlayer.sendMessage(ChatColor.DARK_RED + "Teleportation canceled!"); //TODO Locale! teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Cancelled"));
return; return;
} }
int recentlyhurt_cooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown(); int hurtCooldown = Config.getInstance().getPTPCommandRecentlyHurtCooldown();
if (!SkillUtils.cooldownOver(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, teleportingPlayer)) { if (hurtCooldown > 0) {
teleportingPlayer.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, recentlyhurt_cooldown, teleportingPlayer))); int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, teleportingPlayer);
return;
if (timeRemaining > 0) {
teleportingPlayer.sendMessage(LocaleLoader.getString("Item.Injured.Wait", timeRemaining));
return;
}
} }
PtpCommand.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); PtpCommand.handlePartyTeleportEvent(teleportingPlayer, targetPlayer);

View File

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

View File

@@ -0,0 +1,19 @@
package com.gmail.nossr50.runnables.player;
import java.util.concurrent.Callable;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
public class PlayerProfileLoader implements Callable<PlayerProfile> {
private final String playerName;
public PlayerProfileLoader(String player) {
this.playerName = player;
}
@Override
public PlayerProfile call() {
return mcMMO.getDatabaseManager().loadPlayerProfile(playerName, true);
}
}

View File

@@ -17,7 +17,11 @@ public class ScoreboardChangeTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
player.setScoreboard(oldScoreboard); if (player.isOnline()) {
player.setScoreboard(oldScoreboard);
ScoreboardManager.enablePowerLevelDisplay(player);
}
ScoreboardManager.clearPendingTask(player.getName()); ScoreboardManager.clearPendingTask(player.getName());
} }
} }

View File

@@ -7,8 +7,11 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.HiddenConfig; import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
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.events.skills.abilities.McMMOPlayerAbilityDeactivateEvent;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.skills.SkillUtils;
public class AbilityDisableTask extends BukkitRunnable { public class AbilityDisableTask extends BukkitRunnable {
@@ -44,6 +47,9 @@ public class AbilityDisableTask extends BukkitRunnable {
break; break;
} }
McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(player, SkillType.byAbility(ability));
mcMMO.p.getServer().getPluginManager().callEvent(event);
mcMMOPlayer.setAbilityMode(ability, false); mcMMOPlayer.setAbilityMode(ability, false);
mcMMOPlayer.setAbilityInformed(ability, false); mcMMOPlayer.setAbilityInformed(ability, false);
@@ -54,6 +60,6 @@ public class AbilityDisableTask extends BukkitRunnable {
} }
SkillUtils.sendSkillMessage(player, ability.getAbilityPlayerOff(player)); SkillUtils.sendSkillMessage(player, ability.getAbilityPlayerOff(player));
new AbilityCooldownTask(mcMMOPlayer, ability).runTaskLaterAsynchronously(mcMMO.p, ability.getCooldown() * 20); new AbilityCooldownTask(mcMMOPlayer, ability).runTaskLaterAsynchronously(mcMMO.p, PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TICK_CONVERSION_FACTOR);
} }
} }

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