Squashed commit of the following:

commit cb3e057dee1f2b29838ab654a526baac1baab7d6
Author: NuclearW <incongruency@gmail.com>
Date:   Fri Mar 1 00:43:57 2013 -0500

    1.4.00 release

commit 4f9628d2e4cde31c8946e9a911ee6f10e1fb6b35
Author: NuclearW <incongruency@gmail.com>
Date:   Fri Mar 1 00:07:30 2013 -0500

    \r -> \n

commit b2ca22e0477c747143b0f08a28a096967ee6ffd7
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 23:53:56 2013 -0500

    Commented-out code shouldn't be done like that.

commit 92f131712cc671e3e616c14a22e22769ef6d6d0b
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 23:45:36 2013 -0500

    More things we missed.

commit 408b03766f6261a03a862a1ab7f5835772feda4a
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 23:20:13 2013 -0500

    Format: util through spout and backup lib

commit d6bd2c29bbb51bee3607247468cfe145d4f38c9e
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 22:50:08 2013 -0500

    The things we missed the first time through...

commit 393f0b889aa1b7011ee81ee7b15413d8824b8cfb
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 22:05:29 2013 -0500

    Formatting: Skills

commit c097a6e188a7b760dd1b4389ed81dca417146b16
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 19:30:12 2013 -0500

    Organize imports.

commit 34c3e74be7eb5f983f21d969e30155c5d82c01c1
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 19:09:45 2013 -0500

    Fixed a missing fallthrough comment from ChatCommand

commit b4a76c9f022a2fd98bdd8f083accfea03becfd71
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 19:09:36 2013 -0500

    Formatting: datatypes.* through events.*

commit 3e57dd41d3265a7c8106c7eb026df926770a4d15
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 17:56:15 2013 -0500

    Fix issue with bad rebase

commit e8c8e06b2971555b7334e49128257e3af6f36892
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 17:35:32 2013 -0500

    Formatting: DatabaseManager, LeaderboardManager, DatabaseUpdateType, and
    PlayerStat

commit 13ecf1cc41f377a12991e357ac10abdcda24d6de
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 17:31:43 2013 -0500

    Format: listeners.* through runnables.*

commit 71686e3c0d96c2dcf25442b91703fadda1ea3bb0
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 17:13:57 2013 -0500

    Format PartyLockCommand

commit d50abed10bf94e1a88df3dc5cc07c259aea920ea
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 16:54:08 2013 -0500

    Format: base through config.*

commit 7004823eeebbae5be7728bf9cafc3b04e57b64cf
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 15:21:40 2013 -0500

    Example of using spaces to align like things

commit 534190cfe2481e466fe459d65628550458cc2993
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 15:12:19 2013 -0500

    Capitalization

commit 5b61d3ba4c8d81e6f358b0cf4f460abfe9798414
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 15:07:43 2013 -0500

    Updated readme, added standards.md

commit 5ec0df70fb82c527420a2f437f27f31bd758f884
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 14:42:16 2013 -0500

    Markdown was here, Creole is a loser

commit 70d557c59d086b6a5fb5e0e63c0c1d8eb4c8d19c
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 13:46:24 2013 -0500

    Move MCStats shading to .metrics.mcstats

commit eb9d67e66b1659d6abd2397ecf403343cfeffdda
Author: GJ <gjmcferrin@gmail.com>
Date:   Thu Feb 28 13:37:37 2013 -0500

    Move ALL the packages!

commit 8ffa9e7b75417b6c7f158613d4b4ffb783dcf2d0
Author: NuclearW <incongruency@gmail.com>
Date:   Thu Feb 28 12:37:12 2013 -0500

    /r/n -> /n
This commit is contained in:
NuclearW
2013-03-01 00:52:01 -05:00
parent 13111a8d1b
commit a542d6cf3e
263 changed files with 24364 additions and 23982 deletions

View File

@ -1,365 +0,0 @@
package com.gmail.nossr50.util;
import org.bukkit.CropState;
import org.bukkit.block.BlockState;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.CocoaPlant.CocoaPlantSize;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mods.ModChecks;
public final class BlockChecks {
private BlockChecks() {}
/**
* Checks to see if a given block awards XP.
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block awards XP, false otherwise
*/
public static boolean shouldBeWatched(BlockState blockState) {
switch (blockState.getType()) {
case BROWN_MUSHROOM:
case CACTUS:
case CLAY:
case COAL_ORE:
case DIAMOND_ORE:
case DIRT:
case ENDER_STONE:
case GLOWING_REDSTONE_ORE:
case GLOWSTONE:
case GOLD_ORE:
case GRASS:
case GRAVEL:
case IRON_ORE:
case LAPIS_ORE:
case LOG:
case MELON_BLOCK:
case MOSSY_COBBLESTONE:
case MYCEL:
case NETHERRACK:
case OBSIDIAN:
case PUMPKIN:
case RED_MUSHROOM:
case RED_ROSE:
case REDSTONE_ORE:
case SAND:
case SANDSTONE:
case SOUL_SAND:
case STONE:
case SUGAR_CANE_BLOCK:
case VINE:
case WATER_LILY:
case YELLOW_FLOWER:
case COCOA:
case EMERALD_ORE:
case CARROT:
case POTATO:
return true;
default:
return ModChecks.getCustomBlock(blockState) != null;
}
}
/**
* Check if a given block should allow for the activation of abilities
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should allow ability activation, false otherwise
*/
public static boolean canActivateAbilities(BlockState blockState) {
switch (blockState.getType()) {
case BED_BLOCK:
case BREWING_STAND:
case BOOKSHELF:
case BURNING_FURNACE:
case CAKE_BLOCK:
case CHEST:
case DISPENSER:
case ENCHANTMENT_TABLE:
case ENDER_CHEST:
case FENCE_GATE:
case FURNACE:
case IRON_DOOR_BLOCK:
case JUKEBOX:
case LEVER:
case NOTE_BLOCK:
case STONE_BUTTON:
case WOOD_BUTTON:
case TRAP_DOOR:
case WALL_SIGN:
case WOODEN_DOOR:
case WORKBENCH:
case BEACON:
case ANVIL:
return false;
default:
int blockId = blockState.getTypeId();
if (blockId == Config.getInstance().getRepairAnvilId() || blockId == Config.getInstance().getSalvageAnvilId()) {
return false;
}
if (ModChecks.isCustomAbilityBlock(blockState)) {
return false;
}
return true;
}
}
/**
* Check if a given block is an ore
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is an ore, false otherwise
*/
public static boolean isOre(BlockState blockState) {
switch (blockState.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case GLOWING_REDSTONE_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case EMERALD_ORE:
return true;
default:
return ModChecks.isCustomOreBlock(blockState);
}
}
/**
* Determine if a given block can be made mossy
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made mossy, false otherwise
*/
public static boolean canMakeMossy(BlockState blockState) {
switch (blockState.getType()) {
case COBBLESTONE:
case DIRT:
return true;
case SMOOTH_BRICK:
case COBBLE_WALL:
return blockState.getRawData() == (byte) 0x0;
default:
return false;
}
}
/**
* Determine if a given block should be affected by Green Terra
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Green Terra, false otherwise
*/
public static boolean affectedByGreenTerra(BlockState blockState) {
switch (blockState.getType()) {
case BROWN_MUSHROOM:
case CACTUS:
case MELON_BLOCK:
case PUMPKIN:
case RED_MUSHROOM:
case RED_ROSE:
case SUGAR_CANE_BLOCK:
case VINE:
case WATER_LILY:
case YELLOW_FLOWER:
return true;
case CARROT:
case CROPS:
case POTATO:
return blockState.getRawData() == CropState.RIPE.getData();
case NETHER_WARTS:
return blockState.getRawData() == (byte) 0x3;
case COCOA:
return ((CocoaPlant) blockState.getData()).getSize() == CocoaPlantSize.LARGE;
default:
return ModChecks.isCustomHerbalismBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Super Breaker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Super Breaker, false otherwise
*/
public static Boolean affectedBySuperBreaker(BlockState blockState) {
switch (blockState.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case ENDER_STONE:
case GLOWING_REDSTONE_ORE:
case GLOWSTONE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case MOSSY_COBBLESTONE:
case NETHERRACK:
case OBSIDIAN:
case REDSTONE_ORE:
case SANDSTONE:
case STONE:
case EMERALD_ORE:
return true;
default:
return ModChecks.isCustomMiningBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Giga Drill Breaker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Giga Drill Breaker, false otherwise
*/
public static boolean affectedByGigaDrillBreaker(BlockState blockState) {
switch (blockState.getType()) {
case CLAY:
case DIRT:
case GRASS:
case GRAVEL:
case MYCEL:
case SAND:
case SOUL_SAND:
return true;
default:
return ModChecks.isCustomExcavationBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Tree Feller
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Tree Feller, false otherwise
*/
public static boolean affectedByTreeFeller(BlockState blockState) {
switch (blockState.getType()) {
case LOG:
case LEAVES:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
return true;
default:
return ModChecks.isCustomWoodcuttingBlock(blockState);
}
}
/**
* Check if a given block is a log
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a log, false otherwise
*/
public static boolean isLog(BlockState blockState) {
switch (blockState.getType()) {
case LOG:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
return true;
default:
return ModChecks.isCustomLogBlock(blockState);
}
}
/**
* Check if a given block is a leaf
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a leaf, false otherwise
*/
public static boolean isLeaves(BlockState blockState) {
switch (blockState.getType()) {
case LEAVES:
return true;
default:
return ModChecks.isCustomLeafBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Flux Mining
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Flux Mining, false otherwise
*/
public static boolean affectedByFluxMining(BlockState blockState) {
switch (blockState.getType()) {
case IRON_ORE:
case GOLD_ORE:
return true;
default:
return false;
}
}
/**
* Determine if a given block can activate Herbalism abilities
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be activate Herbalism abilities, false otherwise
*/
public static boolean canActivateHerbalism(BlockState blockState) {
switch (blockState.getType()) {
case DIRT:
case GRASS:
case SOIL:
return false;
default:
return true;
}
}
/**
* Determine if a given block should be affected by Block Cracker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Block Cracker, false otherwise
*/
public static boolean affectedByBlockCracker(BlockState blockState) {
switch (blockState.getType()) {
case SMOOTH_BRICK:
return blockState.getRawData() == (byte) 0x0;
default:
return false;
}
}
/**
* Determine if a given block can be made into Mycelium
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made in Mycelium, false otherwise
*/
public static boolean canMakeShroomy(BlockState blockState) {
switch (blockState.getType()) {
case DIRT:
case GRASS:
return true;
default:
return false;
}
}
}

View File

@ -0,0 +1,364 @@
package com.gmail.nossr50.util;
import org.bukkit.CropState;
import org.bukkit.block.BlockState;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.CocoaPlant.CocoaPlantSize;
import com.gmail.nossr50.config.Config;
public final class BlockUtils {
private BlockUtils() {}
/**
* Checks to see if a given block awards XP.
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block awards XP, false otherwise
*/
public static boolean shouldBeWatched(BlockState blockState) {
switch (blockState.getType()) {
case BROWN_MUSHROOM:
case CACTUS:
case CLAY:
case COAL_ORE:
case DIAMOND_ORE:
case DIRT:
case ENDER_STONE:
case GLOWING_REDSTONE_ORE:
case GLOWSTONE:
case GOLD_ORE:
case GRASS:
case GRAVEL:
case IRON_ORE:
case LAPIS_ORE:
case LOG:
case MELON_BLOCK:
case MOSSY_COBBLESTONE:
case MYCEL:
case NETHERRACK:
case OBSIDIAN:
case PUMPKIN:
case RED_MUSHROOM:
case RED_ROSE:
case REDSTONE_ORE:
case SAND:
case SANDSTONE:
case SOUL_SAND:
case STONE:
case SUGAR_CANE_BLOCK:
case VINE:
case WATER_LILY:
case YELLOW_FLOWER:
case COCOA:
case EMERALD_ORE:
case CARROT:
case POTATO:
return true;
default:
return ModUtils.getCustomBlock(blockState) != null;
}
}
/**
* Check if a given block should allow for the activation of abilities
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should allow ability activation, false otherwise
*/
public static boolean canActivateAbilities(BlockState blockState) {
switch (blockState.getType()) {
case BED_BLOCK:
case BREWING_STAND:
case BOOKSHELF:
case BURNING_FURNACE:
case CAKE_BLOCK:
case CHEST:
case DISPENSER:
case ENCHANTMENT_TABLE:
case ENDER_CHEST:
case FENCE_GATE:
case FURNACE:
case IRON_DOOR_BLOCK:
case JUKEBOX:
case LEVER:
case NOTE_BLOCK:
case STONE_BUTTON:
case WOOD_BUTTON:
case TRAP_DOOR:
case WALL_SIGN:
case WOODEN_DOOR:
case WORKBENCH:
case BEACON:
case ANVIL:
return false;
default:
int blockId = blockState.getTypeId();
if (blockId == Config.getInstance().getRepairAnvilId() || blockId == Config.getInstance().getSalvageAnvilId()) {
return false;
}
if (ModUtils.isCustomAbilityBlock(blockState)) {
return false;
}
return true;
}
}
/**
* Check if a given block is an ore
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is an ore, false otherwise
*/
public static boolean isOre(BlockState blockState) {
switch (blockState.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case GLOWING_REDSTONE_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case EMERALD_ORE:
return true;
default:
return ModUtils.isCustomOreBlock(blockState);
}
}
/**
* Determine if a given block can be made mossy
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made mossy, false otherwise
*/
public static boolean canMakeMossy(BlockState blockState) {
switch (blockState.getType()) {
case COBBLESTONE:
case DIRT:
return true;
case SMOOTH_BRICK:
case COBBLE_WALL:
return blockState.getRawData() == (byte) 0x0;
default:
return false;
}
}
/**
* Determine if a given block should be affected by Green Terra
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Green Terra, false otherwise
*/
public static boolean affectedByGreenTerra(BlockState blockState) {
switch (blockState.getType()) {
case BROWN_MUSHROOM:
case CACTUS:
case MELON_BLOCK:
case PUMPKIN:
case RED_MUSHROOM:
case RED_ROSE:
case SUGAR_CANE_BLOCK:
case VINE:
case WATER_LILY:
case YELLOW_FLOWER:
return true;
case CARROT:
case CROPS:
case POTATO:
return blockState.getRawData() == CropState.RIPE.getData();
case NETHER_WARTS:
return blockState.getRawData() == (byte) 0x3;
case COCOA:
return ((CocoaPlant) blockState.getData()).getSize() == CocoaPlantSize.LARGE;
default:
return ModUtils.isCustomHerbalismBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Super Breaker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Super Breaker, false otherwise
*/
public static Boolean affectedBySuperBreaker(BlockState blockState) {
switch (blockState.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case ENDER_STONE:
case GLOWING_REDSTONE_ORE:
case GLOWSTONE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case MOSSY_COBBLESTONE:
case NETHERRACK:
case OBSIDIAN:
case REDSTONE_ORE:
case SANDSTONE:
case STONE:
case EMERALD_ORE:
return true;
default:
return ModUtils.isCustomMiningBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Giga Drill Breaker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Giga Drill Breaker, false otherwise
*/
public static boolean affectedByGigaDrillBreaker(BlockState blockState) {
switch (blockState.getType()) {
case CLAY:
case DIRT:
case GRASS:
case GRAVEL:
case MYCEL:
case SAND:
case SOUL_SAND:
return true;
default:
return ModUtils.isCustomExcavationBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Tree Feller
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Tree Feller, false otherwise
*/
public static boolean affectedByTreeFeller(BlockState blockState) {
switch (blockState.getType()) {
case LOG:
case LEAVES:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
return true;
default:
return ModUtils.isCustomWoodcuttingBlock(blockState);
}
}
/**
* Check if a given block is a log
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a log, false otherwise
*/
public static boolean isLog(BlockState blockState) {
switch (blockState.getType()) {
case LOG:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
return true;
default:
return ModUtils.isCustomLogBlock(blockState);
}
}
/**
* Check if a given block is a leaf
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a leaf, false otherwise
*/
public static boolean isLeaves(BlockState blockState) {
switch (blockState.getType()) {
case LEAVES:
return true;
default:
return ModUtils.isCustomLeafBlock(blockState);
}
}
/**
* Determine if a given block should be affected by Flux Mining
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Flux Mining, false otherwise
*/
public static boolean affectedByFluxMining(BlockState blockState) {
switch (blockState.getType()) {
case IRON_ORE:
case GOLD_ORE:
return true;
default:
return false;
}
}
/**
* Determine if a given block can activate Herbalism abilities
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be activate Herbalism abilities, false otherwise
*/
public static boolean canActivateHerbalism(BlockState blockState) {
switch (blockState.getType()) {
case DIRT:
case GRASS:
case SOIL:
return false;
default:
return true;
}
}
/**
* Determine if a given block should be affected by Block Cracker
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Block Cracker, false otherwise
*/
public static boolean affectedByBlockCracker(BlockState blockState) {
switch (blockState.getType()) {
case SMOOTH_BRICK:
return blockState.getRawData() == (byte) 0x0;
default:
return false;
}
}
/**
* Determine if a given block can be made into Mycelium
*
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made in Mycelium, false otherwise
*/
public static boolean canMakeShroomy(BlockState blockState) {
switch (blockState.getType()) {
case DIRT:
case GRASS:
return true;
default:
return false;
}
}
}

View File

@ -6,10 +6,11 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.utilities.SkillTools;
import com.gmail.nossr50.util.metrics.MetricsManager;
import com.gmail.nossr50.metrics.MetricsManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class ChimaeraWing {
private ChimaeraWing() {}
@ -26,13 +27,13 @@ public final class ChimaeraWing {
return;
}
PlayerProfile profile = Users.getPlayer(player).getProfile();
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
Block block = player.getLocation().getBlock();
int amount = inHand.getAmount();
long recentlyHurt = profile.getRecentlyHurt();
if (Permissions.chimaeraWing(player) && inHand.getTypeId() == Config.getInstance().getChimaeraItemId()) {
if (SkillTools.cooldownOver(recentlyHurt, 60, player) && amount >= Config.getInstance().getChimaeraCost()) {
if (SkillUtils.cooldownOver(recentlyHurt, 60, player) && amount >= Config.getInstance().getChimaeraCost()) {
player.setItemInHand(new ItemStack(Config.getInstance().getChimaeraItemId(), amount - Config.getInstance().getChimaeraCost()));
for (int y = 1; block.getY() + y < player.getWorld().getMaxHeight(); y++) {
@ -53,8 +54,8 @@ public final class ChimaeraWing {
MetricsManager.chimeraWingUsed();
player.sendMessage(LocaleLoader.getString("Item.ChimaeraWing.Pass"));
}
else if (!SkillTools.cooldownOver(recentlyHurt, 60, player) && amount >= Config.getInstance().getChimaeraCost()) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillTools.calculateTimeLeft(recentlyHurt, 60, player)));
else if (!SkillUtils.cooldownOver(recentlyHurt, 60, player) && amount >= Config.getInstance().getChimaeraCost()) {
player.sendMessage(LocaleLoader.getString("Item.Injured.Wait", SkillUtils.calculateTimeLeft(recentlyHurt, 60, player)));
}
else if (amount <= Config.getInstance().getChimaeraCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", StringUtils.getPrettyItemString(Config.getInstance().getChimaeraItemId())));

View File

@ -3,12 +3,13 @@ package com.gmail.nossr50.util;
import org.bukkit.entity.Player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.utilities.SkillType;
import com.gmail.nossr50.util.player.UserManager;
public final class Hardcore {
private Hardcore() {}
public final class HardcoreManager {
private HardcoreManager() {}
public static void invokeStatPenalty(Player player) {
double statLossPercentage = Config.getInstance().getHardcoreDeathStatPenaltyPercentage();
@ -17,7 +18,7 @@ public final class Hardcore {
return;
}
PlayerProfile playerProfile = Users.getPlayer(player).getProfile();
PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile();
int totalLost = 0;
for (SkillType skillType : SkillType.values()) {
@ -37,7 +38,7 @@ public final class Hardcore {
playerProfile.modifySkill(skillType, playerSkillLevel - levelsLost);
}
player.sendMessage(LocaleLoader.getString("Hardcore.Player.Loss", new Object[] {totalLost}));
player.sendMessage(LocaleLoader.getString("Hardcore.Player.Loss", totalLost));
}
public static void invokeVampirism(Player killer, Player victim) {
@ -47,8 +48,8 @@ public final class Hardcore {
return;
}
PlayerProfile killerProfile = Users.getPlayer(killer).getProfile();
PlayerProfile victimProfile = Users.getPlayer(victim).getProfile();
PlayerProfile killerProfile = UserManager.getPlayer(killer).getProfile();
PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile();
int totalStolen = 0;
for (SkillType skillType : SkillType.values()) {
@ -79,4 +80,4 @@ public final class Hardcore {
victim.sendMessage(LocaleLoader.getString("Vampirism.Victim.Failure", killer.getName()));
}
}
}
}

View File

@ -25,22 +25,24 @@ import org.bukkit.inventory.meta.FireworkMeta;
import com.gmail.nossr50.mcMMO;
public final class Anniversary {
public final class HolidayManager {
public static ArrayList<String> hasCelebrated;
private Anniversary() {}
private HolidayManager() {}
//This gets called onEnable
// This gets called onEnable
public static void createAnniversaryFile() {
File anniversaryFile = new File(mcMMO.p.getDataFolder().getAbsolutePath() + File.separator + "anniversary");
if (!anniversaryFile.exists()) {
try {
anniversaryFile.createNewFile();
} catch (IOException ex) {
}
catch (IOException ex) {
mcMMO.p.getLogger().severe(ex.toString());
}
}
hasCelebrated = new ArrayList<String>();
try {
@ -54,12 +56,13 @@ public final class Anniversary {
}
reader.close();
} catch (Exception ex) {
}
catch (Exception ex) {
mcMMO.p.getLogger().severe(ex.toString());
}
}
//This gets called onDisable
// This gets called onDisable
public static void saveAnniversaryFiles() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(mcMMO.p.getDataFolder().getAbsolutePath() + File.separator + "anniversary"));
@ -74,7 +77,7 @@ public final class Anniversary {
}
}
//This gets called from /mcmmo command
// This gets called from /mcmmo command
public static void anniversaryCheck(final CommandSender sender) {
if (sender instanceof Player) {
GregorianCalendar anniversaryStart = new GregorianCalendar(2013, Calendar.FEBRUARY, 3);
@ -115,12 +118,27 @@ public final class Anniversary {
int power = (int) (Math.random() * 3) + 1;
int type = (int) (Math.random() * 5) + 1;
Type typen = Type.BALL;
if (type == 1) typen = Type.BALL;
if (type == 2) typen = Type.BALL_LARGE;
if (type == 3) typen = Type.BURST;
if (type == 4) typen = Type.CREEPER;
if (type == 5) typen = Type.STAR;
Type typen;
switch (type) {
case 2:
typen = Type.BALL_LARGE;
break;
case 3:
typen = Type.BURST;
break;
case 4:
typen = Type.CREEPER;
break;
case 5:
typen = Type.STAR;
break;
default:
typen = Type.BALL;
}
Firework fireworks = (Firework) player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK);
FireworkMeta fireworkmeta = fireworks.getFireworkMeta();

View File

@ -1,650 +0,0 @@
package com.gmail.nossr50.util;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.api.SpoutToolsAPI;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mods.config.CustomArmorConfig;
import com.gmail.nossr50.mods.config.CustomToolsConfig;
public class ItemChecks {
private static Config configInstance = Config.getInstance();
private static boolean customToolsEnabled = configInstance.getToolModsEnabled();
private static boolean customArmorEnabled = configInstance.getArmorModsEnabled();
/**
* Checks if the item is a sword.
*
* @param is Item to check
* @return true if the item is a sword, false otherwise
*/
public static boolean isSword(ItemStack is) {
switch (is.getType()) {
case DIAMOND_SWORD:
case GOLD_SWORD:
case IRON_SWORD:
case STONE_SWORD:
case WOOD_SWORD:
return true;
default:
if (customToolsEnabled && CustomToolsConfig.getInstance().customSwordIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutSwords.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a hoe.
*
* @param is Item to check
* @return true if the item is a hoe, false otherwise
*/
public static boolean isHoe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_HOE:
case GOLD_HOE:
case IRON_HOE:
case STONE_HOE:
case WOOD_HOE:
return true;
default:
if (customToolsEnabled && CustomToolsConfig.getInstance().customHoeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutHoes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a shovel.
*
* @param is Item to check
* @return true if the item is a shovel, false otherwise
*/
public static boolean isShovel(ItemStack is) {
switch (is.getType()) {
case DIAMOND_SPADE:
case GOLD_SPADE:
case IRON_SPADE:
case STONE_SPADE:
case WOOD_SPADE:
return true;
default:
if (customToolsEnabled && CustomToolsConfig.getInstance().customShovelIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutShovels.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is an axe.
*
* @param is Item to check
* @return true if the item is an axe, false otherwise
*/
public static boolean isAxe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case WOOD_AXE:
return true;
default:
if (customToolsEnabled && CustomToolsConfig.getInstance().customAxeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutAxes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a pickaxe.
*
* @param is Item to check
* @return true if the item is a pickaxe, false otherwise
*/
public static boolean isPickaxe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case WOOD_PICKAXE:
return true;
default:
if (customToolsEnabled && CustomToolsConfig.getInstance().customPickaxeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutPickaxes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a helmet.
*
* @param is Item to check
* @return true if the item is a helmet, false otherwise
*/
public static boolean isHelmet(ItemStack is) {
switch (is.getType()) {
case DIAMOND_HELMET:
case GOLD_HELMET:
case IRON_HELMET:
case LEATHER_HELMET:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customHelmetIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a chestplate.
*
* @param is Item to check
* @return true if the item is a chestplate, false otherwise
*/
public static boolean isChestplate(ItemStack is) {
switch (is.getType()) {
case DIAMOND_CHESTPLATE:
case GOLD_CHESTPLATE:
case IRON_CHESTPLATE:
case LEATHER_CHESTPLATE:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customChestplateIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a pair of pants.
*
* @param is Item to check
* @return true if the item is a pair of pants, false otherwise
*/
public static boolean isLeggings(ItemStack is) {
switch (is.getType()) {
case DIAMOND_LEGGINGS:
case GOLD_LEGGINGS:
case IRON_LEGGINGS:
case LEATHER_LEGGINGS:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customLeggingIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a pair of boots.
*
* @param is Item to check
* @return true if the item is a pair of boots, false otherwise
*/
public static boolean isBoots(ItemStack is) {
switch (is.getType()) {
case DIAMOND_BOOTS:
case GOLD_BOOTS:
case IRON_BOOTS:
case LEATHER_BOOTS:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customBootIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks to see if an item is a wearable armor piece.
*
* @param is Item to check
* @return true if the item is armor, false otherwise
*/
public static boolean isArmor(ItemStack is) {
return isHelmet(is) || isChestplate(is) || isLeggings(is) || isBoots(is);
}
/**
* Checks to see if an item is a wearable armor piece.
*
* @param is Item to check
* @return true if the item is armor, false otherwise
*/
public static boolean isMinecraftArmor(ItemStack is) {
return isDiamondArmor(is) || isGoldArmor(is) || isIronArmor(is) || isDiamondArmor(is);
}
/**
* Checks to see if an item is a leather armor piece.
*
* @param is Item to check
* @return true if the item is leather armor, false otherwise
*/
public static boolean isLeatherArmor(ItemStack is) {
switch (is.getType()) {
case LEATHER_BOOTS:
case LEATHER_CHESTPLATE:
case LEATHER_HELMET:
case LEATHER_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a gold armor piece.
*
* @param is Item to check
* @return true if the item is gold armor, false otherwise
*/
public static boolean isGoldArmor(ItemStack is) {
switch (is.getType()) {
case GOLD_BOOTS:
case GOLD_CHESTPLATE:
case GOLD_HELMET:
case GOLD_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is an iron armor piece.
*
* @param is Item to check
* @return true if the item is iron armor, false otherwise
*/
public static boolean isIronArmor(ItemStack is) {
switch (is.getType()) {
case IRON_BOOTS:
case IRON_CHESTPLATE:
case IRON_HELMET:
case IRON_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a diamond armor piece.
*
* @param is Item to check
* @return true if the item is diamond armor, false otherwise
*/
public static boolean isDiamondArmor(ItemStack is) {
switch (is.getType()) {
case DIAMOND_BOOTS:
case DIAMOND_CHESTPLATE:
case DIAMOND_HELMET:
case DIAMOND_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a tool.
*
* @param is Item to check
* @return true if the item is a tool, false otherwise
*/
public static boolean isMinecraftTool(ItemStack is) {
return isStoneTool(is) || isWoodTool(is) || isGoldTool(is) || isIronTool(is) || isDiamondTool(is) || isStringTool(is);
}
/**
* Checks to see if an item is a stone tool.
*
* @param is Item to check
* @return true if the item is a stone tool, false otherwise
*/
public static boolean isStoneTool(ItemStack is) {
switch (is.getType()) {
case STONE_AXE:
case STONE_HOE:
case STONE_PICKAXE:
case STONE_SPADE:
case STONE_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a wooden tool.
*
* @param is Item to check
* @return true if the item is a wooden tool, false otherwise
*/
public static boolean isWoodTool(ItemStack is) {
switch (is.getType()) {
case WOOD_AXE:
case WOOD_HOE:
case WOOD_PICKAXE:
case WOOD_SPADE:
case WOOD_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a string tool.
*
* @param is Item to check
* @return true if the item is a string tool, false otherwise
*/
public static boolean isStringTool(ItemStack is) {
switch (is.getType()) {
case BOW:
case CARROT_STICK:
case FISHING_ROD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a gold tool.
*
* @param is Item to check
* @return true if the item is a stone tool, false otherwise
*/
public static boolean isGoldTool(ItemStack is) {
switch (is.getType()) {
case GOLD_AXE:
case GOLD_HOE:
case GOLD_PICKAXE:
case GOLD_SPADE:
case GOLD_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is an iron tool.
*
* @param is Item to check
* @return true if the item is an iron tool, false otherwise
*/
public static boolean isIronTool(ItemStack is) {
switch (is.getType()) {
case BUCKET:
case FLINT_AND_STEEL:
case IRON_AXE:
case IRON_HOE:
case IRON_PICKAXE:
case IRON_SPADE:
case IRON_SWORD:
case SHEARS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a diamond tool.
*
* @param is Item to check
* @return true if the item is a diamond tool, false otherwise
*/
public static boolean isDiamondTool(ItemStack is) {
switch (is.getType()) {
case DIAMOND_AXE:
case DIAMOND_HOE:
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is enchantable.
*
* @param is Item to check
* @return true if the item is enchantable, false otherwise
*/
public static boolean isEnchantable(ItemStack is) {
Material type = is.getType();
return isArmor(is) || isSword(is) || isAxe(is) || isShovel(is) || isPickaxe(is) ||
type == Material.SHEARS || type == Material.FISHING_ROD || type == Material.CARROT_STICK ||
type == Material.FLINT_AND_STEEL || type == Material.BOW;
}
public static boolean isSmeltable(ItemStack itemStack) {
switch (itemStack.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case GLOWING_REDSTONE_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case EMERALD_ORE:
return true;
default:
return false;
}
}
public static boolean isSmelted(ItemStack itemStack) {
switch (itemStack.getType()) {
case COAL:
case DIAMOND:
case REDSTONE:
case GOLD_INGOT:
case IRON_INGOT:
case EMERALD:
return true;
case INK_SACK:
if (itemStack.getData().getData() == DyeColor.BLUE.getDyeData()) {
return true;
}
return false;
default:
return false;
}
}
/**
* Check if an item is sharable.
*
* @param item Item that will get shared
* @return True if the item can be shared.
*/
public static boolean isShareable(ItemStack is) {
return isMiningDrop(is) || isWoodcuttingDrop(is) || isMobDrop(is) || isHerbalismDrop(is);
}
/**
* Checks to see if an item is a mining drop.
*
* @param is Item to check
* @return true if the item is a mining drop, false otherwise
*/
public static boolean isMiningDrop(ItemStack is) {
switch (is.getType()) {
case COAL:
case COAL_ORE:
case DIAMOND:
case DIAMOND_ORE:
case EMERALD:
case EMERALD_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case REDSTONE:
case GLOWSTONE_DUST:
return true;
case INK_SACK:
if (is.getData().getData() == DyeColor.BLUE.getDyeData()) {
return true;
}
return false;
default:
return false;
}
}
public static boolean isHerbalismDrop(ItemStack is) {
switch (is.getType()) {
case WHEAT:
case SEEDS:
case CARROT:
case POTATO:
case COCOA:
case NETHER_WARTS:
case BROWN_MUSHROOM:
case RED_MUSHROOM:
case RED_ROSE:
case YELLOW_FLOWER:
case CACTUS:
case SUGAR_CANE:
case MELON:
case PUMPKIN:
case WATER_LILY:
case VINE:
return true;
case INK_SACK:
return is.getData().getData() == DyeColor.BROWN.getDyeData();
default:
return false;
}
}
public static boolean isMobDrop(ItemStack is) {
switch (is.getType()) {
case STRING:
case FEATHER:
case RAW_CHICKEN:
case COOKED_CHICKEN:
case LEATHER:
case RAW_BEEF:
case COOKED_BEEF:
case PORK:
case GRILLED_PORK:
case WOOL:
case RED_ROSE:
case IRON_INGOT:
case SNOW_BALL:
case BLAZE_ROD:
case SPIDER_EYE:
case SULPHUR:
case ENDER_PEARL:
case GHAST_TEAR:
case MAGMA_CREAM:
case BONE:
case ARROW:
case SLIME_BALL:
case NETHER_STAR:
case COAL:
case ROTTEN_FLESH:
case GOLD_NUGGET:
case EGG:
return true;
default:
return false;
}
}
public static boolean isWoodcuttingDrop(ItemStack is) {
switch (is.getType()) {
case LOG:
case LEAVES:
case SAPLING:
case APPLE:
return true;
default:
return false;
}
}
}

View File

@ -0,0 +1,647 @@
package com.gmail.nossr50.util;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.api.SpoutToolsAPI;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.mods.CustomArmorConfig;
import com.gmail.nossr50.config.mods.CustomToolConfig;
public class ItemUtils {
private static Config configInstance = Config.getInstance();
private static boolean customToolsEnabled = configInstance.getToolModsEnabled();
private static boolean customArmorEnabled = configInstance.getArmorModsEnabled();
/**
* Checks if the item is a sword.
*
* @param is Item to check
* @return true if the item is a sword, false otherwise
*/
public static boolean isSword(ItemStack is) {
switch (is.getType()) {
case DIAMOND_SWORD:
case GOLD_SWORD:
case IRON_SWORD:
case STONE_SWORD:
case WOOD_SWORD:
return true;
default:
if (customToolsEnabled && CustomToolConfig.getInstance().customSwordIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutSwords.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a hoe.
*
* @param is Item to check
* @return true if the item is a hoe, false otherwise
*/
public static boolean isHoe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_HOE:
case GOLD_HOE:
case IRON_HOE:
case STONE_HOE:
case WOOD_HOE:
return true;
default:
if (customToolsEnabled && CustomToolConfig.getInstance().customHoeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutHoes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a shovel.
*
* @param is Item to check
* @return true if the item is a shovel, false otherwise
*/
public static boolean isShovel(ItemStack is) {
switch (is.getType()) {
case DIAMOND_SPADE:
case GOLD_SPADE:
case IRON_SPADE:
case STONE_SPADE:
case WOOD_SPADE:
return true;
default:
if (customToolsEnabled && CustomToolConfig.getInstance().customShovelIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutShovels.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is an axe.
*
* @param is Item to check
* @return true if the item is an axe, false otherwise
*/
public static boolean isAxe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case WOOD_AXE:
return true;
default:
if (customToolsEnabled && CustomToolConfig.getInstance().customAxeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutAxes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a pickaxe.
*
* @param is Item to check
* @return true if the item is a pickaxe, false otherwise
*/
public static boolean isPickaxe(ItemStack is) {
switch (is.getType()) {
case DIAMOND_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case WOOD_PICKAXE:
return true;
default:
if (customToolsEnabled && CustomToolConfig.getInstance().customPickaxeIDs.contains(is.getTypeId())) {
return true;
}
else if (mcMMO.spoutEnabled && SpoutToolsAPI.spoutPickaxes.contains(is)) {
return true;
}
else {
return false;
}
}
}
/**
* Checks if the item is a helmet.
*
* @param is Item to check
* @return true if the item is a helmet, false otherwise
*/
public static boolean isHelmet(ItemStack is) {
switch (is.getType()) {
case DIAMOND_HELMET:
case GOLD_HELMET:
case IRON_HELMET:
case LEATHER_HELMET:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customHelmetIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a chestplate.
*
* @param is Item to check
* @return true if the item is a chestplate, false otherwise
*/
public static boolean isChestplate(ItemStack is) {
switch (is.getType()) {
case DIAMOND_CHESTPLATE:
case GOLD_CHESTPLATE:
case IRON_CHESTPLATE:
case LEATHER_CHESTPLATE:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customChestplateIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a pair of pants.
*
* @param is Item to check
* @return true if the item is a pair of pants, false otherwise
*/
public static boolean isLeggings(ItemStack is) {
switch (is.getType()) {
case DIAMOND_LEGGINGS:
case GOLD_LEGGINGS:
case IRON_LEGGINGS:
case LEATHER_LEGGINGS:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customLeggingIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks if the item is a pair of boots.
*
* @param is Item to check
* @return true if the item is a pair of boots, false otherwise
*/
public static boolean isBoots(ItemStack is) {
switch (is.getType()) {
case DIAMOND_BOOTS:
case GOLD_BOOTS:
case IRON_BOOTS:
case LEATHER_BOOTS:
return true;
default:
if (customArmorEnabled && CustomArmorConfig.getInstance().customBootIDs.contains(is.getTypeId())) {
return true;
}
return false;
}
}
/**
* Checks to see if an item is a wearable armor piece.
*
* @param is Item to check
* @return true if the item is armor, false otherwise
*/
public static boolean isArmor(ItemStack is) {
return isHelmet(is) || isChestplate(is) || isLeggings(is) || isBoots(is);
}
/**
* Checks to see if an item is a wearable armor piece.
*
* @param is Item to check
* @return true if the item is armor, false otherwise
*/
public static boolean isMinecraftArmor(ItemStack is) {
return isDiamondArmor(is) || isGoldArmor(is) || isIronArmor(is) || isDiamondArmor(is);
}
/**
* Checks to see if an item is a leather armor piece.
*
* @param is Item to check
* @return true if the item is leather armor, false otherwise
*/
public static boolean isLeatherArmor(ItemStack is) {
switch (is.getType()) {
case LEATHER_BOOTS:
case LEATHER_CHESTPLATE:
case LEATHER_HELMET:
case LEATHER_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a gold armor piece.
*
* @param is Item to check
* @return true if the item is gold armor, false otherwise
*/
public static boolean isGoldArmor(ItemStack is) {
switch (is.getType()) {
case GOLD_BOOTS:
case GOLD_CHESTPLATE:
case GOLD_HELMET:
case GOLD_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is an iron armor piece.
*
* @param is Item to check
* @return true if the item is iron armor, false otherwise
*/
public static boolean isIronArmor(ItemStack is) {
switch (is.getType()) {
case IRON_BOOTS:
case IRON_CHESTPLATE:
case IRON_HELMET:
case IRON_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a diamond armor piece.
*
* @param is Item to check
* @return true if the item is diamond armor, false otherwise
*/
public static boolean isDiamondArmor(ItemStack is) {
switch (is.getType()) {
case DIAMOND_BOOTS:
case DIAMOND_CHESTPLATE:
case DIAMOND_HELMET:
case DIAMOND_LEGGINGS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a tool.
*
* @param is Item to check
* @return true if the item is a tool, false otherwise
*/
public static boolean isMinecraftTool(ItemStack is) {
return isStoneTool(is) || isWoodTool(is) || isGoldTool(is) || isIronTool(is) || isDiamondTool(is) || isStringTool(is);
}
/**
* Checks to see if an item is a stone tool.
*
* @param is Item to check
* @return true if the item is a stone tool, false otherwise
*/
public static boolean isStoneTool(ItemStack is) {
switch (is.getType()) {
case STONE_AXE:
case STONE_HOE:
case STONE_PICKAXE:
case STONE_SPADE:
case STONE_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a wooden tool.
*
* @param is Item to check
* @return true if the item is a wooden tool, false otherwise
*/
public static boolean isWoodTool(ItemStack is) {
switch (is.getType()) {
case WOOD_AXE:
case WOOD_HOE:
case WOOD_PICKAXE:
case WOOD_SPADE:
case WOOD_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a string tool.
*
* @param is Item to check
* @return true if the item is a string tool, false otherwise
*/
public static boolean isStringTool(ItemStack is) {
switch (is.getType()) {
case BOW:
case CARROT_STICK:
case FISHING_ROD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a gold tool.
*
* @param is Item to check
* @return true if the item is a stone tool, false otherwise
*/
public static boolean isGoldTool(ItemStack is) {
switch (is.getType()) {
case GOLD_AXE:
case GOLD_HOE:
case GOLD_PICKAXE:
case GOLD_SPADE:
case GOLD_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is an iron tool.
*
* @param is Item to check
* @return true if the item is an iron tool, false otherwise
*/
public static boolean isIronTool(ItemStack is) {
switch (is.getType()) {
case BUCKET:
case FLINT_AND_STEEL:
case IRON_AXE:
case IRON_HOE:
case IRON_PICKAXE:
case IRON_SPADE:
case IRON_SWORD:
case SHEARS:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is a diamond tool.
*
* @param is Item to check
* @return true if the item is a diamond tool, false otherwise
*/
public static boolean isDiamondTool(ItemStack is) {
switch (is.getType()) {
case DIAMOND_AXE:
case DIAMOND_HOE:
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_SWORD:
return true;
default:
return false;
}
}
/**
* Checks to see if an item is enchantable.
*
* @param is Item to check
* @return true if the item is enchantable, false otherwise
*/
public static boolean isEnchantable(ItemStack is) {
Material type = is.getType();
return isArmor(is) || isSword(is) || isAxe(is) || isShovel(is) || isPickaxe(is) || type == Material.SHEARS || type == Material.FISHING_ROD || type == Material.CARROT_STICK || type == Material.FLINT_AND_STEEL || type == Material.BOW;
}
public static boolean isSmeltable(ItemStack itemStack) {
switch (itemStack.getType()) {
case COAL_ORE:
case DIAMOND_ORE:
case GLOWING_REDSTONE_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case EMERALD_ORE:
return true;
default:
return false;
}
}
public static boolean isSmelted(ItemStack itemStack) {
switch (itemStack.getType()) {
case COAL:
case DIAMOND:
case REDSTONE:
case GOLD_INGOT:
case IRON_INGOT:
case EMERALD:
return true;
case INK_SACK:
if (itemStack.getData().getData() == DyeColor.BLUE.getDyeData()) {
return true;
}
return false;
default:
return false;
}
}
/**
* Check if an item is sharable.
*
* @param item Item that will get shared
* @return True if the item can be shared.
*/
public static boolean isShareable(ItemStack is) {
return isMiningDrop(is) || isWoodcuttingDrop(is) || isMobDrop(is) || isHerbalismDrop(is);
}
/**
* Checks to see if an item is a mining drop.
*
* @param is Item to check
* @return true if the item is a mining drop, false otherwise
*/
public static boolean isMiningDrop(ItemStack is) {
switch (is.getType()) {
case COAL:
case COAL_ORE:
case DIAMOND:
case DIAMOND_ORE:
case EMERALD:
case EMERALD_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case REDSTONE_ORE:
case REDSTONE:
case GLOWSTONE_DUST:
return true;
case INK_SACK:
if (is.getData().getData() == DyeColor.BLUE.getDyeData()) {
return true;
}
return false;
default:
return false;
}
}
public static boolean isHerbalismDrop(ItemStack is) {
switch (is.getType()) {
case WHEAT:
case SEEDS:
case CARROT:
case POTATO:
case COCOA:
case NETHER_WARTS:
case BROWN_MUSHROOM:
case RED_MUSHROOM:
case RED_ROSE:
case YELLOW_FLOWER:
case CACTUS:
case SUGAR_CANE:
case MELON:
case PUMPKIN:
case WATER_LILY:
case VINE:
return true;
case INK_SACK:
return is.getData().getData() == DyeColor.BROWN.getDyeData();
default:
return false;
}
}
public static boolean isMobDrop(ItemStack is) {
switch (is.getType()) {
case STRING:
case FEATHER:
case RAW_CHICKEN:
case COOKED_CHICKEN:
case LEATHER:
case RAW_BEEF:
case COOKED_BEEF:
case PORK:
case GRILLED_PORK:
case WOOL:
case RED_ROSE:
case IRON_INGOT:
case SNOW_BALL:
case BLAZE_ROD:
case SPIDER_EYE:
case SULPHUR:
case ENDER_PEARL:
case GHAST_TEAR:
case MAGMA_CREAM:
case BONE:
case ARROW:
case SLIME_BALL:
case NETHER_STAR:
case COAL:
case ROTTEN_FLESH:
case GOLD_NUGGET:
case EGG:
return true;
default:
return false;
}
}
public static boolean isWoodcuttingDrop(ItemStack is) {
switch (is.getType()) {
case LOG:
case LEAVES:
case SAPLING:
case APPLE:
return true;
default:
return false;
}
}
}

View File

@ -11,7 +11,6 @@ import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.events.items.McMMOItemSpawnEvent;
import com.gmail.nossr50.mods.ModChecks;
public final class Misc {
private static Random random = new Random();
@ -19,13 +18,14 @@ public final class Misc {
public static final int PLAYER_RESPAWN_COOLDOWN_SECONDS = 5;
public static final int TIME_CONVERSION_FACTOR = 1000;
public static final double SKILL_MESSAGE_MAX_SENDING_DISTANCE = 10.0;
//Sound Pitches & Volumes from CB
public static final float ANVIL_USE_PITCH = 0.3F; // Not in CB directly, I went off the place sound values
// Sound Pitches & Volumes from CB
public static final float ANVIL_USE_PITCH = 0.3F; // Not in CB directly, I went off the place sound values
public static final float ANVIL_USE_VOLUME = 1.0F; // Not in CB directly, I went off the place sound values
public static final float FIZZ_PITCH = 2.6F + (Misc.getRandom().nextFloat() - Misc.getRandom().nextFloat()) * 0.8F;
public static final float FIZZ_VOLUME = 0.5F;
public static final float POP_PITCH = ((getRandom().nextFloat() - getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F;
public static final float POP_VOLUME = 0.2F;
public static final float FIZZ_PITCH = 2.6F + (Misc.getRandom().nextFloat() - Misc.getRandom().nextFloat()) * 0.8F;
public static final float FIZZ_VOLUME = 0.5F;
public static final float POP_PITCH = ((getRandom().nextFloat() - getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F;
public static final float POP_VOLUME = 0.2F;
private Misc() {};
@ -46,23 +46,23 @@ public final class Misc {
public static int getTier(ItemStack inHand) {
int tier = 0;
if (ItemChecks.isWoodTool(inHand)) {
if (ItemUtils.isWoodTool(inHand)) {
tier = 1;
}
else if (ItemChecks.isStoneTool(inHand)) {
else if (ItemUtils.isStoneTool(inHand)) {
tier = 2;
}
else if (ItemChecks.isIronTool(inHand)) {
else if (ItemUtils.isIronTool(inHand)) {
tier = 3;
}
else if (ItemChecks.isGoldTool(inHand)) {
else if (ItemUtils.isGoldTool(inHand)) {
tier = 1;
}
else if (ItemChecks.isDiamondTool(inHand)) {
else if (ItemUtils.isDiamondTool(inHand)) {
tier = 4;
}
else if (ModChecks.isCustomTool(inHand)) {
tier = ModChecks.getToolFromItemStack(inHand).getTier();
else if (ModUtils.isCustomTool(inHand)) {
tier = ModUtils.getToolFromItemStack(inHand).getTier();
}
return tier;
@ -147,8 +147,9 @@ public final class Misc {
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack);
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled())
if (event.isCancelled()) {
return;
}
Item newItem = location.getWorld().dropItemNaturally(location, itemStack);

View File

@ -0,0 +1,294 @@
package com.gmail.nossr50.util;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.mods.CustomArmorConfig;
import com.gmail.nossr50.config.mods.CustomBlockConfig;
import com.gmail.nossr50.config.mods.CustomEntityConfig;
import com.gmail.nossr50.config.mods.CustomToolConfig;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
import com.gmail.nossr50.datatypes.mods.CustomEntity;
import com.gmail.nossr50.datatypes.mods.CustomItem;
import com.gmail.nossr50.datatypes.mods.CustomTool;
public final class ModUtils {
private static Config configInstance = Config.getInstance();
private static boolean customToolsEnabled = configInstance.getToolModsEnabled();
private static boolean customArmorEnabled = configInstance.getArmorModsEnabled();
private static boolean customBlocksEnabled = configInstance.getBlockModsEnabled();
private static boolean customEntitiesEnabled = configInstance.getEntityModsEnabled();
private ModUtils() {}
/**
* Get the custom armor associated with an item.
*
* @param item The item to check
* @return the armor if it exists, null otherwise
*/
public static CustomItem getArmorFromItemStack(ItemStack item) {
return CustomArmorConfig.getInstance().customArmor.get(item.getTypeId());
}
/**
* Get the custom tool associated with an item.
*
* @param item The item to check
* @return the tool if it exists, null otherwise
*/
public static CustomTool getToolFromItemStack(ItemStack item) {
return CustomToolConfig.getInstance().customTools.get(item.getTypeId());
}
/**
* Get the custom block associated with an block.
*
* @param blockState The block to check
* @return the block if it exists, null otherwise
*/
public static CustomBlock getCustomBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customItems.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return block;
}
}
}
}
return null;
}
public static CustomEntity getCustomEntity(Entity entity) {
if (!CustomEntityConfig.getInstance().customEntityIds.contains(entity.getEntityId()) && !CustomEntityConfig.getInstance().customEntityTypes.contains(entity.getType())) {
return null;
}
for (CustomEntity customEntity : CustomEntityConfig.getInstance().customEntities) {
if ((customEntity.getEntityID() == entity.getEntityId()) && (customEntity.getEntityType() == entity.getType())) {
return customEntity;
}
}
return null;
}
/**
* Check if a custom block is a woodcutting block.
*
* @param block The block to check
* @return true if the block represents a log, false otherwise
*/
public static boolean isCustomWoodcuttingBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customWoodcuttingBlocks.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block should not activate abilites.
*
* @param block The block to check
* @return true if the block represents an ability block, false otherwise
*/
public static boolean isCustomAbilityBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customAbilityBlocks.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is a mining block.
*
* @param block The block to check
* @return true if the block is custom, false otherwise
*/
public static boolean isCustomMiningBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customMiningBlocks.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is an excavation block.
*
* @param block The block to check
* @return true if the block is custom, false otherwise
*/
public static boolean isCustomExcavationBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customExcavationBlocks.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is an herbalism block.
*
* @param blockState The block to check
* @return true if the block is custom, false otherwise
*/
public static boolean isCustomHerbalismBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customHerbalismBlocks.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is a leaf block.
*
* @param block The block to check
* @return true if the block represents leaves, false otherwise
*/
public static boolean isCustomLeafBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customLeaves.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is a log block.
*
* @param block The block to check
* @return true if the block represents a log, false otherwise
*/
public static boolean isCustomLogBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customLogs.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Check if a custom block is an ore block.
*
* @param blockState The block to check
* @return true if the block represents an ore, false otherwise
*/
public static boolean isCustomOreBlock(BlockState blockState) {
if (customBlocksEnabled) {
ItemStack item = blockState.getData().toItemStack();
if (CustomBlockConfig.getInstance().customOres.contains(item)) {
for (CustomBlock block : CustomBlockConfig.getInstance().customBlocks) {
if ((block.getItemID() == blockState.getTypeId()) && (block.getDataValue() == blockState.getRawData())) {
return true;
}
}
}
}
return false;
}
/**
* Checks to see if an item is a custom tool.
*
* @param item Item to check
* @return true if the item is a custom tool, false otherwise
*/
public static boolean isCustomTool(ItemStack item) {
if (customToolsEnabled && CustomToolConfig.getInstance().customTools.containsKey(item.getTypeId())) {
return true;
}
return false;
}
/**
* Checks to see if an item is custom armor.
*
* @param item Item to check
* @return true if the item is custom armor, false otherwise
*/
public static boolean isCustomArmor(ItemStack item) {
if (customArmorEnabled && CustomArmorConfig.getInstance().customArmor.containsKey(item.getTypeId())) {
return true;
}
return false;
}
public static boolean isCustomEntity(Entity entity) {
if (customEntitiesEnabled && CustomEntityConfig.getInstance().customEntityIds.contains(entity.getEntityId())) {
return true;
}
return false;
}
}

View File

@ -1,115 +1,122 @@
package com.gmail.nossr50.util;
import java.text.DecimalFormat;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.utilities.PerksUtils;
import com.gmail.nossr50.skills.utilities.SkillType;
public final class Motd {
private static final String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix");
private static final PluginDescriptionFile pluginDescription = mcMMO.p.getDescription();
private Motd() {}
public static void displayAll(Player player) {
displayVersion(player, pluginDescription.getVersion());
displayHardcoreSettings(player);
displayXpPerks(player);
displayCooldownPerks(player);
displayActivationPerks(player);
displayLuckyPerks(player);
displayWebsite(player, pluginDescription.getWebsite());
}
/**
* Display version info.
* @param player Target player
* @param version Plugin version
*/
public static void displayVersion(Player player, String version) {
player.sendMessage(LocaleLoader.getString("MOTD.Version", version));
}
/**
* Display Hardcore Mode settings.
* @param player Target player
*/
public static void displayHardcoreSettings(Player player) {
if (Config.getInstance().getHardcoreEnabled()) {
if (Config.getInstance().getHardcoreVampirismEnabled()) {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.VampireOn"));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Stats", Config.getInstance().getHardcoreDeathStatPenaltyPercentage()));
player.sendMessage(LocaleLoader.getString("MOTD.Vampire.Stats", Config.getInstance().getHardcoreVampirismStatLeechPercentage()));
}
else {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.VampireOff"));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Stats", Config.getInstance().getHardcoreDeathStatPenaltyPercentage()));
}
}
}
/**
* Display XP perks.
* @param player Target player
*/
public static void displayXpPerks(Player player) {
int perkAmount = PerksUtils.handleXpPerks(player, 1);
if (perkAmount > 1) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.xp.name"), LocaleLoader.getString("Perks.xp.desc", perkAmount)));
}
}
/**
* Display cooldown perks.
* @param player Target player
*/
public static void displayCooldownPerks(Player player) {
double cooldownReduction = 1 - (PerksUtils.handleCooldownPerks(player, 12) / 12.0);
if (cooldownReduction > 0.0) {
DecimalFormat percent = new DecimalFormat("##0.00%");
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.cooldowns.name"), LocaleLoader.getString("Perks.cooldowns.desc", percent.format(cooldownReduction))));
}
}
/**
* Display activiation perks.
* @param player Target player
*/
public static void displayActivationPerks(Player player) {
int perkAmount = PerksUtils.handleActivationPerks(player, 0, 0);
if (perkAmount > 0) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.activationtime.name"), LocaleLoader.getString("Perks.activationtime.desc", perkAmount)));
}
}
/**
* Display "lucky" perks.
* @param player Target player
*/
public static void displayLuckyPerks(Player player) {
for (SkillType skill : SkillType.values()) {
if (Permissions.lucky(player, skill)) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc.login")));
return;
}
}
}
/**
* Display website info.
* @param player Target player
* @param website Plugin website
*/
public static void displayWebsite(Player player, String website) {
player.sendMessage(LocaleLoader.getString("MOTD.Website", website));
}
}
package com.gmail.nossr50.util;
import java.text.DecimalFormat;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.skills.PerksUtils;
public final class Motd {
private static final String perkPrefix = LocaleLoader.getString("MOTD.PerksPrefix");
private static final PluginDescriptionFile pluginDescription = mcMMO.p.getDescription();
private Motd() {}
public static void displayAll(Player player) {
displayVersion(player, pluginDescription.getVersion());
displayHardcoreSettings(player);
displayXpPerks(player);
displayCooldownPerks(player);
displayActivationPerks(player);
displayLuckyPerks(player);
displayWebsite(player, pluginDescription.getWebsite());
}
/**
* Display version info.
*
* @param player Target player
* @param version Plugin version
*/
public static void displayVersion(Player player, String version) {
player.sendMessage(LocaleLoader.getString("MOTD.Version", version));
}
/**
* Display Hardcore Mode settings.
*
* @param player Target player
*/
public static void displayHardcoreSettings(Player player) {
if (Config.getInstance().getHardcoreEnabled()) {
if (Config.getInstance().getHardcoreVampirismEnabled()) {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.VampireOn"));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Stats", Config.getInstance().getHardcoreDeathStatPenaltyPercentage()));
player.sendMessage(LocaleLoader.getString("MOTD.Vampire.Stats", Config.getInstance().getHardcoreVampirismStatLeechPercentage()));
}
else {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.VampireOff"));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Stats", Config.getInstance().getHardcoreDeathStatPenaltyPercentage()));
}
}
}
/**
* Display XP perks.
*
* @param player Target player
*/
public static void displayXpPerks(Player player) {
int perkAmount = PerksUtils.handleXpPerks(player, 1);
if (perkAmount > 1) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.xp.name"), LocaleLoader.getString("Perks.xp.desc", perkAmount)));
}
}
/**
* Display cooldown perks.
*
* @param player Target player
*/
public static void displayCooldownPerks(Player player) {
double cooldownReduction = 1 - (PerksUtils.handleCooldownPerks(player, 12) / 12.0);
if (cooldownReduction > 0.0) {
DecimalFormat percent = new DecimalFormat("##0.00%");
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.cooldowns.name"), LocaleLoader.getString("Perks.cooldowns.desc", percent.format(cooldownReduction))));
}
}
/**
* Display activiation perks.
*
* @param player Target player
*/
public static void displayActivationPerks(Player player) {
int perkAmount = PerksUtils.handleActivationPerks(player, 0, 0);
if (perkAmount > 0) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.activationtime.name"), LocaleLoader.getString("Perks.activationtime.desc", perkAmount)));
}
}
/**
* Display "lucky" perks.
*
* @param player Target player
*/
public static void displayLuckyPerks(Player player) {
for (SkillType skill : SkillType.values()) {
if (Permissions.lucky(player, skill)) {
player.sendMessage(perkPrefix + LocaleLoader.getString("Effects.Template", LocaleLoader.getString("Perks.lucky.name"), LocaleLoader.getString("Perks.lucky.desc.login")));
return;
}
}
}
/**
* Display website info.
*
* @param player Target player
* @param website Plugin website
*/
public static void displayWebsite(Player player, String website) {
player.sendMessage(LocaleLoader.getString("MOTD.Website", website));
}
}

View File

@ -9,8 +9,8 @@ import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.commands.PartySubcommandType;
import com.gmail.nossr50.skills.utilities.SkillType;
import com.gmail.nossr50.commands.party.PartySubcommandType;
import com.gmail.nossr50.datatypes.skills.SkillType;
public final class Permissions {
private Permissions() {}

View File

@ -1,136 +1,135 @@
package com.gmail.nossr50.util;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
public class StringUtils {
/**
* Gets a capitalized version of the target string.
*
* @param target String to capitalize
* @return the capitalized string
*/
public static String getCapitalized(String target) {
String firstLetter = target.substring(0,1);
String remainder = target.substring(1);
String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
return capitalized;
}
/**
* Gets a nicely formatted string version of an item name from a given item ID.
*
* @param itemID The ID of the item to convert to string.
* @return the nicely formatted string
*/
public static String getPrettyItemString(int itemID) {
return createPrettyEnumString(Material.getMaterial(itemID).toString());
}
public static String getPrettyItemString(Material material) {
return createPrettyEnumString(material.toString());
}
public static String getPrettyEntityTypeString(EntityType entity) {
return createPrettyEnumString(entity.toString());
}
private static String createPrettyEnumString(String baseString) {
String[] substrings = baseString.split("_");
String prettyString = "";
int size = 1;
for (String string : substrings) {
prettyString = prettyString.concat(getCapitalized(string));
if (size < substrings.length) {
prettyString = prettyString.concat(" ");
}
size++;
}
return prettyString;
}
/**
* Gets the int represented by this string.
*
* @param string The string to parse
* @return the int represented by this string
*/
public static int getInt(String string) {
try {
return Integer.parseInt(string);
}
catch (NumberFormatException nFE) {
return 0;
}
}
/**
* Gets the long represented by this string.
*
* @param string The string to parse
* @return the long represented by this string
*/
public static long getLong(String string) {
try {
return Long.parseLong(string);
}
catch (NumberFormatException nFE) {
return 0;
}
}
/**
* Determine if a string represents an Integer
*
* @param string String to check
* @return true if the string is an Integer, false otherwise
*/
public static boolean isInt(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
/**
* Determine if a string represents a Long
*
* @param string String to check
* @return true if the string is a Long, false otherwise
*/
public static boolean isLong(String string) {
try {
Long.parseLong(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
/**
* Determine if a string represents a Double
*
* @param string String to check
* @return true if the string is a Double, false otherwise
*/
public static boolean isDouble(String string) {
try {
Double.parseDouble(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
}
package com.gmail.nossr50.util;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
public class StringUtils {
/**
* Gets a capitalized version of the target string.
*
* @param target String to capitalize
* @return the capitalized string
*/
public static String getCapitalized(String target) {
String firstLetter = target.substring(0, 1);
String remainder = target.substring(1);
String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
return capitalized;
}
/**
* Gets a nicely formatted string version of an item name from a given item ID.
*
* @param itemID The ID of the item to convert to string.
* @return the nicely formatted string
*/
public static String getPrettyItemString(int itemID) {
return createPrettyEnumString(Material.getMaterial(itemID).toString());
}
public static String getPrettyItemString(Material material) {
return createPrettyEnumString(material.toString());
}
public static String getPrettyEntityTypeString(EntityType entity) {
return createPrettyEnumString(entity.toString());
}
private static String createPrettyEnumString(String baseString) {
String[] substrings = baseString.split("_");
String prettyString = "";
int size = 1;
for (String string : substrings) {
prettyString = prettyString.concat(getCapitalized(string));
if (size < substrings.length) {
prettyString = prettyString.concat(" ");
}
size++;
}
return prettyString;
}
/**
* Gets the int represented by this string.
*
* @param string The string to parse
* @return the int represented by this string
*/
public static int getInt(String string) {
try {
return Integer.parseInt(string);
}
catch (NumberFormatException nFE) {
return 0;
}
}
/**
* Gets the long represented by this string.
*
* @param string The string to parse
* @return the long represented by this string
*/
public static long getLong(String string) {
try {
return Long.parseLong(string);
}
catch (NumberFormatException nFE) {
return 0;
}
}
/**
* Determine if a string represents an Integer
*
* @param string String to check
* @return true if the string is an Integer, false otherwise
*/
public static boolean isInt(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
/**
* Determine if a string represents a Long
*
* @param string String to check
* @return true if the string is a Long, false otherwise
*/
public static boolean isLong(String string) {
try {
Long.parseLong(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
/**
* Determine if a string represents a Double
*
* @param string String to check
* @return true if the string is a Double, false otherwise
*/
public static boolean isDouble(String string) {
try {
Double.parseDouble(string);
return true;
}
catch (NumberFormatException nFE) {
return false;
}
}
}

View File

@ -11,8 +11,8 @@ import org.json.simple.parser.ParseException;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
public class UpdateCheck {
private UpdateCheck() {}
public class UpdateChecker {
private UpdateChecker() {}
public static boolean updateAvailable() throws Exception {
String checkType = "release";
@ -20,11 +20,12 @@ public class UpdateCheck {
checkType = "latest";
}
String version = mcMMO.p.getDescription().getVersion();
URL url = new URL("http://api.bukget.org/api2/bukkit/plugin/mcmmo/"+checkType);
URL url = new URL("http://api.bukget.org/api2/bukkit/plugin/mcmmo/" + checkType);
InputStreamReader isr;
try {
isr = new InputStreamReader(url.openStream());
} catch (UnknownHostException e) {
}
catch (UnknownHostException e) {
return false;
}
@ -54,7 +55,8 @@ public class UpdateCheck {
}
}
return false;
} catch (ParseException e) {
}
catch (ParseException e) {
isr.close();
return false;
}

View File

@ -6,7 +6,7 @@ import org.bukkit.block.Block;
public interface ChunkletManager {
/**
* Loads a specific chunklet
*
*
* @param cx Chunklet X coordinate that needs to be loaded
* @param cy Chunklet Y coordinate that needs to be loaded
* @param cz Chunklet Z coordinate that needs to be loaded

View File

@ -22,11 +22,17 @@ public class HashChunkletManager implements ChunkletManager {
public void loadChunklet(int cx, int cy, int cz, World world) {
File dataDir = new File(world.getWorldFolder(), "mcmmo_data");
File cxDir = new File(dataDir, "" + cx);
if (!cxDir.exists()) return;
if (!cxDir.exists()) {
return;
}
File czDir = new File(cxDir, "" + cz);
if (!czDir.exists()) return;
if (!czDir.exists()) {
return;
}
File yFile = new File(czDir, "" + cy);
if (!yFile.exists()) return;
if (!yFile.exists()) {
return;
}
ChunkletStore in = deserializeChunkletStore(yFile);
if (in != null) {
@ -39,9 +45,13 @@ public class HashChunkletManager implements ChunkletManager {
File dataDir = new File(world.getWorldFolder(), "mcmmo_data");
if (store.containsKey(world.getName() + "," + cx + "," + cz + "," + cy)) {
File cxDir = new File(dataDir, "" + cx);
if (!cxDir.exists()) cxDir.mkdir();
if (!cxDir.exists()) {
cxDir.mkdir();
}
File czDir = new File(cxDir, "" + cz);
if (!czDir.exists()) czDir.mkdir();
if (!czDir.exists()) {
czDir.mkdir();
}
File yFile = new File(czDir, "" + cy);
ChunkletStore out = store.get(world.getName() + "," + cx + "," + cz + "," + cy);
@ -54,9 +64,13 @@ public class HashChunkletManager implements ChunkletManager {
public void loadChunk(int cx, int cz, World world) {
File dataDir = new File(world.getWorldFolder(), "mcmmo_data");
File cxDir = new File(dataDir, "" + cx);
if (!cxDir.exists()) return;
if (!cxDir.exists()) {
return;
}
File czDir = new File(cxDir, "" + cz);
if (!czDir.exists()) return;
if (!czDir.exists()) {
return;
}
for (int y = 0; y < 4; y++) {
File yFile = new File(czDir, "" + y);
@ -78,9 +92,13 @@ public class HashChunkletManager implements ChunkletManager {
for (int y = 0; y < 4; y++) {
if (store.containsKey(world.getName() + "," + cx + "," + cz + "," + y)) {
File cxDir = new File(dataDir, "" + cx);
if (!cxDir.exists()) cxDir.mkdir();
if (!cxDir.exists()) {
cxDir.mkdir();
}
File czDir = new File(cxDir, "" + cz);
if (!czDir.exists()) czDir.mkdir();
if (!czDir.exists()) {
czDir.mkdir();
}
File yFile = new File(czDir, "" + y);
ChunkletStore out = store.get(world.getName() + "," + cx + "," + cz + "," + y);
@ -104,16 +122,21 @@ public class HashChunkletManager implements ChunkletManager {
public void saveWorld(World world) {
String worldName = world.getName();
File dataDir = new File(world.getWorldFolder(), "mcmmo_data");
if (!dataDir.exists())
if (!dataDir.exists()) {
dataDir.mkdirs();
}
for (String key : store.keySet()) {
String[] info = key.split(",");
if (worldName.equals(info[0])) {
File cxDir = new File(dataDir, "" + info[1]);
if (!cxDir.exists()) cxDir.mkdir();
if (!cxDir.exists()) {
cxDir.mkdir();
}
File czDir = new File(cxDir, "" + info[2]);
if (!czDir.exists()) czDir.mkdir();
if (!czDir.exists()) {
czDir.mkdir();
}
File yFile = new File(czDir, "" + info[3]);
serializeChunkletStore(store.get(key), yFile);
@ -139,7 +162,7 @@ public class HashChunkletManager implements ChunkletManager {
@Override
public void loadWorld(World world) {
//for (Chunk chunk : world.getLoadedChunks()) {
// this.chunkLoaded(chunk.getX(), chunk.getZ(), world);
// this.chunkLoaded(chunk.getX(), chunk.getZ(), world);
//}
}
@ -237,7 +260,7 @@ public class HashChunkletManager implements ChunkletManager {
ChunkletStore cStore = store.get(key);
if (cStore == null) {
return; //No need to make a store for something we will be setting to false
return; // No need to make a store for something we will be setting to false
}
cStore.setFalse(ix, iy, iz);
@ -256,16 +279,24 @@ public class HashChunkletManager implements ChunkletManager {
File dataDir = new File(Bukkit.getWorld(info[0]).getWorldFolder(), "mcmmo_data");
File cxDir = new File(dataDir, "" + info[1]);
if (!cxDir.exists()) continue;
if (!cxDir.exists()) {
continue;
}
File czDir = new File(cxDir, "" + info[2]);
if (!czDir.exists()) continue;
if (!czDir.exists()) {
continue;
}
File yFile = new File(czDir, "" + info[3]);
yFile.delete();
//Delete empty directories
if (czDir.list().length == 0) czDir.delete();
if (cxDir.list().length == 0) cxDir.delete();
// Delete empty directories
if (czDir.list().length == 0) {
czDir.delete();
}
if (cxDir.list().length == 0) {
cxDir.delete();
}
}
}
}
@ -279,8 +310,9 @@ public class HashChunkletManager implements ChunkletManager {
ObjectOutputStream objOut = null;
try {
if (!location.exists())
if (!location.exists()) {
location.createNewFile();
}
fileOut = new FileOutputStream(location);
objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(cStore);

View File

@ -26,7 +26,9 @@ public class PrimitiveChunkletStore implements ChunkletStore {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < 64; y++) {
if (store[x][z][y]) return false;
if (store[x][z][y]) {
return false;
}
}
}
}

View File

@ -31,7 +31,9 @@ public class PrimitiveExChunkletStore implements ChunkletStore, Externalizable {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < 64; y++) {
if (store[x][z][y]) return false;
if (store[x][z][y]) {
return false;
}
}
}
}

View File

@ -9,13 +9,16 @@ import org.bukkit.entity.Entity;
public interface ChunkManager {
public void closeAll();
public ChunkStore readChunkStore(World world, int x, int z) throws IOException;
public void writeChunkStore(World world, int x, int z, ChunkStore data);
public void closeChunkStore(World world, int x, int z);
/**
* Loads a specific chunklet
*
*
* @param cx Chunklet X coordinate that needs to be loaded
* @param cy Chunklet Y coordinate that needs to be loaded
* @param cz Chunklet Z coordinate that needs to be loaded

View File

@ -12,4 +12,4 @@ public class ChunkManagerFactory {
return new NullChunkManager();
}
}
}

View File

@ -14,24 +14,28 @@ public interface ChunkStore extends Serializable {
* @return true if the has been modified since it was last saved
*/
public boolean isDirty();
/**
* Checks the chunk's save state
*
* @param dirty the save state of the current chunk
*/
public void setDirty(boolean dirty);
/**
* Checks the chunk's x coordinate
*
* @return the chunk's x coordinate.
*/
public int getChunkX();
/**
* Checks the chunk's z coordinate
*
* @return the chunk's z coordinate.
*/
public int getChunkZ();
/**
* Checks the value at the given coordinates
*
@ -71,4 +75,4 @@ public interface ChunkStore extends Serializable {
* @param otherStore Another ChunkletStore that this one should copy all data from
*/
public void copyFrom(ChunkletStore otherStore);
}
}

View File

@ -7,4 +7,4 @@ public class ChunkStoreFactory {
// TODO: Add in loading from config what type of store we want.
return new PrimitiveChunkStore(world, x, z);
}
}
}

View File

@ -16,12 +16,11 @@ import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.getspout.spoutapi.chunkstore.mcMMOSimpleRegionFile;
import com.gmail.nossr50.util.blockmeta.conversion.BlockStoreConversionZDirectory;
public class HashChunkManager implements ChunkManager {
private HashMap<UUID, HashMap<Long, mcMMOSimpleRegionFile>> regionFiles = new HashMap<UUID, HashMap<Long, mcMMOSimpleRegionFile>>();
private HashMap<UUID, HashMap<Long, McMMOSimpleRegionFile>> regionFiles = new HashMap<UUID, HashMap<Long, McMMOSimpleRegionFile>>();
public HashMap<String, ChunkStore> store = new HashMap<String, ChunkStore>();
public ArrayList<BlockStoreConversionZDirectory> converters = new ArrayList<BlockStoreConversionZDirectory>();
private HashMap<UUID, Boolean> oldData = new HashMap<UUID, Boolean>();
@ -29,9 +28,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void closeAll() {
for (UUID uid : regionFiles.keySet()) {
HashMap<Long, mcMMOSimpleRegionFile> worldRegions = regionFiles.get(uid);
for (Iterator<mcMMOSimpleRegionFile> worldRegionIterator = worldRegions.values().iterator(); worldRegionIterator.hasNext();) {
mcMMOSimpleRegionFile rf = worldRegionIterator.next();
HashMap<Long, McMMOSimpleRegionFile> worldRegions = regionFiles.get(uid);
for (Iterator<McMMOSimpleRegionFile> worldRegionIterator = worldRegions.values().iterator(); worldRegionIterator.hasNext();) {
McMMOSimpleRegionFile rf = worldRegionIterator.next();
if (rf != null) {
rf.close();
worldRegionIterator.remove();
@ -43,7 +42,7 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized ChunkStore readChunkStore(World world, int x, int z) throws IOException {
mcMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
McMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
InputStream in = rf.getInputStream(x, z);
if (in == null) {
return null;
@ -56,11 +55,13 @@ public class HashChunkManager implements ChunkManager {
}
throw new RuntimeException("Wrong class type read for chunk meta data for " + x + ", " + z);
} catch (IOException e) {
}
catch (IOException e) {
// Assume the format changed
return null;
//throw new RuntimeException("Unable to process chunk meta data for " + x + ", " + z, e);
} catch (ClassNotFoundException e) {
}
catch (ClassNotFoundException e) {
// Assume the format changed
//System.out.println("[SpoutPlugin] is Unable to find serialized class for " + x + ", " + z + ", " + e.getMessage());
return null;
@ -77,36 +78,37 @@ public class HashChunkManager implements ChunkManager {
return;
}
try {
mcMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
McMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
ObjectOutputStream objectStream = new ObjectOutputStream(rf.getOutputStream(x, z));
objectStream.writeObject(data);
objectStream.flush();
objectStream.close();
data.setDirty(false);
} catch (IOException e) {
}
catch (IOException e) {
throw new RuntimeException("Unable to write chunk meta data for " + x + ", " + z, e);
}
}
@Override
public synchronized void closeChunkStore(World world, int x, int z) {
mcMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
McMMOSimpleRegionFile rf = getSimpleRegionFile(world, x, z);
if (rf != null) {
rf.close();
}
}
private synchronized mcMMOSimpleRegionFile getSimpleRegionFile(World world, int x, int z) {
private synchronized McMMOSimpleRegionFile getSimpleRegionFile(World world, int x, int z) {
File directory = new File(world.getWorldFolder(), "mcmmo_regions");
directory.mkdirs();
UUID key = world.getUID();
HashMap<Long, mcMMOSimpleRegionFile> worldRegions = regionFiles.get(key);
HashMap<Long, McMMOSimpleRegionFile> worldRegions = regionFiles.get(key);
if (worldRegions == null) {
worldRegions = new HashMap<Long, mcMMOSimpleRegionFile>();
worldRegions = new HashMap<Long, McMMOSimpleRegionFile>();
regionFiles.put(key, worldRegions);
}
@ -115,11 +117,11 @@ public class HashChunkManager implements ChunkManager {
long key2 = (((long) rx) << 32) | ((rz) & 0xFFFFFFFFL);
mcMMOSimpleRegionFile regionFile = worldRegions.get(key2);
McMMOSimpleRegionFile regionFile = worldRegions.get(key2);
if (regionFile == null) {
File file = new File(directory, "mcmmo_" + rx + "_" + rz + "_.mcm");
regionFile = new mcMMOSimpleRegionFile(file, rx, rz);
regionFile = new McMMOSimpleRegionFile(file, rx, rz);
worldRegions.put(key2, regionFile);
}
@ -138,8 +140,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void loadChunk(int cx, int cz, World world, Entity[] entities) {
if (world == null || store.containsKey(world.getName() + "," + cx + "," + cz))
if (world == null || store.containsKey(world.getName() + "," + cx + "," + cz)) {
return;
}
UUID key = world.getUID();
@ -147,8 +150,9 @@ public class HashChunkManager implements ChunkManager {
oldData.put(key, (new File(world.getWorldFolder(), "mcmmo_data")).exists());
}
else if (oldData.get(key)) {
if (convertChunk(new File(world.getWorldFolder(), "mcmmo_data"), cx, cz, world, true))
if (convertChunk(new File(world.getWorldFolder(), "mcmmo_data"), cx, cz, world, true)) {
return;
}
}
ChunkStore chunkStore = null;
@ -158,8 +162,9 @@ public class HashChunkManager implements ChunkManager {
}
catch (Exception e) {}
if (chunkStore == null)
if (chunkStore == null) {
return;
}
store.put(world.getName() + "," + cx + "," + cz, chunkStore);
}
@ -171,22 +176,24 @@ public class HashChunkManager implements ChunkManager {
if (store.containsKey(world.getName() + "," + cx + "," + cz)) {
store.remove(world.getName() + "," + cx + "," + cz);
// closeChunkStore(world, cx, cz);
//closeChunkStore(world, cx, cz);
}
}
@Override
public synchronized void saveChunk(int cx, int cz, World world) {
if (world == null)
if (world == null) {
return;
}
String key = world.getName() + "," + cx + "," + cz;
if (store.containsKey(key)) {
ChunkStore out = store.get(world.getName() + "," + cx + "," + cz);
if (!out.isDirty())
if (!out.isDirty()) {
return;
}
writeChunkStore(world, cx, cz, out);
}
@ -194,8 +201,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized boolean isChunkLoaded(int cx, int cz, World world) {
if (world == null)
if (world == null) {
return false;
}
return store.containsKey(world.getName() + "," + cx + "," + cz);
}
@ -205,16 +213,18 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void chunkUnloaded(int cx, int cz, World world) {
if (world == null)
if (world == null) {
return;
}
unloadChunk(cx, cz, world);
}
@Override
public synchronized void saveWorld(World world) {
if (world == null)
if (world == null) {
return;
}
closeAll();
String worldName = world.getName();
@ -230,7 +240,7 @@ public class HashChunkManager implements ChunkManager {
cx = Integer.parseInt(info[1]);
cz = Integer.parseInt(info[2]);
}
catch(Exception e) {
catch (Exception e) {
continue;
}
saveChunk(cx, cz, world);
@ -240,8 +250,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void unloadWorld(World world) {
if (world == null)
if (world == null) {
return;
}
closeAll();
String worldName = world.getName();
@ -257,7 +268,7 @@ public class HashChunkManager implements ChunkManager {
cx = Integer.parseInt(info[1]);
cz = Integer.parseInt(info[2]);
}
catch(Exception e) {
catch (Exception e) {
continue;
}
unloadChunk(cx, cz, world);
@ -288,8 +299,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized boolean isTrue(int x, int y, int z, World world) {
if (world == null)
if (world == null) {
return false;
}
int cx = x / 16;
int cz = z / 16;
@ -312,8 +324,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized boolean isTrue(Block block) {
if (block == null)
if (block == null) {
return false;
}
return isTrue(block.getX(), block.getY(), block.getZ(), block.getWorld());
}
@ -329,8 +342,9 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void setTrue(int x, int y, int z, World world) {
if (world == null)
if (world == null) {
return;
}
int cx = x / 16;
int cz = z / 16;
@ -356,24 +370,27 @@ public class HashChunkManager implements ChunkManager {
@Override
public synchronized void setTrue(Block block) {
if (block == null)
if (block == null) {
return;
}
setTrue(block.getX(), block.getY(), block.getZ(), block.getWorld());
}
@Override
public void setTrue(BlockState blockState) {
if (blockState == null)
if (blockState == null) {
return;
}
setTrue(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld());
}
@Override
public synchronized void setFalse(int x, int y, int z, World world) {
if (world == null)
if (world == null) {
return;
}
int cx = x / 16;
int cz = z / 16;
@ -390,7 +407,7 @@ public class HashChunkManager implements ChunkManager {
ChunkStore cStore = store.get(key);
if (cStore == null) {
return; //No need to make a store for something we will be setting to false
return; // No need to make a store for something we will be setting to false
}
cStore.setFalse(ix, y, iz);
@ -422,22 +439,30 @@ public class HashChunkManager implements ChunkManager {
}
public synchronized boolean convertChunk(File dataDir, int cx, int cz, World world, boolean actually) {
if (!actually)
if (!actually || !dataDir.exists()) {
return false;
if (!dataDir.exists()) return false;
}
File cxDir = new File(dataDir, "" + cx);
if (!cxDir.exists()) return false;
if (!cxDir.exists()) {
return false;
}
File czDir = new File(cxDir, "" + cz);
if (!czDir.exists()) return false;
if (!czDir.exists()) {
return false;
}
boolean conversionSet = false;
for (BlockStoreConversionZDirectory converter : this.converters) {
if (converter == null)
if (converter == null) {
continue;
}
if (converter.taskID >= 0)
if (converter.taskID >= 0) {
continue;
}
converter.start(world, cxDir, czDir);
conversionSet = true;

View File

@ -0,0 +1,39 @@
/*
* This file is part of SpoutPlugin.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* SpoutPlugin is licensed under the GNU Lesser General Public License.
*
* SpoutPlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SpoutPlugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gmail.nossr50.util.blockmeta.chunkmeta;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class McMMOSimpleChunkBuffer extends ByteArrayOutputStream {
final McMMOSimpleRegionFile rf;
final int index;
McMMOSimpleChunkBuffer(McMMOSimpleRegionFile rf, int index) {
super(1024);
this.rf = rf;
this.index = index;
}
@Override
public void close() throws IOException {
rf.write(index, buf, count);
}
}

View File

@ -0,0 +1,311 @@
/*
* This file is part of SpoutPlugin.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* SpoutPlugin is licensed under the GNU Lesser General Public License.
*
* SpoutPlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SpoutPlugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gmail.nossr50.util.blockmeta.chunkmeta;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public class McMMOSimpleRegionFile {
private RandomAccessFile file;
private final int[] dataStart = new int[1024];
private final int[] dataActualLength = new int[1024];
private final int[] dataLength = new int[1024];
private final ArrayList<Boolean> inuse = new ArrayList<Boolean>();
private int segmentSize;
private int segmentMask;
private final int rx;
private final int rz;
private final int defaultSegmentSize;
private final File parent;
@SuppressWarnings("unused")
private long lastAccessTime = System.currentTimeMillis();
@SuppressWarnings("unused")
private static long TIMEOUT_TIME = 300000; // 5 min
public McMMOSimpleRegionFile(File f, int rx, int rz) {
this(f, rx, rz, 10);
}
public McMMOSimpleRegionFile(File f, int rx, int rz, int defaultSegmentSize) {
this.rx = rx;
this.rz = rz;
this.defaultSegmentSize = defaultSegmentSize;
this.parent = f;
lastAccessTime = System.currentTimeMillis();
if (file == null) {
try {
this.file = new RandomAccessFile(parent, "rw");
if (file.length() < 4096 * 3) {
for (int i = 0; i < 1024 * 3; i++) {
file.writeInt(0);
}
file.seek(4096 * 2);
file.writeInt(defaultSegmentSize);
}
file.seek(4096 * 2);
this.segmentSize = file.readInt();
this.segmentMask = (1 << segmentSize) - 1;
int reservedSegments = this.sizeToSegments(4096 * 3);
for (int i = 0; i < reservedSegments; i++) {
while (inuse.size() <= i) {
inuse.add(false);
}
inuse.set(i, true);
}
file.seek(0);
for (int i = 0; i < 1024; i++) {
dataStart[i] = file.readInt();
}
for (int i = 0; i < 1024; i++) {
dataActualLength[i] = file.readInt();
dataLength[i] = sizeToSegments(dataActualLength[i]);
setInUse(i, true);
}
extendFile();
}
catch (IOException fnfe) {
throw new RuntimeException(fnfe);
}
}
}
public synchronized final RandomAccessFile getFile() {
lastAccessTime = System.currentTimeMillis();
if (file == null) {
try {
this.file = new RandomAccessFile(parent, "rw");
if (file.length() < 4096 * 3) {
for (int i = 0; i < 1024 * 3; i++) {
file.writeInt(0);
}
file.seek(4096 * 2);
file.writeInt(defaultSegmentSize);
}
file.seek(4096 * 2);
this.segmentSize = file.readInt();
this.segmentMask = (1 << segmentSize) - 1;
int reservedSegments = this.sizeToSegments(4096 * 3);
for (int i = 0; i < reservedSegments; i++) {
while (inuse.size() <= i) {
inuse.add(false);
}
inuse.set(i, true);
}
file.seek(0);
for (int i = 0; i < 1024; i++) {
dataStart[i] = file.readInt();
}
for (int i = 0; i < 1024; i++) {
dataActualLength[i] = file.readInt();
dataLength[i] = sizeToSegments(dataActualLength[i]);
setInUse(i, true);
}
extendFile();
}
catch (IOException fnfe) {
throw new RuntimeException(fnfe);
}
}
return file;
}
public synchronized boolean testCloseTimeout() {
/*
if (System.currentTimeMillis() - TIMEOUT_TIME > lastAccessTime) {
close();
return true;
}
*/
return false;
}
public synchronized DataOutputStream getOutputStream(int x, int z) {
int index = getChunkIndex(x, z);
return new DataOutputStream(new DeflaterOutputStream(new McMMOSimpleChunkBuffer(this, index)));
}
public synchronized DataInputStream getInputStream(int x, int z) throws IOException {
int index = getChunkIndex(x, z);
int actualLength = dataActualLength[index];
if (actualLength == 0) {
return null;
}
byte[] data = new byte[actualLength];
getFile().seek(dataStart[index] << segmentSize);
getFile().readFully(data);
return new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(data)));
}
synchronized void write(int index, byte[] buffer, int size) throws IOException {
int oldStart = setInUse(index, false);
int start = findSpace(oldStart, size);
getFile().seek(start << segmentSize);
getFile().write(buffer, 0, size);
dataStart[index] = start;
dataActualLength[index] = size;
dataLength[index] = sizeToSegments(size);
setInUse(index, true);
saveFAT();
}
public synchronized void close() {
try {
if (file != null) {
file.seek(4096 * 2);
file.close();
}
file = null;
}
catch (IOException ioe) {
throw new RuntimeException("Unable to close file", ioe);
}
}
private synchronized int setInUse(int index, boolean used) {
if (dataActualLength[index] == 0) {
return dataStart[index];
}
int start = dataStart[index];
int end = start + dataLength[index];
for (int i = start; i < end; i++) {
while (i > inuse.size() - 1) {
inuse.add(false);
}
Boolean old = inuse.set(i, used);
if (old != null && old == used) {
if (old) {
throw new IllegalStateException("Attempting to overwrite an in-use segment");
}
throw new IllegalStateException("Attempting to delete empty segment");
}
}
return dataStart[index];
}
private synchronized void extendFile() throws IOException {
long extend = (-getFile().length()) & segmentMask;
getFile().seek(getFile().length());
while ((extend--) > 0) {
getFile().write(0);
}
}
private synchronized int findSpace(int oldStart, int size) {
int segments = sizeToSegments(size);
boolean oldFree = true;
for (int i = oldStart; i < inuse.size() && i < oldStart + segments; i++) {
if (inuse.get(i)) {
oldFree = false;
break;
}
}
if (oldFree) {
return oldStart;
}
int start = 0;
int end = 0;
while (end < inuse.size()) {
if (inuse.get(end)) {
end++;
start = end;
}
else {
end++;
}
if (end - start >= segments) {
return start;
}
}
return start;
}
private synchronized int sizeToSegments(int size) {
if (size <= 0) {
return 1;
}
return ((size - 1) >> segmentSize) + 1;
}
private synchronized Integer getChunkIndex(int x, int z) {
if (rx != (x >> 5) || rz != (z >> 5)) {
throw new RuntimeException(x + ", " + z + " not in region " + rx + ", " + rz);
}
x = x & 0x1F;
z = z & 0x1F;
return (x << 5) + z;
}
private synchronized void saveFAT() throws IOException {
getFile().seek(0);
for (int i = 0; i < 1024; i++) {
getFile().writeInt(dataStart[i]);
}
for (int i = 0; i < 1024; i++) {
getFile().writeInt(dataActualLength[i]);
}
}
}

View File

@ -99,4 +99,4 @@ public class NullChunkManager implements ChunkManager {
@Override
public void cleanUp() {}
}
}

View File

@ -72,7 +72,9 @@ public class PrimitiveChunkStore implements ChunkStore {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < this.worldHeight; y++) {
if (store[x][z][y]) return false;
if (store[x][z][y]) {
return false;
}
}
}
}
@ -108,7 +110,7 @@ public class PrimitiveChunkStore implements ChunkStore {
int magic = in.readInt();
// Can be used to determine the format of the file
int fileVersionNumber = in.readInt();
if (magic != MAGIC_NUMBER) {
fileVersionNumber = 0;
}
@ -141,9 +143,9 @@ public class PrimitiveChunkStore implements ChunkStore {
try {
store[x][z][y] = temp[x][y][z];
}
catch(Exception e) {}
catch (Exception e) {}
}
}
}
}
}
}

View File

@ -24,8 +24,9 @@ public class BlockStoreConversionMain implements Runnable {
}
public void start() {
if (this.taskID >= 0)
if (this.taskID >= 0) {
return;
}
this.taskID = this.scheduler.scheduleSyncDelayedTask(mcMMO.p, this, 1);
return;

View File

@ -79,4 +79,4 @@ public class BlockStoreConversionXDirectory implements Runnable {
this.scheduler = null;
this.converters = null;
}
}
}

View File

@ -5,12 +5,12 @@ import java.io.File;
import org.bukkit.scheduler.BukkitScheduler;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.blockmeta.chunkmeta.HashChunkManager;
import com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore;
import com.gmail.nossr50.util.blockmeta.ChunkletStore;
import com.gmail.nossr50.util.blockmeta.HashChunkletManager;
import com.gmail.nossr50.util.blockmeta.PrimitiveChunkletStore;
import com.gmail.nossr50.util.blockmeta.PrimitiveExChunkletStore;
import com.gmail.nossr50.util.blockmeta.chunkmeta.HashChunkManager;
import com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore;
public class BlockStoreConversionZDirectory implements Runnable {
public int taskID, cx, cz, x, y, z, y2, xPos, zPos, cxPos, czPos;
@ -74,7 +74,7 @@ public class BlockStoreConversionZDirectory implements Runnable {
this.cx = Integer.parseInt(this.cxs);
this.cz = Integer.parseInt(this.czs);
}
catch(Exception e) {
catch (Exception e) {
this.dataDir.delete();
stop();
return;
@ -117,7 +117,7 @@ public class BlockStoreConversionZDirectory implements Runnable {
this.newManager.setTrue(this.cxPos, this.y2, this.czPos, this.world);
}
catch(Exception e) {}
catch (Exception e) {}
}
}
}
@ -171,8 +171,9 @@ public class BlockStoreConversionZDirectory implements Runnable {
}
public void stop() {
if (this.taskID < 0)
if (this.taskID < 0) {
return;
}
this.scheduler.cancelTask(taskID);
this.taskID = -1;
@ -189,4 +190,4 @@ public class BlockStoreConversionZDirectory implements Runnable {
this.primitiveExChunklet = null;
this.currentChunk = null;
}
}
}

View File

@ -0,0 +1,369 @@
package com.gmail.nossr50.util.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.PluginCommand;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.McabilityCommand;
import com.gmail.nossr50.commands.McgodCommand;
import com.gmail.nossr50.commands.McmmoCommand;
import com.gmail.nossr50.commands.McnotifyCommand;
import com.gmail.nossr50.commands.McrefreshCommand;
import com.gmail.nossr50.commands.XprateCommand;
import com.gmail.nossr50.commands.chat.AdminChatCommand;
import com.gmail.nossr50.commands.chat.PartyChatCommand;
import com.gmail.nossr50.commands.database.McpurgeCommand;
import com.gmail.nossr50.commands.database.McremoveCommand;
import com.gmail.nossr50.commands.database.MmoupdateCommand;
import com.gmail.nossr50.commands.experience.AddlevelsCommand;
import com.gmail.nossr50.commands.experience.AddxpCommand;
import com.gmail.nossr50.commands.experience.MmoeditCommand;
import com.gmail.nossr50.commands.experience.SkillresetCommand;
import com.gmail.nossr50.commands.hardcore.HardcoreCommand;
import com.gmail.nossr50.commands.hardcore.VampirismCommand;
import com.gmail.nossr50.commands.party.PartyCommand;
import com.gmail.nossr50.commands.party.PtpCommand;
import com.gmail.nossr50.commands.player.InspectCommand;
import com.gmail.nossr50.commands.player.McrankCommand;
import com.gmail.nossr50.commands.player.McstatsCommand;
import com.gmail.nossr50.commands.player.MctopCommand;
import com.gmail.nossr50.commands.skills.AcrobaticsCommand;
import com.gmail.nossr50.commands.skills.ArcheryCommand;
import com.gmail.nossr50.commands.skills.AxesCommand;
import com.gmail.nossr50.commands.skills.ExcavationCommand;
import com.gmail.nossr50.commands.skills.FishingCommand;
import com.gmail.nossr50.commands.skills.HerbalismCommand;
import com.gmail.nossr50.commands.skills.MiningCommand;
import com.gmail.nossr50.commands.skills.RepairCommand;
import com.gmail.nossr50.commands.skills.SmeltingCommand;
import com.gmail.nossr50.commands.skills.SwordsCommand;
import com.gmail.nossr50.commands.skills.TamingCommand;
import com.gmail.nossr50.commands.skills.UnarmedCommand;
import com.gmail.nossr50.commands.skills.WoodcuttingCommand;
import com.gmail.nossr50.commands.spout.MchudCommand;
import com.gmail.nossr50.commands.spout.XplockCommand;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class CommandRegistrationManager {
private CommandRegistrationManager() {};
private static String permissionsMessage = LocaleLoader.getString("mcMMO.NoPermission");
public static void registerSkillCommands() {
for (SkillType skill : SkillType.values()) {
String commandName = skill.toString().toLowerCase();
String localizedName = SkillUtils.getSkillName(skill);
PluginCommand command;
command = mcMMO.p.getCommand(commandName);
command.setDescription(LocaleLoader.getString("Commands.Description.Skill", StringUtils.getCapitalized(localizedName)));
command.setPermission("mcmmo.commands." + commandName);
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", localizedName));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.2", localizedName, "?", "[" + LocaleLoader.getString("Commands.Usage.Page") + "]"));
switch (skill) {
case ACROBATICS:
command.setExecutor(new AcrobaticsCommand());
break;
case ARCHERY:
command.setExecutor(new ArcheryCommand());
break;
case AXES:
command.setExecutor(new AxesCommand());
break;
case EXCAVATION:
command.setExecutor(new ExcavationCommand());
break;
case FISHING:
command.setExecutor(new FishingCommand());
break;
case HERBALISM:
command.setExecutor(new HerbalismCommand());
break;
case MINING:
command.setExecutor(new MiningCommand());
break;
case REPAIR:
command.setExecutor(new RepairCommand());
break;
case SMELTING:
command.setExecutor(new SmeltingCommand());
break;
case SWORDS:
command.setExecutor(new SwordsCommand());
break;
case TAMING:
command.setExecutor(new TamingCommand());
break;
case UNARMED:
command.setExecutor(new UnarmedCommand());
break;
case WOODCUTTING:
command.setExecutor(new WoodcuttingCommand());
break;
default:
break;
}
}
}
public static void registerAddlevelsCommand() {
PluginCommand command = mcMMO.p.getCommand("addlevels");
command.setDescription(LocaleLoader.getString("Commands.Description.addlevels"));
command.setPermission("mcmmo.commands.addlevels;mcmmo.commands.addlevels.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.3", "addlevels", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.Level") + ">"));
command.setExecutor(new AddlevelsCommand());
}
public static void registerAddxpCommand() {
PluginCommand command = mcMMO.p.getCommand("addxp");
command.setDescription(LocaleLoader.getString("Commands.Description.addxp"));
command.setPermission("mcmmo.commands.addxp;mcmmo.commands.addxp.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.3", "addxp", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.XP") + ">"));
command.setExecutor(new AddxpCommand());
}
public static void registerMcgodCommand() {
PluginCommand command = mcMMO.p.getCommand("mcgod");
command.setDescription(LocaleLoader.getString("Commands.Description.mcgod"));
command.setPermission("mcmmo.commands.mcgod;mcmmo.commands.mcgod.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcgod", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]"));
command.setExecutor(new McgodCommand());
}
public static void registerMcrefreshCommand() {
PluginCommand command = mcMMO.p.getCommand("mcrefresh");
command.setDescription(LocaleLoader.getString("Commands.Description.mcrefresh"));
command.setPermission("mcmmo.commands.mcrefresh;mcmmo.commands.mcrefresh.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrefresh", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]"));
command.setExecutor(new McrefreshCommand());
}
public static void registerMmoeditCommand() {
PluginCommand command = mcMMO.p.getCommand("mmoedit");
command.setDescription(LocaleLoader.getString("Commands.Description.mmoedit"));
command.setPermission("mcmmo.commands.mmoedit;mcmmo.commands.mmoedit.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.3", "mmoedit", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">", "<" + LocaleLoader.getString("Commands.Usage.Level") + ">"));
command.setExecutor(new MmoeditCommand());
}
public static void registerSkillresetCommand() {
PluginCommand command = mcMMO.p.getCommand("skillreset");
command.setDescription(LocaleLoader.getString("Commands.Description.skillreset"));
command.setPermission("mcmmo.commands.skillreset;mcmmo.commands.skillreset.others"); // Only need the main ones, not the individual skill ones
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.2", "skillreset", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">"));
command.setExecutor(new SkillresetCommand());
}
public static void registerXprateCommand() {
List<String> aliasList = new ArrayList<String>();
aliasList.add("mcxprate");
PluginCommand command = mcMMO.p.getCommand("xprate");
command.setDescription(LocaleLoader.getString("Commands.Description.xprate"));
command.setPermission("mcmmo.commands.xprate;mcmmo.commands.xprate.reset;mcmmo.commands.xprate.set");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.2", "xprate", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">", "<true|false>"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "xprate", "reset"));
command.setAliases(aliasList);
command.setExecutor(new XprateCommand());
}
public static void registerInspectCommand() {
PluginCommand command = mcMMO.p.getCommand("inspect");
command.setDescription(LocaleLoader.getString("Commands.Description.inspect"));
command.setPermission("mcmmo.commands.inspect;mcmmo.commands.inspect.far;mcmmo.commands.inspect.offline");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "inspect", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">"));
command.setExecutor(new InspectCommand());
}
public static void registerMcabilityCommand() {
PluginCommand command = mcMMO.p.getCommand("mcability");
command.setDescription(LocaleLoader.getString("Commands.Description.mcability"));
command.setPermission("mcmmo.commands.mcability;mcmmo.commands.mcability.others");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcability", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]"));
command.setExecutor(new McabilityCommand());
}
public static void registerMcmmoCommand() {
PluginCommand command = mcMMO.p.getCommand("mcmmo");
command.setDescription(LocaleLoader.getString("Commands.Description.mcmmo"));
command.setPermission("mcmmo.commands.mcmmo.description;mcmmo.commands.mcmmo.help");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcmmo"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "mcmmo", "help"));
command.setExecutor(new McmmoCommand());
}
public static void registerMcrankCommand() {
PluginCommand command = mcMMO.p.getCommand("mcrank");
command.setDescription(LocaleLoader.getString("Commands.Description.mcrank"));
command.setPermission("mcmmo.commands.mcrank;mcmmo.commands.mcrank.others;mcmmo.commands.mcrank.others.far;mcmmo.commands.mcrank.others.offline");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcrank", "[" + LocaleLoader.getString("Commands.Usage.Player") + "]"));
command.setExecutor(new McrankCommand());
}
public static void registerMcstatsCommand() {
PluginCommand command = mcMMO.p.getCommand("mcstats");
command.setDescription(LocaleLoader.getString("Commands.Description.mcstats"));
command.setPermission("mcmmo.commands.mcstats");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcstats"));
command.setExecutor(new McstatsCommand());
}
public static void registerMctopCommand() {
PluginCommand command = mcMMO.p.getCommand("mctop");
command.setDescription(LocaleLoader.getString("Commands.Description.mctop"));
command.setPermission("mcmmo.commands.mctop"); // Only need the main one, not the individual skill ones
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.2", "mctop", "[" + LocaleLoader.getString("Commands.Usage.Skill") + "]", "[" + LocaleLoader.getString("Commands.Usage.Page") + "]"));
command.setExecutor(new MctopCommand());
}
public static void registerMcpurgeCommand() {
PluginCommand command = mcMMO.p.getCommand("mcpurge");
command.setDescription(LocaleLoader.getString("Commands.Description.mcpurge", Config.getInstance().getOldUsersCutoff()));
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcpurge"));
command.setExecutor(new McpurgeCommand());
}
public static void registerMcremoveCommand() {
PluginCommand command = mcMMO.p.getCommand("mcremove");
command.setDescription(LocaleLoader.getString("Commands.Description.mcremove"));
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mcremove", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">"));
command.setExecutor(new McremoveCommand());
}
public static void registerMmoupdateCommand() {
PluginCommand command = mcMMO.p.getCommand("mmoupdate");
command.setDescription(LocaleLoader.getString("Commands.Description.mmoupdate"));
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mmoupdate"));
command.setExecutor(new MmoupdateCommand());
}
public static void registerAdminChatCommand() {
PluginCommand command = mcMMO.p.getCommand("adminchat");
command.setDescription(LocaleLoader.getString("Commands.Description.adminchat"));
command.setPermission("mcmmo.chat.adminchat");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "adminchat"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "adminchat", "<on|off>"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "adminchat", "<" + LocaleLoader.getString("Commands.Usage.Message") + ">"));
command.setExecutor(new AdminChatCommand());
}
public static void registerPartyChatCommand() {
PluginCommand command = mcMMO.p.getCommand("partychat");
command.setDescription(LocaleLoader.getString("Commands.Description.partychat"));
command.setPermission("mcmmo.chat.partychat;mcmmo.commands.party");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "partychat"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "partychat", "<on|off>"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "partychat", "<" + LocaleLoader.getString("Commands.Usage.Message") + ">"));
command.setExecutor(new PartyChatCommand());
}
public static void registerMchudCommand() {
PluginCommand command = mcMMO.p.getCommand("mchud");
command.setDescription(LocaleLoader.getString("Commands.Description.mchud"));
command.setPermission("mcmmo.commands.mchud");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "mchud", "<DISABLED | STANDARD | SMALL | RETRO>"));
command.setExecutor(new MchudCommand());
}
public static void registerXplockCommand() {
PluginCommand command = mcMMO.p.getCommand("xplock");
command.setDescription(LocaleLoader.getString("Commands.Description.xplock"));
command.setPermission("mcmmo.commands.xplock");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "xplock"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "xplock", "<on|off>"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "xplock", "<" + LocaleLoader.getString("Commands.Usage.Skill") + ">"));
command.setExecutor(new XplockCommand());
}
public static void registerPartyCommand() {
PluginCommand command = mcMMO.p.getCommand("party");
command.setDescription(LocaleLoader.getString("Commands.Description.party"));
command.setPermission("mcmmo.commands.party;mcmmo.commands.party.accept;mcmmo.commands.party.create;mcmmo.commands.party.disband;" +
"mcmmo.commands.party.expshare;mcmmo.commands.party.invite;mcmmo.commands.party.itemshare;mcmmo.commands.party.join;" +
"mcmmo.commands.party.kick;mcmmo.commands.party.lock;mcmmo.commands.party.owner;mcmmo.commands.party.password;" +
"mcmmo.commands.party.quit;mcmmo.commands.party.rename;mcmmo.commands.party.unlock");
command.setPermissionMessage(permissionsMessage);
command.setExecutor(new PartyCommand());
}
public static void registerPtpCommand() {
PluginCommand command = mcMMO.p.getCommand("ptp");
command.setDescription(LocaleLoader.getString("Commands.Description.ptp"));
command.setPermission("mcmmo.commands.ptp;mcmmo.commands.ptp.accept;mcmmo.commands.ptp.acceptall;mcmmo.commands.ptp.toggle");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "ptp", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "ptp", "<toggle|accept|acceptall>"));
command.setExecutor(new PtpCommand());
}
public static void registerHardcoreCommand() {
PluginCommand command = mcMMO.p.getCommand("hardcore");
command.setDescription(LocaleLoader.getString("Commands.Description.hardcore"));
command.setPermission("mcmmo.commands.hardcore;mcmmo.commands.hardcore.toggle;mcmmo.commands.hardcore.modify");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "hardcore", "[on|off]"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "hardcore", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
command.setExecutor(new HardcoreCommand());
}
public static void registerVampirismCommand() {
PluginCommand command = mcMMO.p.getCommand("vampirism");
command.setDescription(LocaleLoader.getString("Commands.Description.vampirism"));
command.setPermission("mcmmo.commands.vampirism;mcmmo.commands.vampirism.toggle;mcmmo.commands.vampirism.modify");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "vampirism", "[on|off]"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "vampirism", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
command.setExecutor(new VampirismCommand());
}
public static void registerMcnotifyCommand() {
PluginCommand command = mcMMO.p.getCommand("mcnotify");
command.setDescription(LocaleLoader.getString("Commands.Description.mcnotify"));
command.setPermission("mcmmo.commands.mcnotify");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcnotify"));
command.setExecutor(new McnotifyCommand());
}
}

View File

@ -0,0 +1,122 @@
package com.gmail.nossr50.util.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class CommandUtils {
private CommandUtils() {}
public static boolean noConsoleUsage(CommandSender sender) {
if (!(sender instanceof Player)) {
sender.sendMessage(LocaleLoader.getString("Commands.NoConsole"));
return true;
}
return false;
}
/**
* Print out details on Gathering skills. Only for online players.
*
* @param inspect The player to retrieve stats for
* @param profile The player's profile
* @param display The sender to display stats to
*/
public static void printGatheringSkills(Player inspect, PlayerProfile profile, CommandSender display) {
if (SkillUtils.hasGatheringSkills(inspect)) {
display.sendMessage(LocaleLoader.getString("Stats.Header.Gathering"));
if (Permissions.skillEnabled(inspect, SkillType.EXCAVATION)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Excavation.Listener"), profile.getSkillLevel(SkillType.EXCAVATION), profile.getSkillXpLevel(SkillType.EXCAVATION), profile.getXpToLevel(SkillType.EXCAVATION)));
}
if (Permissions.skillEnabled(inspect, SkillType.FISHING)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Fishing.Listener"), profile.getSkillLevel(SkillType.FISHING), profile.getSkillXpLevel(SkillType.FISHING), profile.getXpToLevel(SkillType.FISHING)));
}
if (Permissions.skillEnabled(inspect, SkillType.HERBALISM)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Herbalism.Listener"), profile.getSkillLevel(SkillType.HERBALISM), profile.getSkillXpLevel(SkillType.HERBALISM), profile.getXpToLevel(SkillType.HERBALISM)));
}
if (Permissions.skillEnabled(inspect, SkillType.MINING)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Mining.Listener"), profile.getSkillLevel(SkillType.MINING), profile.getSkillXpLevel(SkillType.MINING), profile.getXpToLevel(SkillType.MINING)));
}
if (Permissions.skillEnabled(inspect, SkillType.WOODCUTTING)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Woodcutting.Listener"), profile.getSkillLevel(SkillType.WOODCUTTING), profile.getSkillXpLevel(SkillType.WOODCUTTING), profile.getXpToLevel(SkillType.WOODCUTTING)));
}
}
}
public static void printGatheringSkills(Player player, PlayerProfile profile) {
printGatheringSkills(player, profile, player);
}
/**
* Print out details on Combat skills. Only for online players.
*
* @param inspect The player to retrieve stats for
* @param profile The player's profile
* @param display The sender to display stats to
*/
public static void printCombatSkills(Player inspect, PlayerProfile profile, CommandSender display) {
if (SkillUtils.hasCombatSkills(inspect)) {
display.sendMessage(LocaleLoader.getString("Stats.Header.Combat"));
if (Permissions.skillEnabled(inspect, SkillType.AXES)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Axes.Listener"), profile.getSkillLevel(SkillType.AXES), profile.getSkillXpLevel(SkillType.AXES), profile.getXpToLevel(SkillType.AXES)));
}
if (Permissions.skillEnabled(inspect, SkillType.ARCHERY)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Archery.Listener"), profile.getSkillLevel(SkillType.ARCHERY), profile.getSkillXpLevel(SkillType.ARCHERY), profile.getXpToLevel(SkillType.ARCHERY)));
}
if (Permissions.skillEnabled(inspect, SkillType.SWORDS)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Swords.Listener"), profile.getSkillLevel(SkillType.SWORDS), profile.getSkillXpLevel(SkillType.SWORDS), profile.getXpToLevel(SkillType.SWORDS)));
}
if (Permissions.skillEnabled(inspect, SkillType.TAMING)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Taming.Listener"), profile.getSkillLevel(SkillType.TAMING), profile.getSkillXpLevel(SkillType.TAMING), profile.getXpToLevel(SkillType.TAMING)));
}
if (Permissions.skillEnabled(inspect, SkillType.UNARMED)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Unarmed.Listener"), profile.getSkillLevel(SkillType.UNARMED), profile.getSkillXpLevel(SkillType.UNARMED), profile.getXpToLevel(SkillType.UNARMED)));
}
}
}
public static void printCombatSkills(Player player, PlayerProfile profile) {
printCombatSkills(player, profile, player);
}
/**
* Print out details on Misc skills. Only for online players.
*
* @param inspect The player to retrieve stats for
* @param profile The player's profile
* @param display The sender to display stats to
*/
public static void printMiscSkills(Player inspect, PlayerProfile profile, CommandSender display) {
if (SkillUtils.hasMiscSkills(inspect)) {
display.sendMessage(LocaleLoader.getString("Stats.Header.Misc"));
if (Permissions.skillEnabled(inspect, SkillType.ACROBATICS)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Acrobatics.Listener"), profile.getSkillLevel(SkillType.ACROBATICS), profile.getSkillXpLevel(SkillType.ACROBATICS), profile.getXpToLevel(SkillType.ACROBATICS)));
}
if (Permissions.skillEnabled(inspect, SkillType.REPAIR)) {
display.sendMessage(LocaleLoader.getString("Skills.Stats", LocaleLoader.getString("Repair.Listener"), profile.getSkillLevel(SkillType.REPAIR), profile.getSkillXpLevel(SkillType.REPAIR), profile.getXpToLevel(SkillType.REPAIR)));
}
}
}
public static void printMiscSkills(Player player, PlayerProfile profile) {
printMiscSkills(player, profile, player);
}
}

View File

@ -1,338 +0,0 @@
package com.gmail.nossr50.util.metrics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.locale.LocaleLoader;
import com.turt2live.metrics.EMetrics;
import com.turt2live.metrics.Metrics;
import com.turt2live.metrics.Metrics.Graph;
import com.turt2live.metrics.tracker.Tracker;
import com.turt2live.metrics.data.*;
public class MetricsManager {
private static boolean setup = false;
private static Tracker chimeraUseTracker;
private static Tracker chimeraServerUseTracker;
private static boolean customConfig = false;
private static DataTracker tracker;
private static EMetrics emetrics;
public static void setup() {
if (setup) {
return;
}
if (Config.getInstance().getStatsTrackingEnabled()) {
try {
emetrics = new EMetrics(mcMMO.p);
Metrics metrics = emetrics.getMetrics();
// Timings Graph
Graph timingsGraph = metrics.createGraph("Percentage of servers using timings");
if (mcMMO.p.getServer().getPluginManager().useTimings()) {
timingsGraph.addPlotter(new Metrics.Plotter("Enabled") {
@Override
public int getValue() {
return 1;
}
});
}
else {
timingsGraph.addPlotter(new Metrics.Plotter("Disabled") {
@Override
public int getValue() {
return 1;
}
});
}
// Donut Version Graph
Graph versionDonutGraph = metrics.createGraph("Donut Version");
boolean haveVersionInformation = false;
boolean isOfficialBuild = false;
String officialKey = "e14cfacdd442a953343ebd8529138680";
String version = mcMMO.p.getDescription().getVersion();
InputStreamReader isr = new InputStreamReader(mcMMO.p.getResource(".jenkins"));
BufferedReader br = new BufferedReader(isr);
char[] key = new char[32];
br.read(key);
if (officialKey.equals(String.valueOf(key))) {
isOfficialBuild = true;
}
if (version.contains("-")) {
String majorVersion = version.substring(0, version.indexOf("-"));
String subVersion = "";
if (isOfficialBuild) {
int startIndex = version.indexOf("-");
if (version.substring(startIndex + 1).contains("-")) {
subVersion = version.substring(startIndex, version.indexOf("-", startIndex + 1));
} else {
subVersion = "-release";
}
} else {
subVersion = "-custom";
}
version = majorVersion + "~=~" + subVersion;
haveVersionInformation = true;
} else {
haveVersionInformation = false;
}
if (haveVersionInformation) {
versionDonutGraph.addPlotter(new Metrics.Plotter(version) {
@Override
public int getValue() {
return 1;
}
});
}
// Official v Custom build Graph
Graph officialGraph = metrics.createGraph("Built by official ci");
if (isOfficialBuild) {
officialGraph.addPlotter(new Metrics.Plotter("Yes") {
@Override
public int getValue() {
return 1;
}
});
}
else {
officialGraph.addPlotter(new Metrics.Plotter("No") {
@Override
public int getValue() {
return 1;
}
});
}
// Chunkmeta enabled Graph
Graph chunkmetaGraph = metrics.createGraph("Uses Chunkmeta");
if (HiddenConfig.getInstance().getChunkletsEnabled()) {
chunkmetaGraph.addPlotter(new Metrics.Plotter("Yes") {
@Override
public int getValue() {
return 1;
}
});
}
else {
chunkmetaGraph.addPlotter(new Metrics.Plotter("No") {
@Override
public int getValue() {
return 1;
}
});
}
// Storage method Graph
Graph storageGraph = metrics.createGraph("Storage method");
if (Config.getInstance().getUseMySQL()) {
storageGraph.addPlotter(new Metrics.Plotter("SQL") {
@Override
public int getValue() {
return 1;
}
});
}
else {
storageGraph.addPlotter(new Metrics.Plotter("Flatfile") {
@Override
public int getValue() {
return 1;
}
});
}
// Locale Graph
Graph localeGraph = metrics.createGraph("Locale");
localeGraph.addPlotter(new Metrics.Plotter(LocaleLoader.getCurrentLocale().getDisplayLanguage(Locale.US)) {
@Override
public int getValue() {
return 1;
}
});
// GlobalMultiplier Graph
Graph globalMultiplierGraph = metrics.createGraph("Global Multiplier Graph");
globalMultiplierGraph.addPlotter(new Metrics.Plotter(Config.getInstance().getExperienceGainsGlobalMultiplier() + "") {
@Override
public int getValue() {
return 1;
}
});
// GlobalCurveModifier Graph
Graph globalCurveModifierGraph = metrics.createGraph("Global Curve Modifier Graph");
globalCurveModifierGraph.addPlotter(new Metrics.Plotter(Config.getInstance().getFormulaMultiplierCurve() + "") {
@Override
public int getValue() {
return 1;
}
});
// GlobalMultiplierGraph Fuzzy Logic Numbers
Graph globalMultiplierGraphFuzzy = metrics.createGraph("Global Multiplier Fuzz");
if (Config.getInstance().getExperienceGainsGlobalMultiplier() > 1.0) {
globalMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Higher") {
@Override
public int getValue() {
return 1;
}
});
}
else if (Config.getInstance().getExperienceGainsGlobalMultiplier() < 1.0) {
globalMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Lower") {
@Override
public int getValue() {
return 1;
}
});
}
else {
globalMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Default") {
@Override
public int getValue() {
return 1;
}
});
}
//GlobalCurveModifier Fuzzy Logic Numbers
Graph globalCurveMultiplierGraphFuzzy = metrics.createGraph("Global Curve Multiplier Fuzz");
if (Config.getInstance().getFormulaMultiplierCurve() > 20.0) {
globalCurveMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Higher") {
@Override
public int getValue() {
return 1;
}
});
}
else if (Config.getInstance().getFormulaMultiplierCurve() < 20.0) {
globalCurveMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Lower") {
@Override
public int getValue() {
return 1;
}
});
}
else {
globalCurveMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Default") {
@Override
public int getValue() {
return 1;
}
});
}
// Chimera Wing Usage Trackers
final String chimeraGraphName = "Chimera Wing Usage";
chimeraUseTracker = EMetrics.createBasicTracker(chimeraGraphName, "Player use");
chimeraServerUseTracker = EMetrics.createEnabledTracker(chimeraGraphName, "Server use");
emetrics.addTracker(chimeraUseTracker);
emetrics.addTracker(chimeraServerUseTracker);
// Chimera Wing Enabled Graph
Graph chimeraGraph = metrics.createGraph("Chimera Wing");
if (Config.getInstance().getChimaeraEnabled()) {
chimeraGraph.addPlotter(new Metrics.Plotter("Enabled") {
@Override
public int getValue() {
return 1;
}
});
}
else {
chimeraGraph.addPlotter(new Metrics.Plotter("Disabled") {
@Override
public int getValue() {
return 1;
}
});
}
// Vanilla v Modified config graph
Graph customConfigGraph = metrics.createGraph("Modified Configs");
if (customConfig) {
customConfigGraph.addPlotter(new Metrics.Plotter("Edited") {
@Override
public int getValue() {
return 1;
}
});
}
else {
customConfigGraph.addPlotter(new Metrics.Plotter("Vanilla") {
@Override
public int getValue() {
return 1;
}
});
}
/* Debug stuff
tracker = emetrics.getDataTracker();
tracker.enable();
tracker.setFilter(new DataEvent.DataType [] { DataEvent.DataType.SEND_DATA });
*/
emetrics.startMetrics();
}
catch (IOException e) {
mcMMO.p.getLogger().warning("Failed to submit stats.");
}
}
}
public static void chimeraWingUsed() {
chimeraUseTracker.increment();
chimeraServerUseTracker.increment();
}
public static void customConfig() {
customConfig = true;
}
@SuppressWarnings("unused")
private static void debug() {
emetrics.getMetrics().flush();
for (DataEvent event : tracker.getEvents()) {
String graphName = event.getGraphName();
String colName = event.getTrackerName();
int value = event.getValueSent();
System.out.println("Graph: " + graphName + ", Column: " + colName + ", Value: " + value);
}
tracker.resetEvents();
}
}

View File

@ -1,4 +1,4 @@
package com.gmail.nossr50.util;
package com.gmail.nossr50.util.player;
import java.io.File;
import java.io.IOException;
@ -9,13 +9,13 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.McMMOPlayer;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
public final class Users {
public final class UserManager {
private static Map<String, McMMOPlayer> players = new HashMap<String, McMMOPlayer>();
private Users() {};
private UserManager() {};
/**
* Load users.
@ -42,7 +42,7 @@ public final class Users {
McMMOPlayer mcMMOPlayer = players.get(playerName);
if (mcMMOPlayer != null) {
mcMMOPlayer.setPlayer(player); //The player object is different on each reconnection and must be updated
mcMMOPlayer.setPlayer(player); // The player object is different on each reconnection and must be updated
}
else {
mcMMOPlayer = new McMMOPlayer(player);

View File

@ -0,0 +1,600 @@
package com.gmail.nossr50.util.skills;
import org.bukkit.Material;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.skills.AwardCombatXpTask;
import com.gmail.nossr50.runnables.skills.BleedTimerTask;
import com.gmail.nossr50.skills.SkillManagerStore;
import com.gmail.nossr50.skills.axes.AxeManager;
import com.gmail.nossr50.skills.swords.Swords;
import com.gmail.nossr50.skills.taming.Taming;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.ModUtils;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
public final class CombatUtils {
private CombatUtils() {}
/**
* Apply combat modifiers and process and XP gain.
*
* @param event The event to run the combat checks on.
*/
public static void combatChecks(EntityDamageByEntityEvent event, Entity attacker, LivingEntity target) {
boolean targetIsPlayer = (target.getType() == EntityType.PLAYER);
boolean targetIsTamedPet = (target instanceof Tameable) ? ((Tameable) target).isTamed() : false;
Entity damager = event.getDamager();
if (attacker instanceof Player && damager.getType() == EntityType.PLAYER) {
Player player = (Player) attacker;
if (Misc.isNPCEntity(player)) {
return;
}
if (target instanceof Tameable && isFriendlyPet(player, (Tameable) target)) {
return;
}
ItemStack heldItem = player.getItemInHand();
Material heldItemType = heldItem.getType();
if (ItemUtils.isSword(heldItem)) {
if (targetIsPlayer || targetIsTamedPet) {
if (!SkillType.SWORDS.getPVPEnabled()) {
return;
}
}
else if (!SkillType.SWORDS.getPVEEnabled()) {
return;
}
if (Permissions.skillEnabled(player, SkillType.SWORDS)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
PlayerProfile profile = mcMMOPlayer.getProfile();
String playerName = player.getName();
boolean canSerratedStrike = Permissions.serratedStrikes(player); // So we don't have to check the same permission twice
if (profile.getToolPreparationMode(ToolType.SWORD) && canSerratedStrike) {
SkillUtils.abilityCheck(player, SkillType.SWORDS);
}
if (Permissions.bleed(player)) {
SkillManagerStore.getInstance().getSwordsManager(playerName).bleedCheck(target);
}
if (profile.getAbilityMode(AbilityType.SERRATED_STRIKES) && canSerratedStrike) {
SkillManagerStore.getInstance().getSwordsManager(playerName).serratedStrikes(target, event.getDamage());
}
startGainXp(mcMMOPlayer, target, SkillType.SWORDS);
}
}
else if (ItemUtils.isAxe(heldItem)) {
if (((targetIsPlayer || targetIsTamedPet) && !SkillType.AXES.getPVPEnabled()) || (!targetIsPlayer && !targetIsTamedPet && !SkillType.AXES.getPVEEnabled())) {
return;
}
if (Permissions.skillEnabled(player, SkillType.AXES)) {
AxeManager axeManager = SkillManagerStore.getInstance().getAxeManager(player.getName());
if (axeManager.canActivateAbility()) {
SkillUtils.abilityCheck(player, SkillType.AXES);
}
if (axeManager.canUseAxeMastery()) {
event.setDamage(axeManager.axeMasteryCheck(event.getDamage()));
}
if (axeManager.canCriticalHit(target)) {
event.setDamage(axeManager.criticalHitCheck(target, event.getDamage()));
}
if (axeManager.canImpact(target)) {
axeManager.impactCheck(target);
}
else if (axeManager.canGreaterImpact(target)) {
event.setDamage(axeManager.greaterImpactCheck(target, event.getDamage()));
}
if (axeManager.canUseSkullSplitter(target)) {
axeManager.skullSplitterCheck(target, event.getDamage());
}
startGainXp(axeManager.getMcMMOPlayer(), target, SkillType.AXES);
}
}
else if (heldItemType == Material.AIR) {
if (targetIsPlayer || targetIsTamedPet) {
if (!SkillType.UNARMED.getPVPEnabled()) {
return;
}
}
else if (!SkillType.UNARMED.getPVEEnabled()) {
return;
}
if (Permissions.skillEnabled(player, SkillType.UNARMED)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
PlayerProfile profile = mcMMOPlayer.getProfile();
String playerName = player.getName();
boolean canBerserk = Permissions.berserk(player); // So we don't have to check the same permission twice
if (profile.getToolPreparationMode(ToolType.FISTS) && canBerserk) {
SkillUtils.abilityCheck(player, SkillType.UNARMED);
}
if (Permissions.bonusDamage(player, SkillType.UNARMED)) {
event.setDamage(SkillManagerStore.getInstance().getUnarmedManager(playerName).ironArmCheck(event.getDamage()));
}
if (profile.getAbilityMode(AbilityType.BERSERK) && canBerserk) {
event.setDamage(SkillManagerStore.getInstance().getUnarmedManager(playerName).berserkDamage(event.getDamage()));
}
if (target instanceof Player && Permissions.disarm(player)) {
Player defender = (Player) target;
if (defender.getItemInHand().getType() != Material.AIR) {
SkillManagerStore.getInstance().getUnarmedManager(playerName).disarmCheck((Player) target);
}
}
startGainXp(mcMMOPlayer, target, SkillType.UNARMED);
}
}
else if (heldItemType == Material.BONE && target instanceof Tameable && Permissions.beastLore(player)) {
SkillManagerStore.getInstance().getTamingManager(player.getName()).beastLore(target);
}
}
switch (damager.getType()) {
case WOLF:
Wolf wolf = (Wolf) damager;
if (wolf.isTamed() && wolf.getOwner() instanceof Player) {
Player master = (Player) wolf.getOwner();
if (Misc.isNPCEntity(master)) {
return;
}
if (targetIsPlayer || targetIsTamedPet) {
if (!SkillType.TAMING.getPVPEnabled()) {
return;
}
}
else if (!SkillType.TAMING.getPVEEnabled()) {
return;
}
if (Permissions.skillEnabled(master, SkillType.TAMING)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master);
int skillLevel = SkillManagerStore.getInstance().getTamingManager(master.getName()).getSkillLevel();
if (skillLevel >= Taming.fastFoodServiceUnlockLevel && Permissions.fastFoodService(master)) {
SkillManagerStore.getInstance().getTamingManager(master.getName()).fastFoodService(wolf, event.getDamage());
}
if (skillLevel >= Taming.sharpenedClawsUnlockLevel && Permissions.sharpenedClaws(master)) {
SkillManagerStore.getInstance().getTamingManager(master.getName()).sharpenedClaws(event);
}
if (Permissions.gore(master)) {
SkillManagerStore.getInstance().getTamingManager(master.getName()).gore(event);
}
startGainXp(mcMMOPlayer, target, SkillType.TAMING);
}
}
break;
case ARROW:
LivingEntity shooter = ((Arrow) damager).getShooter();
/* Break instead of return due to Dodge/Counter/Deflect abilities */
if (shooter == null || !(shooter instanceof Player)) {
break;
}
if (targetIsPlayer || targetIsTamedPet) {
if (!SkillType.ARCHERY.getPVPEnabled()) {
return;
}
}
else if (!SkillType.ARCHERY.getPVEEnabled()) {
return;
}
archeryCheck((Player) shooter, target, event);
break;
default:
break;
}
if (targetIsPlayer) {
Player player = (Player) target;
if (Misc.isNPCEntity(player)) {
return;
}
ItemStack heldItem = player.getItemInHand();
if (SkillManagerStore.getInstance().getAcrobaticsManager(player.getName()).canDodge(damager)) {
event.setDamage(SkillManagerStore.getInstance().getAcrobaticsManager(player.getName()).dodgeCheck(event.getDamage()));
}
if (damager instanceof Player) {
if (SkillType.SWORDS.getPVPEnabled() && ItemUtils.isSword(heldItem) && Permissions.counterAttack(player)) {
SkillManagerStore.getInstance().getSwordsManager(player.getName()).counterAttackChecks((LivingEntity) damager, event.getDamage());
}
}
else {
if (SkillType.SWORDS.getPVEEnabled() && damager instanceof LivingEntity && ItemUtils.isSword(heldItem) && Permissions.counterAttack(player)) {
SkillManagerStore.getInstance().getSwordsManager(player.getName()).counterAttackChecks((LivingEntity) damager, event.getDamage());
}
}
}
}
/**
* Process archery abilities.
*
* @param shooter The player shooting
* @param target The defending entity
* @param event The event to run the archery checks on.
*/
private static void archeryCheck(Player shooter, LivingEntity target, EntityDamageByEntityEvent event) {
if (Misc.isNPCEntity(shooter)) {
return;
}
if (Permissions.skillEnabled(shooter, SkillType.ARCHERY)) {
String playerName = shooter.getName();
if (SkillManagerStore.getInstance().getArcheryManager(playerName).canSkillShot()) {
event.setDamage(SkillManagerStore.getInstance().getArcheryManager(playerName).skillShotCheck(event.getDamage()));
}
if (target instanceof Player && SkillType.UNARMED.getPVPEnabled() && ((Player) target).getItemInHand().getType() == Material.AIR && Permissions.arrowDeflect((Player) target)) {
event.setCancelled(SkillManagerStore.getInstance().getUnarmedManager(((Player) target).getName()).deflectCheck());
if (event.isCancelled()) {
return;
}
}
if (SkillManagerStore.getInstance().getArcheryManager(playerName).canDaze(target)) {
event.setDamage(SkillManagerStore.getInstance().getArcheryManager(playerName).dazeCheck((Player) target, event.getDamage()));
}
if (SkillManagerStore.getInstance().getArcheryManager(playerName).canTrackArrows()) {
SkillManagerStore.getInstance().getArcheryManager(playerName).trackArrows(target);
}
SkillManagerStore.getInstance().getArcheryManager(playerName).distanceXpBonus(target);
startGainXp(UserManager.getPlayer(shooter), target, SkillType.ARCHERY);
}
}
/**
* Attempt to damage target for value dmg with reason CUSTOM
*
* @param target LivingEntity which to attempt to damage
* @param dmg Amount of damage to attempt to do
*/
public static void dealDamage(LivingEntity target, int dmg) {
dealDamage(target, dmg, EntityDamageEvent.DamageCause.CUSTOM);
}
/**
* Attempt to damage target for value dmg with reason cause
*
* @param target LivingEntity which to attempt to damage
* @param dmg Amount of damage to attempt to do
* @param cause DamageCause to pass to damage event
*/
private static void dealDamage(LivingEntity target, int dmg, DamageCause cause) {
if (Config.getInstance().getEventCallbackEnabled()) {
EntityDamageEvent ede = new FakeEntityDamageEvent(target, cause, dmg);
mcMMO.p.getServer().getPluginManager().callEvent(ede);
if (ede.isCancelled()) {
return;
}
target.damage(ede.getDamage());
}
else {
target.damage(dmg);
}
}
/**
* Attempt to damage target for value dmg with reason ENTITY_ATTACK with damager attacker
*
* @param target LivingEntity which to attempt to damage
* @param dmg Amount of damage to attempt to do
* @param attacker Player to pass to event as damager
*/
private static void dealDamage(LivingEntity target, int dmg, Player attacker) {
if (Config.getInstance().getEventCallbackEnabled()) {
EntityDamageEvent ede = new FakeEntityDamageByEntityEvent(attacker, target, EntityDamageEvent.DamageCause.ENTITY_ATTACK, dmg);
mcMMO.p.getServer().getPluginManager().callEvent(ede);
if (ede.isCancelled()) {
return;
}
target.damage(ede.getDamage());
}
else {
target.damage(dmg);
}
}
/**
* Apply Area-of-Effect ability actions.
*
* @param attacker The attacking player
* @param target The defending entity
* @param damage The initial damage amount
* @param type The type of skill being used
*/
public static void applyAbilityAoE(Player attacker, LivingEntity target, int damage, SkillType type) {
int numberOfTargets = Misc.getTier(attacker.getItemInHand()); // The higher the weapon tier, the more targets you hit
int damageAmount = damage;
if (damageAmount < 1) {
damageAmount = 1;
}
for (Entity entity : target.getNearbyEntities(2.5, 2.5, 2.5)) {
if (Misc.isNPCEntity(entity) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) {
continue;
}
if (numberOfTargets <= 0) {
break;
}
PlayerAnimationEvent armswing = new PlayerAnimationEvent(attacker);
mcMMO.p.getServer().getPluginManager().callEvent(armswing);
switch (type) {
case SWORDS:
if (entity instanceof Player) {
((Player) entity).sendMessage(LocaleLoader.getString("Swords.Combat.SS.Struck"));
}
BleedTimerTask.add((LivingEntity) entity, Swords.serratedStrikesBleedTicks);
break;
case AXES:
if (entity instanceof Player) {
((Player) entity).sendMessage(LocaleLoader.getString("Axes.Combat.Cleave.Struck"));
}
break;
default:
break;
}
dealDamage((LivingEntity) entity, damageAmount, attacker);
numberOfTargets--;
}
}
/**
* Start the task that gives combat XP.
*
* @param mcMMOPlayer The attacking player
* @param target The defending entity
* @param skillType The skill being used
*/
public static void startGainXp(McMMOPlayer mcMMOPlayer, LivingEntity target, SkillType skillType) {
double baseXP = 0;
if (target instanceof Player) {
if (!Config.getInstance().getExperienceGainsPlayerVersusPlayerEnabled()) {
return;
}
Player defender = (Player) target;
if (System.currentTimeMillis() >= UserManager.getPlayer(defender).getProfile().getRespawnATS() + 5) {
baseXP = 20 * Config.getInstance().getPlayerVersusPlayerXP();
}
}
else if (!target.hasMetadata(mcMMO.entityMetadataKey)) {
if (target instanceof Animals) {
if (ModUtils.isCustomEntity(target)) {
baseXP = ModUtils.getCustomEntity(target).getXpMultiplier();
}
else {
baseXP = Config.getInstance().getAnimalsXP();
}
}
else {
EntityType type = target.getType();
switch (type) {
case BAT:
baseXP = Config.getInstance().getAnimalsXP();
break;
case BLAZE:
case CAVE_SPIDER:
case CREEPER:
case ENDER_DRAGON:
case ENDERMAN:
case GHAST:
case GIANT:
case MAGMA_CUBE:
case PIG_ZOMBIE:
case SILVERFISH:
case SLIME:
case SPIDER:
case WITCH:
case WITHER:
case ZOMBIE:
baseXP = Config.getInstance().getCombatXP(type);
break;
// Temporary workaround for custom entities
case UNKNOWN:
baseXP = 1.0;
break;
case SKELETON:
switch (((Skeleton) target).getSkeletonType()) {
case WITHER:
baseXP = Config.getInstance().getWitherSkeletonXP();
break;
default:
baseXP = Config.getInstance().getCombatXP(type);
break;
}
break;
case IRON_GOLEM:
if (!((IronGolem) target).isPlayerCreated()) {
baseXP = Config.getInstance().getCombatXP(type);
}
break;
default:
if (ModUtils.isCustomEntity(target)) {
baseXP = ModUtils.getCustomEntity(target).getXpMultiplier();
}
break;
}
}
baseXP *= 10;
}
if (baseXP != 0) {
mcMMO.p.getServer().getScheduler().scheduleSyncDelayedTask(mcMMO.p, new AwardCombatXpTask(mcMMOPlayer, skillType, baseXP, target), 0);
}
}
/**
* Check to see if the given LivingEntity should be affected by a combat ability.
*
* @param player The attacking Player
* @param entity The defending Entity
* @return true if the Entity should be damaged, false otherwise.
*/
public static boolean shouldBeAffected(Player player, Entity entity) {
if (entity instanceof Player) {
Player defender = (Player) entity;
if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getProfile().getGodMode()) {
return false;
}
if (PartyManager.inSameParty(player, defender) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) {
return false;
}
// It may seem a bit redundant but we need a check here to prevent bleed from being applied in applyAbilityAoE()
EntityDamageEvent ede = new FakeEntityDamageByEntityEvent(player, entity, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1);
mcMMO.p.getServer().getPluginManager().callEvent(ede);
if (ede.isCancelled()) {
return false;
}
}
else if (entity instanceof Tameable) {
if (isFriendlyPet(player, (Tameable) entity)) {
// 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
Player owner = (Player) ((Tameable) entity).getOwner();
if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire(owner))) {
return false;
}
}
}
return true;
}
/**
* Checks to see if an entity is currently invincible.
*
* @param entity The {@link LivingEntity} to check
* @param eventDamage The damage from the event the entity is involved in
* @return true if the entity is invincible, false otherwise
*/
public static boolean isInvincible(LivingEntity entity, int eventDamage) {
/*
* So apparently if you do more damage to a LivingEntity than its last damage int you bypass the invincibility.
* So yeah, this is for that.
*/
if ((entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) && (eventDamage <= entity.getLastDamage())) {
return true;
}
return false;
}
/**
* Checks to see if an entity is currently friendly toward a given player.
*
* @param attacker The player to check.
* @param pet The entity to check.
* @return true if the entity is friendly, false otherwise
*/
public static boolean isFriendlyPet(Player attacker, Tameable pet) {
if (pet.isTamed()) {
AnimalTamer tamer = pet.getOwner();
if (tamer instanceof Player) {
Player owner = (Player) tamer;
if (owner == attacker || PartyManager.inSameParty(attacker, owner)) {
return true;
}
}
}
return false;
}
}

View File

@ -1,89 +1,89 @@
package com.gmail.nossr50.util;
import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import com.gmail.nossr50.config.Config;
public final class ParticleEffectUtils {
private ParticleEffectUtils() {};
public static void playBleedEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getBleedEffectEnabled()) {
return;
}
livingEntity.getWorld().playEffect(livingEntity.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_WIRE);
}
public static void playDodgeEffect(Player player) {
if (!Config.getInstance().getDodgeEffectEnabled()) {
return;
}
Location location = player.getEyeLocation();
World world = player.getWorld();
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH_EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH);
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH_WEST);
world.playEffect(location, Effect.SMOKE, BlockFace.EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.SELF);
world.playEffect(location, Effect.SMOKE, BlockFace.WEST);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH_EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH_WEST);
}
public static void playGreaterImpactEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getGreaterImpactEffectEnabled()) {
return;
}
Location location = livingEntity.getEyeLocation();
livingEntity.getWorld().createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, false);
}
public static void playAbilityEnabledEffect(Player player) {
if (!Config.getInstance().getAbilityActivationEffectEnabled()) {
return;
}
fireworkParticleShower(player, Color.GREEN);
}
public static void playAbilityDisabledEffect(Player player) {
if (!Config.getInstance().getAbilityDeactivationEffectEnabled()) {
return;
}
fireworkParticleShower(player, Color.RED);
}
private static void fireworkParticleShower(Player player, Color color) {
Location location = player.getLocation();
location.setY(location.getY() - 1.0);
location.setPitch(-90);
Firework firework = (Firework) player.getWorld().spawnEntity(location, EntityType.FIREWORK);
FireworkMeta fireworkMeta = firework.getFireworkMeta();
FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(color).with(Type.BALL_LARGE).trail(true).build();
fireworkMeta.addEffect(effect);
fireworkMeta.addEffect(effect);
fireworkMeta.setPower(0);
firework.setFireworkMeta(fireworkMeta);
}
}
package com.gmail.nossr50.util.skills;
import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import com.gmail.nossr50.config.Config;
public final class ParticleEffectUtils {
private ParticleEffectUtils() {};
public static void playBleedEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getBleedEffectEnabled()) {
return;
}
livingEntity.getWorld().playEffect(livingEntity.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_WIRE);
}
public static void playDodgeEffect(Player player) {
if (!Config.getInstance().getDodgeEffectEnabled()) {
return;
}
Location location = player.getEyeLocation();
World world = player.getWorld();
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH_EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH);
world.playEffect(location, Effect.SMOKE, BlockFace.SOUTH_WEST);
world.playEffect(location, Effect.SMOKE, BlockFace.EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.SELF);
world.playEffect(location, Effect.SMOKE, BlockFace.WEST);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH_EAST);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH);
world.playEffect(location, Effect.SMOKE, BlockFace.NORTH_WEST);
}
public static void playGreaterImpactEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getGreaterImpactEffectEnabled()) {
return;
}
Location location = livingEntity.getEyeLocation();
livingEntity.getWorld().createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, false);
}
public static void playAbilityEnabledEffect(Player player) {
if (!Config.getInstance().getAbilityActivationEffectEnabled()) {
return;
}
fireworkParticleShower(player, Color.GREEN);
}
public static void playAbilityDisabledEffect(Player player) {
if (!Config.getInstance().getAbilityDeactivationEffectEnabled()) {
return;
}
fireworkParticleShower(player, Color.RED);
}
private static void fireworkParticleShower(Player player, Color color) {
Location location = player.getLocation();
location.setY(location.getY() - 1.0);
location.setPitch(-90);
Firework firework = (Firework) player.getWorld().spawnEntity(location, EntityType.FIREWORK);
FireworkMeta fireworkMeta = firework.getFireworkMeta();
FireworkEffect effect = FireworkEffect.builder().flicker(false).withColor(color).with(Type.BALL_LARGE).trail(true).build();
fireworkMeta.addEffect(effect);
fireworkMeta.addEffect(effect);
fireworkMeta.setPower(0);
firework.setFireworkMeta(fireworkMeta);
}
}

View File

@ -0,0 +1,79 @@
package com.gmail.nossr50.util.skills;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.Permissions;
public final class PerksUtils {
private static final int LUCKY_SKILL_ACTIVATION_CHANCE = 75;
private static final int NORMAL_SKILL_ACTIVATION_CHANCE = 100;
private PerksUtils() {};
public static int handleCooldownPerks(Player player, int cooldown) {
if (Permissions.halvedCooldowns(player)) {
cooldown *= 0.5;
}
else if (Permissions.thirdedCooldowns(player)) {
cooldown *= (1.0 / 3.0);
}
else if (Permissions.quarteredCooldowns(player)) {
cooldown *= 0.75;
}
return cooldown;
}
public static int handleActivationPerks(Player player, int ticks, int maxTicks) {
if (Permissions.twelveSecondActivationBoost(player)) {
ticks += 12;
}
else if (Permissions.eightSecondActivationBoost(player)) {
ticks += 8;
}
else if (Permissions.fourSecondActivationBoost(player)) {
ticks += 4;
}
if (maxTicks != 0 && ticks > maxTicks) {
ticks = maxTicks;
}
return ticks;
}
public static int handleXpPerks(Player player, int xp) {
if (Permissions.quadrupleXp(player)) {
xp *= 4;
}
else if (Permissions.tripleXp(player)) {
xp *= 3;
}
else if (Permissions.doubleAndOneHalfXp(player)) {
xp *= 2.5;
}
else if (Permissions.doubleXp(player)) {
xp *= 2;
}
else if (Permissions.oneAndOneHalfXp(player)) {
xp *= 1.5;
}
return xp;
}
/**
* Calculate activation chance for a skill.
*
* @param isLucky true if the player has the appropriate "lucky" perk, false otherwise
* @return the activation chance
*/
public static int handleLuckyPerks(Player player, SkillType skill) {
if (Permissions.lucky(player, skill)) {
return LUCKY_SKILL_ACTIVATION_CHANCE;
}
return NORMAL_SKILL_ACTIVATION_CHANCE;
}
}

View File

@ -0,0 +1,628 @@
package com.gmail.nossr50.util.skills;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.config.spout.SpoutConfig;
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.ToolType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.events.fake.FakeBlockDamageEvent;
import com.gmail.nossr50.events.fake.FakePlayerAnimationEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.ModUtils;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.spout.SpoutUtils;
public class SkillUtils {
public static int handleFoodSkills(Player player, SkillType skill, int eventFoodLevel, int baseLevel, int maxLevel, int rankChange) {
int skillLevel = UserManager.getPlayer(player).getProfile().getSkillLevel(skill);
int currentFoodLevel = player.getFoodLevel();
int foodChange = eventFoodLevel - currentFoodLevel;
for (int i = baseLevel; i <= maxLevel; i += rankChange) {
if (skillLevel >= i) {
foodChange++;
}
}
return currentFoodLevel + foodChange;
}
/**
* Checks to see if the cooldown for an item or ability is expired.
*
* @param oldTime The time the ability or item was last used
* @param cooldown The amount of time that must pass between uses
* @param player The player whose cooldown is being checked
* @return true if the cooldown is over, false otherwise
*/
public static boolean cooldownOver(long oldTime, int cooldown, Player player) {
long currentTime = System.currentTimeMillis();
int adjustedCooldown = PerksUtils.handleCooldownPerks(player, cooldown);
if (currentTime - oldTime >= (adjustedCooldown * Misc.TIME_CONVERSION_FACTOR)) {
return true;
}
return false;
}
/**
* Calculate the time remaining until the cooldown expires.
*
* @param deactivatedTimeStamp Time of deactivation
* @param cooldown The length of the cooldown
* @return the number of seconds remaining before the cooldown expires
*/
public static int calculateTimeLeft(long deactivatedTimeStamp, int cooldown, Player player) {
return (int) (((deactivatedTimeStamp + (PerksUtils.handleCooldownPerks(player, cooldown) * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) / Misc.TIME_CONVERSION_FACTOR);
}
/**
* Sends a message to the player when the cooldown expires.
*
* @param player The player to send a message to
* @param profile The profile of the player
* @param ability The ability to watch cooldowns for
*/
public static void watchCooldown(Player player, PlayerProfile profile, AbilityType ability) {
if (player == null || profile == null || ability == null) {
return;
}
if (!profile.getAbilityInformed(ability) && cooldownOver(profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)) {
profile.setAbilityInformed(ability, true);
player.sendMessage(ability.getAbilityRefresh());
}
}
/**
* Process activating abilities & readying the tool.
*
* @param player The player using the ability
* @param skill The skill the ability is tied to
*/
public static void activationCheck(Player player, SkillType skill) {
if (Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && !player.isSneaking()) {
return;
}
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
AbilityType ability = skill.getAbility();
ToolType tool = skill.getTool();
ItemStack inHand = player.getItemInHand();
if (ModUtils.isCustomTool(inHand) && !ModUtils.getToolFromItemStack(inHand).isAbilityEnabled()) {
return;
}
/* Check if any abilities are active */
if (profile == null) {
return;
}
if (!profile.getAbilityUse()) {
return;
}
for (AbilityType x : AbilityType.values()) {
if (profile.getAbilityMode(x)) {
return;
}
}
/*
* Woodcutting & Axes need to be treated differently.
* Basically the tool always needs to ready and we check to see if the cooldown is over when the user takes action
*/
if (ability.getPermissions(player) && tool.inHand(inHand) && !profile.getToolPreparationMode(tool)) {
if (skill != SkillType.WOODCUTTING && skill != SkillType.AXES) {
if (!profile.getAbilityMode(ability) && !cooldownOver(profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", calculateTimeLeft(profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)));
return;
}
}
if (Config.getInstance().getAbilityMessagesEnabled()) {
player.sendMessage(tool.getRaiseTool());
}
profile.setToolPreparationATS(tool, System.currentTimeMillis());
profile.setToolPreparationMode(tool, true);
}
}
/**
* Monitors various things relating to skill abilities.
*
* @param player The player using the skill
* @param profile The profile of the player
* @param curTime The current system time
* @param skill The skill being monitored
*/
public static void monitorSkill(Player player, PlayerProfile profile, long curTime, SkillType skill) {
final int FOUR_SECONDS = 4000;
ToolType tool = skill.getTool();
AbilityType ability = skill.getAbility();
if (profile == null) {
return;
}
if (profile.getToolPreparationMode(tool) && curTime - (profile.getToolPreparationATS(tool) * Misc.TIME_CONVERSION_FACTOR) >= FOUR_SECONDS) {
profile.setToolPreparationMode(tool, false);
if (Config.getInstance().getAbilityMessagesEnabled()) {
player.sendMessage(tool.getLowerTool());
}
}
if (ability.getPermissions(player)) {
if (profile.getAbilityMode(ability) && (profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR) <= curTime) {
if (ability == AbilityType.BERSERK) {
player.setCanPickupItems(true);
}
else if (ability == AbilityType.SUPER_BREAKER || ability == AbilityType.GIGA_DRILL_BREAKER) {
handleAbilitySpeedDecrease(player);
}
profile.setAbilityMode(ability, false);
profile.setAbilityInformed(ability, false);
ParticleEffectUtils.playAbilityDisabledEffect(player);
if (profile.useChatNotifications()) {
player.sendMessage(ability.getAbilityOff());
}
sendSkillMessage(player, ability.getAbilityPlayerOff(player));
}
}
}
/**
* Check the XP of a skill.
*
* @param skillType The skill to check
* @param player The player whose skill to check
* @param profile The profile of the player whose skill to check
*/
public static void xpCheckSkill(SkillType skillType, Player player, PlayerProfile profile) {
int skillups = 0;
int xpRemoved = 0;
if (profile.getSkillXpLevel(skillType) >= profile.getXpToLevel(skillType)) {
while (profile.getSkillXpLevel(skillType) >= profile.getXpToLevel(skillType)) {
if ((skillType.getMaxLevel() >= profile.getSkillLevel(skillType) + 1) && (Config.getInstance().getPowerLevelCap() >= UserManager.getPlayer(player).getPowerLevel() + 1)) {
int xp = profile.getXpToLevel(skillType);
xpRemoved += xp;
profile.removeXp(skillType, xp);
skillups++;
profile.skillUp(skillType, 1);
}
else {
profile.addLevels(skillType, 0);
}
}
McMMOPlayerLevelUpEvent eventToFire = new McMMOPlayerLevelUpEvent(player, skillType, skillups);
mcMMO.p.getServer().getPluginManager().callEvent(eventToFire);
if (eventToFire.isCancelled()) {
profile.modifySkill(skillType, profile.getSkillLevel(skillType) - skillups);
profile.setSkillXpLevel(skillType, profile.getSkillXpLevel(skillType) + xpRemoved);
return;
}
String capitalized = StringUtils.getCapitalized(skillType.toString());
/* Spout Stuff */
if (mcMMO.spoutEnabled) {
SpoutPlayer spoutPlayer = SpoutManager.getPlayer(player);
if (spoutPlayer != null && spoutPlayer.isSpoutCraftEnabled()) {
SpoutUtils.levelUpNotification(skillType, spoutPlayer);
/* Update custom titles */
if (SpoutConfig.getInstance().getShowPowerLevel()) {
spoutPlayer.setTitle(LocaleLoader.getString("Spout.Title", spoutPlayer.getName(), UserManager.getPlayer(player).getPowerLevel()));
}
}
else {
player.sendMessage(LocaleLoader.getString(capitalized + ".Skillup", skillups, profile.getSkillLevel(skillType)));
}
}
else {
player.sendMessage(LocaleLoader.getString(capitalized + ".Skillup", skillups, profile.getSkillLevel(skillType)));
}
}
if (mcMMO.spoutEnabled) {
SpoutPlayer spoutPlayer = SpoutManager.getPlayer(player);
if (spoutPlayer != null && spoutPlayer.isSpoutCraftEnabled()) {
if (SpoutConfig.getInstance().getXPBarEnabled()) {
profile.getSpoutHud().updateXpBar();
}
}
}
}
/**
* Checks if the given string represents a valid skill
*
* @param skillName The name of the skill to check
* @return true if this is a valid skill, false otherwise
*/
public static boolean isSkill(String skillName) {
if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) {
return isLocalizedSkill(skillName);
}
if (SkillType.getSkill(skillName) != null) {
return true;
}
return false;
}
private static boolean isLocalizedSkill(String skillName) {
for (SkillType skill : SkillType.values()) {
if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".SkillName"))) {
return true;
}
}
return false;
}
public static String getSkillName(SkillType skill) {
if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) {
return StringUtils.getCapitalized(LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".SkillName"));
}
return StringUtils.getCapitalized(skill.toString());
}
/**
* Check if the player has any combat skill permissions.
*
* @param player The player to check permissions for
* @return true if the player has combat skills, false otherwise
*/
public static boolean hasCombatSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.AXES)
|| Permissions.skillEnabled(player, SkillType.ARCHERY)
|| Permissions.skillEnabled(player, SkillType.SWORDS)
|| Permissions.skillEnabled(player, SkillType.TAMING)
|| Permissions.skillEnabled(player, SkillType.UNARMED)) {
return true;
}
return false;
}
/**
* Check if the player has any gathering skill permissions.
*
* @param player The player to check permissions for
* @return true if the player has gathering skills, false otherwise
*/
public static boolean hasGatheringSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.EXCAVATION)
|| Permissions.skillEnabled(player, SkillType.FISHING)
|| Permissions.skillEnabled(player, SkillType.HERBALISM)
|| Permissions.skillEnabled(player, SkillType.MINING)
|| Permissions.skillEnabled(player, SkillType.WOODCUTTING)) {
return true;
}
return false;
}
/**
* Check if the player has any misc skill permissions.
*
* @param player The player to check permissions for
* @return true if the player has misc skills, false otherwise
*/
public static boolean hasMiscSkills(Player player) {
if (Permissions.skillEnabled(player, SkillType.ACROBATICS)
|| Permissions.skillEnabled(player, SkillType.SMELTING)
|| Permissions.skillEnabled(player, SkillType.REPAIR)) {
return true;
}
return false;
}
/**
* Check to see if an ability can be activated.
*
* @param player The player activating the ability
* @param type The skill the ability is based on
*/
public static void abilityCheck(Player player, SkillType type) {
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
ToolType tool = type.getTool();
AbilityType ability = type.getAbility();
profile.setToolPreparationMode(tool, false);
/*
* Axes and Woodcutting are odd because they share the same tool.
* We show them the too tired message when they take action.
*/
if (type == SkillType.WOODCUTTING || type == SkillType.AXES) {
if (!profile.getAbilityMode(ability) && !cooldownOver(profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", calculateTimeLeft(profile.getSkillDATS(ability) * Misc.TIME_CONVERSION_FACTOR, ability.getCooldown(), player)));
return;
}
}
if (!profile.getAbilityMode(ability) && cooldownOver(profile.getSkillDATS(ability), ability.getCooldown(), player)) {
int ticks = PerksUtils.handleActivationPerks(player, 2 + (profile.getSkillLevel(type) / AdvancedConfig.getInstance().getAbilityLength()), ability.getMaxTicks());
ParticleEffectUtils.playAbilityEnabledEffect(player);
if (profile.useChatNotifications()) {
player.sendMessage(ability.getAbilityOn());
}
SkillUtils.sendSkillMessage(player, ability.getAbilityPlayer(player));
profile.setSkillDATS(ability, System.currentTimeMillis() + (ticks * Misc.TIME_CONVERSION_FACTOR));
profile.setAbilityMode(ability, true);
if (ability == AbilityType.BERSERK) {
player.setCanPickupItems(false);
}
else if (ability == AbilityType.SUPER_BREAKER || ability == AbilityType.GIGA_DRILL_BREAKER) {
handleAbilitySpeedIncrease(player);
}
}
}
/**
* Check to see if ability should be triggered.
*
* @param player The player using the ability
* @param block The block modified by the ability
* @param ability The ability to check
* @return true if the ability should activate, false otherwise
*/
public static boolean triggerCheck(Player player, Block block, AbilityType ability) {
boolean activate = true;
switch (ability) {
case BERSERK:
case LEAF_BLOWER:
if (!ability.blockCheck(block.getState())) {
activate = false;
break;
}
if (!blockBreakSimulate(block, player, true)) {
activate = false;
break;
}
break;
case GIGA_DRILL_BREAKER:
case SUPER_BREAKER:
case GREEN_TERRA:
if (!ability.blockCheck(block.getState())) {
activate = false;
break;
}
break;
default:
activate = false;
break;
}
return activate;
}
public static void sendSkillMessage(Player player, String message) {
for (Player otherPlayer : player.getWorld().getPlayers()) {
if (otherPlayer != player && Misc.isNear(player.getLocation(), otherPlayer.getLocation(), Misc.SKILL_MESSAGE_MAX_SENDING_DISTANCE)) {
otherPlayer.sendMessage(message);
}
}
}
/**
* Check if a skill level is higher than the max bonus level of the ability.
*
* @param skillLevel Skill level to check
* @param maxLevel Max level of the ability
* @return whichever value is lower
*/
public static int skillCheck(int skillLevel, int maxLevel) {
// TODO: Could we just use Math.min(skillLevel, maxLevel) here?
if (skillLevel > maxLevel) {
return maxLevel;
}
return skillLevel;
}
public static void handleAbilitySpeedIncrease(Player player) {
if (HiddenConfig.getInstance().useEnchantmentBuffs()) {
ItemStack heldItem = player.getItemInHand();
if (heldItem == null || heldItem.getType() == Material.AIR) {
return;
}
int efficiencyLevel = heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED);
ItemMeta itemMeta = heldItem.getItemMeta();
List<String> itemLore = new ArrayList<String>();
if (itemMeta.hasLore()) {
itemLore = itemMeta.getLore();
}
itemLore.add("mcMMO Ability Tool");
itemMeta.addEnchant(Enchantment.DIG_SPEED, efficiencyLevel + 5, true);
itemMeta.setLore(itemLore);
heldItem.setItemMeta(itemMeta);
}
else {
int duration = 0;
int amplifier = 0;
if (player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) {
for (PotionEffect effect : player.getActivePotionEffects()) {
if (effect.getType() == PotionEffectType.FAST_DIGGING) {
duration = effect.getDuration();
amplifier = effect.getAmplifier();
break;
}
}
}
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
int ticks = 0;
if (profile.getAbilityMode(AbilityType.SUPER_BREAKER)) {
ticks = ((int) (profile.getSkillDATS(AbilityType.SUPER_BREAKER) - System.currentTimeMillis())) / Misc.TIME_CONVERSION_FACTOR;
}
else if (profile.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER)) {
ticks = ((int) (profile.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER) - System.currentTimeMillis())) / Misc.TIME_CONVERSION_FACTOR;
}
PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10);
player.addPotionEffect(abilityBuff, true);
}
}
public static void handleAbilitySpeedDecrease(Player player) {
if (HiddenConfig.getInstance().useEnchantmentBuffs()) {
PlayerInventory playerInventory = player.getInventory();
for (int i = 0; i < playerInventory.getContents().length; i++) {
ItemStack item = playerInventory.getItem(i);
playerInventory.setItem(i, removeAbilityBuff(item));
}
}
else {
player.removePotionEffect(PotionEffectType.FAST_DIGGING);
}
}
public static ItemStack removeAbilityBuff(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
return item;
}
if (!ItemUtils.isPickaxe(item) && !ItemUtils.isShovel(item)) {
return item;
}
if (item.containsEnchantment(Enchantment.DIG_SPEED)) {
ItemMeta itemMeta = item.getItemMeta();
if (itemMeta.hasLore()) {
List<String> itemLore = itemMeta.getLore();
if (itemLore.remove("mcMMO Ability Tool")) {
int efficiencyLevel = item.getEnchantmentLevel(Enchantment.DIG_SPEED);
if (efficiencyLevel <= 5) {
itemMeta.removeEnchant(Enchantment.DIG_SPEED);
}
else {
itemMeta.addEnchant(Enchantment.DIG_SPEED, efficiencyLevel - 5, true);
}
itemMeta.setLore(itemLore);
item.setItemMeta(itemMeta);
}
}
}
return item;
}
/**
* Simulate a block break event.
*
* @param block The block to break
* @param player The player breaking the block
* @param shouldArmSwing true if an armswing event should be fired, false otherwise
* @return true if the event wasn't cancelled, false otherwise
*/
public static boolean blockBreakSimulate(Block block, Player player, Boolean shouldArmSwing) {
PluginManager pluginManger = mcMMO.p.getServer().getPluginManager();
// Support for NoCheat
if (shouldArmSwing) {
pluginManger.callEvent(new FakePlayerAnimationEvent(player));
}
FakeBlockDamageEvent damageEvent = new FakeBlockDamageEvent(player, block, player.getItemInHand(), true);
pluginManger.callEvent(damageEvent);
FakeBlockBreakEvent breakEvent = new FakeBlockBreakEvent(block, player);
pluginManger.callEvent(breakEvent);
if (!damageEvent.isCancelled() && !breakEvent.isCancelled()) {
return true;
}
return false;
}
public static boolean activationSuccessful(Player player, SkillType skill, double maxChance, int maxLevel) {
int skillLevel = UserManager.getPlayer(player).getProfile().getSkillLevel(skill);
int activationChance = PerksUtils.handleLuckyPerks(player, skill);
double chance = (maxChance / maxLevel) * Math.min(skillLevel, maxLevel);
return chance > Misc.getRandom().nextInt(activationChance);
}
public static boolean activationSuccessful(Player player, SkillType skill, double chance) {
return chance > Misc.getRandom().nextInt(PerksUtils.handleLuckyPerks(player, skill));
}
public static boolean unlockLevelReached(Player player, SkillType skill, int unlockLevel) {
return UserManager.getPlayer(player).getProfile().getSkillLevel(skill) > unlockLevel;
}
public static boolean treasureDropSuccessful(double dropChance, int activationChance) {
return dropChance > Misc.getRandom().nextDouble() * activationChance;
}
}

View File

@ -0,0 +1,17 @@
package com.gmail.nossr50.util.spout;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.SpoutManager;
import com.gmail.nossr50.mcMMO;
public class SpoutSoundUtils {
/**
* Play noise on level-up.
*
* @param player The player who leveled up
*/
protected static void playLevelUpNoise(Player player, mcMMO plugin) {
SpoutManager.getSoundManager().playCustomSoundEffect(plugin, SpoutManager.getPlayer(player), "level.wav", false);
}
}

View File

@ -0,0 +1,586 @@
package com.gmail.nossr50.util.spout;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.event.spout.SpoutCraftEnableEvent;
import org.getspout.spoutapi.keyboard.Keyboard;
import org.getspout.spoutapi.player.FileManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.spout.SpoutConfig;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.listeners.SpoutListener;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
public class SpoutUtils {
private static mcMMO plugin = mcMMO.p;
public final static String spoutDirectory = mcMMO.getMainDirectory() + "Resources" + File.separator;
public final static String hudDirectory = spoutDirectory + "HUD" + File.separator;
public final static String hudStandardDirectory = hudDirectory + "Standard" + File.separator;
public final static String hudRetroDirectory = hudDirectory + "Retro" + File.separator;
public final static String soundDirectory = spoutDirectory + "Sound" + File.separator;
public static boolean showPowerLevel;
private final static SpoutListener spoutListener = new SpoutListener();
public static Keyboard menuKey;
/**
* Write file to disk.
*
* @param theFileName The name of the file
* @param theFilePath The name of the file path
*/
private static void writeFile(String theFileName, String theFilePath) {
InputStream is = null;
OutputStream os = null;
JarFile jar = null;
try {
File currentFile = new File(theFilePath + theFileName);
// No point in writing the file again if it already exists.
if (currentFile.exists()) {
return;
}
jar = new JarFile(mcMMO.mcmmo);
JarEntry entry = jar.getJarEntry("resources/" + theFileName);
is = jar.getInputStream(entry);
byte[] buf = new byte[2048];
int nbRead;
os = new BufferedOutputStream(new FileOutputStream(currentFile));
while ((nbRead = is.read(buf)) != -1) {
os.write(buf, 0, nbRead);
}
os.flush();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (os != null) {
try {
os.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
if (jar != null) {
try {
jar.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
/**
* Extract Spout files to the Resources directory.
*/
public static void extractFiles() {
// Setup directories
new File(spoutDirectory).mkdir();
new File(hudDirectory).mkdir();
new File(hudStandardDirectory).mkdir();
new File(hudRetroDirectory).mkdir();
new File(soundDirectory).mkdir();
// XP Bar images
for (int x = 0; x < 255; x++) {
String theFileName;
if (x < 10) {
theFileName = "xpbar_inc00" + x + ".png";
}
else if (x < 100) {
theFileName = "xpbar_inc0" + x + ".png";
}
else {
theFileName = "xpbar_inc" + x + ".png";
}
writeFile(theFileName, hudStandardDirectory);
}
// Standard XP Icons
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
String skillTypeString = StringUtils.getCapitalized(skillType.toString());
writeFile(skillTypeString + ".png", hudStandardDirectory);
writeFile(skillTypeString + "_r.png", hudRetroDirectory);
}
// Blank icons
writeFile("Icon.png", hudStandardDirectory);
writeFile("Icon_r.png", hudRetroDirectory);
// Sound FX
writeFile("level.wav", soundDirectory);
}
/**
* Setup Spout config options
*/
public static void setupSpoutConfigs() {
showPowerLevel = SpoutConfig.getInstance().getShowPowerLevel();
String temp = SpoutConfig.getInstance().getMenuKey();
for (Keyboard x : Keyboard.values()) {
if (x.toString().equalsIgnoreCase(temp)) {
menuKey = x;
}
}
if (menuKey == null) {
mcMMO.p.getLogger().warning("Invalid KEY for Menu.Key, using KEY_M");
menuKey = Keyboard.KEY_M;
}
}
/**
* Get all the Spout files in the Resources folder.
*
* @return a list of all files is the Resources folder
*/
public static ArrayList<File> getFiles() {
ArrayList<File> files = new ArrayList<File>();
// XP BAR
for (int x = 0; x < 255; x++) {
if (x < 10) {
files.add(new File(hudStandardDirectory + "xpbar_inc00" + x + ".png"));
}
else if (x < 100) {
files.add(new File(hudStandardDirectory + "xpbar_inc0" + x + ".png"));
}
else {
files.add(new File(hudStandardDirectory + "xpbar_inc" + x + ".png"));
}
}
// Standard XP Icons
for (SkillType skillType : SkillType.values()) {
if (skillType.isChildSkill()) {
continue;
}
String skillTypeString = StringUtils.getCapitalized(skillType.toString());
files.add(new File(hudStandardDirectory + skillTypeString + ".png"));
files.add(new File(hudRetroDirectory + skillTypeString + "_r.png"));
}
// Blank icons
files.add(new File(hudStandardDirectory + "Icon.png"));
files.add(new File(hudRetroDirectory + "Icon_r.png"));
// Level SFX
files.add(new File(soundDirectory + "level.wav"));
return files;
}
/**
* Register custom Spout events.
*/
public static void registerCustomEvent() {
plugin.getServer().getPluginManager().registerEvents(spoutListener, plugin);
}
/**
* Handle level-up notifications through Spout.
*
* @param skillType The skill that leveled up
* @param spoutPlayer The player that leveled up
*/
public static void levelUpNotification(SkillType skillType, SpoutPlayer spoutPlayer) {
PlayerProfile profile = UserManager.getPlayer(spoutPlayer).getProfile();
int notificationTier = getNotificationTier(profile.getSkillLevel(skillType));
Material mat = null;
switch (skillType) {
case TAMING:
switch (notificationTier) {
case 1:
case 2:
mat = Material.PORK;
break;
case 3:
case 4:
mat = Material.GRILLED_PORK;
break;
case 5:
mat = Material.BONE;
break;
default:
break;
}
break;
case MINING:
switch (notificationTier) {
case 1:
mat = Material.COAL_ORE;
break;
case 2:
mat = Material.IRON_ORE;
break;
case 3:
mat = Material.GOLD_ORE;
break;
case 4:
mat = Material.DIAMOND_ORE;
break;
case 5:
mat = Material.EMERALD_ORE;
break;
default:
break;
}
break;
case WOODCUTTING:
switch (notificationTier) {
case 1:
mat = Material.STICK;
break;
case 2:
case 3:
mat = Material.WOOD;
break;
case 4:
case 5:
mat = Material.LOG;
break;
default:
break;
}
break;
case REPAIR:
mat = Material.ANVIL;
break;
case HERBALISM:
switch (notificationTier) {
case 1:
mat = Material.YELLOW_FLOWER;
break;
case 2:
mat = Material.RED_ROSE;
break;
case 3:
mat = Material.BROWN_MUSHROOM;
break;
case 4:
mat = Material.RED_MUSHROOM;
break;
case 5:
mat = Material.PUMPKIN;
break;
default:
break;
}
break;
case ACROBATICS:
switch (notificationTier) {
case 1:
mat = Material.LEATHER_BOOTS;
break;
case 2:
mat = Material.CHAINMAIL_BOOTS;
break;
case 3:
mat = Material.IRON_BOOTS;
break;
case 4:
mat = Material.GOLD_BOOTS;
break;
case 5:
mat = Material.DIAMOND_BOOTS;
break;
default:
break;
}
break;
case SWORDS:
switch (notificationTier) {
case 1:
mat = Material.WOOD_SWORD;
break;
case 2:
mat = Material.STONE_SWORD;
break;
case 3:
mat = Material.IRON_SWORD;
break;
case 4:
mat = Material.GOLD_SWORD;
break;
case 5:
mat = Material.DIAMOND_SWORD;
break;
default:
break;
}
break;
case ARCHERY:
switch (notificationTier) {
case 1:
case 2:
case 3:
mat = Material.ARROW;
break;
case 4:
case 5:
mat = Material.BOW;
break;
default:
break;
}
break;
case UNARMED:
switch (notificationTier) {
case 1:
mat = Material.LEATHER_HELMET;
break;
case 2:
mat = Material.CHAINMAIL_HELMET;
break;
case 3:
mat = Material.IRON_HELMET;
break;
case 4:
mat = Material.GOLD_HELMET;
break;
case 5:
mat = Material.DIAMOND_HELMET;
break;
default:
break;
}
break;
case EXCAVATION:
switch (notificationTier) {
case 1:
mat = Material.WOOD_SPADE;
break;
case 2:
mat = Material.STONE_SPADE;
break;
case 3:
mat = Material.IRON_SPADE;
break;
case 4:
mat = Material.GOLD_SPADE;
break;
case 5:
mat = Material.DIAMOND_SPADE;
break;
default:
break;
}
break;
case AXES:
switch (notificationTier) {
case 1:
mat = Material.WOOD_AXE;
break;
case 2:
mat = Material.STONE_AXE;
break;
case 3:
mat = Material.IRON_AXE;
break;
case 4:
mat = Material.GOLD_AXE;
break;
case 5:
mat = Material.DIAMOND_AXE;
break;
default:
break;
}
break;
case FISHING:
switch (notificationTier) {
case 1:
case 2:
mat = Material.RAW_FISH;
break;
case 3:
case 4:
mat = Material.COOKED_FISH;
break;
case 5:
mat = Material.FISHING_ROD;
break;
default:
break;
}
break;
default:
mat = Material.WATCH;
break;
}
spoutPlayer.sendNotification(LocaleLoader.getString("Spout.LevelUp.1"), LocaleLoader.getString("Spout.LevelUp.2", SkillUtils.getSkillName(skillType), profile.getSkillLevel(skillType)), mat);
SpoutSoundUtils.playLevelUpNoise(spoutPlayer, plugin);
}
/**
* Gets the notification tier of a skill.
*
* @param level The level of the skill
* @return the notification tier of the skill
*/
private static int getNotificationTier(int level) {
if (level >= AdvancedConfig.getInstance().getSpoutNotificationTier4()) {
return 5;
}
else if (level >= AdvancedConfig.getInstance().getSpoutNotificationTier3()) {
return 4;
}
else if (level >= AdvancedConfig.getInstance().getSpoutNotificationTier2()) {
return 3;
}
else if (level >= AdvancedConfig.getInstance().getSpoutNotificationTier1()) {
return 2;
}
else {
return 1;
}
}
/**
* Re-enable SpoutCraft for players after a /reload
*/
public static void reloadSpoutPlayers() {
for (SpoutPlayer spoutPlayer : SpoutManager.getPlayerChunkMap().getOnlinePlayers()) {
mcMMO.p.getServer().getPluginManager().callEvent(new SpoutCraftEnableEvent(spoutPlayer));
}
}
public static void reloadSpoutPlayer(Player player) {
SpoutPlayer spoutPlayer = SpoutManager.getPlayer(player);
if (spoutPlayer != null) {
mcMMO.p.getServer().getPluginManager().callEvent(new SpoutCraftEnableEvent(spoutPlayer));
}
}
public static void preCacheFiles() {
extractFiles(); // Extract source materials
FileManager FM = SpoutManager.getFileManager();
FM.addToPreLoginCache(plugin, getFiles());
}
}