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

Compare commits

..

2 Commits

Author SHA1 Message Date
TfT_02
3b249aa4e6 This function is designed for API usage. 2014-10-11 12:03:08 +02:00
TfT_02
1a2d586086 More Javadocs 2014-10-11 11:53:12 +02:00
146 changed files with 6194 additions and 8984 deletions

1
.gitignore vendored
View File

@@ -2,7 +2,6 @@
/.classpath
/.project
/.settings
/dependency-reduced-pom.xml
# netbeans
/nbproject

View File

@@ -7,66 +7,7 @@ Key:
! Change
- Removal
Version 2.0.00
= Fixed an interaction between Tree Feller and Stripped Wood
! Fireworks no longer fire by default for ability activation/deactivation
! Website has been changed and the MOTD string relating to it reflects this
! Discord link added to mcMMO command
! Updated misc strings relating to mcMMO
Version 1.5.05-SNAPSHOT
Version 1.5.04
+ Added option to config.yml to control mcMMO generated sound volume
+ Added option to config.yml to truncate existing player skill levels that exceed the skill level cap
+ Falling blocks persist mcMMO natural data
= Woodcutting double drops correctly identify acacia and dark oak logs
= Skill Reset command now correctly identifies arguments
= Hylian Treasure config options are now actually used
= Child skills now use parent skills configured skill caps properly
= Auto Update config now properly works
! Item dropped from blocks now drop from the center
! Potions Config updated for 1.9
! Flux mining now simulates a block break event for other plugins to act upon
! Zombie Pigmen spawned from nether portals are now considered spawner mobs
! Flux Pickaxe lore now appends to existing lore as opposed to replacing it
! Party chat no longer displays colors when logged in server console
- Treefeller no longer lowers exp for big trees
- No longer supports 1.8 :(
- Removed plugin metrics
Version 1.5.03
= Fixed bug where absorption hearts could be attacked by allied players
= Fixed bug where new forms of stone would drop the wrong type when mined with Silk Touch
= Fixed bug where blocks would not get tracked correctly when using sticky pistons and slime blocks in certain situations
= Fixed bug where config value for Daze damage was ignored
= Fixed UUID updater to not lose data on errors
= Fixed bug where uuid update could result in large amounts of user data being deleted
= Fixed bug where custom potions were missed in potion stage calculation
= Fixed piston dupe bugs permanently
= Fixed bug involving user name changes
= Fixed old user purge to properly calculate months
= Fixed bug where Repair would incorrectly check items
= Fixed bug where apostrophes in locale files would not read correctly
= Fixed bug where treasure data was limited to 255 instead of Short.MAX_VALUE
! Moved more user loading calculations to async loading thread to reduce lag on login
Version 1.5.02
+ Added option to config.yml for Chimaera Wings to stop using bed spawn points
+ Added option to config.yml to let non-tools in hand count as unarmed
+ Added option to experience.yml to control XP gained by killing bred animals
+ Added support for 1.8 mobs and features
= Fixed bug where no Mining XP was granted when Flux Mining was successful
= Fixed bug with UUID conversions in Flatfile
= Fixed a couple Dupe bugs that were introduced recently
= Fixed bug where MobHealthbarTypes were not saved between server restarts
! Changed Flux Mining mechanics. In order to use the ability, you need to infuse a pickaxe with furnace powers first.
! Scoreboard tips are only shown a couple of times to the player, instead of once per login session
! Changed Archery distance multiplier to be configurable
! Archery distance XP bonus cannot exceed indefinitely anymore
Version 1.5.01
Version 1.5.01-dev
+ Added new child skill; Salvage
+ Added UUID support!
+ Added SQL connection pooling and async loading!
@@ -115,7 +56,6 @@ Version 1.5.01
! Changed Alchemy XP distribution. XP is granted based on the stage of the potion.
! Changed behavior of the Blast Mining ability "Demolition Expert"; now only decreases damage for the ability user
! Updated for new getOnlinePlayers() behavior
! Updated for new blocks and entities
! Changed McMMOPlayerDeathPenaltyEvent to get fired after hardcore penalty calculations, use McMMOPlayerPreDeathPenaltyEvent for old behavior
! Moved Refresh_Chunks setting from hidden.yml to config.yml
- Removed salvage ability from Repair, salvage has it's own (child) skill now

View File

@@ -1,10 +1,8 @@
# mcMMO
## The RPG lovers mod
### Builds
Currently, you can obtain our builds via the Spigot resource page: https://www.spigotmc.org/resources/official-mcmmo.63489/
### Dev builds
Our latest development builds are available ~~[here](http://ci.mcmmo.info)~~. Unfortunately, the mcMMO site is down; a temporary dev build location is hosted [here](http://ci.ecocitycraft.com/job/mcMMO/).
### Brief Description
The goal of mcMMO is to take core Minecraft game mechanics and expand them into add an extensive and quality RPG experience. Everything in mcMMO has been carefully thought out and is constantly being improved upon. Currently, mcMMO adds fourteen unique skills to train and level in. Each of these skills is highly customizable through our configuration files, allowing server admins to tweak mcMMO to best suit the needs of his or her server. Know that the mcMMO team is dedicated to providing an ever-evolving experience, and that we carefully read all feedback and bug reports in order to evaluate and balance the mechanics of mcMMO in every update.
@@ -12,24 +10,31 @@ The goal of mcMMO is to take core Minecraft game mechanics and expand them into
## About the Team
mcMMO is currently developed by a team of individuals from all over the world.
### Project Lead & Founder
[![nossr50](http://www.gravatar.com/avatar/f2ee41eedfd645fb4a3a2c8f6cb1b18c.png)](https://github.com/nossr50)
### Former Lead
[![gmcferrin](http://www.gravatar.com/avatar/b64c52daf25d206b27650788b5813b7b.png)](https://github.com/gmcferrin)
### Glorious Leader
[![gmcferrin](http://www.gravatar.com/avatar/b64c52daf25d206b27650788b5813b7b.png)]
(https://github.com/gmcferrin)
### Developers
[![bm01](http://www.gravatar.com/avatar/ec8146f5358177f12e9a252271bbc391.png)](https://github.com/bm01)
[![Glitchfinder](http://www.gravatar.com/avatar/5aa4cce22f72ae9c002ecec30f061d00.png)](https://github.com/Glitchfinder)
[![NuclearW](http://www.gravatar.com/avatar/90926bdcf1c8a75918df5ea5fa801ce6.png)](https://github.com/NuclearW)
[![shatteredbeam](http://www.gravatar.com/avatar/cad3b5d7d39cf5387afb87f494389610.png)](https://github.com/shatteredbeam)
[![TfT_02](http://www.gravatar.com/avatar/b8914f9970e1f6ffd5281ce4770e20a7.png)](https://github.com/TfT-02)
[![t00thpick1](http://www.gravatar.com/avatar/ee23c7794a0c40120c3474287c7bce06.png)](https://github.com/t00thpick1)
[![riking](https://1.gravatar.com/avatar/aca9f37e569ac3a63929920035a91ba4.png)](https://github.com/riking)
[![bm01](http://www.gravatar.com/avatar/ec8146f5358177f12e9a252271bbc391.png)]
(https://github.com/bm01)
[![Glitchfinder](http://www.gravatar.com/avatar/5aa4cce22f72ae9c002ecec30f061d00.png)]
(https://github.com/Glitchfinder)
[![nossr50](http://www.gravatar.com/avatar/f2ee41eedfd645fb4a3a2c8f6cb1b18c.png)]
(https://github.com/nossr50)
[![NuclearW](http://www.gravatar.com/avatar/90926bdcf1c8a75918df5ea5fa801ce6.png)]
(https://github.com/NuclearW)
[![shatteredbeam](http://www.gravatar.com/avatar/cad3b5d7d39cf5387afb87f494389610.png)]
(https://github.com/shatteredbeam)
[![TfT_02](http://www.gravatar.com/avatar/b8914f9970e1f6ffd5281ce4770e20a7.png)]
(https://github.com/TfT-02)
[![t00thpick1](http://www.gravatar.com/avatar/ee23c7794a0c40120c3474287c7bce06.png)]
(https://github.com/t00thpick1)
[![riking](https://1.gravatar.com/avatar/aca9f37e569ac3a63929920035a91ba4.png)]
(https://github.com/riking)
### Special thanks
[![EasyMFnE](https://www.gravatar.com/avatar/99c9a1fa3bbf957791ceac7b45daadb0.png)](https://github.com/EasyMFnE)
[![EasyMFnE](https://www.gravatar.com/avatar/99c9a1fa3bbf957791ceac7b45daadb0.png)]
(https://github.com/EasyMFnE)
Added the Alchemy skill
## Compiling
@@ -39,7 +44,8 @@ mcMMO uses Maven 3 to manage dependencies, packaging, and shading of necessary c
The typical command used to build mcMMO is: `mvn clean package install`
Required Libraries:
* Bukkit
* JUnit
* EMetrics
* Bukkit
https://www.spigotmc.org/resources/official-mcmmo.63489/ for more up to date information.
http://dev.bukkit.org/server-mods/mcmmo for more up to date information.

75
pom.xml
View File

@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId>
<version>2.0.0-SNAPSHOT</version>
<version>1.5.01-SNAPSHOT</version>
<name>mcMMO</name>
<url>https://github.com/mcMMO-Dev/mcMMO</url>
<issueManagement>
@@ -38,14 +38,6 @@
<include>*.yml</include>
</includes>
</resource>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}</directory>
<includes>
<include>LICENSE</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
@@ -53,8 +45,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>1.6</source>
<target>1.6</target>
<excludes>
</excludes>
</configuration>
@@ -79,27 +71,27 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<version>1.5</version>
<configuration>
<artifactSet>
<includes>
<include>com.turt2live.metrics:MetricsExtension</include>
<include>commons-logging:commons-logging</include>
<include>org.apache.tomcat:tomcat-jdbc</include>
<include>org.apache.tomcat:tomcat-juli</include>
<include>net.snaq:dbpool</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.turt2live.metrics</pattern>
<shadedPattern>com.gmail.nossr50.metrics.mcstats</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.commons.logging</pattern>
<shadedPattern>com.gmail.nossr50.commons.logging</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.juli</pattern>
<shadedPattern>com.gmail.nossr50.database.tomcat.juli</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.tomcat</pattern>
<shadedPattern>com.gmail.nossr50.database.tomcat</shadedPattern>
<pattern>net.snaq</pattern>
<shadedPattern>com.gmail.nossr50.dbpool</shadedPattern>
</relocation>
</relocations>
</configuration>
@@ -121,11 +113,26 @@
</extension>
</extensions>
</build>
<repositories>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public/</url>
</repository>
<repository>
<id>md_5-releases</id>
<url>http://repo.md-5.net/content/repositories/releases/</url>
</repository>
<repository>
<id>Plugin MetricsExtension</id>
<url>http://repo.turt2live.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.13.1-R0.1-SNAPSHOT</version>
<version>1.7.10-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
@@ -135,13 +142,31 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>7.0.52</version>
<scope>compile</scope>
<groupId>com.turt2live.metrics</groupId>
<artifactId>MetricsExtension</artifactId>
<version>0.0.5-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>net.snaq</groupId>
<artifactId>dbpool</artifactId>
<version>5.1</version>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>md_5-releases</id>
<url>http://repo.md-5.net/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>md_5-snapshots</id>
<url>http://repo.md-5.net/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<ciManagement>
<system>Jenkins</system>
<url>http://ci.ecocitycraft.com/job/mcMMO</url>
</ciManagement>
</project>

View File

@@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: com.gmail.nossr50.mcMMO

View File

@@ -11,34 +11,106 @@ import com.gmail.nossr50.util.player.UserManager;
public final class AbilityAPI {
private AbilityAPI() {}
/**
* Checks if the ability "Berserk" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Berserk" is active
*/
public static boolean berserkEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.BERSERK);
}
/**
* Checks if the ability "Giga Drill Breaker" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Giga Drill Breaker" is active
*/
public static boolean gigaDrillBreakerEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.GIGA_DRILL_BREAKER);
}
/**
* Checks if the ability "Green Terra" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Green Terra" is active
*/
public static boolean greenTerraEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.GREEN_TERRA);
}
/**
* Checks if the ability "Serrated Strikes" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Serrated Strikes" is active
*/
public static boolean serratedStrikesEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.SERRATED_STRIKES);
}
/**
* Checks if the ability "Skull Splitter" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Skull Splitter" is active
*/
public static boolean skullSplitterEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.SKULL_SPLITTER);
}
/**
* Checks if the ability "Super Breaker" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Super Breaker" is active
*/
public static boolean superBreakerEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.SUPER_BREAKER);
}
/**
* Checks if the ability "Tree Feller" is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if "Tree Feller" is active
*/
public static boolean treeFellerEnabled(Player player) {
return UserManager.getPlayer(player).getAbilityMode(AbilityType.TREE_FELLER);
}
/**
* Checks if any ability is active.
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to check
*
* @return true if any ability is active
*/
public static boolean isAnyAbilityEnabled(Player player) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
@@ -51,38 +123,110 @@ public final class AbilityAPI {
return false;
}
/**
* Reset the ability cooldowns for a player
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to reset the cooldowns for
*/
public static void resetCooldowns(Player player) {
UserManager.getPlayer(player).resetCooldowns();
}
/**
* Set the cooldown for the "Berserk" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setBerserkCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.BERSERK, cooldown);
}
/**
* Set the cooldown for the "Giga Drill Breaker" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setGigaDrillBreakerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.GIGA_DRILL_BREAKER, cooldown);
}
/**
* Set the cooldown for the "Green Terra" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setGreenTerraCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.GREEN_TERRA, cooldown);
}
/**
* Set the cooldown for the "Serrated Strikes" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setSerratedStrikesCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.SERRATED_STRIKES, cooldown);
}
/**
* Set the cooldown for the "Skull Splitter" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setSkullSplitterCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.SKULL_SPLITTER, cooldown);
}
/**
* Set the cooldown for the "Super Breaker" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setSuperBreakerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.SUPER_BREAKER, cooldown);
}
/**
* Set the cooldown for the "Tree Feller" ability
* </br>
* This function is designed for API usage.
*
* @param player The {@link Player} to set the cooldown for
* @param cooldown The cooldown length to set
*/
public static void setTreeFellerCooldown(Player player, long cooldown) {
UserManager.getPlayer(player).setAbilityDATS(AbilityType.TREE_FELLER, cooldown);
}
/**
* Check if a LivingEntity is bleeding
* </br>
* This function is designed for API usage.
*
* @param entity The {@link LivingEntity} to check
* @return true if entity is bleeding, false otherwise
*/
public static boolean isBleeding(LivingEntity entity) {
return BleedTimerTask.isBleeding(entity);
}

View File

@@ -71,6 +71,8 @@ public final class ChatAPI {
/**
* Check if a player is currently talking in party chat.
* </br>
* This function is designed for API usage.
*
* @param player The player to check
* @return true if the player is using party chat, false otherwise
@@ -81,6 +83,8 @@ public final class ChatAPI {
/**
* Check if a player is currently talking in party chat.
* </br>
* This function is designed for API usage.
*
* @param playerName The name of the player to check
* @return true if the player is using party chat, false otherwise
@@ -91,6 +95,8 @@ public final class ChatAPI {
/**
* Check if a player is currently talking in admin chat.
* </br>
* This function is designed for API usage.
*
* @param player The player to check
* @return true if the player is using admin chat, false otherwise
@@ -101,6 +107,8 @@ public final class ChatAPI {
/**
* Check if a player is currently talking in admin chat.
* </br>
* This function is designed for API usage.
*
* @param playerName The name of the player to check
* @return true if the player is using admin chat, false otherwise
@@ -111,6 +119,8 @@ public final class ChatAPI {
/**
* Toggle the party chat mode of a player.
* </br>
* This function is designed for API usage.
*
* @param player The player to toggle party chat on.
*/
@@ -120,6 +130,8 @@ public final class ChatAPI {
/**
* Toggle the party chat mode of a player.
* </br>
* This function is designed for API usage.
*
* @param playerName The name of the player to toggle party chat on.
*/
@@ -129,6 +141,8 @@ public final class ChatAPI {
/**
* Toggle the admin chat mode of a player.
* </br>
* This function is designed for API usage.
*
* @param player The player to toggle admin chat on.
*/
@@ -138,6 +152,8 @@ public final class ChatAPI {
/**
* Toggle the admin chat mode of a player.
* </br>
* This function is designed for API usage.
*
* @param playerName The name of the player to toggle party chat on.
*/

View File

@@ -192,6 +192,14 @@ public final class PartyAPI {
return PartyManager.getOnlineMembers(player);
}
/**
* Check is a certain party has an ally
* </br>
* This function is designed for API usage.
*
* @param partyName The name of the party to check
* @return true if the party has an ally, false otherwise
*/
public static boolean hasAlly(String partyName) {
return getAllyName(partyName) != null;
}

View File

@@ -1,46 +0,0 @@
package com.gmail.nossr50.commands;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.FlatfileDatabaseManager;
import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class MHDCommand implements TabExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (mcMMO.getDatabaseManager() instanceof SQLDatabaseManager) {
SQLDatabaseManager m = (SQLDatabaseManager) mcMMO.getDatabaseManager();
m.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(Config.getInstance().getMobHealthbarDefault());
}
sender.sendMessage("Mob health reset");
return true;
}
if (mcMMO.getDatabaseManager() instanceof FlatfileDatabaseManager) {
FlatfileDatabaseManager m = (FlatfileDatabaseManager) mcMMO.getDatabaseManager();
m.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(Config.getInstance().getMobHealthbarDefault());
}
sender.sendMessage("Mob health reset");
return true;
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return ImmutableList.of();
}
}

View File

@@ -27,7 +27,7 @@ public class McmmoCommand implements CommandExecutor {
if (Config.getInstance().getDonateMessageEnabled()) {
sender.sendMessage(LocaleLoader.getString("MOTD.Donate"));
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "nossr50@gmail.com" + ChatColor.GOLD + " Paypal");
sender.sendMessage(ChatColor.GOLD + " - " + ChatColor.GREEN + "tft_02@hotmail.com" + ChatColor.GOLD + " Paypal");
}
if (Permissions.showversion(sender)) {

View File

@@ -2,9 +2,7 @@ package com.gmail.nossr50.commands.experience;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
@@ -18,6 +16,7 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public abstract class ExperienceCommand implements TabExecutor {
@@ -46,12 +45,6 @@ public abstract class ExperienceCommand implements TabExecutor {
skill = null;
}
if (skill != null && skill.isChildSkill())
{
sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill"));
return true;
}
editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill, Integer.parseInt(args[1]));
return true;
@@ -71,12 +64,6 @@ public abstract class ExperienceCommand implements TabExecutor {
skill = null;
}
if (skill != null && skill.isChildSkill())
{
sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill"));
return true;
}
int value = Integer.parseInt(args[2]);
String playerName = CommandUtils.getMatchedPlayerName(args[0]);
@@ -84,12 +71,7 @@ public abstract class ExperienceCommand implements TabExecutor {
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
UUID uuid = null;
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(playerName);
if (player != null) {
uuid = player.getUniqueId();
}
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, uuid, false);
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false);
if (CommandUtils.unloadedProfile(sender, profile)) {
return true;

View File

@@ -2,9 +2,7 @@ package com.gmail.nossr50.commands.experience;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
@@ -21,6 +19,7 @@ import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
/**
@@ -30,7 +29,6 @@ import com.google.common.collect.ImmutableList;
public class SkillresetCommand implements TabExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
SkillType skill;
switch (args.length) {
case 1:
if (CommandUtils.noConsoleUsage(sender)) {
@@ -46,14 +44,7 @@ public class SkillresetCommand implements TabExecutor {
return true;
}
if (args[0].equalsIgnoreCase("all")) {
skill = null;
}
else {
skill = SkillType.getSkill(args[1]);
}
editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill);
editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), SkillType.getSkill(args[0]));
return true;
case 2:
@@ -66,6 +57,7 @@ public class SkillresetCommand implements TabExecutor {
return true;
}
SkillType skill;
if (args[1].equalsIgnoreCase("all")) {
skill = null;
}
@@ -78,12 +70,7 @@ public class SkillresetCommand implements TabExecutor {
// If the mcMMOPlayer doesn't exist, create a temporary profile and check if it's present in the database. If it's not, abort the process.
if (mcMMOPlayer == null) {
UUID uuid = null;
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(playerName);
if (player != null) {
uuid = player.getUniqueId();
}
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, uuid, false);
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false);
if (CommandUtils.unloadedProfile(sender, profile)) {
return true;
@@ -147,7 +134,7 @@ public class SkillresetCommand implements TabExecutor {
}
private boolean validateArguments(CommandSender sender, String skillName) {
return skillName.equalsIgnoreCase("all") || !CommandUtils.isInvalidSkill(sender, skillName);
return !(CommandUtils.isInvalidSkill(sender, skillName) && !skillName.equalsIgnoreCase("all"));
}
protected static void handleSenderMessage(CommandSender sender, String playerName, SkillType skill) {

View File

@@ -1,16 +1,8 @@
package com.gmail.nossr50.commands.player;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
@@ -18,8 +10,17 @@ import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.List;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
public class MctopCommand implements TabExecutor {
@Override
@@ -90,12 +91,7 @@ public class MctopCommand implements TabExecutor {
long cooldownMillis = Math.max(Config.getInstance().getDatabasePlayerCooldown(), 1750);
if (mcMMOPlayer.getDatabaseATS() + cooldownMillis > System.currentTimeMillis()) {
double seconds = ((mcMMOPlayer.getDatabaseATS() + cooldownMillis) - System.currentTimeMillis()) / 1000;
if (seconds < 1) {
seconds = 1;
}
sender.sendMessage(LocaleLoader.formatString(LocaleLoader.getString("Commands.Database.Cooldown"), seconds));
sender.sendMessage(LocaleLoader.getString("Commands.Database.Cooldown"));
return;
}

View File

@@ -1,15 +1,16 @@
package com.gmail.nossr50.commands.skills;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.herbalism.Herbalism;
import com.gmail.nossr50.util.Permissions;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class HerbalismCommand extends SkillCommand {
private String greenTerraLength;
@@ -86,8 +87,8 @@ public class HerbalismCommand extends SkillCommand {
protected void permissionsCheck(Player player) {
hasHylianLuck = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.HYLIAN_LUCK);
canGreenTerra = Permissions.greenTerra(player);
canGreenThumbPlants = Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOT) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA);
canGreenThumbBlocks = Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) || Permissions.greenThumbBlock(player, Material.STONE_BRICKS);
canGreenThumbPlants = Permissions.greenThumbPlant(player, Material.CROPS) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.NETHER_WARTS) || Permissions.greenThumbPlant(player, Material.COCOA);
canGreenThumbBlocks = Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLE_WALL) || Permissions.greenThumbBlock(player, Material.SMOOTH_BRICK);
canFarmersDiet = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FARMERS_DIET);
canDoubleDrop = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.HERBALISM_DOUBLE_DROPS) && !skill.getDoubleDropsDisabled();
canShroomThumb = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.SHROOM_THUMB);

View File

@@ -1,10 +1,16 @@
package com.gmail.nossr50.commands.skills;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.ArcaneForging;
import com.gmail.nossr50.skills.repair.ArcaneForging.Tier;
import com.gmail.nossr50.skills.repair.Repair;
@@ -12,11 +18,6 @@ import com.gmail.nossr50.skills.repair.RepairManager;
import com.gmail.nossr50.skills.repair.repairables.Repairable;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class RepairCommand extends SkillCommand {
private String repairMasteryBonus;
@@ -48,7 +49,7 @@ public class RepairCommand extends SkillCommand {
protected void dataCalculations(Player player, float skillValue, boolean isLucky) {
// We're using pickaxes here, not the best but it works
Repairable diamondRepairable = mcMMO.getRepairableManager().getRepairable(Material.DIAMOND_PICKAXE);
Repairable goldRepairable = mcMMO.getRepairableManager().getRepairable(Material.GOLDEN_PICKAXE);
Repairable goldRepairable = mcMMO.getRepairableManager().getRepairable(Material.GOLD_PICKAXE);
Repairable ironRepairable = mcMMO.getRepairableManager().getRepairable(Material.IRON_PICKAXE);
Repairable stoneRepairable = mcMMO.getRepairableManager().getRepairable(Material.STONE_PICKAXE);

View File

@@ -45,7 +45,7 @@ public class TamingCommand extends SkillCommand {
protected void permissionsCheck(Player player) {
canBeastLore = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.BEAST_LORE);
canCallWild = Permissions.callOfTheWild(player, EntityType.HORSE) || Permissions.callOfTheWild(player, EntityType.WOLF) || Permissions.callOfTheWild(player, EntityType.OCELOT);
canEnvironmentallyAware = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.ENVIRONMENTALLY_AWARE);
canEnvironmentallyAware = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.ENVIROMENTALLY_AWARE);
canFastFood = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FAST_FOOD);
canGore = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.GORE);
canSharpenedClaws = Permissions.secondaryAbilityEnabled(player, SecondaryAbility.SHARPENED_CLAWS);

View File

@@ -200,7 +200,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
}
if (getSkullSplitterModifier() < 1) {
reason.add("Skills.Axes.SkullSplitter.DamageModifier should be at least 1!");
reason.add("Skills.Axes.SkullSplitter.DamagerModifier should be at least 1!");
}
/* FISHING */
@@ -733,7 +733,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public double getImpactChance() { return config.getDouble("Skills.Axes.ArmorImpact.Chance", 25.0D); }
public double getArmorImpactMaxDurabilityDamage() { return config.getDouble("Skills.Axes.ArmorImpact.MaxPercentageDurabilityDamage", 20.0D); }
public double getSkullSplitterModifier() { return config.getDouble("Skills.Axes.SkullSplitter.DamageModifier", 2.0D); }
public double getSkullSplitterModifier() { return config.getDouble("Skills.Axes.SkullSplitter.DamagerModifier", 2.0D); }
/* EXCAVATION */
//Nothing to configure, everything is already configurable in config.yml
@@ -802,9 +802,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
public int getSmeltingVanillaXPBoostMultiplier(Smelting.Tier tier) { return config.getInt("Skills.Smelting.VanillaXPMultiplier.Rank_" + tier.toNumerical()); }
/* SWORDS */
public double getBleedDamagePlayer() { return config.getDouble("Skills.Swords.Bleed.DamagePlayer", 1.0); }
public double getBleedDamageMobs() { return config.getDouble("Skills.Swords.Bleed.DamageMobs", 2.0); }
public int getBleedMaxTicks() { return config.getInt("Skills.Swords.Bleed.MaxTicks", 3); }
public int getBleedBaseTicks() { return config.getInt("Skills.Swords.Bleed.BaseTicks", 2); }

View File

@@ -6,13 +6,14 @@ import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.gmail.nossr50.metrics.MetricsManager;
public abstract class AutoUpdateConfigLoader extends ConfigLoader {
public AutoUpdateConfigLoader(String relativePath, String fileName) {
super(relativePath, fileName);
@@ -25,7 +26,7 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
@Override
protected void loadFile() {
super.loadFile();
FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(plugin.getResourceAsReader(fileName));
FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(plugin.getResource(fileName));
Set<String> configKeys = config.getKeys(true);
Set<String> internalConfigKeys = internalConfig.getKeys(true);
@@ -45,8 +46,8 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
}
for (String key : oldKeys) {
plugin.debug("Detected potentially unused key: " + key);
//config.set(key, null);
plugin.debug("Removing unused key: " + key);
config.set(key, null);
}
for (String key : newKeys) {
@@ -70,7 +71,7 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
try {
// Read internal
BufferedReader reader = new BufferedReader(new InputStreamReader(plugin.getResource(fileName)));
LinkedHashMap<String, String> comments = new LinkedHashMap<String, String>();
HashMap<String, String> comments = new HashMap<String, String>();
String temp = "";
String line;
@@ -81,15 +82,6 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
else if (line.contains(":")) {
line = line.substring(0, line.indexOf(":") + 1);
if (!temp.isEmpty()) {
if(comments.containsKey(line)) {
int index = 0;
while(comments.containsKey(line + index)) {
index++;
}
line = line + index;
}
comments.put(line, temp);
temp = "";
}
@@ -97,20 +89,9 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
}
// Dump to the new one
HashMap<String, Integer> indexed = new HashMap<String, Integer>();
for (String key : comments.keySet()) {
String actualkey = key.substring(0, key.indexOf(":") + 1);
int index = 0;
if(indexed.containsKey(actualkey)) {
index = indexed.get(actualkey);
}
boolean isAtTop = !output.contains("\n" + actualkey);
index = output.indexOf((isAtTop ? "" : "\n") + actualkey, index);
if (index >= 0) {
output = output.substring(0, index) + "\n" + comments.get(key) + output.substring(isAtTop ? index : index + 1);
indexed.put(actualkey, index + comments.get(key).length() + actualkey.length() + 1);
if (output.contains(key)) {
output = output.substring(0, output.indexOf(key)) + comments.get(key) + output.substring(output.indexOf(key));
}
}
}
@@ -135,5 +116,13 @@ public abstract class AutoUpdateConfigLoader extends ConfigLoader {
e.printStackTrace();
}
}
else {
for (String key : configKeys) {
if (!config.isConfigurationSection(key) && !config.get(key).equals(internalConfig.get(key))) {
MetricsManager.customConfig();
break;
}
}
}
}
}

View File

@@ -1,19 +1,20 @@
package com.gmail.nossr50.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import com.gmail.nossr50.database.SQLDatabaseManager.PoolIdentifier;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.party.PartyFeature;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.StringUtils;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Config extends AutoUpdateConfigLoader {
private static Config instance;
@@ -177,10 +178,6 @@ public class Config extends AutoUpdateConfigLoader {
reason.add("Abilities.Limits.Tree_Feller_Threshold should be greater than 0!");
}
if (getFishingLureModifier() < 0) {
reason.add("Abilities.Fishing.Lure_Modifier should be at least 0!");
}
if (getDetonatorItem() == null) {
reason.add("Skills.Mining.Detonator_Item is invalid!");
}
@@ -268,8 +265,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getLevelUpSoundsEnabled() { return config.getBoolean("General.LevelUp_Sounds", true); }
public boolean getRefreshChunksEnabled() { return config.getBoolean("General.Refresh_Chunks", false); }
public boolean getMobHealthbarEnabled() { return config.getBoolean("Mob_Healthbar.Enabled", true); }
/* Mob Healthbar */
public MobHealthbarType getMobHealthbarDefault() {
try {
@@ -285,7 +280,6 @@ public class Config extends AutoUpdateConfigLoader {
/* Scoreboards */
public boolean getPowerLevelTagsEnabled() { return config.getBoolean("Scoreboard.Power_Level_Tags", false); }
public boolean getAllowKeepBoard() { return config.getBoolean("Scoreboard.Allow_Keep", true); }
public int getTipsAmount() { return config.getInt("Scoreboard.Tips_Amount", 5); }
public boolean getShowStatsAfterLogin() { return config.getBoolean("Scoreboard.Show_Stats_After_Login", false); }
public boolean getScoreboardRainbows() { return config.getBoolean("Scoreboard.Rainbows", false); }
public boolean getShowAbilityNames() { return config.getBoolean("Scoreboard.Ability_Names", true); }
@@ -378,21 +372,16 @@ public class Config extends AutoUpdateConfigLoader {
public Material getChimaeraItem() { return Material.matchMaterial(config.getString("Items.Chimaera_Wing.Item_Name", "Feather")); }
public boolean getChimaeraEnabled() { return config.getBoolean("Items.Chimaera_Wing.Enabled", true); }
public boolean getChimaeraPreventUseUnderground() { return config.getBoolean("Items.Chimaera_Wing.Prevent_Use_Underground", true); }
public boolean getChimaeraUseBedSpawn() { return config.getBoolean("Items.Chimaera_Wing.Use_Bed_Spawn", true); }
public int getChimaeraCooldown() { return config.getInt("Items.Chimaera_Wing.Cooldown", 240); }
public int getChimaeraWarmup() { return config.getInt("Items.Chimaera_Wing.Warmup", 5); }
public int getChimaeraRecentlyHurtCooldown() { return config.getInt("Items.Chimaera_Wing.RecentlyHurt_Cooldown", 60); }
public boolean getChimaeraSoundEnabled() { return config.getBoolean("Items.Chimaera_Wing.Sound_Enabled", true); }
public boolean getFluxPickaxeEnabled() { return config.getBoolean("Items.Flux_Pickaxe.Enabled", true); }
public boolean getFluxPickaxeSoundEnabled() { return config.getBoolean("Items.Flux_Pickaxe.Sound_Enabled", true); }
/* Particles */
public boolean getAbilityActivationEffectEnabled() { return config.getBoolean("Particles.Ability_Activation", true); }
public boolean getAbilityDeactivationEffectEnabled() { return config.getBoolean("Particles.Ability_Deactivation", true); }
public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); }
public boolean getDodgeEffectEnabled() { return config.getBoolean("Particles.Dodge", true); }
public boolean getFluxEffectEnabled() { return config.getBoolean("Particles.Flux", true); }
public boolean getBleedEffectEnabled() { return config.getBoolean("Particles.Bleed", true); }
public boolean getGreaterImpactEffectEnabled() { return config.getBoolean("Particles.Greater_Impact", true); }
public boolean getCallOfTheWildEffectEnabled() { return config.getBoolean("Particles.Call_of_the_Wild", true); }
public boolean getLevelUpEffectsEnabled() { return config.getBoolean("Particles.LevelUp_Enabled", true); }
@@ -456,8 +445,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getDoubleDropsDisabled(SkillType skill) {
String skillName = StringUtils.getCapitalized(skill.toString());
ConfigurationSection section = config.getConfigurationSection("Double_Drops." + skillName);
if (section == null)
return false;
Set<String> keys = section.getKeys(false);
boolean disabled = true;
@@ -484,7 +471,6 @@ public class Config extends AutoUpdateConfigLoader {
public boolean getFishingDropsEnabled() { return config.getBoolean("Skills.Fishing.Drops_Enabled", true); }
public boolean getFishingOverrideTreasures() { return config.getBoolean("Skills.Fishing.Override_Vanilla_Treasures", true); }
public boolean getFishingExtraFish() { return config.getBoolean("Skills.Fishing.Extra_Fish", true); }
public double getFishingLureModifier() { return config.getDouble("Skills.Fishing.Lure_Modifier", 4.0D); }
/* Mining */
public Material getDetonatorItem() { return Material.matchMaterial(config.getString("Skills.Mining.Detonator_Name", "FLINT_AND_STEEL")); }
@@ -506,7 +492,6 @@ public class Config extends AutoUpdateConfigLoader {
/* Unarmed */
public boolean getUnarmedBlockCrackerSmoothbrickToCracked() { return config.getBoolean("Skills.Unarmed.Block_Cracker.SmoothBrick_To_CrackedBrick", true); }
public boolean getUnarmedItemPickupDisabled() { return config.getBoolean("Skills.Unarmed.Item_Pickup_Disabled_Full_Inventory", true); }
public boolean getUnarmedItemsAsUnarmed() { return config.getBoolean("Skills.Unarmed.Items_As_Unarmed", false); }
/* Taming */
public Material getTamingCOTWMaterial(EntityType type) { return Material.matchMaterial(config.getString("Skills.Taming.Call_Of_The_Wild." + StringUtils.getPrettyEntityTypeString(type) + ".Item_Material")); }
@@ -517,7 +502,7 @@ public class Config extends AutoUpdateConfigLoader {
public double getTamingCOTWRange() { return config.getDouble("Skills.Taming.Call_Of_The_Wild.Range", 40.0D); }
/* Woodcutting */
public boolean getWoodcuttingDoubleDropsEnabled(BlockData material) { return config.getBoolean("Double_Drops.Woodcutting." + StringUtils.getFriendlyConfigBlockDataString(material)); }
public boolean getWoodcuttingDoubleDropsEnabled(TreeSpecies species) { return config.getBoolean("Double_Drops.Woodcutting." + StringUtils.getPrettyTreeSpeciesString(species).replace(" ", "_")); }
public boolean getTreeFellerSoundsEnabled() { return config.getBoolean("Skills.Woodcutting.Tree_Feller_Sounds", true); }
/* AFK Leveling */
@@ -536,11 +521,7 @@ public class Config extends AutoUpdateConfigLoader {
return (cap <= 0) ? Integer.MAX_VALUE : cap;
}
public boolean getTruncateSkills() { return config.getBoolean("General.TruncateSkills", false); }
/* PVP & PVE Settings */
public boolean getPVPEnabled(SkillType skill) { return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVP", true); }
public boolean getPVEEnabled(SkillType skill) { return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVE", true); }
public float getMasterVolume() { return (float) config.getDouble("Sounds.MasterVolume", 1.0); }
}

View File

@@ -1,7 +1,5 @@
package com.gmail.nossr50.config;
import java.io.InputStreamReader;
import org.bukkit.configuration.file.YamlConfiguration;
import com.gmail.nossr50.mcMMO;
@@ -31,9 +29,8 @@ public class HiddenConfig {
}
public void load() {
InputStreamReader reader = mcMMO.p.getResourceAsReader(fileName);
if (reader != null) {
config = YamlConfiguration.loadConfiguration(reader);
if (mcMMO.p.getResource(fileName) != null) {
config = YamlConfiguration.loadConfiguration(mcMMO.p.getResource(fileName));
chunkletsEnabled = config.getBoolean("Options.Chunklets", true);
conversionRate = config.getInt("Options.ConversionRate", 1);
useEnchantmentBuffs = config.getBoolean("Options.EnchantmentBuffs", true);

View File

@@ -1,17 +1,21 @@
package com.gmail.nossr50.config.experience;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.GrassSpecies;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.entity.EntityType;
import org.bukkit.material.LongGrass;
import org.bukkit.material.MaterialData;
import com.gmail.nossr50.config.AutoUpdateConfigLoader;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage;
import com.gmail.nossr50.util.StringUtils;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.EntityType;
import java.util.ArrayList;
import java.util.List;
public class ExperienceConfig extends AutoUpdateConfigLoader {
private static ExperienceConfig instance;
@@ -68,11 +72,6 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
reason.add("Experience_Formula.Mobspawners.Multiplier should be at least 0!");
}
/* Bred Mob modifier */
if (getBredMobXpMultiplier() < 0) {
reason.add("Experience_Formula.Breeding.Multiplier should be at least 0!");
}
/* Conversion */
if (getExpModifier() <= 0) {
reason.add("Conversion.Exp_Modifier should be greater than 0!");
@@ -89,16 +88,15 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
}
/* Archery */
if (getArcheryDistanceMultiplier() < 0) {
reason.add("Experience.Archery.Distance_Multiplier should be at least 0!");
}
/* Combat XP Multipliers */
if (getAnimalsXP() < 0) {
reason.add("Experience.Combat.Multiplier.Animals should be at least 0!");
}
if (getWitherSkeletonXP() < 0) {
reason.add("Experience.Combat.Multiplier.Wither_Skeleton should be at least 0!");
}
if (getDodgeXPModifier() < 0) {
reason.add("Skills.Acrobatics.Dodge_XP_Modifier should be at least 0!");
}
@@ -124,14 +122,31 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
/* Taming */
if (getTamingXP(EntityType.WOLF) <= 0) {
if (getTamingXPWolf() <= 0) {
reason.add("Experience.Taming.Animal_Taming.Wolf should be greater than 0!");
}
if (getTamingXP(EntityType.OCELOT) <= 0) {
if (getTamingXPOcelot() <= 0) {
reason.add("Experience.Taming.Animal_Taming.Ocelot should be greater than 0!");
}
/* Woodcutting */
for (TreeSpecies species : TreeSpecies.values()) {
String key = "Experience.Woodcutting." + StringUtils.getPrettyTreeSpeciesString(species).replace(" ", "_");
if (config.getInt(key) <= 0) {
reason.add(key + " should be greater than 0!");
}
}
if (getWoodcuttingXPHugeBrownMushroom() <= 0) {
reason.add("Experience.Woodcutting.Huge_Mushroom_Brown should be greater than 0!");
}
if (getWoodcuttingXPHugeRedMushroom() <= 0) {
reason.add("Experience.Woodcutting.Huge_Mushroom_Red should be greater than 0!");
}
return noErrorsInConfig(reason);
}
@@ -157,7 +172,6 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
/* Spawned Mob modifier */
public double getSpawnedMobXpMultiplier() { return config.getDouble("Experience_Formula.Mobspawners.Multiplier", 0.0); }
public double getBredMobXpMultiplier() { return config.getDouble("Experience_Formula.Breeding.Multiplier", 1.0); }
/* Skill modifiers */
public double getFormulaSkillModifier(SkillType skill) { return config.getDouble("Experience_Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
@@ -182,67 +196,11 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
/* Combat XP Multipliers */
public double getCombatXP(EntityType entity) { return config.getDouble("Experience.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_")); }
public double getAnimalsXP(EntityType entity) { return config.getDouble("Experience.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_"), getAnimalsXP()); }
public double getAnimalsXP() { return config.getDouble("Experience.Combat.Multiplier.Animals", 1.0); }
public boolean hasCombatXP(EntityType entity) {return config.contains("Experience.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_")); }
public double getWitherSkeletonXP() { return config.getDouble("Experience.Combat.Multiplier.Wither_Skeleton", 4.0); }
/* Materials */
public int getXp(SkillType skill, Material data)
{
String baseString = "Experience." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigMaterialString(data);
if (config.contains(explicitString))
return config.getInt(explicitString);
String friendlyString = baseString + StringUtils.getFriendlyConfigMaterialString(data);
if (config.contains(friendlyString))
return config.getInt(friendlyString);
String wildcardString = baseString + StringUtils.getWildcardConfigMaterialString(data);
if (config.contains(wildcardString))
return config.getInt(wildcardString);
return 0;
}
/* Materials */
public int getXp(SkillType skill, BlockData data)
{
String baseString = "Experience." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigBlockDataString(data);
if (config.contains(explicitString))
return config.getInt(explicitString);
String friendlyString = baseString + StringUtils.getFriendlyConfigBlockDataString(data);
if (config.contains(friendlyString))
return config.getInt(friendlyString);
String wildcardString = baseString + StringUtils.getWildcardConfigBlockDataString(data);
if (config.contains(wildcardString))
return config.getInt(wildcardString);
return 0;
}
public boolean isSkillBlock(SkillType skill, Material data)
{
String baseString = "Experience." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigMaterialString(data);
if (config.contains(explicitString))
return true;
String friendlyString = baseString + StringUtils.getFriendlyConfigMaterialString(data);
if (config.contains(friendlyString))
return true;
String wildcardString = baseString + StringUtils.getWildcardConfigMaterialString(data);
return config.contains(wildcardString);
}
public boolean isSkillBlock(SkillType skill, BlockData data)
{
String baseString = "Experience." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigBlockDataString(data);
if (config.contains(explicitString))
return true;
String friendlyString = baseString + StringUtils.getFriendlyConfigBlockDataString(data);
if (config.contains(friendlyString))
return true;
String wildcardString = baseString + StringUtils.getWildcardConfigBlockDataString(data);
return config.contains(wildcardString);
}
public int getXp(SkillType skill, Material material) { return config.getInt("Experience." + StringUtils.getCapitalized(skill.toString()) + "." + StringUtils.getPrettyItemString(material).replace(" ", "_")); }
/* Acrobatics */
public int getDodgeXPModifier() { return config.getInt("Experience.Acrobatics.Dodge", 120); }
@@ -254,18 +212,160 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
/* Alchemy */
public double getPotionXP(PotionStage stage) { return config.getDouble("Experience.Alchemy.Potion_Stage_" + stage.toNumerical(), 10D); }
/* Archery */
public double getArcheryDistanceMultiplier() { return config.getDouble("Experience.Archery.Distance_Multiplier", 0.025); }
/* Excavation */
public int getDirtAndSandXp(MaterialData data) {
Material type = data.getItemType();
if (type == Material.DIRT) {
switch (data.getData()) {
case 0x0:
return config.getInt("Experience.Excavation.Dirt", 40);
case 0x1:
return config.getInt("Experience.Excavation.Coarse_Dirt", 40);
case 0x2:
return config.getInt("Experience.Excavation.Podzol", 40);
default:
return 0;
}
}
else if (type == Material.SAND) {
switch (data.getData()) {
case 0x0:
return config.getInt("Experience.Excavation.Sand", 40);
case 0x1:
return config.getInt("Experience.Excavation.Red_Sand", 40);
default:
return 0;
}
}
return 0;
}
/* Fishing */
public int getFishXp(MaterialData data) {
switch (data.getData()) {
case 0x0:
return config.getInt("Experience.Fishing.Raw_Fish", 800);
case 0x1:
return config.getInt("Experience.Fishing.Raw_Salmon", 800);
case 0x2:
return config.getInt("Experience.Fishing.Clownfish", 800);
case 0x3:
return config.getInt("Experience.Fishing.Pufferfish", 800);
default:
return 0;
}
}
public int getFishingShakeXP() { return config.getInt("Experience.Fishing.Shake", 50); }
/* Herbalism */
public int getFlowerAndGrassXp(MaterialData data) {
Material type = data.getItemType();
if (type == Material.RED_ROSE) {
switch (data.getData()) {
case 0x0:
return config.getInt("Experience.Herbalism.Poppy", 100);
case 0x1:
return config.getInt("Experience.Herbalism.Blue_Orchid", 150);
case 0x2:
return config.getInt("Experience.Herbalism.Allium", 300);
case 0x3:
return config.getInt("Experience.Herbalism.Azure_Bluet", 150);
case 0x4:
return config.getInt("Experience.Herbalism.Red_Tulip", 150);
case 0x5:
return config.getInt("Experience.Herbalism.Orange_Tulip", 150);
case 0x6:
return config.getInt("Experience.Herbalism.White_Tulip", 150);
case 0x7:
return config.getInt("Experience.Herbalism.Pink_Tulip", 150);
case 0x8:
return config.getInt("Experience.Herbalism.Oxeye_Daisy", 150);
default:
return 0;
}
}
else if (type == Material.LONG_GRASS) {
GrassSpecies species = ((LongGrass) data).getSpecies();
if (species == null) {
return 0;
}
switch (species) {
case DEAD:
return config.getInt("Experience.Herbalism.Dead_Bush", 30);
case FERN_LIKE:
return config.getInt("Experience.Herbalism.Small_Fern", 10);
case NORMAL:
return config.getInt("Experience.Herbalism.Small_Grass", 10);
default:
return 0;
}
}
else if (type == Material.DOUBLE_PLANT) {
switch (data.getData()) {
case 0x0:
return config.getInt("Experience.Herbalism.Sunflower", 50);
case 0x1:
return config.getInt("Experience.Herbalism.Lilac", 50);
case 0x2:
return config.getInt("Experience.Herbalism.Tall_Grass", 50);
case 0x3:
return config.getInt("Experience.Herbalism.Tall_Fern", 50);
case 0x4:
return config.getInt("Experience.Herbalism.Rose_Bush", 50);
case 0x5:
return config.getInt("Experience.Herbalism.Peony", 50);
default:
return 0;
}
}
return 0;
}
/* Repair */
public double getRepairXPBase() { return config.getDouble("Experience.Repair.Base", 1000.0); }
public double getRepairXP(MaterialType repairMaterialType) { return config.getDouble("Experience.Repair." + StringUtils.getCapitalized(repairMaterialType.toString())); }
/* Taming */
public int getTamingXP(EntityType type)
{
return config.getInt("Experience.Taming.Animal_Taming." + StringUtils.getPrettyEntityTypeString(type));
}
public int getTamingXPHorse() { return config.getInt("Experience.Taming.Animal_Taming.Horse", 1000); }
public int getTamingXPWolf() { return config.getInt("Experience.Taming.Animal_Taming.Wolf", 250); }
public int getTamingXPOcelot() { return config.getInt("Experience.Taming.Animal_Taming.Ocelot", 500); }
/* Woodcutting */
public int getWoodcuttingTreeXP(TreeSpecies species) { return config.getInt("Experience.Woodcutting." + StringUtils.getPrettyTreeSpeciesString(species).replace(" ", "_")); }
public int getWoodcuttingXPHugeBrownMushroom() { return config.getInt("Experience.Woodcutting.Huge_Mushroom_Brown", 70); }
public int getWoodcuttingXPHugeRedMushroom() { return config.getInt("Experience.Woodcutting.Huge_Mushroom_Red", 70); }
}

View File

@@ -1,27 +1,29 @@
package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.material.MaterialData;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
public class CustomBlockConfig extends ConfigLoader {
private boolean needsUpdate = false;
public List<Material> customExcavationBlocks = new ArrayList<>();
public List<Material> customHerbalismBlocks = new ArrayList<>();
public List<Material> customMiningBlocks = new ArrayList<>();
public List<Material> customOres = new ArrayList<>();
public List<Material> customLogs = new ArrayList<>();
public List<Material> customLeaves = new ArrayList<>();
public List<Material> customAbilityBlocks = new ArrayList<>();
public List<MaterialData> customExcavationBlocks = new ArrayList<MaterialData>();
public List<MaterialData> customHerbalismBlocks = new ArrayList<MaterialData>();
public List<MaterialData> customMiningBlocks = new ArrayList<MaterialData>();
public List<MaterialData> customOres = new ArrayList<MaterialData>();
public List<MaterialData> customLogs = new ArrayList<MaterialData>();
public List<MaterialData> customLeaves = new ArrayList<MaterialData>();
public List<MaterialData> customAbilityBlocks = new ArrayList<MaterialData>();
public HashMap<Material, CustomBlock> customBlockMap = new HashMap<>();
public HashMap<MaterialData, CustomBlock> customBlockMap = new HashMap<MaterialData, CustomBlock>();
protected CustomBlockConfig(String fileName) {
super("mods", fileName);
@@ -42,7 +44,7 @@ public class CustomBlockConfig extends ConfigLoader {
}
}
private void loadBlocks(String skillType, List<Material> blockList) {
private void loadBlocks(String skillType, List<MaterialData> blockList) {
if (needsUpdate) {
return;
}
@@ -56,7 +58,7 @@ public class CustomBlockConfig extends ConfigLoader {
Set<String> skillConfigSet = skillSection.getKeys(false);
for (String blockName : skillConfigSet) {
if (config.contains(skillType + "." + blockName + ".Drop_Item")) {
if (config.contains(skillType + "." + blockName + "." + ".Drop_Item")) {
needsUpdate = true;
return;
}
@@ -70,8 +72,11 @@ public class CustomBlockConfig extends ConfigLoader {
continue;
}
byte blockData = (blockInfo.length == 2) ? Byte.valueOf(blockInfo[1]) : 0;
MaterialData blockMaterialData = new MaterialData(blockMaterial, blockData);
if (blockList != null) {
blockList.add(blockMaterial);
blockList.add(blockMaterialData);
}
if (skillType.equals("Ability_Blocks")) {
@@ -82,20 +87,20 @@ public class CustomBlockConfig extends ConfigLoader {
int smeltingXp = 0;
if (skillType.equals("Mining") && config.getBoolean(skillType + "." + blockName + ".Is_Ore")) {
customOres.add(blockMaterial);
customOres.add(blockMaterialData);
smeltingXp = config.getInt(skillType + "." + blockName + ".Smelting_XP_Gain", xp / 10);
}
else if (skillType.equals("Woodcutting")) {
if (config.getBoolean(skillType + "." + blockName + ".Is_Log")) {
customLogs.add(blockMaterial);
customLogs.add(blockMaterialData);
}
else {
customLeaves.add(blockMaterial);
customLeaves.add(blockMaterialData);
xp = 0; // Leaves don't grant XP
}
}
customBlockMap.put(blockMaterial, new CustomBlock(xp, config.getBoolean(skillType + "." + blockName + ".Double_Drops_Enabled"), smeltingXp));
customBlockMap.put(blockMaterialData, new CustomBlock(xp, config.getBoolean(skillType + "." + blockName + ".Double_Drops_Enabled"), smeltingXp));
}
}
}

View File

@@ -3,7 +3,7 @@ package com.gmail.nossr50.config.mods;
import java.util.HashMap;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomEntity;
@@ -54,7 +54,7 @@ public class CustomEntityConfig extends ConfigLoader {
canBeSummoned = false;
}
CustomEntity entity = new CustomEntity(xpMultiplier, canBeTamed, tamingXp, canBeSummoned, (canBeSummoned ? new ItemStack(callOfTheWildMaterial) : null), callOfTheWildAmount);
CustomEntity entity = new CustomEntity(xpMultiplier, canBeTamed, tamingXp, canBeSummoned, (canBeSummoned ? new MaterialData(callOfTheWildMaterial, callOfTheWildData).toItemStack(1) : null), callOfTheWildAmount);
customEntityTypeMap.put(entityTypeName, entity);
customEntityClassMap.put(clazz == null ? null : clazz.getName(), entity);

View File

@@ -5,16 +5,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.ConfigLoader;
@@ -32,7 +27,7 @@ public class PotionConfig extends ConfigLoader {
private List<ItemStack> concoctionsIngredientsTierSeven = new ArrayList<ItemStack>();
private List<ItemStack> concoctionsIngredientsTierEight = new ArrayList<ItemStack>();
private Map<String, AlchemyPotion> potionMap = new HashMap<String, AlchemyPotion>();
private Map<Short, AlchemyPotion> potionMap = new HashMap<Short, AlchemyPotion>();
private PotionConfig() {
super("potions.yml");
@@ -94,11 +89,11 @@ public class PotionConfig extends ConfigLoader {
int pass = 0;
int fail = 0;
for (String potionName : potionSection.getKeys(false)) {
AlchemyPotion potion = loadPotion(potionSection.getConfigurationSection(potionName));
for (String dataValue : potionSection.getKeys(false)) {
AlchemyPotion potion = loadPotion(potionSection.getConfigurationSection(dataValue));
if (potion != null) {
potionMap.put(potionName, potion);
potionMap.put(potion.getDataValue(), potion);
pass++;
}
else {
@@ -119,33 +114,14 @@ public class PotionConfig extends ConfigLoader {
*/
private AlchemyPotion loadPotion(ConfigurationSection potion_section) {
try {
short dataValue = Short.parseShort(potion_section.getName());
String name = potion_section.getString("Name");
if (name != null) {
name = ChatColor.translateAlternateColorCodes('&', name);
}
PotionData data;
if (!potion_section.contains("PotionData")) { // Backwards config compatability
short dataValue = Short.parseShort(potion_section.getName());
Potion potion = Potion.fromDamage(dataValue);
data = new PotionData(potion.getType(), potion.hasExtendedDuration(), potion.getLevel() == 2);
} else {
ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData");
data = new PotionData(PotionType.valueOf(potionData.getString("PotionType", "WATER")), potionData.getBoolean("Extended", false), potionData.getBoolean("Upgraded", false));
}
Material material = Material.POTION;
String mat = potion_section.getString("Material", null);
if (mat != null) {
material = Material.valueOf(mat);
}
List<String> lore = new ArrayList<String>();
if (potion_section.contains("Lore")) {
for (String line : potion_section.getStringList("Lore")) {
lore.add(ChatColor.translateAlternateColorCodes('&', line));
lore.add(line);
}
}
@@ -166,21 +142,13 @@ public class PotionConfig extends ConfigLoader {
}
}
}
Color color = null;
if (potion_section.contains("Color")) {
color = Color.fromRGB(potion_section.getInt("Color"));
}
else {
color = this.generateColor(effects);
}
Map<ItemStack, String> children = new HashMap<ItemStack, String>();
Map<ItemStack, Short> children = new HashMap<ItemStack, Short>();
if (potion_section.contains("Children")) {
for (String child : potion_section.getConfigurationSection("Children").getKeys(false)) {
ItemStack ingredient = loadIngredient(child);
if (ingredient != null) {
children.put(ingredient, potion_section.getConfigurationSection("Children").getString(child));
children.put(ingredient, Short.parseShort(potion_section.getConfigurationSection("Children").getString(child)));
}
else {
mcMMO.p.getLogger().warning("Failed to parse child for potion " + name + ": " + child);
@@ -188,7 +156,7 @@ public class PotionConfig extends ConfigLoader {
}
}
return new AlchemyPotion(material, data, name, lore, effects, color, children);
return new AlchemyPotion(dataValue, name, lore, effects, children);
}
catch (Exception e) {
mcMMO.p.getLogger().warning("Failed to load Alchemy potion: " + potion_section.getName());
@@ -210,10 +178,13 @@ public class PotionConfig extends ConfigLoader {
return null;
}
Material material = Material.getMaterial(ingredient);
String[] parts = ingredient.split(":");
Material material = parts.length > 0 ? Material.getMaterial(parts[0]) : null;
short data = parts.length > 1 ? Short.parseShort(parts[1]) : 0;
if (material != null) {
return new ItemStack(material, 1);
return new ItemStack(material, 1, data);
}
return null;
@@ -242,51 +213,10 @@ public class PotionConfig extends ConfigLoader {
}
public boolean isValidPotion(ItemStack item) {
return getPotion(item) != null;
return potionMap.containsKey(item.getDurability());
}
public AlchemyPotion getPotion(String name) {
return potionMap.get(name);
public AlchemyPotion getPotion(short durability) {
return potionMap.get(durability);
}
public AlchemyPotion getPotion(ItemStack item) {
for (AlchemyPotion potion : potionMap.values()) {
if (potion.isSimilar(item)) {
return potion;
}
}
return null;
}
public Color generateColor(List<PotionEffect> effects) {
if (effects != null && !effects.isEmpty()) {
List<Color> colors = new ArrayList<Color>();
for (PotionEffect effect : effects) {
if (effect.getType().getColor() != null) {
colors.add(effect.getType().getColor());
}
}
if (!colors.isEmpty()) {
if (colors.size() > 1) {
return calculateAverageColor(colors);
}
return colors.get(0);
}
}
return null;
}
public Color calculateAverageColor(List<Color> colors) {
int red = 0;
int green = 0;
int blue = 0;
for (Color color : colors) {
red += color.getRed();
green += color.getGreen();
blue += color.getBlue();
}
Color color = Color.fromRGB(red/colors.size(), green/colors.size(), blue/colors.size());
return color;
}
}

View File

@@ -1,36 +1,70 @@
package com.gmail.nossr50.config.treasure;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.treasure.*;
import com.gmail.nossr50.util.EnchantmentUtils;
import com.gmail.nossr50.util.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.TreeSpecies;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TreasureConfig extends ConfigLoader {
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Dye;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionType;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.datatypes.treasure.EnchantmentTreasure;
import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure;
import com.gmail.nossr50.datatypes.treasure.FishingTreasure;
import com.gmail.nossr50.datatypes.treasure.HylianTreasure;
import com.gmail.nossr50.datatypes.treasure.Rarity;
import com.gmail.nossr50.datatypes.treasure.ShakeTreasure;
import com.gmail.nossr50.util.EnchantmentUtils;
public class TreasureConfig extends ConfigLoader {
private static TreasureConfig instance;
public HashMap<String, List<ExcavationTreasure>> excavationMap = new HashMap<String, List<ExcavationTreasure>>();
public List<ExcavationTreasure> excavationFromDirt = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromGrass = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromSand = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromGravel = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromClay = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromMycel = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromSoulSand = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromSnow = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromRedSand = new ArrayList<ExcavationTreasure>();
public List<ExcavationTreasure> excavationFromPodzol = new ArrayList<ExcavationTreasure>();
public HashMap<EntityType, List<ShakeTreasure>> shakeMap = new HashMap<EntityType, List<ShakeTreasure>>();
public HashMap<String, List<HylianTreasure>> hylianMap = new HashMap<String, List<HylianTreasure>>();
public List<HylianTreasure> hylianFromBushes = new ArrayList<HylianTreasure>();
public List<HylianTreasure> hylianFromFlowers = new ArrayList<HylianTreasure>();
public List<HylianTreasure> hylianFromPots = new ArrayList<HylianTreasure>();
public HashMap<Rarity, List<FishingTreasure>> fishingRewards = new HashMap<Rarity, List<FishingTreasure>>();
public List<ShakeTreasure> shakeFromBlaze = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCaveSpider = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSpider = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromChicken = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCow = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromCreeper = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromEnderman = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromGhast = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromHorse = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromIronGolem = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromMagmaCube = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromMushroomCow = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromPig = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromPigZombie = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSheep = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSkeleton = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSlime = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSnowman = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromSquid = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromWitch = new ArrayList<ShakeTreasure>();
public List<ShakeTreasure> shakeFromZombie = new ArrayList<ShakeTreasure>();
public HashMap<Rarity, List<FishingTreasure>> fishingRewards = new HashMap<Rarity, List<FishingTreasure>>();
public HashMap<Rarity, List<EnchantmentTreasure>> fishingEnchantments = new HashMap<Rarity, List<EnchantmentTreasure>>();
private TreasureConfig() {
@@ -51,6 +85,7 @@ public class TreasureConfig extends ConfigLoader {
protected boolean validateKeys() {
// Validate all the settings!
List<String> reason = new ArrayList<String>();
for (String tier : config.getConfigurationSection("Enchantment_Drop_Rates").getKeys(false)) {
double totalEnchantDropRate = 0;
double totalItemDropRate = 0;
@@ -90,19 +125,19 @@ public class TreasureConfig extends ConfigLoader {
return;
}
loadTreasures("Fishing");
loadTreasures("Excavation");
loadTreasures("Hylian_Luck");
loadTreaures("Fishing");
loadTreaures("Excavation");
loadTreaures("Hylian_Luck");
loadEnchantments();
for (EntityType entity : EntityType.values()) {
if (entity.isAlive()) {
loadTreasures("Shake." + entity.toString());
loadTreaures("Shake." + entity.toString());
}
}
}
private void loadTreasures(String type) {
private void loadTreaures(String type) {
boolean isFishing = type.equals("Fishing");
boolean isShake = type.contains("Shake");
boolean isExcavation = type.equals("Excavation");
@@ -133,18 +168,18 @@ public class TreasureConfig extends ConfigLoader {
*/
Material material;
if (materialName.contains("INVENTORY")) {
// Use magic material BEDROCK to know that we're grabbing something from the inventory and not a normal treasure
if (!shakeMap.containsKey(EntityType.PLAYER))
shakeMap.put(EntityType.PLAYER, new ArrayList<ShakeTreasure>());
shakeMap.get(EntityType.PLAYER).add(new ShakeTreasure(new ItemStack(Material.BEDROCK, 1, (byte) 0), 1, getInventoryStealDropChance(), getInventoryStealDropLevel()));
continue;
} else {
if (materialName.contains("POTION")) {
material = Material.POTION;
}
else if (materialName.contains("INK_SACK")) {
material = Material.INK_SACK;
}
else {
material = Material.matchMaterial(materialName);
}
int amount = config.getInt(type + "." + treasureName + ".Amount");
short data = (treasureInfo.length == 2) ? Short.parseShort(treasureInfo[1]) : (short) config.getInt(type + "." + treasureName + ".Data");
short data = (treasureInfo.length == 2) ? Byte.valueOf(treasureInfo[1]) : (short) config.getInt(type + "." + treasureName + ".Data");
if (material == null) {
reason.add("Invalid material: " + materialName);
@@ -197,52 +232,40 @@ public class TreasureConfig extends ConfigLoader {
ItemStack item = null;
if (materialName.contains("POTION")) {
Material mat = Material.matchMaterial(materialName);
if (mat == null) {
reason.add("Potion format for Treasures.yml has changed");
} else {
item = new ItemStack(mat, amount, data);
PotionMeta itemMeta = (PotionMeta) item.getItemMeta();
String potionType = materialName.substring(7);
PotionType potionType = null;
try {
potionType = PotionType.valueOf(config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"));
} catch (IllegalArgumentException ex) {
reason.add("Invalid Potion_Type: " + config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"));
}
boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false);
boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false);
itemMeta.setBasePotionData(new PotionData(potionType, extended, upgraded));
if (config.contains(type + "." + treasureName + ".Custom_Name")) {
itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name")));
}
if (config.contains(type + "." + treasureName + ".Lore")) {
List<String> lore = new ArrayList<String>();
for (String s : config.getStringList(type + "." + treasureName + ".Lore")) {
lore.add(ChatColor.translateAlternateColorCodes('&', s));
}
itemMeta.setLore(lore);
}
item.setItemMeta(itemMeta);
try {
item = new Potion(PotionType.valueOf(potionType.toUpperCase().trim())).toItemStack(amount);
}
} else if (material != null) {
catch (IllegalArgumentException ex) {
reason.add("Invalid Potion_Type: " + potionType);
}
}
else if (materialName.contains("INK_SACK")) {
String color = materialName.substring(9);
try {
Dye dye = new Dye();
dye.setColor(DyeColor.valueOf(color.toUpperCase().trim()));
item = dye.toItemStack(amount);
}
catch (IllegalArgumentException ex) {
reason.add("Invalid Dye_Color: " + color);
}
}
else if (material != null) {
item = new ItemStack(material, amount, data);
if (config.contains(type + "." + treasureName + ".Custom_Name")) {
ItemMeta itemMeta = item.getItemMeta();
itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name")));
itemMeta.setDisplayName(config.getString(type + "." + treasureName + ".Custom_Name"));
item.setItemMeta(itemMeta);
}
if (config.contains(type + "." + treasureName + ".Lore")) {
ItemMeta itemMeta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
for (String s : config.getStringList(type + "." + treasureName + ".Lore")) {
lore.add(ChatColor.translateAlternateColorCodes('&', s));
}
itemMeta.setLore(lore);
itemMeta.setLore(config.getStringList(type + "." + treasureName + ".Lore"));
item.setItemMeta(itemMeta);
}
}
@@ -250,66 +273,138 @@ public class TreasureConfig extends ConfigLoader {
if (noErrorsInConfig(reason)) {
if (isFishing) {
fishingRewards.get(rarity).add(new FishingTreasure(item, xp));
} else if (isShake) {
}
else if (isShake) {
ShakeTreasure shakeTreasure = new ShakeTreasure(item, xp, dropChance, dropLevel);
EntityType entityType = EntityType.valueOf(type.substring(6));
if (!shakeMap.containsKey(entityType))
shakeMap.put(entityType, new ArrayList<ShakeTreasure>());
shakeMap.get(entityType).add(shakeTreasure);
} else if (isExcavation) {
if (type.equals("Shake.BLAZE")) {
shakeFromBlaze.add(shakeTreasure);
}
else if (type.equals("Shake.CAVE_SPIDER")) {
shakeFromCaveSpider.add(shakeTreasure);
}
else if (type.equals("Shake.CHICKEN")) {
shakeFromChicken.add(shakeTreasure);
}
else if (type.equals("Shake.COW")) {
shakeFromCow.add(shakeTreasure);
}
else if (type.equals("Shake.CREEPER")) {
shakeFromCreeper.add(shakeTreasure);
}
else if (type.equals("Shake.ENDERMAN")) {
shakeFromEnderman.add(shakeTreasure);
}
else if (type.equals("Shake.GHAST")) {
shakeFromGhast.add(shakeTreasure);
}
else if (type.equals("Shake.HORSE")) {
shakeFromHorse.add(shakeTreasure);
}
else if (type.equals("Shake.IRON_GOLEM")) {
shakeFromIronGolem.add(shakeTreasure);
}
else if (type.equals("Shake.MAGMA_CUBE")) {
shakeFromMagmaCube.add(shakeTreasure);
}
else if (type.equals("Shake.MUSHROOM_COW")) {
shakeFromMushroomCow.add(shakeTreasure);
}
else if (type.equals("Shake.PIG")) {
shakeFromPig.add(shakeTreasure);
}
else if (type.equals("Shake.PIG_ZOMBIE")) {
shakeFromPigZombie.add(shakeTreasure);
}
else if (type.equals("Shake.SHEEP")) {
shakeFromSheep.add(shakeTreasure);
}
else if (type.equals("Shake.SKELETON")) {
shakeFromSkeleton.add(shakeTreasure);
}
else if (type.equals("Shake.SLIME")) {
shakeFromSlime.add(shakeTreasure);
}
else if (type.equals("Shake.SPIDER")) {
shakeFromSpider.add(shakeTreasure);
}
else if (type.equals("Shake.SNOWMAN")) {
shakeFromSnowman.add(shakeTreasure);
}
else if (type.equals("Shake.SQUID")) {
shakeFromSquid.add(shakeTreasure);
}
else if (type.equals("Shake.WITCH")) {
shakeFromWitch.add(shakeTreasure);
}
else if (type.equals("Shake.ZOMBIE")) {
shakeFromZombie.add(shakeTreasure);
}
}
else if (isExcavation) {
ExcavationTreasure excavationTreasure = new ExcavationTreasure(item, xp, dropChance, dropLevel);
List<String> dropList = config.getStringList(type + "." + treasureName + ".Drops_From");
for (String blockType : dropList) {
if (!excavationMap.containsKey(blockType))
excavationMap.put(blockType, new ArrayList<ExcavationTreasure>());
excavationMap.get(blockType).add(excavationTreasure);
if (dropList.contains("Dirt")) {
excavationFromDirt.add(excavationTreasure);
}
} else if (isHylian) {
if (dropList.contains("Grass")) {
excavationFromGrass.add(excavationTreasure);
}
if (dropList.contains("Sand")) {
excavationFromSand.add(excavationTreasure);
}
if (dropList.contains("Gravel")) {
excavationFromGravel.add(excavationTreasure);
}
if (dropList.contains("Clay")) {
excavationFromClay.add(excavationTreasure);
}
if (dropList.contains("Mycelium")) {
excavationFromMycel.add(excavationTreasure);
}
if (dropList.contains("Soul_Sand")) {
excavationFromSoulSand.add(excavationTreasure);
}
if (dropList.contains("Snow")) {
excavationFromSnow.add(excavationTreasure);
}
if (dropList.contains("Red_Sand")) {
excavationFromRedSand.add(excavationTreasure);
}
if (dropList.contains("Podzol")) {
excavationFromPodzol.add(excavationTreasure);
}
}
else if (isHylian) {
HylianTreasure hylianTreasure = new HylianTreasure(item, xp, dropChance, dropLevel);
List<String> dropList = config.getStringList(type + "." + treasureName + ".Drops_From");
for (String dropper : dropList) {
if (dropper.equals("Bushes")) {
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.FERN), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.TALL_GRASS), hylianTreasure);
for (Material species : Tag.SAPLINGS.getValues())
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(species), hylianTreasure);
if (dropList.contains("Bushes")) {
hylianFromBushes.add(hylianTreasure);
}
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.DEAD_BUSH), hylianTreasure);
continue;
}
if (dropper.equals("Flowers")) {
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.POPPY), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.DANDELION), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.BLUE_ORCHID), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.ALLIUM), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.AZURE_BLUET), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.ORANGE_TULIP), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.PINK_TULIP), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.RED_TULIP), hylianTreasure);
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(Material.WHITE_TULIP), hylianTreasure);
continue;
}
if (dropper.equals("Pots")) {
for (Material species : Tag.FLOWER_POTS.getValues())
AddHylianTreasure(StringUtils.getFriendlyConfigMaterialString(species), hylianTreasure);
continue;
}
AddHylianTreasure(dropper, hylianTreasure);
if (dropList.contains("Flowers")) {
hylianFromFlowers.add(hylianTreasure);
}
if (dropList.contains("Pots")) {
hylianFromPots.add(hylianTreasure);
}
}
}
}
}
private void AddHylianTreasure(String dropper, HylianTreasure treasure) {
if (!hylianMap.containsKey(dropper))
hylianMap.put(dropper, new ArrayList<HylianTreasure>());
hylianMap.get(dropper).add(treasure);
}
private void loadEnchantments() {
for (Rarity rarity : Rarity.values()) {
if (rarity == Rarity.TRAP || rarity == Rarity.RECORD) {
@@ -340,27 +435,6 @@ public class TreasureConfig extends ConfigLoader {
}
}
public boolean getInventoryStealEnabled() {
return config.contains("Shake.PLAYER.INVENTORY");
}
public boolean getInventoryStealStacks() {
return config.getBoolean("Shake.PLAYER.INVENTORY.Whole_Stacks");
}
public double getInventoryStealDropChance() {
return config.getDouble("Shake.PLAYER.INVENTORY.Drop_Chance");
}
public int getInventoryStealDropLevel() {
return config.getInt("Shake.PLAYER.INVENTORY.Drop_Level");
}
public double getItemDropRate(int tier, Rarity rarity) {
return config.getDouble("Item_Drop_Rates.Tier_" + tier + "." + rarity.toString());
}
public double getEnchantmentDropRate(int tier, Rarity rarity) {
return config.getDouble("Enchantment_Drop_Rates.Tier_" + tier + "." + rarity.toString());
}
public double getItemDropRate(int tier, Rarity rarity) { return config.getDouble("Item_Drop_Rates.Tier_" + tier + "." + rarity.toString()); }
public double getEnchantmentDropRate(int tier, Rarity rarity) { return config.getDouble("Enchantment_Drop_Rates.Tier_" + tier + "." + rarity.toString()); }
}

View File

@@ -11,8 +11,8 @@ import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.SkillType;
public interface DatabaseManager {
// One month in milliseconds
public final long PURGE_TIME = 2630000000L * Config.getInstance().getOldUsersCutoff();
// One month in seconds
public final long PURGE_TIME = 2630000L * Config.getInstance().getOldUsersCutoff();
// During convertUsers, how often to output a status
public final int progressInterval = 200;
@@ -55,7 +55,7 @@ public interface DatabaseManager {
/**
* Retrieve rank info into a HashMap from SkillType to the rank.
* <p>
* The special value <code>null</code> is used to represent the Power
* The special value {@code null} is used to represent the Power
* Level rank (the combination of all skill levels).
*
* @param playerName The name of the user to retrieve the rankings for

View File

@@ -44,7 +44,7 @@ public class DatabaseManagerFactory {
*/
public static void setCustomDatabaseManagerClass(Class<? extends DatabaseManager> clazz) {
try {
clazz.getConstructor();
clazz.getConstructor((Class<?>) null);
customManager = clazz;
}
catch (Throwable e) {
@@ -78,10 +78,10 @@ public class DatabaseManagerFactory {
}
public static DatabaseManager createDefaultCustomDatabaseManager() throws Throwable {
return customManager.getConstructor().newInstance();
return customManager.getConstructor((Class<?>) null).newInstance((Object[]) null);
}
public static DatabaseManager createCustomDatabaseManager(Class<? extends DatabaseManager> clazz) throws Throwable {
return clazz.getConstructor().newInstance();
return clazz.getConstructor((Class<?>) null).newInstance((Object[]) null);
}
}

View File

@@ -7,7 +7,6 @@ import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
@@ -139,7 +138,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
String name = character[USERNAME];
String name = character[0];
long lastPlayed = 0;
boolean rewrite = false;
try {
@@ -214,7 +213,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
// Write out the same file but when we get to the player we want to remove, we skip his line.
if (!worked && line.split(":")[USERNAME].equalsIgnoreCase(playerName)) {
if (!worked && line.split(":")[0].equalsIgnoreCase(playerName)) {
mcMMO.p.getLogger().info("User found, removing...");
worked = true;
continue; // Skip the player
@@ -273,7 +272,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
// Read the line in and copy it to the output if it's not the player we want to edit
String[] character = line.split(":");
if (!(uuid != null && character[UUID_INDEX].equalsIgnoreCase(uuid.toString())) && !character[USERNAME].equalsIgnoreCase(playerName)) {
if (!character[41].equalsIgnoreCase(uuid.toString()) && !character[0].equalsIgnoreCase(playerName)) {
writer.append(line).append("\r\n");
}
else {
@@ -320,8 +319,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
writer.append(mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()).append(":");
writer.append(profile.getSkillLevel(SkillType.ALCHEMY)).append(":");
writer.append(profile.getSkillXpLevel(SkillType.ALCHEMY)).append(":");
writer.append(uuid != null ? uuid.toString() : "NULL").append(":");
writer.append(profile.getScoreboardTipsShown()).append(":");
writer.append(uuid.toString()).append(":");
writer.append("\r\n");
}
}
@@ -428,7 +426,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
out.append("0:"); // Alchemy
out.append("0:"); // AlchemyXp
out.append(uuid != null ? uuid.toString() : "NULL").append(":"); // UUID
out.append("0:"); // Scoreboard tips shown
// Add more in the same format as the line above
out.newLine();
@@ -474,20 +472,20 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
// Compare names because we don't have a valid uuid for that player even
// if input uuid is not null
if (character[UUID_INDEX].equalsIgnoreCase("NULL")) {
if (!character[USERNAME].equalsIgnoreCase(playerName)) {
if (character[41].equalsIgnoreCase("NULL")) {
if (!character[0].equalsIgnoreCase(playerName)) {
continue;
}
}
// If input uuid is not null then we should compare uuids
else if ((uuid != null && !character[UUID_INDEX].equalsIgnoreCase(uuid.toString())) || (uuid == null && !character[USERNAME].equalsIgnoreCase(playerName))) {
else if ((uuid != null && !character[41].equalsIgnoreCase(uuid.toString())) || (uuid == null && !character[0].equalsIgnoreCase(playerName))) {
continue;
}
// Update playerName in database after name change
if (!character[USERNAME].equalsIgnoreCase(playerName)) {
mcMMO.p.debug("Name change detected: " + character[USERNAME] + " => " + playerName);
character[USERNAME] = playerName;
if (!character[0].equalsIgnoreCase(playerName)) {
mcMMO.p.debug("Name change detected: " + character[0] + " => " + playerName);
character[0] = playerName;
}
return loadFromLine(character);
@@ -573,7 +571,6 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
public boolean saveUserUUID(String userName, UUID uuid) {
boolean worked = false;
int i = 0;
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
@@ -586,18 +583,17 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
if (!worked && character[USERNAME].equalsIgnoreCase(userName)) {
if (!worked && character[0].equalsIgnoreCase(userName)) {
if (character.length < 42) {
mcMMO.p.getLogger().severe("Could not update UUID for " + userName + "!");
mcMMO.p.getLogger().severe("Database entry is invalid.");
continue;
break;
}
line = line.replace(character[UUID_INDEX], uuid.toString());
line = line.replace(character[41], uuid.toString());
worked = true;
}
i++;
writer.append(line).append("\r\n");
}
@@ -608,7 +604,6 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
mcMMO.p.getLogger().info(i + " entries written while saving UUID for " + userName);
if (in != null) {
try {
in.close();
@@ -635,7 +630,6 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
int i = 0;
synchronized (fileWritingLock) {
try {
@@ -643,20 +637,19 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
StringBuilder writer = new StringBuilder();
String line;
while (((line = in.readLine()) != null)) {
while (((line = in.readLine()) != null) && !fetchedUUIDs.isEmpty()) {
String[] character = line.split(":");
if (!fetchedUUIDs.isEmpty() && fetchedUUIDs.containsKey(character[USERNAME])) {
if (fetchedUUIDs.containsKey(character[0])) {
if (character.length < 42) {
mcMMO.p.getLogger().severe("Could not update UUID for " + character[USERNAME] + "!");
mcMMO.p.getLogger().severe("Could not update UUID for " + character[0] + "!");
mcMMO.p.getLogger().severe("Database entry is invalid.");
continue;
}
character[UUID_INDEX] = fetchedUUIDs.remove(character[USERNAME]).toString();
character[41] = fetchedUUIDs.remove(character[0]).toString();
line = new StringBuilder(org.apache.commons.lang.StringUtils.join(character, ":")).append(":").toString();
}
i++;
writer.append(line).append("\r\n");
}
@@ -667,7 +660,6 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
mcMMO.p.getLogger().info(i + " entries written while saving UUID batch");
if (in != null) {
try {
in.close();
@@ -703,7 +695,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
users.add(character[USERNAME]);
users.add(character[0]);
}
}
catch (Exception e) {
@@ -761,7 +753,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
String[] data = line.split(":");
playerName = data[USERNAME];
playerName = data[0];
int powerLevel = 0;
Map<SkillType, Integer> skills = getSkillMapFromLine(data);
@@ -857,20 +849,15 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
if (line.charAt(line.length() - 1) != ':') {
line = line.concat(":");
}
boolean updated = false;
String[] character = line.split(":");
// Prevent the same username from being present multiple times
if (!usernames.add(character[USERNAME])) {
character[USERNAME] = "_INVALID_OLD_USERNAME_'";
updated = true;
if (character.length < UUID_INDEX + 1 || character[UUID_INDEX].equals("NULL")) {
continue;
}
if (!usernames.add(character[0])) {
continue;
}
// Prevent the same player from being present multiple times
if (character.length >= 42 && (!character[UUID_INDEX].isEmpty() && !character[UUID_INDEX].equals("NULL") && !players.add(character[UUID_INDEX]))) {
if (character.length == 42 && (!character[41].isEmpty() && !players.add(character[41]))) {
continue;
}
@@ -882,54 +869,39 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
String oldVersion = null;
if (character.length > 33 && !character[33].isEmpty()) {
// Removal of Spout Support
// Version 1.4.07-dev2
// commit 7bac0e2ca5143bce84dc160617fed97f0b1cb968
character[33] = "";
if (oldVersion == null) {
oldVersion = "1.4.07";
}
updated = true;
}
if (Config.getInstance().getTruncateSkills()) {
for (SkillType skill : SkillType.NON_CHILD_SKILLS) {
int index = getSkillIndex(skill);
if (index >= character.length) {
continue;
}
int cap = Config.getInstance().getLevelCap(skill);
if (Integer.valueOf(character[index]) > cap) {
mcMMO.p.getLogger().warning("Truncating " + skill.getName() + " to configured max level for player " + character[USERNAME]);
character[index] = cap + "";
updated = true;
}
}
}
// If they're valid, rewrite them to the file.
if (!updated && character.length == 43) {
writer.append(line).append("\r\n");
continue;
}
if (character.length <= 33) {
// Introduction of HUDType
// Version 1.1.06
// commit 78f79213cdd7190cd11ae54526f3b4ea42078e8a
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = "";
line = line.concat(" :");
character = line.split(":");
oldVersion = "1.1.06";
}
if (!character[33].isEmpty()) {
// Removal of Spout Support
// Version 1.4.07-dev2
// commit 7bac0e2ca5143bce84dc160617fed97f0b1cb968
line = line.replace(character[33], "");
if (oldVersion == null) {
oldVersion = "1.4.07";
}
}
// If they're valid, rewrite them to the file.
if (character.length == 42) {
writer.append(line).append("\r\n");
continue;
}
StringBuilder newLine = new StringBuilder(line);
if (character.length <= 35) {
// Introduction of Fishing
// Version 1.2.00
// commit a814b57311bc7734661109f0e77fc8bab3a0bd29
character = Arrays.copyOf(character, character.length + 2);
character[character.length - 1] = "0";
character[character.length - 2] = "0";
newLine.append(0).append(":");
newLine.append(0).append(":");
if (oldVersion == null) {
oldVersion = "1.2.00";
}
@@ -938,8 +910,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
// Introduction of Blast Mining cooldowns
// Version 1.3.00-dev
// commit fadbaf429d6b4764b8f1ad0efaa524a090e82ef5
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = "0";
newLine.append(0).append(":");
if (oldVersion == null) {
oldVersion = "1.3.00";
}
@@ -949,8 +920,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
// Version 1.4.00-dev
// commmit 3f6c07ba6aaf44e388cc3b882cac3d8f51d0ac28
// XXX Cannot create an OfflinePlayer at startup, use 0 and fix in purge
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = "0";
newLine.append("0").append(":");
if (oldVersion == null) {
oldVersion = "1.4.00";
}
@@ -959,8 +929,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
// Addition of mob healthbars
// Version 1.4.06
// commit da29185b7dc7e0d992754bba555576d48fa08aa6
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = Config.getInstance().getMobHealthbarDefault().toString();
newLine.append(Config.getInstance().getMobHealthbarDefault().toString()).append(":");
if (oldVersion == null) {
oldVersion = "1.4.06";
}
@@ -968,9 +937,8 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
if (character.length <= 39) {
// Addition of Alchemy
// Version 1.4.08
character = Arrays.copyOf(character, character.length + 2);
character[character.length - 1] = "0";
character[character.length - 2] = "0";
newLine.append("0").append(":");
newLine.append("0").append(":");
if (oldVersion == null) {
oldVersion = "1.4.08";
}
@@ -979,75 +947,61 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
// Addition of UUIDs
// Version 1.5.01
// Add a value because otherwise it gets removed
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = "NULL";
newLine.append("NULL:");
if (oldVersion == null) {
oldVersion = "1.5.01";
}
}
if (character.length <= 42) {
// Addition of scoreboard tips auto disable
// Version 1.5.02
character = Arrays.copyOf(character, character.length + 1);
character[character.length - 1] = "0";
if (oldVersion == null) {
oldVersion = "1.5.02";
}
}
// Remove any blanks that shouldn't be there, and validate the other fields
String[] newCharacter = newLine.toString().split(":");
boolean corrupted = false;
for (int i = 0; i < character.length; i++) {
if (character[i].isEmpty() && !(i == 2 || i == 3 || i == 23 || i == 33 || i == 41)) {
for (int i = 0; i < newCharacter.length; i++) {
if (newCharacter[i].isEmpty() && !(i == 2 || i == 3 || i == 23 || i == 33 || i == 41)) {
corrupted = true;
if (i == 37) {
character[i] = String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
else if (i == 38) {
character[i] = Config.getInstance().getMobHealthbarDefault().toString();
if (newCharacter.length != 42) {
newCharacter = (String[]) ArrayUtils.remove(newCharacter, i);
}
else {
character[i] = "0";
if (i == 37) {
newCharacter[i] = String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
else if (i == 38) {
newCharacter[i] = Config.getInstance().getMobHealthbarDefault().toString();
}
else {
newCharacter[i] = "0";
}
}
}
if (StringUtils.isInt(character[i]) && i == 38) {
if (StringUtils.isInt(newCharacter[i]) && i == 38) {
corrupted = true;
character[i] = Config.getInstance().getMobHealthbarDefault().toString();
newCharacter[i] = Config.getInstance().getMobHealthbarDefault().toString();
}
if (!StringUtils.isInt(character[i]) && !(i == 0 || i == 2 || i == 3 || i == 23 || i == 33 || i == 38 || i == 41)) {
if (!StringUtils.isInt(newCharacter[i]) && !(i == 0 || i == 2 || i == 3 || i == 23 || i == 33 || i == 38 || i == 41)) {
corrupted = true;
character[i] = "0";
newCharacter[i] = "0";
}
}
if (corrupted) {
mcMMO.p.debug("Updating corrupted database line for player " + character[USERNAME]);
mcMMO.p.debug("Updating corrupted database line for player " + newCharacter[0]);
}
if (oldVersion != null) {
mcMMO.p.debug("Updating database line from before version " + oldVersion + " for player " + character[USERNAME]);
mcMMO.p.debug("Updating database line from before version " + oldVersion + " for player " + character[0]);
}
updated |= corrupted;
updated |= oldVersion != null;
if (Config.getInstance().getTruncateSkills()) {
Map<SkillType, Integer> skills = getSkillMapFromLine(character);
for (SkillType skill : SkillType.NON_CHILD_SKILLS) {
int cap = Config.getInstance().getLevelCap(skill);
if (skills.get(skill) > cap) {
updated = true;
}
}
if (corrupted || oldVersion != null) {
newLine = new StringBuilder(org.apache.commons.lang.StringUtils.join(newCharacter, ":"));
newLine = newLine.append(":");
}
if (updated) {
line = new StringBuilder(org.apache.commons.lang.StringUtils.join(character, ":")).append(":").toString();
}
writer.append(line).append("\r\n");
writer.append(newLine).append("\r\n");
}
// Write the new file
@@ -1133,39 +1087,38 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
Map<SkillType, Float> skillsXp = new EnumMap<SkillType, Float>(SkillType.class); // Skill & XP
Map<AbilityType, Integer> skillsDATS = new EnumMap<AbilityType, Integer>(AbilityType.class); // Ability & Cooldown
MobHealthbarType mobHealthbarType;
int scoreboardTipsShown;
// TODO on updates, put new values in a try{} ?
skillsXp.put(SkillType.TAMING, (float) Integer.valueOf(character[EXP_TAMING]));
skillsXp.put(SkillType.MINING, (float) Integer.valueOf(character[EXP_MINING]));
skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(character[EXP_REPAIR]));
skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(character[EXP_WOODCUTTING]));
skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(character[EXP_UNARMED]));
skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(character[EXP_HERBALISM]));
skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(character[EXP_EXCAVATION]));
skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(character[EXP_ARCHERY]));
skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(character[EXP_SWORDS]));
skillsXp.put(SkillType.AXES, (float) Integer.valueOf(character[EXP_AXES]));
skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(character[EXP_ACROBATICS]));
skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(character[EXP_FISHING]));
skillsXp.put(SkillType.ALCHEMY, (float) Integer.valueOf(character[EXP_ALCHEMY]));
skillsXp.put(SkillType.TAMING, (float) Integer.valueOf(character[25]));
skillsXp.put(SkillType.MINING, (float) Integer.valueOf(character[4]));
skillsXp.put(SkillType.REPAIR, (float) Integer.valueOf(character[15]));
skillsXp.put(SkillType.WOODCUTTING, (float) Integer.valueOf(character[6]));
skillsXp.put(SkillType.UNARMED, (float) Integer.valueOf(character[16]));
skillsXp.put(SkillType.HERBALISM, (float) Integer.valueOf(character[17]));
skillsXp.put(SkillType.EXCAVATION, (float) Integer.valueOf(character[18]));
skillsXp.put(SkillType.ARCHERY, (float) Integer.valueOf(character[19]));
skillsXp.put(SkillType.SWORDS, (float) Integer.valueOf(character[20]));
skillsXp.put(SkillType.AXES, (float) Integer.valueOf(character[21]));
skillsXp.put(SkillType.ACROBATICS, (float) Integer.valueOf(character[22]));
skillsXp.put(SkillType.FISHING, (float) Integer.valueOf(character[35]));
skillsXp.put(SkillType.ALCHEMY, (float) Integer.valueOf(character[40]));
// Taming - Unused
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(character[COOLDOWN_SUPER_BREAKER]));
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(character[32]));
// Repair - Unused
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(character[COOLDOWN_TREE_FELLER]));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(character[COOLDOWN_BERSERK]));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(character[COOLDOWN_GREEN_TERRA]));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(character[COOLDOWN_GIGA_DRILL_BREAKER]));
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(character[28]));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(character[26]));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(character[29]));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(character[27]));
// Archery - Unused
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(character[COOLDOWN_SERRATED_STRIKES]));
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(character[COOLDOWN_SKULL_SPLITTER]));
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(character[30]));
skillsDATS.put(AbilityType.SKULL_SPLITTER, Integer.valueOf(character[31]));
// Acrobatics - Unused
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(character[COOLDOWN_BLAST_MINING]));
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(character[36]));
try {
mobHealthbarType = MobHealthbarType.valueOf(character[HEALTHBAR]);
mobHealthbarType = MobHealthbarType.valueOf(character[38]);
}
catch (Exception e) {
mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
@@ -1173,38 +1126,31 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
UUID uuid;
try {
uuid = UUID.fromString(character[UUID_INDEX]);
uuid = UUID.fromString(character[41]);
}
catch (Exception e) {
uuid = null;
}
try {
scoreboardTipsShown = Integer.valueOf(character[SCOREBOARD_TIPS]);
}
catch (Exception e) {
scoreboardTipsShown = 0;
}
return new PlayerProfile(character[USERNAME], uuid, skills, skillsXp, skillsDATS, mobHealthbarType, scoreboardTipsShown);
return new PlayerProfile(character[0], uuid, skills, skillsXp, skillsDATS, mobHealthbarType);
}
private Map<SkillType, Integer> getSkillMapFromLine(String[] character) {
Map<SkillType, Integer> skills = new EnumMap<SkillType, Integer>(SkillType.class); // Skill & Level
skills.put(SkillType.TAMING, Integer.valueOf(character[SKILLS_TAMING]));
skills.put(SkillType.MINING, Integer.valueOf(character[SKILLS_MINING]));
skills.put(SkillType.REPAIR, Integer.valueOf(character[SKILLS_REPAIR]));
skills.put(SkillType.WOODCUTTING, Integer.valueOf(character[SKILLS_WOODCUTTING]));
skills.put(SkillType.UNARMED, Integer.valueOf(character[SKILLS_UNARMED]));
skills.put(SkillType.HERBALISM, Integer.valueOf(character[SKILLS_HERBALISM]));
skills.put(SkillType.EXCAVATION, Integer.valueOf(character[SKILLS_EXCAVATION]));
skills.put(SkillType.ARCHERY, Integer.valueOf(character[SKILLS_ARCHERY]));
skills.put(SkillType.SWORDS, Integer.valueOf(character[SKILLS_SWORDS]));
skills.put(SkillType.AXES, Integer.valueOf(character[SKILLS_AXES]));
skills.put(SkillType.ACROBATICS, Integer.valueOf(character[SKILLS_ACROBATICS]));
skills.put(SkillType.FISHING, Integer.valueOf(character[SKILLS_FISHING]));
skills.put(SkillType.ALCHEMY, Integer.valueOf(character[SKILLS_ALCHEMY]));
skills.put(SkillType.TAMING, Integer.valueOf(character[24]));
skills.put(SkillType.MINING, Integer.valueOf(character[1]));
skills.put(SkillType.REPAIR, Integer.valueOf(character[7]));
skills.put(SkillType.WOODCUTTING, Integer.valueOf(character[5]));
skills.put(SkillType.UNARMED, Integer.valueOf(character[8]));
skills.put(SkillType.HERBALISM, Integer.valueOf(character[9]));
skills.put(SkillType.EXCAVATION, Integer.valueOf(character[10]));
skills.put(SkillType.ARCHERY, Integer.valueOf(character[11]));
skills.put(SkillType.SWORDS, Integer.valueOf(character[12]));
skills.put(SkillType.AXES, Integer.valueOf(character[13]));
skills.put(SkillType.ACROBATICS, Integer.valueOf(character[14]));
skills.put(SkillType.FISHING, Integer.valueOf(character[34]));
skills.put(SkillType.ALCHEMY, Integer.valueOf(character[39]));
return skills;
}
@@ -1215,131 +1161,4 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
@Override
public void onDisable() { }
private int getSkillIndex(SkillType skill) {
switch (skill) {
case ACROBATICS:
return SKILLS_ACROBATICS;
case ALCHEMY:
return SKILLS_ALCHEMY;
case ARCHERY:
return SKILLS_ARCHERY;
case AXES:
return SKILLS_AXES;
case EXCAVATION:
return SKILLS_EXCAVATION;
case FISHING:
return SKILLS_FISHING;
case HERBALISM:
return SKILLS_HERBALISM;
case MINING:
return SKILLS_MINING;
case REPAIR:
return SKILLS_REPAIR;
case SWORDS:
return SKILLS_SWORDS;
case TAMING:
return SKILLS_TAMING;
case UNARMED:
return SKILLS_UNARMED;
case WOODCUTTING:
return SKILLS_WOODCUTTING;
default:
throw new RuntimeException("Primary Skills only");
}
}
public static int USERNAME = 0;
public static int SKILLS_MINING = 1;
public static int EXP_MINING = 4;
public static int SKILLS_WOODCUTTING = 5;
public static int EXP_WOODCUTTING = 6;
public static int SKILLS_REPAIR = 7;
public static int SKILLS_UNARMED = 8;
public static int SKILLS_HERBALISM = 9;
public static int SKILLS_EXCAVATION = 10;
public static int SKILLS_ARCHERY = 11;
public static int SKILLS_SWORDS = 12;
public static int SKILLS_AXES = 13;
public static int SKILLS_ACROBATICS = 14;
public static int EXP_REPAIR = 15;
public static int EXP_UNARMED = 16;
public static int EXP_HERBALISM = 17;
public static int EXP_EXCAVATION = 18;
public static int EXP_ARCHERY = 19;
public static int EXP_SWORDS = 20;
public static int EXP_AXES = 21;
public static int EXP_ACROBATICS = 22;
public static int SKILLS_TAMING = 24;
public static int EXP_TAMING = 25;
public static int COOLDOWN_BERSERK = 26;
public static int COOLDOWN_GIGA_DRILL_BREAKER = 27;
public static int COOLDOWN_TREE_FELLER = 28;
public static int COOLDOWN_GREEN_TERRA = 29;
public static int COOLDOWN_SERRATED_STRIKES = 30;
public static int COOLDOWN_SKULL_SPLITTER = 31;
public static int COOLDOWN_SUPER_BREAKER = 32;
public static int SKILLS_FISHING = 34;
public static int EXP_FISHING = 35;
public static int COOLDOWN_BLAST_MINING = 36;
public static int LAST_LOGIN = 37;
public static int HEALTHBAR = 38;
public static int SKILLS_ALCHEMY = 39;
public static int EXP_ALCHEMY = 40;
public static int UUID_INDEX = 41;
public static int SCOREBOARD_TIPS = 42;
public void resetMobHealthSettings() {
BufferedReader in = null;
FileWriter out = null;
String usersFilePath = mcMMO.getUsersFilePath();
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
StringBuilder writer = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
// Remove empty lines from the file
if (line.isEmpty()) {
continue;
}
String[] character = line.split(":");
character[HEALTHBAR] = Config.getInstance().getMobHealthbarDefault().toString();
line = new StringBuilder(org.apache.commons.lang.StringUtils.join(character, ":")).append(":").toString();
writer.append(line).append("\r\n");
}
// Write the new file
out = new FileWriter(usersFilePath);
out.write(writer.toString());
}
catch (IOException e) {
mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString());
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// Ignore
}
}
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// Ignore
}
}
}
}
}
}

View File

@@ -9,8 +9,5 @@ public enum UpgradeType {
DROP_SPOUT,
ADD_ALCHEMY,
ADD_UUIDS,
ADD_UUIDS_PARTY,
ADD_SCOREBOARD_TIPS,
DROP_NAME_UNIQUENESS,
ADD_SKILL_TOTAL,
ADD_UUIDS_PARTY;
}

View File

@@ -1,18 +1,5 @@
package com.gmail.nossr50.datatypes.party;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -20,6 +7,20 @@ import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
public class Party {
private final LinkedHashMap<UUID, String> members = new LinkedHashMap<UUID, String>();
private final List<Player> onlineMembers = new ArrayList<Player>();
@@ -226,7 +227,7 @@ public class Party {
leader.sendMessage(LocaleLoader.getString("Party.LevelUp", levelsGained, getLevel()));
if (Config.getInstance().getLevelUpSoundsEnabled()) {
leader.playSound(leader.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
leader.playSound(leader.getLocation(), Sound.LEVEL_UP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
}
}
return;
@@ -336,7 +337,7 @@ public class Party {
}
if (!nearMembers.contains(member) && !playerName.equalsIgnoreCase(memberName)) {
memberList.append(ChatColor.ITALIC);
memberList.append(ChatColor.ITALIC).append("");
}
memberList.append(memberName).append(ChatColor.RESET).append(" ");

View File

@@ -1,5 +1,18 @@
package com.gmail.nossr50.datatypes.player;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
@@ -12,11 +25,9 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.skills.AbilityDisableTask;
import com.gmail.nossr50.runnables.skills.BleedTimerTask;
import com.gmail.nossr50.runnables.skills.ToolLowerTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
@@ -39,23 +50,11 @@ import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.Validate;
public class McMMOPlayer {
private Player player;
@@ -99,6 +98,12 @@ public class McMMOPlayer {
this.player = player;
playerMetadata = new FixedMetadataValue(mcMMO.p, playerName);
this.profile = profile;
party = PartyManager.getPlayerParty(playerName, uuid);
ptpRecord = new PartyTeleportRecord();
if (inParty()) {
loginParty();
}
if (profile.getUniqueId() == null) {
profile.setUniqueId(uuid);
@@ -502,7 +507,7 @@ public class McMMOPlayer {
}
if (Config.getInstance().getLevelUpSoundsEnabled()) {
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
player.playSound(player.getLocation(), Sound.LEVEL_UP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
}
player.sendMessage(LocaleLoader.getString(StringUtils.getCapitalized(skillType.toString()) + ".Skillup", levelsGained, getSkillLevel(skillType)));
@@ -524,15 +529,6 @@ public class McMMOPlayer {
* Party Stuff
*/
public void setupPartyData() {
party = PartyManager.getPlayerParty(player.getName(), player.getUniqueId());
ptpRecord = new PartyTeleportRecord();
if (inParty()) {
loginParty();
}
}
public void setPartyInvite(Party invite) {
this.invite = invite;
}
@@ -589,6 +585,10 @@ public class McMMOPlayer {
party.addOnlineMember(this.getPlayer());
}
public void logoutParty() {
party.removeOnlineMember(this.getPlayer());
}
public int getItemShareModifier() {
if (itemShareModifier < 10) {
setItemShareModifier(10);
@@ -687,7 +687,7 @@ public class McMMOPlayer {
xp = (float) (xp / skillType.getXpModifier() * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier());
if (Config.getInstance().getToolModsEnabled()) {
CustomTool tool = mcMMO.getModManager().getTool(player.getInventory().getItemInMainHand());
CustomTool tool = mcMMO.getModManager().getTool(player.getItemInHand());
if (tool != null) {
xp *= tool.getXpMultiplier();
@@ -771,7 +771,7 @@ public class McMMOPlayer {
return;
}
ItemStack inHand = player.getInventory().getItemInMainHand();
ItemStack inHand = player.getItemInHand();
if (mcMMO.getModManager().isCustomTool(inHand) && !mcMMO.getModManager().getTool(inHand).isAbilityEnabled()) {
return;
@@ -879,28 +879,4 @@ public class McMMOPlayer {
public FixedMetadataValue getPlayerMetadata() {
return playerMetadata;
}
/**
* This method is called by PlayerQuitEvent to tear down the mcMMOPlayer.
*
* @param syncSave if true, data is saved synchronously
*/
public void logout(boolean syncSave) {
Player thisPlayer = getPlayer();
resetAbilityMode();
BleedTimerTask.bleedOut(thisPlayer);
if (syncSave) {
getProfile().save();
} else {
getProfile().scheduleAsyncSave();
}
UserManager.remove(thisPlayer);
ScoreboardManager.teardownPlayer(thisPlayer);
if (inParty()) {
party.removeOnlineMember(thisPlayer);
}
}
}

View File

@@ -28,7 +28,6 @@ public class PlayerProfile {
/* HUDs */
private MobHealthbarType mobHealthbarType;
private int scoreboardTipsShown;
/* Skill Data */
private final Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level
@@ -49,7 +48,6 @@ public class PlayerProfile {
this.playerName = playerName;
mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
scoreboardTipsShown = 0;
for (AbilityType abilityType : AbilityType.values()) {
abilityDATS.put(abilityType, 0);
@@ -72,11 +70,10 @@ public class PlayerProfile {
this.loaded = isLoaded;
}
public PlayerProfile(String playerName, UUID uuid, Map<SkillType, Integer> levelData, Map<SkillType, Float> xpData, Map<AbilityType, Integer> cooldownData, MobHealthbarType mobHealthbarType, int scoreboardTipsShown) {
public PlayerProfile(String playerName, UUID uuid, Map<SkillType, Integer> levelData, Map<SkillType, Float> xpData, Map<AbilityType, Integer> cooldownData, MobHealthbarType mobHealthbarType) {
this.playerName = playerName;
this.uuid = uuid;
this.mobHealthbarType = mobHealthbarType;
this.scoreboardTipsShown = scoreboardTipsShown;
skills.putAll(levelData);
skillsXp.putAll(xpData);
@@ -95,7 +92,7 @@ public class PlayerProfile {
}
// TODO should this part be synchronized?
PlayerProfile profileCopy = new PlayerProfile(playerName, uuid, ImmutableMap.copyOf(skills), ImmutableMap.copyOf(skillsXp), ImmutableMap.copyOf(abilityDATS), mobHealthbarType, scoreboardTipsShown);
PlayerProfile profileCopy = new PlayerProfile(playerName, uuid, ImmutableMap.copyOf(skills), ImmutableMap.copyOf(skillsXp), ImmutableMap.copyOf(abilityDATS), mobHealthbarType);
changed = !mcMMO.getDatabaseManager().saveUser(profileCopy);
if (changed) {
@@ -130,25 +127,9 @@ public class PlayerProfile {
}
public void setMobHealthbarType(MobHealthbarType mobHealthbarType) {
changed = true;
this.mobHealthbarType = mobHealthbarType;
}
public int getScoreboardTipsShown() {
return scoreboardTipsShown;
}
public void setScoreboardTipsShown(int scoreboardTipsShown) {
changed = true;
this.scoreboardTipsShown = scoreboardTipsShown;
}
public void increaseTipsShown() {
setScoreboardTipsShown(getScoreboardTipsShown() + 1);
}
/*
* Cooldowns
*/
@@ -355,7 +336,7 @@ public class PlayerProfile {
int sum = 0;
for (SkillType parent : parents) {
sum += Math.min(getSkillLevel(parent), parent.getMaxLevel());
sum += Math.min(getSkillLevel(parent), 1000);
}
return sum / parents.size();

View File

@@ -85,30 +85,67 @@ public enum AbilityType {
this.abilityPlayerOff = abilityPlayerOff;
}
/**
* Get the cooldown time in seconds for this ability
*
* @return cooldown time in seconds
*/
public int getCooldown() {
return Config.getInstance().getCooldown(this);
}
/**
* Get the maximum length in seconds for this ability
*
* @return maximum length in seconds
*/
public int getMaxLength() {
return Config.getInstance().getMaxLength(this);
}
/**
* Get the locale string for when the ability activates
*
* @return localized activation message
*/
public String getAbilityOn() {
return LocaleLoader.getString(this.abilityOn);
}
/**
* Get the locale string for when the ability deactivates
*
* @return localized deactivation message
*/
public String getAbilityOff() {
return LocaleLoader.getString(this.abilityOff);
}
/**
* Get the locale string for nearby players when someone activates this ability
*
* @param player {@link Player} object that activates this ability
* @return localized activation message
*/
public String getAbilityPlayer(Player player) {
return LocaleLoader.getString(this.abilityPlayer, player.getName());
}
/**
* Get the locale string for nearby players when someone deactivates this ability
*
* @param player {@link Player} object that deactivates this ability
* @return localized deactivation message
*/
public String getAbilityPlayerOff(Player player) {
return LocaleLoader.getString(this.abilityPlayerOff, player.getName());
}
/**
* Get ability refresh message
*
* @return Localized ability refresh message
*/
public String getAbilityRefresh() {
return LocaleLoader.getString(this.abilityRefresh);
}

View File

@@ -21,7 +21,7 @@ public enum MaterialType {
return Material.LEATHER;
case WOOD:
return Material.OAK_PLANKS;
return Material.WOOD;
case STONE:
return Material.COBBLESTONE;

View File

@@ -64,7 +64,7 @@ public enum SecondaryAbility {
/* Taming */
BEAST_LORE,
CALL_OF_THE_WILD,
ENVIRONMENTALLY_AWARE,
ENVIROMENTALLY_AWARE,
FAST_FOOD,
GORE,
HOLY_HOUND,

View File

@@ -48,7 +48,7 @@ public enum SkillType {
SALVAGE(SalvageManager.class, Color.ORANGE, ImmutableList.of(SecondaryAbility.ADVANCED_SALVAGE, SecondaryAbility.ARCANE_SALVAGE)),
SMELTING(SmeltingManager.class, Color.YELLOW, ImmutableList.of(SecondaryAbility.FLUX_MINING, SecondaryAbility.FUEL_EFFICIENCY, SecondaryAbility.SECOND_SMELT)),
SWORDS(SwordsManager.class, Color.fromRGB(178, 34, 34), AbilityType.SERRATED_STRIKES, ToolType.SWORD, ImmutableList.of(SecondaryAbility.BLEED, SecondaryAbility.COUNTER)),
TAMING(TamingManager.class, Color.PURPLE, ImmutableList.of(SecondaryAbility.BEAST_LORE, SecondaryAbility.CALL_OF_THE_WILD, SecondaryAbility.ENVIRONMENTALLY_AWARE, SecondaryAbility.FAST_FOOD, SecondaryAbility.GORE, SecondaryAbility.HOLY_HOUND, SecondaryAbility.SHARPENED_CLAWS, SecondaryAbility.SHOCK_PROOF, SecondaryAbility.THICK_FUR, SecondaryAbility.PUMMEL)),
TAMING(TamingManager.class, Color.PURPLE, ImmutableList.of(SecondaryAbility.BEAST_LORE, SecondaryAbility.CALL_OF_THE_WILD, SecondaryAbility.ENVIROMENTALLY_AWARE, SecondaryAbility.FAST_FOOD, SecondaryAbility.GORE, SecondaryAbility.HOLY_HOUND, SecondaryAbility.SHARPENED_CLAWS, SecondaryAbility.SHOCK_PROOF, SecondaryAbility.THICK_FUR, SecondaryAbility.PUMMEL)),
UNARMED(UnarmedManager.class, Color.BLACK, AbilityType.BERSERK, ToolType.FISTS, ImmutableList.of(SecondaryAbility.BLOCK_CRACKER, SecondaryAbility.DEFLECT, SecondaryAbility.DISARM, SecondaryAbility.IRON_ARM, SecondaryAbility.IRON_GRIP)),
WOODCUTTING(WoodcuttingManager.class, Color.OLIVE, AbilityType.TREE_FELLER, ToolType.AXE, ImmutableList.of(SecondaryAbility.LEAF_BLOWER, SecondaryAbility.WOODCUTTING_DOUBLE_DROPS));

View File

@@ -4,44 +4,35 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import com.gmail.nossr50.config.skills.alchemy.PotionConfig;
public class AlchemyPotion {
private Material material;
private PotionData data;
private short dataValue;
private String name;
private List<String> lore;
private List<PotionEffect> effects;
private Color color;
private Map<ItemStack, String> children;
private Map<ItemStack, Short> children;
public AlchemyPotion(Material material, PotionData data, String name, List<String> lore, List<PotionEffect> effects, Color color, Map<ItemStack, String> children) {
this.material = material;
this.data = data;
public AlchemyPotion(short dataValue, String name, List<String> lore, List<PotionEffect> effects, Map<ItemStack, Short> children) {
this.dataValue = dataValue;
this.lore = lore;
this.name = name;
this.effects = effects;
this.children = children;
this.color = color;
}
public String toString() {
return "AlchemyPotion{" + data + ", " + name + ", Effects[" + effects.size() + "], Children[" + children.size() + "]}";
return "AlchemyPotion{" + dataValue + ", " + name + ", Effects[" + effects.size() + "], Children[" + children.size() + "]}";
}
public ItemStack toItemStack(int amount) {
ItemStack potion = new ItemStack(material, amount);
ItemStack potion = new ItemStack(Material.POTION, amount, this.getDataValue());
PotionMeta meta = (PotionMeta) potion.getItemMeta();
meta.setBasePotionData(data);
if (this.getName() != null) {
meta.setDisplayName(this.getName());
}
@@ -55,29 +46,21 @@ public class AlchemyPotion {
meta.addCustomEffect(effect, true);
}
}
if (this.getColor() != null) {
meta.setColor(this.getColor());
}
potion.setItemMeta(meta);
return potion;
}
public Material getMaterial() {
return material;
}
public Potion toPotion(int amount) {
return Potion.fromItemStack(this.toItemStack(amount));
}
public PotionData getData() {
return data;
public short getDataValue() {
return dataValue;
}
public void setData(PotionData data) {
this.data = data;
public void setDataValue(short data_value) {
this.dataValue = data_value;
}
public String getName() {
@@ -104,65 +87,22 @@ public class AlchemyPotion {
this.effects = effects;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Map<ItemStack, String> getChildren() {
public Map<ItemStack, Short> getChildren() {
return children;
}
public void setChildren(Map<ItemStack, String> children) {
public void setChildren(Map<ItemStack, Short> children) {
this.children = children;
}
public AlchemyPotion getChild(ItemStack ingredient) {
public Short getChildDataValue(ItemStack ingredient) {
if (!children.isEmpty()) {
for (Entry<ItemStack, String> child : children.entrySet()) {
for (Entry<ItemStack, Short> child : children.entrySet()) {
if (ingredient.isSimilar(child.getKey())) {
return PotionConfig.getInstance().getPotion(child.getValue());
return child.getValue();
}
}
}
return null;
}
public boolean isSimilar(ItemStack item) {
if (item.getType() != material) {
return false;
}
if (!item.hasItemMeta()) {
return false;
}
PotionMeta meta = (PotionMeta) item.getItemMeta();
PotionData that = meta.getBasePotionData();
if (data.getType() != that.getType()) {
return false;
}
if (data.isExtended() != that.isExtended()) {
return false;
}
if (data.isUpgraded() != that.isUpgraded()) {
return false;
}
for (PotionEffect effect : effects) {
if (!meta.hasCustomEffect(effect.getType())) {
return false;
}
}
if (!meta.hasLore() && !lore.isEmpty()) {
return false;
}
if (!(lore.isEmpty() && !meta.hasLore()) && !meta.getLore().equals(lore)) {
return false;
}
if (!meta.hasDisplayName() && name != null) {
return false;
}
return (name == null && !meta.hasDisplayName()) || meta.getDisplayName().equals(name);
return -1;
}
}

View File

@@ -1,12 +1,6 @@
package com.gmail.nossr50.datatypes.skills.alchemy;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionType;
public enum PotionStage {
FIVE(5),
@@ -45,40 +39,31 @@ public enum PotionStage {
}
private static boolean isWaterBottle(AlchemyPotion input) {
return input.getData().getType() == PotionType.WATER;
return input.getDataValue() == 0;
}
public static PotionStage getPotionStage(AlchemyPotion alchemyPotion) {
PotionData data = alchemyPotion.getData();
List<PotionEffect> effects = alchemyPotion.getEffects();
Potion potion = alchemyPotion.toPotion(1);
int stage = 1;
// Check if potion has an effect of any sort
if (data.getType().getEffectType() != null || !effects.isEmpty()) {
// Check if potion isn't awkward or mundane
if (potion.getType() != null) {
stage++;
}
// Check if potion has a glowstone dust amplifier
// Else check if the potion has a custom effect with an amplifier added by mcMMO
if (data.isUpgraded()) {
if (potion.getLevel() > 1) {
stage++;
} else if(!effects.isEmpty()) {
for (PotionEffect effect : effects){
if(effect.getAmplifier() > 0){
stage++;
break;
}
}
}
// Check if potion has a redstone dust amplifier
if (data.isExtended()) {
if (potion.hasExtendedDuration()) {
stage++;
}
// Check if potion has a gunpowder amplifier
if (alchemyPotion.getMaterial() == Material.SPLASH_POTION || alchemyPotion.getMaterial() == Material.LINGERING_POTION) {
if (potion.isSplash()) {
stage++;
}

View File

@@ -64,7 +64,8 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/** Rest of file is required boilerplate for custom events **/
private static final HandlerList handlers = new HandlerList();
@Override

View File

@@ -1,7 +1,6 @@
package com.gmail.nossr50.events.experience;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
@@ -47,15 +46,4 @@ public class McMMOPlayerLevelDownEvent extends McMMOPlayerLevelChangeEvent {
public int getLevelsLost() {
return levelsLost;
}
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@@ -1,7 +1,6 @@
package com.gmail.nossr50.events.experience;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
@@ -47,15 +46,4 @@ public class McMMOPlayerLevelUpEvent extends McMMOPlayerLevelChangeEvent {
public int getLevelsGained() {
return levelsGained;
}
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@@ -1,7 +1,6 @@
package com.gmail.nossr50.events.experience;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
@@ -52,15 +51,4 @@ public class McMMOPlayerXpGainEvent extends McMMOPlayerExperienceEvent {
public void setXpGained(int xpGained) {
this.xpGained = xpGained;
}
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@@ -5,7 +5,7 @@ import org.bukkit.event.inventory.BrewEvent;
import org.bukkit.inventory.BrewerInventory;
public class FakeBrewEvent extends BrewEvent {
public FakeBrewEvent(Block brewer, BrewerInventory contents, int fuelLevel) {
super(brewer, contents, fuelLevel);
public FakeBrewEvent(Block brewer, BrewerInventory contents) {
super(brewer, contents);
}
}

View File

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

View File

@@ -1,58 +0,0 @@
package com.gmail.nossr50.events.skills.salvage;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent;
/**
* Called just before a player salvages an item with mcMMO.
*/
public class McMMOPlayerSalvageCheckEvent extends McMMOPlayerSkillEvent implements Cancellable {
private ItemStack salvageItem;
private ItemStack salvageResults;
private ItemStack enchantedBook;
private boolean cancelled;
public McMMOPlayerSalvageCheckEvent(Player player, ItemStack salvageItem, ItemStack salvageResults, ItemStack enchantedBook) {
super(player, SkillType.SALVAGE);
this.salvageItem = salvageItem;
this.salvageResults = salvageResults;
this.enchantedBook = enchantedBook;
this.cancelled = false;
}
/**
* @return The item that should get salvaged.
*/
public ItemStack getSalvageItem() {
return salvageItem;
}
/**
* @return The results that should be dropped after salvaging.
*/
public ItemStack getSalvageResults() {
return salvageResults;
}
/**
* @return The enchanted book that should drop after salvaging or null if no book should be dropped.
*/
public ItemStack getEnchantedBook() {
return enchantedBook;
}
/** Following are required for Cancellable **/
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}

View File

@@ -1,5 +1,28 @@
package com.gmail.nossr50.listeners;
import java.util.List;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.BrewingStand;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -8,7 +31,8 @@ import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.events.fake.FakeBlockDamageEvent;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.PistonTrackerTask;
import com.gmail.nossr50.runnables.StickyPistonTrackerTask;
import com.gmail.nossr50.skills.alchemy.Alchemy;
import com.gmail.nossr50.skills.excavation.ExcavationManager;
import com.gmail.nossr50.skills.herbalism.Herbalism;
@@ -18,27 +42,13 @@ import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.salvage.Salvage;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.skills.woodcutting.WoodcuttingManager;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.BrewingStand;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import java.util.List;
public class BlockListener implements Listener {
private final mcMMO plugin;
@@ -54,16 +64,27 @@ public class BlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
BlockFace direction = event.getDirection();
Block movedBlock = event.getBlock();
movedBlock = movedBlock.getRelative(direction, 2);
if (!EventUtils.shouldProcessEvent(event.getBlock(), true)) {
return;
}
for (Block b : event.getBlocks()) {
BlockFace direction = event.getDirection();
Block futureEmptyBlock = event.getBlock().getRelative(direction); // Block that would be air after piston is finished
if (futureEmptyBlock.getType() == Material.AIR) {
return;
}
List<Block> blocks = event.getBlocks();
for (Block b : blocks) {
if (BlockUtils.shouldBeWatched(b.getState()) && mcMMO.getPlaceStore().isTrue(b)) {
movedBlock = b.getRelative(direction);
mcMMO.getPlaceStore().setTrue(movedBlock);
b.getRelative(direction).setMetadata(mcMMO.blockMetadataKey, mcMMO.metadataValue);
}
}
// Needed because blocks sometimes don't move when two pistons push towards each other
new PistonTrackerTask(blocks, direction, futureEmptyBlock).runTaskLater(plugin, 2);
}
/**
@@ -73,43 +94,18 @@ public class BlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
// Get opposite direction so we get correct block
BlockFace direction = event.getDirection();
Block movedBlock = event.getBlock().getRelative(direction);
mcMMO.getPlaceStore().setTrue(movedBlock);
for (Block block : event.getBlocks()) {
movedBlock = block.getRelative(direction);
mcMMO.getPlaceStore().setTrue(movedBlock);
if (!EventUtils.shouldProcessEvent(event.getBlock(), false)) {
return;
}
}
/**
* Monitor falling blocks.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onFallingBlock(EntityChangeBlockEvent event) {
if (BlockUtils.shouldBeWatched(event.getBlock().getState()) && event.getEntityType().equals(EntityType.FALLING_BLOCK)) {
if (event.getTo().equals(Material.AIR) && mcMMO.getPlaceStore().isTrue(event.getBlock())) {
event.getEntity().setMetadata("mcMMOBlockFall", new FixedMetadataValue( plugin, event.getBlock().getLocation()));
} else {
List<MetadataValue> values = event.getEntity().getMetadata( "mcMMOBlockFall" );
if (!values.isEmpty()) {
if (values.get(0).value() == null) return;
Block spawn = ((org.bukkit.Location) values.get(0).value()).getBlock();
mcMMO.getPlaceStore().setTrue( event.getBlock() );
mcMMO.getPlaceStore().setFalse( spawn );
}
}
if (!event.isSticky()) {
return;
}
Block movedBlock = event.getRetractLocation().getBlock();
// Needed only because under some circumstances Minecraft doesn't move the block
new StickyPistonTrackerTask(event.getDirection(), event.getBlock(), movedBlock).runTaskLater(plugin, 2);
}
/**
@@ -128,10 +124,8 @@ public class BlockListener implements Listener {
BlockState blockState = event.getBlock().getState();
/* Check if the blocks placed should be monitored so they do not give out XP in the future */
if (BlockUtils.shouldBeWatched(blockState) && blockState.getType() != Material.CHORUS_FLOWER) {
// Don't count de-barking wood
if (!Tag.LOGS.isTagged(event.getBlockReplacedState().getType()) || !Tag.LOGS.isTagged(event.getBlockPlaced().getType()))
mcMMO.getPlaceStore().setTrue(blockState);
if (BlockUtils.shouldBeWatched(blockState)) {
mcMMO.getPlaceStore().setTrue(blockState);
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
@@ -144,18 +138,6 @@ public class BlockListener implements Listener {
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event)
{
BlockState blockState = event.getBlock().getState();
if (!BlockUtils.shouldBeWatched(blockState)) {
return;
}
mcMMO.getPlaceStore().setFalse(blockState);
}
/**
* Monitor BlockBreak events.
*
@@ -186,7 +168,7 @@ public class BlockListener implements Listener {
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
/* HERBALISM */
if (BlockUtils.affectedByGreenTerra(blockState)) {
@@ -215,6 +197,7 @@ public class BlockListener implements Listener {
/* WOOD CUTTING */
else if (BlockUtils.isLog(blockState) && ItemUtils.isAxe(heldItem) && SkillType.WOODCUTTING.getPermissions(player) && !mcMMO.getPlaceStore().isTrue(blockState)) {
WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager();
if (woodcuttingManager.canUseTreeFeller(heldItem)) {
woodcuttingManager.processTreeFeller(blockState);
}
@@ -255,7 +238,7 @@ public class BlockListener implements Listener {
}
BlockState blockState = event.getBlock().getState();
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
if (Herbalism.isRecentlyRegrown(blockState)) {
event.setCancelled(true);
@@ -277,7 +260,7 @@ public class BlockListener implements Listener {
}
}
}
else if (ItemUtils.isFluxPickaxe(heldItem) && !heldItem.containsEnchantment(Enchantment.SILK_TOUCH)) {
else if (ItemUtils.isPickaxe(heldItem) && !heldItem.containsEnchantment(Enchantment.SILK_TOUCH)) {
SmeltingManager smeltingManager = UserManager.getPlayer(player).getSmeltingManager();
if (smeltingManager.canUseFluxMining(blockState)) {
@@ -315,7 +298,7 @@ public class BlockListener implements Listener {
* We check permissions here before processing activation.
*/
if (BlockUtils.canActivateAbilities(blockState)) {
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
if (HiddenConfig.getInstance().useEnchantmentBuffs()) {
if ((ItemUtils.isPickaxe(heldItem) && !mcMMOPlayer.getAbilityMode(AbilityType.SUPER_BREAKER)) || (ItemUtils.isShovel(heldItem) && !mcMMOPlayer.getAbilityMode(AbilityType.GIGA_DRILL_BREAKER))) {
@@ -351,7 +334,7 @@ public class BlockListener implements Listener {
* We don't need to check permissions here because they've already been checked for the ability to even activate.
*/
if (mcMMOPlayer.getAbilityMode(AbilityType.TREE_FELLER) && BlockUtils.isLog(blockState) && Config.getInstance().getTreeFellerSoundsEnabled()) {
player.playSound(blockState.getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, Misc.FIZZ_VOLUME, Misc.getFizzPitch());
player.playSound(blockState.getLocation(), Sound.FIZZ, Misc.FIZZ_VOLUME, Misc.getFizzPitch());
}
}
@@ -373,7 +356,7 @@ public class BlockListener implements Listener {
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
Block block = event.getBlock();
BlockState blockState = block.getState();
@@ -390,7 +373,7 @@ public class BlockListener implements Listener {
else if (mcMMOPlayer.getAbilityMode(AbilityType.BERSERK) && heldItem.getType() == Material.AIR) {
if (AbilityType.BERSERK.blockCheck(block.getState()) && EventUtils.simulateBlockBreak(block, player, true)) {
event.setInstaBreak(true);
player.playSound(block.getLocation(), Sound.ENTITY_ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
player.playSound(block.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
}
else if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState) && EventUtils.simulateBlockBreak(block, player, true)) {
if (mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) {
@@ -400,7 +383,7 @@ public class BlockListener implements Listener {
}
else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isLeaves(blockState) && EventUtils.simulateBlockBreak(block, player, true)) {
event.setInstaBreak(true);
player.playSound(blockState.getLocation(), Sound.ENTITY_ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
player.playSound(blockState.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
}
}
}

View File

@@ -1,5 +1,45 @@
package com.gmail.nossr50.listeners;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -7,7 +47,6 @@ import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageEvent;
import com.gmail.nossr50.events.fake.FakeEntityTameEvent;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.skills.BleedTimerTask;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
@@ -24,23 +63,6 @@ import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
public class EntityListener implements Listener {
private final mcMMO plugin;
@@ -82,15 +104,13 @@ public class EntityListener implements Listener {
/**
* Monitor EntityChangeBlock events.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Block block = event.getBlock();
// When the event is fired for the falling block that changes back to a
// normal block
// When the event is fired for the falling block that changes back to a normal block
// event.getBlock().getType() returns AIR
if (!BlockUtils.shouldBeWatched(block.getState()) && block.getType() != Material.AIR) {
return;
@@ -108,7 +128,8 @@ public class EntityListener implements Listener {
else if (isTracked) {
mcMMO.getPlaceStore().setTrue(block);
}
} else if ((block.getType() == Material.REDSTONE_ORE)) {
}
else if ((block.getType() == Material.REDSTONE_ORE || block.getType() == Material.GLOWING_REDSTONE_ORE) && (event.getTo() == Material.REDSTONE_ORE || event.getTo() == Material.GLOWING_REDSTONE_ORE)) {
return;
}
else {
@@ -121,8 +142,7 @@ public class EntityListener implements Listener {
/**
* Handle EntityDamageByEntity events that involve modifying the event.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
@@ -130,35 +150,13 @@ public class EntityListener implements Listener {
return;
}
if (event.getEntity() instanceof ArmorStand) {
return;
}
if (event.getDamager().hasMetadata(mcMMO.funfettiMetadataKey))
{
event.setCancelled(true);
return;
}
double damage = event.getFinalDamage();
Entity defender = event.getEntity();
Entity attacker = event.getDamager();
if (damage <= 0) {
if (defender instanceof Player && attacker instanceof Player) {
Player defendingPlayer = (Player) defender;
Player attackingPlayer = (Player) attacker;
if (event.getDamage(DamageModifier.ABSORPTION) > 0) {
if ((PartyManager.inSameParty(defendingPlayer, attackingPlayer) || PartyManager.areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) && Permissions.friendlyFire(defendingPlayer))) {
event.setCancelled(true);
return;
}
}
}
return;
}
Entity defender = event.getEntity();
if (defender.hasMetadata(mcMMO.customDamageKey)) {
defender.removeMetadata(mcMMO.customDamageKey, plugin);
@@ -175,7 +173,7 @@ public class EntityListener implements Listener {
return;
}
Entity attacker = event.getDamager();
if (Misc.isNPCEntity(attacker)) {
return;
@@ -209,8 +207,7 @@ public class EntityListener implements Listener {
return;
}
// We want to make sure we're not gaining XP or applying abilities
// when we hit ourselves
// We want to make sure we're not gaining XP or applying abilities when we hit ourselves
if (defendingPlayer.equals(attackingPlayer)) {
return;
}
@@ -228,8 +225,7 @@ public class EntityListener implements Listener {
/**
* Handle EntityDamage events that involve modifying the event.
*
* @param event
* The event to modify
* @param event The event to modify
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
@@ -375,8 +371,7 @@ public class EntityListener implements Listener {
/**
* Monitor EntityDeath events.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDeathLowest(EntityDeathEvent event) {
@@ -395,17 +390,12 @@ public class EntityListener implements Listener {
entity.setCustomNameVisible(entity.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean());
entity.removeMetadata(mcMMO.customVisibleKey, plugin);
}
if (entity.hasMetadata(mcMMO.entityMetadataKey)) {
entity.removeMetadata(mcMMO.entityMetadataKey, plugin);
}
}
/**
* Monitor EntityDeath events.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDeath(EntityDeathEvent event) {
@@ -422,30 +412,23 @@ public class EntityListener implements Listener {
/**
* Monitor CreatureSpawn events.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
LivingEntity entity = event.getEntity();
switch (event.getSpawnReason()) {
case NETHER_PORTAL:
case SPAWNER:
case SPAWNER_EGG:
entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
LivingEntity entity = event.getEntity();
Entity passenger = entity.getPassenger();
entity.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
if (passenger != null) {
passenger.setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
}
return;
case BREEDING:
entity.setMetadata(mcMMO.bredMetadataKey, mcMMO.metadataValue);
return;
default:
return;
}
@@ -454,8 +437,7 @@ public class EntityListener implements Listener {
/**
* Handle ExplosionPrime events that involve modifying the event.
*
* @param event
* The event to modify
* @param event The event to modify
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
@@ -465,8 +447,7 @@ public class EntityListener implements Listener {
return;
}
// We can make this assumption because we (should) be the only ones
// using this exact metadata
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayerExact(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
if (!UserManager.hasPlayerDataKey(player)) {
@@ -483,8 +464,7 @@ public class EntityListener implements Listener {
/**
* Handle EntityExplode events that involve modifying the event.
*
* @param event
* The event to modify
* @param event The event to modify
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEnitityExplode(EntityExplodeEvent event) {
@@ -494,8 +474,7 @@ public class EntityListener implements Listener {
return;
}
// We can make this assumption because we (should) be the only ones
// using this exact metadata
// We can make this assumption because we (should) be the only ones using this exact metadata
Player player = plugin.getServer().getPlayerExact(entity.getMetadata(mcMMO.tntMetadataKey).get(0).asString());
if (!UserManager.hasPlayerDataKey(player)) {
@@ -513,8 +492,7 @@ public class EntityListener implements Listener {
/**
* Handle EntityExplode events that involve modifying the event.
*
* @param event
* The event to modify
* @param event The event to modify
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onEntityExplodeMonitor(EntityExplodeEvent event) {
@@ -530,8 +508,7 @@ public class EntityListener implements Listener {
/**
* Handle FoodLevelChange events that involve modifying the event.
*
* @param event
* The event to modify
* @param event The event to modify
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
@@ -556,60 +533,39 @@ public class EntityListener implements Listener {
}
/*
* Some foods have 3 ranks Some foods have 5 ranks The number of ranks
* is based on how 'common' the item is We can adjust this quite easily
* if we find something is giving too much of a bonus
* Some foods have 3 ranks
* Some foods have 5 ranks
* The number of ranks is based on how 'common' the item is
* We can adjust this quite easily if we find something is giving too much of a bonus
*/
switch (player.getInventory().getItemInMainHand().getType()) {
case BAKED_POTATO: /*
* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @
* 1000
*/
case BEETROOT:
case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
case CARROT: /*
* RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @
* 1000
*/
case GOLDEN_CARROT: /*
* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @
* 1000
*/
case MUSHROOM_STEW: /*
* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @
* 1000
*/
case PUMPKIN_PIE: /*
* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @
* 1000
*/
switch (player.getItemInHand().getType()) {
case BAKED_POTATO: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
case CARROT_ITEM: /* RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ 1000 */
case GOLDEN_CARROT: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */
case MUSHROOM_SOUP: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
case PUMPKIN_PIE: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */
if (Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FARMERS_DIET)) {
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel1, newFoodLevel));
}
return;
case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
case MELON_SLICE: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case POISONOUS_POTATO: /*
* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER
* @ 1000
*/
case POTATO: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
case MELON: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case POISONOUS_POTATO: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case POTATO_ITEM: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */
if (Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FARMERS_DIET)) {
event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(Herbalism.farmersDietRankLevel2, newFoodLevel));
}
return;
case COOKED_SALMON: /*
* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @
* 1000
*/
case COOKED_FISH: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */
if (Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FISHERMANS_DIET)) {
event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel1, newFoodLevel));
}
return;
case SALMON: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
case RAW_FISH: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */
if (Permissions.secondaryAbilityEnabled(player, SecondaryAbility.FISHERMANS_DIET)) {
event.setFoodLevel(UserManager.getPlayer(player).getFishingManager().handleFishermanDiet(Fishing.fishermansDietRankLevel2, newFoodLevel));
}
@@ -623,8 +579,7 @@ public class EntityListener implements Listener {
/**
* Monitor EntityTame events.
*
* @param event
* The event to watch
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityTame(EntityTameEvent event) {
@@ -646,8 +601,7 @@ public class EntityListener implements Listener {
/**
* Handle EntityTarget events.
*
* @param event
* The event to process
* @param event The event to process
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityTarget(EntityTargetEvent event) {
@@ -665,8 +619,7 @@ public class EntityListener implements Listener {
return;
}
// isFriendlyPet ensures that the Tameable is: Tamed, owned by a player,
// and the owner is in the same party
// isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party
// So we can make some assumptions here, about our casting and our check
if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire((Player) tameable.getOwner()))) {
event.setCancelled(true);
@@ -674,11 +627,9 @@ public class EntityListener implements Listener {
}
/**
* Handle PotionSplash events in order to fix broken Splash Potion of
* Saturation.
* Handle PotionSplash events in order to fix broken Splash Potion of Saturation.
*
* @param event
* The event to process
* @param event The event to process
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
@@ -693,11 +644,4 @@ public class EntityListener implements Listener {
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPigZapEvent(PigZapEvent event) {
if (event.getEntity().hasMetadata(mcMMO.entityMetadataKey)) {
event.getPigZombie().setMetadata(mcMMO.entityMetadataKey, mcMMO.metadataValue);
}
}
}

View File

@@ -2,9 +2,6 @@ package com.gmail.nossr50.listeners;
import java.util.List;
import com.gmail.nossr50.events.fake.FakeBrewEvent;
import com.gmail.nossr50.skills.alchemy.AlchemyManager;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@@ -15,7 +12,17 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceExtractEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.BrewerInventory;
import org.bukkit.inventory.FurnaceInventory;
import org.bukkit.inventory.Inventory;
@@ -116,8 +123,10 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onFurnaceExtractEvent(FurnaceExtractEvent event) {
Block furnaceBlock = event.getBlock();
BlockState furnaceState = furnaceBlock.getState();
ItemStack result = furnaceState instanceof Furnace ? ((Furnace) furnaceState).getInventory().getResult() : null;
if (!ItemUtils.isSmelted(new ItemStack(event.getItemType(), event.getItemAmount()))) {
if (!ItemUtils.isSmelted(result)) {
return;
}
@@ -127,8 +136,7 @@ public class InventoryListener implements Listener {
return;
}
int exp = UserManager.getPlayer(player).getSmeltingManager().vanillaXPBoost(event.getExpToDrop());
event.setExpToDrop(exp);
event.setExpToDrop(UserManager.getPlayer(player).getSmeltingManager().vanillaXPBoost(event.getExpToDrop()));
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@@ -156,7 +164,7 @@ public class InventoryListener implements Listener {
ItemStack clicked = event.getCurrentItem();
ItemStack cursor = event.getCursor();
if ((clicked != null && (clicked.getType() == Material.POTION || clicked.getType() == Material.SPLASH_POTION || clicked.getType() == Material.LINGERING_POTION)) || (cursor != null && (cursor.getType() == Material.POTION || cursor.getType() == Material.SPLASH_POTION || cursor.getType() == Material.LINGERING_POTION))) {
if ((clicked != null && clicked.getType() == Material.POTION) || (cursor != null && cursor.getType() == Material.POTION)) {
AlchemyPotionBrewer.scheduleCheck(player, stand);
return;
}
@@ -271,19 +279,6 @@ public class InventoryListener implements Listener {
}
}
// Apparently sometimes vanilla brewing beats our task listener to the actual brew. We handle this by cancelling the vanilla event and finishing our brew ourselves.
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBrew(BrewEvent event)
{
if (event instanceof FakeBrewEvent)
return;
Location location = event.getBlock().getLocation();
if (Alchemy.brewingStandMap.containsKey(location)) {
Alchemy.brewingStandMap.get(location).finishImmediately();
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {
Inventory inventory = event.getDestination();
@@ -300,12 +295,12 @@ public class InventoryListener implements Listener {
ItemStack item = event.getItem();
if (Config.getInstance().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) {
if (Config.getInstance().getPreventHopperTransferIngredients() && item.getType() != Material.POTION) {
event.setCancelled(true);
return;
}
if (Config.getInstance().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) {
if (Config.getInstance().getPreventHopperTransferBottles() && item.getType() == Material.POTION) {
event.setCancelled(true);
return;
}
@@ -318,14 +313,6 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClickEvent(InventoryClickEvent event) {
SkillUtils.removeAbilityBuff(event.getCurrentItem());
if (event.getAction() == InventoryAction.HOTBAR_SWAP) {
SkillUtils.removeAbilityBuff(event.getWhoClicked().getInventory().getItem(event.getHotbarButton()));
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpenEvent(InventoryOpenEvent event) {
SkillUtils.removeAbilityBuff(event.getPlayer().getInventory().getItemInMainHand());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)

View File

@@ -1,5 +1,34 @@
package com.gmail.nossr50.listeners;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerStatisticIncrementEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.chat.ChatManagerFactory;
import com.gmail.nossr50.chat.PartyChatManager;
@@ -11,9 +40,9 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.runnables.player.PlayerProfileLoadingTask;
import com.gmail.nossr50.runnables.skills.BleedTimerTask;
import com.gmail.nossr50.skills.fishing.FishingManager;
import com.gmail.nossr50.skills.herbalism.HerbalismManager;
import com.gmail.nossr50.skills.mining.MiningManager;
@@ -23,22 +52,18 @@ import com.gmail.nossr50.skills.salvage.Salvage;
import com.gmail.nossr50.skills.salvage.SalvageManager;
import com.gmail.nossr50.skills.taming.TamingManager;
import com.gmail.nossr50.skills.unarmed.Unarmed;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.ChimaeraWing;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.HardcoreManager;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.MobHealthbarUtils;
import com.gmail.nossr50.util.Motd;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
public class PlayerListener implements Listener {
private final mcMMO plugin;
@@ -198,16 +223,13 @@ public class PlayerListener implements Listener {
event.setCancelled(fishingManager.exploitPrevention());
}
return;
case CAUGHT_FISH:
//TODO Update to new API once available! Waiting for case CAUGHT_TREASURE:
Item fishingCatch = (Item) event.getCaught();
if (Config.getInstance().getFishingOverrideTreasures() &&
fishingCatch.getItemStack().getType() != Material.SALMON &&
fishingCatch.getItemStack().getType() != Material.COD &&
fishingCatch.getItemStack().getType() != Material.TROPICAL_FISH &&
fishingCatch.getItemStack().getType() != Material.PUFFERFISH) {
fishingCatch.setItemStack(new ItemStack(Material.SALMON, 1));
if (Config.getInstance().getFishingOverrideTreasures() && fishingCatch.getItemStack().getType() != Material.RAW_FISH) {
fishingCatch.setItemStack(new ItemStack(Material.RAW_FISH, 1));
}
if (Permissions.vanillaXpBoost(player, SkillType.FISHING)) {
@@ -303,18 +325,18 @@ public class PlayerListener implements Listener {
event.setCancelled(ShareHandler.handleItemShare(drop, mcMMOPlayer));
if (event.isCancelled()) {
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
player.playSound(player.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
return;
}
}
if ((mcMMOPlayer.isUsingUnarmed() && ItemUtils.isSharable(dropStack) && !Config.getInstance().getUnarmedItemsAsUnarmed()) || mcMMOPlayer.getAbilityMode(AbilityType.BERSERK)) {
if ((mcMMOPlayer.isUsingUnarmed() && ItemUtils.isSharable(dropStack)) || mcMMOPlayer.getAbilityMode(AbilityType.BERSERK)) {
boolean pickupSuccess = Unarmed.handleItemPickup(player.getInventory(), drop);
boolean cancel = Config.getInstance().getUnarmedItemPickupDisabled() || pickupSuccess;
event.setCancelled(cancel);
if (pickupSuccess) {
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
player.playSound(player.getLocation(), Sound.ITEM_PICKUP, Misc.POP_VOLUME, Misc.getPopPitch());
player.updateInventory();
return;
}
@@ -339,7 +361,16 @@ public class PlayerListener implements Listener {
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
mcMMOPlayer.logout(false);
mcMMOPlayer.resetAbilityMode();
BleedTimerTask.bleedOut(player);
mcMMOPlayer.getProfile().scheduleAsyncSave();
UserManager.remove(player);
ScoreboardManager.teardownPlayer(player);
if (mcMMOPlayer.inParty()) {
mcMMOPlayer.logoutParty();
}
}
/**
@@ -368,6 +399,11 @@ public class PlayerListener implements Listener {
if (plugin.isXPEventEnabled()) {
player.sendMessage(LocaleLoader.getString("XPRate.Event", ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()));
}
if (Permissions.updateNotifications(player) && plugin.isUpdateAvailable()) {
player.sendMessage(LocaleLoader.getString("UpdateChecker.Outdated"));
player.sendMessage(LocaleLoader.getString("UpdateChecker.NewAvailable"));
}
}
/**
@@ -399,14 +435,14 @@ public class PlayerListener implements Listener {
public void onPlayerInteractLowest(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) {
if (!UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) {
return;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
MiningManager miningManager = mcMMOPlayer.getMiningManager();
Block block = event.getClickedBlock();
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
switch (event.getAction()) {
case RIGHT_CLICK_BLOCK:
@@ -452,7 +488,7 @@ public class PlayerListener implements Listener {
case LEFT_CLICK_BLOCK:
type = block.getType();
if (!Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() || player.isSneaking()) {
if ((Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && player.isSneaking()) || !Config.getInstance().getAbilitiesOnlyActivateWhenSneaking()) {
/* REPAIR CHECKS */
if (type == Repair.anvilMaterial && SkillType.REPAIR.getPermissions(player) && mcMMO.getRepairableManager().isRepairable(heldItem)) {
RepairManager repairManager = mcMMOPlayer.getRepairManager();
@@ -491,19 +527,15 @@ public class PlayerListener implements Listener {
public void onPlayerInteractMonitor(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) {
if (!UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) {
return;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
switch (event.getAction()) {
case RIGHT_CLICK_BLOCK:
if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) {
break;
}
Block block = event.getClickedBlock();
BlockState blockState = block.getState();
@@ -528,20 +560,8 @@ public class PlayerListener implements Listener {
/* GREEN THUMB CHECK */
HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager();
if (heldItem.getType() == Material.BONE_MEAL) {
switch (blockState.getType()) {
case BEETROOTS:
case CARROT:
case COCOA:
case WHEAT:
case NETHER_WART_BLOCK:
case POTATO:
mcMMO.getPlaceStore().setFalse(blockState);
}
}
if (herbalismManager.canGreenThumbBlock(blockState)) {
player.getInventory().setItemInMainHand(new ItemStack(Material.WHEAT_SEEDS, heldItem.getAmount() - 1));
player.setItemInHand(new ItemStack(Material.SEEDS, heldItem.getAmount() - 1));
if (herbalismManager.processGreenThumbBlocks(blockState) && EventUtils.simulateBlockBreak(block, player, false)) {
blockState.update(true);
@@ -550,7 +570,6 @@ public class PlayerListener implements Listener {
/* SHROOM THUMB CHECK */
else if (herbalismManager.canUseShroomThumb(blockState)) {
event.setCancelled(true);
if (herbalismManager.processShroomThumb(blockState) && EventUtils.simulateBlockBreak(block, player, false)) {
blockState.update(true);
}
@@ -558,10 +577,7 @@ public class PlayerListener implements Listener {
break;
case RIGHT_CLICK_AIR:
if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) {
break;
}
/* ACTIVATION CHECKS */
if (Config.getInstance().getAbilitiesEnabled()) {
mcMMOPlayer.processAbilityActivation(SkillType.AXES);

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.listeners;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -45,10 +44,9 @@ public class SelfListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerXpGain(McMMOPlayerXpGainEvent event) {
if (event.getXpGainReason() == XPGainReason.COMMAND)
return;
SkillType skillType = event.getSkill();
int threshold = ExperienceConfig.getInstance().getDiminishedReturnsThreshold(skillType);
if (threshold <= 0 || !ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) {
// Diminished returns is turned off
return;

View File

@@ -57,7 +57,7 @@ public final class LocaleLoader {
public static String formatString(String string, Object... messageArguments) {
if (messageArguments != null) {
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(string.replace("'", "''"));
formatter.applyPattern(string);
string = formatter.format(messageArguments);
}

View File

@@ -1,5 +1,16 @@
package com.gmail.nossr50;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
@@ -14,10 +25,17 @@ import com.gmail.nossr50.config.skills.salvage.SalvageConfigManager;
import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.database.DatabaseManager;
import com.gmail.nossr50.database.DatabaseManagerFactory;
import com.gmail.nossr50.listeners.*;
import com.gmail.nossr50.listeners.BlockListener;
import com.gmail.nossr50.listeners.EntityListener;
import com.gmail.nossr50.listeners.InventoryListener;
import com.gmail.nossr50.listeners.PlayerListener;
import com.gmail.nossr50.listeners.SelfListener;
import com.gmail.nossr50.listeners.WorldListener;
import com.gmail.nossr50.metrics.MetricsManager;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.CheckDateTask;
import com.gmail.nossr50.runnables.SaveTimerTask;
import com.gmail.nossr50.runnables.UpdaterResultAsyncTask;
import com.gmail.nossr50.runnables.backups.CleanBackupsTask;
import com.gmail.nossr50.runnables.database.UserPurgeTask;
import com.gmail.nossr50.runnables.party.PartyAutoKickTask;
@@ -33,8 +51,12 @@ import com.gmail.nossr50.skills.repair.repairables.SimpleRepairableManager;
import com.gmail.nossr50.skills.salvage.salvageables.Salvageable;
import com.gmail.nossr50.skills.salvage.salvageables.SalvageableManager;
import com.gmail.nossr50.skills.salvage.salvageables.SimpleSalvageableManager;
import com.gmail.nossr50.skills.smelting.SmeltingManager;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.ChimaeraWing;
import com.gmail.nossr50.util.HolidayManager;
import com.gmail.nossr50.util.LogFilter;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.ModManager;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManager;
import com.gmail.nossr50.util.blockmeta.chunkmeta.ChunkManagerFactory;
import com.gmail.nossr50.util.commands.CommandRegistrationManager;
@@ -42,22 +64,8 @@ import com.gmail.nossr50.util.experience.FormulaManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.upgrade.UpgradeManager;
import com.google.common.base.Charsets;
import net.shatteredlands.shatt.backup.ZipLibrary;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import net.shatteredlands.shatt.backup.ZipLibrary;
public class mcMMO extends JavaPlugin {
/* Managers */
@@ -81,6 +89,9 @@ public class mcMMO extends JavaPlugin {
// Jar Stuff
public static File mcmmo;
// Update Check
private boolean updateAvailable;
/* Plugin Checks */
private static boolean healthBarPluginEnabled;
@@ -95,7 +106,6 @@ public class mcMMO extends JavaPlugin {
public final static String blockMetadataKey = "mcMMO: Piston Tracking";
public final static String furnaceMetadataKey = "mcMMO: Tracked Furnace";
public final static String tntMetadataKey = "mcMMO: Tracked TNT";
public final static String funfettiMetadataKey = "mcMMO: Funfetti";
public final static String tntsafeMetadataKey = "mcMMO: Safe TNT";
public final static String customNameKey = "mcMMO: Custom Name";
public final static String customVisibleKey = "mcMMO: Name Visibility";
@@ -107,8 +117,8 @@ public class mcMMO extends JavaPlugin {
public final static String disarmedItemKey = "mcMMO: Disarmed Item";
public final static String playerDataKey = "mcMMO: Player Data";
public final static String greenThumbDataKey = "mcMMO: Green Thumb";
public final static String pistonDataKey = "mcMMO: Piston State";
public final static String databaseCommandKey = "mcMMO: Processing Database Command";
public final static String bredMetadataKey = "mcMMO: Bred Animal";
public static FixedMetadataValue metadataValue;
@@ -169,8 +179,12 @@ public class mcMMO extends JavaPlugin {
scheduleTasks();
CommandRegistrationManager.registerCommands();
MetricsManager.setup();
placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager
checkForUpdates();
if (Config.getInstance().getPTPCommandWorldPermissions()) {
Permissions.generateWorldTeleportPermissions();
}
@@ -251,6 +265,14 @@ public class mcMMO extends JavaPlugin {
return modDirectory;
}
public boolean isUpdateAvailable() {
return updateAvailable;
}
public void setUpdateAvailable(boolean available) {
this.updateAvailable = available;
}
public boolean isXPEventEnabled() {
return xpEventEnabled;
}
@@ -369,6 +391,14 @@ public class mcMMO extends JavaPlugin {
currentFlatfilePath.mkdirs();
}
private void checkForUpdates() {
if (!Config.getInstance().getUpdateCheckEnabled()) {
return;
}
new UpdaterResultAsyncTask(this).runTaskAsynchronously(mcMMO.p);
}
private void loadConfigFiles() {
// Force the loading of config files
TreasureConfig.getInstance();
@@ -422,19 +452,9 @@ public class mcMMO extends JavaPlugin {
}
private void registerCustomRecipes() {
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> {
if (Config.getInstance().getChimaeraEnabled()) {
getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe());
}
if (Config.getInstance().getFluxPickaxeEnabled()) {
getServer().addRecipe(SmeltingManager.getFluxPickaxeRecipe(Material.DIAMOND_PICKAXE));
getServer().addRecipe(SmeltingManager.getFluxPickaxeRecipe(Material.GOLDEN_PICKAXE));
getServer().addRecipe(SmeltingManager.getFluxPickaxeRecipe(Material.IRON_PICKAXE));
getServer().addRecipe(SmeltingManager.getFluxPickaxeRecipe(Material.STONE_PICKAXE));
getServer().addRecipe(SmeltingManager.getFluxPickaxeRecipe(Material.WOODEN_PICKAXE));
}
}, 40);
if (Config.getInstance().getChimaeraEnabled()) {
getServer().addRecipe(ChimaeraWing.getChimaeraWingRecipe());
}
}
private void scheduleTasks() {
@@ -502,9 +522,4 @@ public class mcMMO extends JavaPlugin {
getLogger().info("To enable, set Mods.Entity_Mods_Enabled to TRUE in config.yml.");
}
}
public InputStreamReader getResourceAsReader(String fileName) {
InputStream in = getResource(fileName);
return in == null ? null : new InputStreamReader(in, Charsets.UTF_8);
}
}

View File

@@ -0,0 +1,353 @@
package com.gmail.nossr50.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.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
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.data.DataEvent;
import com.turt2live.metrics.data.DataTracker;
import com.turt2live.metrics.tracker.Tracker;
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;
}
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;
}
});
// ExperienceFormulaShape Graph
Graph experienceFormulaShapeGraph = metrics.createGraph("Experience Formula Shape Graph");
experienceFormulaShapeGraph.addPlotter(new Metrics.Plotter(ExperienceConfig.getInstance().getFormulaType().toString()) {
@Override
public int getValue() {
return 1;
}
});
// GlobalMultiplier Graph
Graph globalMultiplierGraph = metrics.createGraph("Global Multiplier Graph");
globalMultiplierGraph.addPlotter(new Metrics.Plotter(ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier() + "") {
@Override
public int getValue() {
return 1;
}
});
// GlobalCurveModifier Graph
Graph globalCurveModifierGraph = metrics.createGraph("Global Curve Modifier Graph");
globalCurveModifierGraph.addPlotter(new Metrics.Plotter(ExperienceConfig.getInstance().getMultiplier(FormulaType.LINEAR) + "") {
@Override
public int getValue() {
return 1;
}
});
// GlobalMultiplierGraph Fuzzy Logic Numbers
Graph globalMultiplierGraphFuzzy = metrics.createGraph("Global Multiplier Fuzz");
if (ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier() > 1.0) {
globalMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Higher") {
@Override
public int getValue() {
return 1;
}
});
}
else if (ExperienceConfig.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 (ExperienceConfig.getInstance().getMultiplier(FormulaType.LINEAR) > 20.0) {
globalCurveMultiplierGraphFuzzy.addPlotter(new Metrics.Plotter("Higher") {
@Override
public int getValue() {
return 1;
}
});
}
else if (ExperienceConfig.getInstance().getMultiplier(FormulaType.LINEAR) < 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,5 +1,18 @@
package com.gmail.nossr50.party;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.chat.ChatMode;
import com.gmail.nossr50.datatypes.database.UpgradeType;
@@ -13,20 +26,8 @@ import com.gmail.nossr50.events.party.McMMOPartyAllianceChangeEvent;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
public final class PartyManager {
private static String partiesFilePath = mcMMO.getFlatFileDirectory() + "parties.yml";
@@ -70,7 +71,9 @@ public final class PartyManager {
removeFromParty(mcMMOPlayer);
}
else return handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY);
else if (!handlePartyChangeEvent(player, null, newPartyName, EventReason.JOINED_PARTY)) {
return false;
}
return true;
}
@@ -726,7 +729,7 @@ public final class PartyManager {
member.sendMessage(LocaleLoader.getString("Party.LevelUp", levelsGained, level));
if (levelUpSoundsEnabled) {
member.playSound(member.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
member.playSound(member.getLocation(), Sound.LEVEL_UP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
}
}
}

View File

@@ -157,7 +157,7 @@ public final class ShareHandler {
private static void awardDrop(Player winningPlayer, ItemStack drop) {
if (winningPlayer.getInventory().addItem(drop).size() != 0) {
winningPlayer.getWorld().dropItem(winningPlayer.getLocation(), drop);
winningPlayer.getWorld().dropItemNaturally(winningPlayer.getLocation(), drop);
}
winningPlayer.updateInventory();

View File

@@ -20,7 +20,7 @@ public class StickyPistonTrackerTask extends BukkitRunnable {
@Override
public void run() {
if (!mcMMO.getPlaceStore().isTrue(movedBlock.getRelative(direction))) {
if (!mcMMO.getPlaceStore().isTrue(movedBlock)) {
return;
}
@@ -30,7 +30,7 @@ public class StickyPistonTrackerTask extends BukkitRunnable {
}
// The sticky piston actually pulled the block so move the PlaceStore data
mcMMO.getPlaceStore().setFalse(movedBlock.getRelative(direction));
mcMMO.getPlaceStore().setTrue(movedBlock);
mcMMO.getPlaceStore().setFalse(movedBlock);
mcMMO.getPlaceStore().setTrue(block.getRelative(direction));
}
}

View File

@@ -0,0 +1,36 @@
package com.gmail.nossr50.runnables;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.locale.LocaleLoader;
import net.gravitydevelopment.updater.mcmmo.Updater;
public class UpdaterResultAsyncTask extends BukkitRunnable {
private mcMMO plugin;
public UpdaterResultAsyncTask(mcMMO plugin) {
this.plugin = plugin;
}
@Override
public void run() {
Updater updater = new Updater(plugin, 31030, plugin.mcmmo, Updater.UpdateType.NO_DOWNLOAD, false);
if (updater.getResult() != Updater.UpdateResult.UPDATE_AVAILABLE) {
plugin.setUpdateAvailable(false);
return;
}
if (updater.getLatestType().equals("beta") && !Config.getInstance().getPreferBeta()) {
plugin.setUpdateAvailable(false);
return;
}
plugin.setUpdateAvailable(true);
plugin.getLogger().info(LocaleLoader.getString("UpdateChecker.Outdated"));
plugin.getLogger().info(LocaleLoader.getString("UpdateChecker.NewAvailable"));
}
}

View File

@@ -1,16 +1,17 @@
package com.gmail.nossr50.runnables.commands;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
/**
* Display the results of {@link MctopCommandAsyncTask} to the sender.
@@ -44,27 +45,15 @@ public class MctopCommandDisplayTask extends BukkitRunnable {
if (sender instanceof Player) {
((Player) sender).removeMetadata(mcMMO.databaseCommandKey, mcMMO.p);
}
if(sender instanceof Player)
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip"));
sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip"));
}
private void displayChat() {
if (skill == null) {
if(sender instanceof Player) {
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")));
}
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"));
}
else {
if(sender instanceof Player) {
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName()));
}
else {
sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName())));
}
sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName()));
}
int place = (page * 10) - 9;
@@ -73,13 +62,7 @@ public class MctopCommandDisplayTask extends BukkitRunnable {
// Format:
// 01. Playername - skill value
// 12. Playername - skill value
if(sender instanceof Player) {
sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal));
}
else {
sender.sendMessage(String.format("%2d. %s - %s", place, stat.name, stat.statVal));
}
sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal));
place++;
}
}

View File

@@ -20,7 +20,7 @@ public class UUIDUpdateAsyncTask extends BukkitRunnable {
private static final int MAX_LOOKUP = Math.max(HiddenConfig.getInstance().getUUIDConvertAmount(), 100);
private static final int RATE_LIMIT = HiddenConfig.getInstance().getMojangRateLimit();
private static final long LIMIT_PERIOD = HiddenConfig.getInstance().getMojangLimitPeriod();
private static final int BATCH_SIZE = MAX_LOOKUP * 3;
private static final int BATCH_SIZE = 5000;
private List<String> userNames;
private int size;
@@ -68,18 +68,6 @@ public class UUIDUpdateAsyncTask extends BukkitRunnable {
fetchedUUIDs.putAll(new UUIDFetcher(userNamesSection).call());
}
catch (Exception e) {
// Handle 429
if (e.getMessage().contains("429")) {
size += userNamesSection.size();
try {
Thread.sleep(LIMIT_PERIOD);
} catch (InterruptedException ex) {
e.printStackTrace();
return;
}
continue;
}
plugin.getLogger().log(Level.SEVERE, "Unable to fetch UUIDs!", e);
return;
}
@@ -89,7 +77,7 @@ public class UUIDUpdateAsyncTask extends BukkitRunnable {
size = userNames.size();
Misc.printProgress(checkedUsers, DatabaseManager.progressInterval, startMillis);
if (fetchedUUIDs.size() >= BATCH_SIZE) {
if (fetchedUUIDs.size() > BATCH_SIZE) {
mcMMO.getDatabaseManager().saveUserUUIDs(fetchedUUIDs);
fetchedUUIDs = new HashMap<String, UUID>();
}

View File

@@ -31,11 +31,10 @@ public class ChimaeraWingWarmup extends BukkitRunnable {
if (player.getLocation().distanceSquared(previousLocation) > 1.0 || !player.getInventory().containsAtLeast(ChimaeraWing.getChimaeraWing(0), 1)) {
player.sendMessage(LocaleLoader.getString("Teleport.Cancelled"));
mcMMOPlayer.setTeleportCommenceLocation(null);
return;
}
ItemStack inHand = player.getInventory().getItemInMainHand();
ItemStack inHand = player.getItemInHand();
if (!ItemUtils.isChimaeraWing(inHand) || inHand.getAmount() < Config.getInstance().getChimaeraUseCost()) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", LocaleLoader.getString("Item.ChimaeraWing.Name")));

View File

@@ -1,15 +1,16 @@
package com.gmail.nossr50.runnables.party;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader;
public class PartyChatTask extends BukkitRunnable {
private Plugin plugin;
@@ -45,6 +46,6 @@ public class PartyChatTask extends BukkitRunnable {
}
}
plugin.getServer().getConsoleSender().sendMessage(ChatColor.stripColor("[mcMMO] [P]<" + party.getName() + ">" + message));
plugin.getServer().getConsoleSender().sendMessage("[mcMMO] [P]<" + party.getName() + ">" + message);
}
}

View File

@@ -44,7 +44,7 @@ public class PlayerProfileLoadingTask extends BukkitRunnable {
PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), player.getUniqueId(), true);
// If successful, schedule the apply
if (profile.isLoaded()) {
new ApplySuccessfulProfile(new McMMOPlayer(player, profile)).runTask(mcMMO.p);
new ApplySuccessfulProfile(profile).runTask(mcMMO.p);
return;
}
@@ -59,10 +59,10 @@ public class PlayerProfileLoadingTask extends BukkitRunnable {
}
private class ApplySuccessfulProfile extends BukkitRunnable {
private final McMMOPlayer mcMMOPlayer;
private final PlayerProfile profile;
private ApplySuccessfulProfile(McMMOPlayer mcMMOPlayer) {
this.mcMMOPlayer = mcMMOPlayer;
private ApplySuccessfulProfile(PlayerProfile profile) {
this.profile = profile;
}
// Synchronized task
@@ -74,7 +74,7 @@ public class PlayerProfileLoadingTask extends BukkitRunnable {
return;
}
mcMMOPlayer.setupPartyData();
McMMOPlayer mcMMOPlayer = new McMMOPlayer(player, profile);
UserManager.track(mcMMOPlayer);
mcMMOPlayer.actualizeRespawnATS();
ScoreboardManager.setupPlayer(player);

View File

@@ -70,8 +70,8 @@ public class AbilityDisableTask extends BukkitRunnable {
int chunkX = chunk.getX();
int chunkZ = chunk.getZ();
for (int x = chunkX - radius; x <= chunkX + radius; x++) {
for (int z = chunkZ - radius; z <= chunkZ + radius; z++) {
for (int x = chunkX - radius; x < chunkX + radius; x++) {
for (int z = chunkZ - radius; z < chunkZ + radius; z++) {
world.refreshChunk(x, z);
}
}

View File

@@ -26,7 +26,7 @@ public class AlchemyBrewCheckTask extends BukkitRunnable {
public void run() {
Location location = brewingStand.getLocation();
ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4);
boolean validBrew = brewingStand.getFuelLevel() > 0 && AlchemyPotionBrewer.isValidBrew(player, newInventory);
boolean validBrew = AlchemyPotionBrewer.isValidBrew(player, newInventory);
if (Alchemy.brewingStandMap.containsKey(location)) {
if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) {

View File

@@ -27,8 +27,6 @@ public class AlchemyBrewTask extends BukkitRunnable {
private double brewSpeed;
private double brewTimer;
private Player player;
private int fuel;
private boolean firstRun = true;
public AlchemyBrewTask(BlockState brewingStand, Player player) {
this.brewingStand = brewingStand;
@@ -53,18 +51,13 @@ public class AlchemyBrewTask extends BukkitRunnable {
Alchemy.brewingStandMap.get(location).cancel();
}
fuel = ((BrewingStand) brewingStand).getFuelLevel();
if (((BrewingStand) brewingStand).getBrewingTime() == -1) // Only decrement on our end if it isn't a vanilla ingredient.
fuel--;
Alchemy.brewingStandMap.put(location, this);
this.runTaskTimer(mcMMO.p, 1, 1);
}
@Override
public void run() {
if (player == null || !player.isValid() || brewingStand == null || brewingStand.getType() != Material.BREWING_STAND || !AlchemyPotionBrewer.isValidIngredient(player, ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT])) {
if (player == null || !player.isValid() || brewingStand == null || brewingStand.getType() != Material.BREWING_STAND) {
if (Alchemy.brewingStandMap.containsKey(location)) {
Alchemy.brewingStandMap.remove(location);
}
@@ -74,11 +67,6 @@ public class AlchemyBrewTask extends BukkitRunnable {
return;
}
if (firstRun) {
firstRun = false;
((BrewingStand) brewingStand).setFuelLevel(fuel);
}
brewTimer -= brewSpeed;
// Vanilla potion brewing completes when BrewingTime == 1

View File

@@ -1,14 +1,15 @@
package com.gmail.nossr50.runnables.skills;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.HolidayManager;
import com.gmail.nossr50.util.Misc;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.HolidayManager;
import com.gmail.nossr50.util.Misc;
public class AprilTask extends BukkitRunnable {
@Override
@@ -22,7 +23,7 @@ public class AprilTask extends BukkitRunnable {
int random = Misc.getRandom().nextInt(40) + 11;
int betterRandom = Misc.getRandom().nextInt(2000);
if (betterRandom == 0) {
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
player.playSound(player.getLocation(), Sound.LEVEL_UP, Misc.LEVELUP_VOLUME, Misc.LEVELUP_PITCH);
player.sendMessage(unknown("superskill") + " skill increased by 1. Total (" + unknown("12") + ")");
fireworksShow(player);
}

View File

@@ -9,7 +9,6 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
@@ -29,10 +28,10 @@ public class BleedTimerTask extends BukkitRunnable {
continue;
}
double damage;
int damage;
if (entity instanceof Player) {
damage = AdvancedConfig.getInstance().getBleedDamagePlayer();
damage = 1;
Player player = (Player) entity;
if (!player.isOnline()) {
@@ -45,14 +44,14 @@ public class BleedTimerTask extends BukkitRunnable {
ParticleEffectUtils.playBleedEffect(entity);
}
entry.setValue(entry.getValue() - 1);
entry.setValue(entry.getValue() - damage);
if (entry.getValue() <= 0) {
player.sendMessage(LocaleLoader.getString("Swords.Combat.Bleeding.Stopped"));
}
}
else {
damage = AdvancedConfig.getInstance().getBleedDamageMobs();
damage = 2;
// Anticipate the entity's death to prevent CME because of our EntityDeathEvent listener
if (entity.getHealth() - damage > 0) {

View File

@@ -1,29 +1,30 @@
package com.gmail.nossr50.runnables.skills;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.util.Misc;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.util.Misc;
public class KrakenAttackTask extends BukkitRunnable {
private LivingEntity kraken;
private Creature kraken;
private Player player;
private Location location;
private final boolean GLOBAL_EFFECTS = AdvancedConfig.getInstance().getKrakenGlobalEffectsEnabled();
private final String DEFEAT_MESSAGE = AdvancedConfig.getInstance().getPlayerDefeatMessage();
private final String ESCAPE_MESSAGE = AdvancedConfig.getInstance().getPlayerEscapeMessage();
public KrakenAttackTask(LivingEntity kraken2, Player player) {
this.kraken = kraken2;
public KrakenAttackTask(Creature kraken, Player player) {
this.kraken = kraken;
this.player = player;
}
public KrakenAttackTask(LivingEntity kraken2, Player player, Location location) {
this.kraken = kraken2;
public KrakenAttackTask(Creature kraken, Player player, Location location) {
this.kraken = kraken;
this.player = player;
this.location = location;
}
@@ -85,11 +86,11 @@ public class KrakenAttackTask extends BukkitRunnable {
player.damage(AdvancedConfig.getInstance().getKrakenAttackDamage(), kraken);
if (GLOBAL_EFFECTS) {
world.playSound(playerLocation, Sound.ENTITY_GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
world.playSound(playerLocation, Sound.GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
world.strikeLightningEffect(playerLocation);
}
else {
player.playSound(playerLocation, Sound.ENTITY_GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
player.playSound(playerLocation, Sound.GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
world.createExplosion(playerLocation.getX(), playerLocation.getY(), playerLocation.getZ(), 0F, false, false);
}
}

View File

@@ -19,10 +19,26 @@ public final class Acrobatics {
private Acrobatics() {};
/**
* Calculates how much damage should be dealt when Dodging
*
* @param damage the base damage
* @param damageModifier the damage modifier
*
* @return modified damage
*/
protected static double calculateModifiedDodgeDamage(double damage, double damageModifier) {
return Math.max(damage / damageModifier, 1.0);
}
/**
* Calculates how much damage should be dealt when Rolling
*
* @param damage the base damage
* @param damageThreshold the damage threshold
*
* @return modified damage
*/
protected static double calculateModifiedRollDamage(double damage, double damageThreshold) {
return Math.max(damage - damageThreshold, 0.0);
}

View File

@@ -28,10 +28,22 @@ public class AcrobaticsManager extends SkillManager {
super(mcMMOPlayer, SkillType.ACROBATICS);
}
/**
* Check if the player is allowed to use Roll,
* checks permissions and exploit prevention.
*
* @return true if the player is allowed to use Roll
*/
public boolean canRoll() {
return !exploitPrevention() && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.ROLL);
}
/**
* Check if the player is allowed to use Dodge
*
* @param damager {@link Entity} that caused damage
* @return true if the player can Dodge damage from damager
*/
public boolean canDodge(Entity damager) {
if (Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DODGE)) {
if (damager instanceof LightningStrike && Acrobatics.dodgeLightningDisabled) {
@@ -137,7 +149,7 @@ public class AcrobaticsManager extends SkillManager {
Player player = getPlayer();
if (player.getInventory().getItemInMainHand().getType() == Material.ENDER_PEARL || player.isInsideVehicle()) {
if (player.getItemInHand().getType() == Material.ENDER_PEARL || player.isInsideVehicle()) {
return true;
}
@@ -152,10 +164,23 @@ public class AcrobaticsManager extends SkillManager {
return fallTries + 1 > maxTries;
}
/**
* Check if a fall is fatal
*
* @param damage amount of damage taken from the fall
* @return true if the fall is fatal, false otherwise
*/
private boolean isFatal(double damage) {
return getPlayer().getHealth() - damage <= 0;
}
/**
* Calculate the amount of XP gained from falling
*
* @param damage amount of damage taken in the fall
* @param isRoll boolean if the player was rolling
* @return amount of XP gained
*/
private float calculateRollXP(double damage, boolean isRoll) {
ItemStack boots = getPlayer().getInventory().getBoots();
float xp = (float) (damage * (isRoll ? Acrobatics.rollXpModifier : Acrobatics.fallXpModifier));

View File

@@ -38,7 +38,16 @@ public class AlchemyManager extends SkillManager {
StringBuilder list = new StringBuilder();
for (ItemStack ingredient : getIngredients()) {
String string = StringUtils.getPrettyItemString(ingredient.getType());
short durability = ingredient.getDurability();
String string = StringUtils.getPrettyItemString(ingredient.getType()) + (durability != 0 ? ":" + durability : "");
if (string.equals("Long Grass:2")) {
string = "Fern";
}
else if (string.equals("Raw Fish:3")) {
string = "Pufferfish";
}
list.append(", ").append(string);
}

View File

@@ -32,11 +32,11 @@ public final class AlchemyPotionBrewer {
}
for (int i = 0; i < 3; i++) {
if (contents[i] == null || contents[i].getType() != Material.POTION && contents[i].getType() != Material.SPLASH_POTION && contents[i].getType() != Material.LINGERING_POTION) {
if (contents[i] == null || contents[i].getType() != Material.POTION) {
continue;
}
if (getChildPotion(PotionConfig.getInstance().getPotion(contents[i]), contents[Alchemy.INGREDIENT_SLOT]) != null) {
if (getChildPotion(PotionConfig.getInstance().getPotion(contents[i].getDurability()), contents[Alchemy.INGREDIENT_SLOT]) != null) {
return true;
}
}
@@ -45,8 +45,8 @@ public final class AlchemyPotionBrewer {
}
private static AlchemyPotion getChildPotion(AlchemyPotion potion, ItemStack ingredient) {
if (potion != null) {
return potion.getChild(ingredient);
if (potion != null && potion.getChildDataValue(ingredient) != -1) {
return PotionConfig.getInstance().getPotion(potion.getChildDataValue(ingredient));
}
return null;
@@ -56,29 +56,23 @@ public final class AlchemyPotionBrewer {
return item == null || item.getType() == Material.AIR || item.getAmount() == 0;
}
private static void removeIngredient(BrewerInventory inventory, Player player) {
private static boolean removeIngredient(BrewerInventory inventory, Player player) {
ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone();
if (isEmpty(ingredient) || !isValidIngredient(player, ingredient)) {
return;
return false;
}
else if (ingredient.getAmount() <= 1) {
inventory.setIngredient(null);
return;
return true;
}
else {
ingredient.setAmount(ingredient.getAmount() - 1);
inventory.setIngredient(ingredient);
return;
return true;
}
}
private static boolean hasIngredient(BrewerInventory inventory, Player player) {
ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone();
return !isEmpty(ingredient) && isValidIngredient(player, ingredient);
}
public static boolean isValidIngredient(Player player, ItemStack item) {
if (isEmpty(item)) {
return false;
@@ -105,7 +99,7 @@ public final class AlchemyPotionBrewer {
BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory();
ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone();
if (!hasIngredient(inventory, player)) {
if (!removeIngredient(inventory, player)) {
return;
}
@@ -118,8 +112,8 @@ public final class AlchemyPotionBrewer {
continue;
}
AlchemyPotion input = PotionConfig.getInstance().getPotion(item);
AlchemyPotion output = input.getChild(ingredient);
AlchemyPotion input = PotionConfig.getInstance().getPotion(item.getDurability());
AlchemyPotion output = PotionConfig.getInstance().getPotion(input.getChildDataValue(ingredient));
inputList.add(input);
@@ -128,17 +122,15 @@ public final class AlchemyPotionBrewer {
}
}
FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory, ((BrewingStand) brewingStand).getFuelLevel());
FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory);
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled() || inputList.isEmpty()) {
return;
}
removeIngredient(inventory, player);
for (AlchemyPotion input : inputList) {
AlchemyPotion output = input.getChild(ingredient);
AlchemyPotion output = PotionConfig.getInstance().getPotion(input.getChildDataValue(ingredient));
if (output != null && player != null) {
PotionStage potionStage = PotionStage.getPotionStage(input, output);

View File

@@ -9,7 +9,6 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.util.Misc;
public class Archery {
@@ -22,8 +21,14 @@ public class Archery {
public static double dazeBonusDamage = AdvancedConfig.getInstance().getDazeBonusDamage();
public static final double DISTANCE_XP_MULTIPLIER = ExperienceConfig.getInstance().getArcheryDistanceMultiplier();
public static final double DISTANCE_XP_MULTIPLIER = 0.025;
/**
* Increment tracked arrow count for a LivingEntity,
* if the entity isn't tracked yet it will get added to the tracker.
*
* @param livingEntity the {@link LivingEntity} to increment the arrow count for
*/
protected static void incrementTrackerValue(LivingEntity livingEntity) {
for (TrackedEntity trackedEntity : trackedEntities) {
if (trackedEntity.getLivingEntity().getEntityId() == livingEntity.getEntityId()) {
@@ -35,6 +40,11 @@ public class Archery {
addToTracker(livingEntity); // If the entity isn't tracked yet
}
/**
* Add a LivingEntity to the tracker.
*
* @param livingEntity the {@link LivingEntity} to add.
*/
protected static void addToTracker(LivingEntity livingEntity) {
TrackedEntity trackedEntity = new TrackedEntity(livingEntity);
@@ -42,6 +52,11 @@ public class Archery {
trackedEntities.add(trackedEntity);
}
/**
* Remove a TrackedEntity from the tracker.
*
* @param trackedEntity the {@link TrackedEntity} to remove.
*/
protected static void removeFromTracker(TrackedEntity trackedEntity) {
trackedEntities.remove(trackedEntity);
}

View File

@@ -23,14 +23,30 @@ public class ArcheryManager extends SkillManager {
super(mcMMOPlayer, SkillType.ARCHERY);
}
/**
* Check if the target can be dazed. Checks if target is valid and if the player has sufficient permissions.
*
* @param target the {@link LivingEntity} object of the target to check
* @return true if the target can be dazed, false otherwise
*/
public boolean canDaze(LivingEntity target) {
return target instanceof Player && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DAZE);
}
/**
* Check if the player can use SkillShot.
*
* @return true if the player can use SkillShot, false otherwise
*/
public boolean canSkillShot() {
return getSkillLevel() >= Archery.skillShotIncreaseLevel && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.SKILL_SHOT);
}
/**
* Check if the player can use RetrieveArrows.
*
* @return true if the player can use RetrieveArrows, false otherwise
*/
public boolean canRetrieveArrows() {
return Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.RETRIEVE);
}
@@ -49,7 +65,7 @@ public class ArcheryManager extends SkillManager {
return;
}
applyXpGain((int) (Math.min(firedLocation.distanceSquared(targetLocation), 2500) * Archery.DISTANCE_XP_MULTIPLIER), getXPGainReason(target, damager));
applyXpGain((int) (firedLocation.distanceSquared(targetLocation) * Archery.DISTANCE_XP_MULTIPLIER), getXPGainReason(target, damager));
}
/**
@@ -67,6 +83,8 @@ public class ArcheryManager extends SkillManager {
* Handle the effects of the Daze ability
*
* @param defender The {@link Player} being affected by the ability
*
* @return amount of damage from Daze
*/
public double daze(Player defender) {
if (!SkillUtils.activationSuccessful(SecondaryAbility.DAZE, getPlayer(), getSkillLevel(), activationChance)) {
@@ -94,6 +112,7 @@ public class ArcheryManager extends SkillManager {
* Handle the effects of the Skill Shot ability
*
* @param damage The amount of damage initially dealt by the event
* @return amount of damage from Skill Shot
*/
public double skillShot(double damage) {
if (!SkillUtils.activationSuccessful(SecondaryAbility.SKILL_SHOT, getPlayer())) {

View File

@@ -23,9 +23,15 @@ public class Axes {
public static double skullSplitterModifier = AdvancedConfig.getInstance().getSkullSplitterModifier();
/**
* Check if the target is wearing any armor.
*
* @param target the {@link LivingEntity} object of the target to check.
* @return true if the target is wearing at least one piece of armor, false otherwise
*/
protected static boolean hasArmor(LivingEntity target) {
for (ItemStack itemStack : target.getEquipment().getArmorContents()) {
if (itemStack != null && ItemUtils.isArmor(itemStack)) {
if (ItemUtils.isArmor(itemStack)) {
return true;
}
}

View File

@@ -74,16 +74,10 @@ public class AxesManager extends SkillManager {
Player player = getPlayer();
if (mcMMOPlayer.useChatNotifications()) {
player.sendMessage(LocaleLoader.getString("Axes.Combat.CriticalHit"));
}
player.sendMessage(LocaleLoader.getString("Axes.Combat.CriticalHit"));
if (target instanceof Player) {
Player defender = (Player) target;
if (UserManager.getPlayer(defender).useChatNotifications()) {
defender.sendMessage(LocaleLoader.getString("Axes.Combat.CritStruck"));
}
((Player) target).sendMessage(LocaleLoader.getString("Axes.Combat.CritStruck"));
damage = (damage * Axes.criticalHitPVPModifier) - damage;
}
@@ -103,7 +97,7 @@ public class AxesManager extends SkillManager {
int durabilityDamage = 1 + (getSkillLevel() / Axes.impactIncreaseLevel);
for (ItemStack armor : target.getEquipment().getArmorContents()) {
if (armor != null && ItemUtils.isArmor(armor)) {
if (ItemUtils.isArmor(armor)) {
if (SkillUtils.activationSuccessful(SecondaryAbility.ARMOR_IMPACT, getPlayer(), Axes.impactChance, activationChance)) {
SkillUtils.handleDurabilityChange(armor, durabilityDamage, Axes.impactMaxDurabilityModifier);
}

View File

@@ -16,7 +16,7 @@ public class ChildConfig extends AutoUpdateConfigLoader {
@Override
protected void loadKeys() {
config.setDefaults(YamlConfiguration.loadConfiguration(plugin.getResourceAsReader("child.yml")));
config.setDefaults(YamlConfiguration.loadConfiguration(plugin.getResource("child.yml")));
FamilyTree.clearRegistrations(); // when reloading, need to clear statics

View File

@@ -1,15 +1,16 @@
package com.gmail.nossr50.skills.excavation;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.StringUtils;
import org.bukkit.block.BlockState;
import java.util.ArrayList;
import java.util.List;
public class Excavation {
/**
@@ -19,14 +20,46 @@ public class Excavation {
* @return the list of treasures that could be found
*/
protected static List<ExcavationTreasure> getTreasures(BlockState blockState) {
String friendly = StringUtils.getFriendlyConfigBlockDataString(blockState.getBlockData());
if (TreasureConfig.getInstance().excavationMap.containsKey(friendly))
return TreasureConfig.getInstance().excavationMap.get(friendly);
return new ArrayList<ExcavationTreasure>();
switch (blockState.getType()) {
case DIRT:
return blockState.getRawData() == 0x2 ? TreasureConfig.getInstance().excavationFromPodzol : TreasureConfig.getInstance().excavationFromDirt;
case GRASS:
return TreasureConfig.getInstance().excavationFromGrass;
case SAND:
return blockState.getRawData() == 0x1 ? TreasureConfig.getInstance().excavationFromRedSand : TreasureConfig.getInstance().excavationFromSand;
case GRAVEL:
return TreasureConfig.getInstance().excavationFromGravel;
case CLAY:
return TreasureConfig.getInstance().excavationFromClay;
case MYCEL:
return TreasureConfig.getInstance().excavationFromMycel;
case SOUL_SAND:
return TreasureConfig.getInstance().excavationFromSoulSand;
case SNOW:
return TreasureConfig.getInstance().excavationFromSnow;
default:
return new ArrayList<ExcavationTreasure>();
}
}
protected static int getBlockXP(BlockState blockState) {
int xp = ExperienceConfig.getInstance().getXp(SkillType.EXCAVATION, blockState.getType());
Material material = blockState.getType();
int xp;
if (material == Material.DIRT || material == Material.SAND) {
xp = ExperienceConfig.getInstance().getDirtAndSandXp(blockState.getData());
}
else {
xp = ExperienceConfig.getInstance().getXp(SkillType.EXCAVATION, material);
}
if (xp == 0 && mcMMO.getModManager().isCustomExcavationBlock(blockState)) {
xp = mcMMO.getModManager().getBlock(blockState).getXpGain();

View File

@@ -34,7 +34,7 @@ public class ExcavationManager extends SkillManager {
if (!treasures.isEmpty()) {
int skillLevel = getSkillLevel();
Location location = Misc.getBlockCenter(blockState);
Location location = blockState.getLocation();
for (ExcavationTreasure treasure : treasures) {
if (skillLevel >= treasure.getDropLevel() && SkillUtils.treasureDropSuccessful(getPlayer(), treasure.getDropChance(), activationChance)) {
@@ -57,6 +57,6 @@ public class ExcavationManager extends SkillManager {
excavationBlockCheck(blockState);
excavationBlockCheck(blockState);
SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), Config.getInstance().getAbilityToolDamage());
SkillUtils.handleDurabilityChange(getPlayer().getItemInHand(), Config.getInstance().getAbilityToolDamage());
}
}

View File

@@ -1,5 +1,6 @@
package com.gmail.nossr50.skills.fishing;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
@@ -7,7 +8,6 @@ import java.util.Set;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Guardian;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
@@ -15,13 +15,18 @@ import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.datatypes.treasure.ShakeTreasure;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.adapter.BiomeAdapter;
public final class Fishing {
// The order of the values is extremely important, a few methods depend on it to work properly
public enum Tier {
EIGHT(8), SEVEN(7), SIX(6), FIVE(5), FOUR(4), THREE(3), TWO(2), ONE(1);
EIGHT(8),
SEVEN(7),
SIX(6),
FIVE(5),
FOUR(4),
THREE(3),
TWO(2),
ONE(1);
int numerical;
@@ -52,30 +57,92 @@ public final class Fishing {
public static int fishermansDietRankLevel2 = fishermansDietRankLevel1 * 2;
public static int fishermansDietMaxLevel = fishermansDietRankLevel1 * 5;
public static Set<Biome> masterAnglerBiomes = BiomeAdapter.WATER_BIOMES;
public static Set<Biome> iceFishingBiomes = BiomeAdapter.ICE_BIOMES;
public static Set<Biome> masterAnglerBiomes = EnumSet.of(Biome.RIVER, Biome.OCEAN, Biome.DEEP_OCEAN);
public static Set<Biome> iceFishingBiomes = EnumSet.of(
Biome.FROZEN_OCEAN, Biome.FROZEN_RIVER,
Biome.TAIGA, Biome.TAIGA_HILLS, Biome.TAIGA_MOUNTAINS,
Biome.ICE_PLAINS, Biome.ICE_MOUNTAINS, Biome.ICE_PLAINS_SPIKES,
Biome.COLD_TAIGA, Biome.COLD_TAIGA_HILLS, Biome.COLD_TAIGA_MOUNTAINS);
private Fishing() {}
/**
* Finds the possible drops of an entity
*
* @param target
* Targeted entity
* @param target Targeted entity
* @return possibleDrops List of ItemStack that can be dropped
*/
protected static List<ShakeTreasure> findPossibleDrops(LivingEntity target) {
if (TreasureConfig.getInstance().shakeMap.containsKey(target.getType()))
return TreasureConfig.getInstance().shakeMap.get(target.getType());
switch (target.getType()) {
case BLAZE:
return TreasureConfig.getInstance().shakeFromBlaze;
return null;
case CAVE_SPIDER:
return TreasureConfig.getInstance().shakeFromCaveSpider;
case CHICKEN:
return TreasureConfig.getInstance().shakeFromChicken;
case COW:
return TreasureConfig.getInstance().shakeFromCow;
case CREEPER:
return TreasureConfig.getInstance().shakeFromCreeper;
case ENDERMAN:
return TreasureConfig.getInstance().shakeFromEnderman;
case GHAST:
return TreasureConfig.getInstance().shakeFromGhast;
case IRON_GOLEM:
return TreasureConfig.getInstance().shakeFromIronGolem;
case MAGMA_CUBE:
return TreasureConfig.getInstance().shakeFromMagmaCube;
case MUSHROOM_COW:
return TreasureConfig.getInstance().shakeFromMushroomCow;
case PIG:
return TreasureConfig.getInstance().shakeFromPig;
case PIG_ZOMBIE:
return TreasureConfig.getInstance().shakeFromPigZombie;
case SHEEP:
return TreasureConfig.getInstance().shakeFromSheep;
case SKELETON:
return TreasureConfig.getInstance().shakeFromSkeleton;
case SLIME:
return TreasureConfig.getInstance().shakeFromSlime;
case SNOWMAN:
return TreasureConfig.getInstance().shakeFromSnowman;
case SPIDER:
return TreasureConfig.getInstance().shakeFromSpider;
case SQUID:
return TreasureConfig.getInstance().shakeFromSquid;
case WITCH:
return TreasureConfig.getInstance().shakeFromWitch;
case ZOMBIE:
return TreasureConfig.getInstance().shakeFromZombie;
default:
return null;
}
}
/**
* Randomly chooses a drop among the list
*
* @param possibleDrops
* List of ItemStack that can be dropped
* @param possibleDrops List of ItemStack that can be dropped
* @return Chosen ItemStack
*/
protected static ItemStack chooseDrop(List<ShakeTreasure> possibleDrops) {

View File

@@ -1,5 +1,40 @@
package com.gmail.nossr50.skills.fishing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.WeatherType;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fish;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Wool;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionType;
import org.bukkit.util.Vector;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
@@ -16,27 +51,16 @@ import com.gmail.nossr50.events.skills.fishing.McMMOPlayerFishingTreasureEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerShakeEvent;
import com.gmail.nossr50.events.skills.secondaryabilities.SecondaryAbilityWeightedActivationCheckEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.skills.KrakenAttackTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.fishing.Fishing.Tier;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionType;
import org.bukkit.util.Vector;
import java.util.*;
public class FishingManager extends SkillManager {
private final long FISHING_COOLDOWN_SECONDS = 1000L;
@@ -96,7 +120,7 @@ public class FishingManager extends SkillManager {
world.strikeLightningEffect(location);
world.strikeLightningEffect(location);
world.playSound(location, Sound.ENTITY_GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
world.playSound(location, Sound.GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
mcMMO.p.getServer().broadcastMessage(ChatColor.RED + AdvancedConfig.getInstance().getServerUnleashMessage().replace("(PLAYER)", player.getDisplayName()));
}
else {
@@ -104,17 +128,14 @@ public class FishingManager extends SkillManager {
world.createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, false);
world.createExplosion(location.getX(), location.getY(), location.getZ(), 0F, false, false);
player.playSound(location, Sound.ENTITY_GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
player.playSound(location, Sound.GHAST_SCREAM, Misc.GHAST_VOLUME, Misc.getGhastPitch());
}
if (player.getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) {
player.getInventory().setItemInMainHand(null);
}
else if (player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD) {
player.getInventory().setItemInOffHand(null);
if (player.getItemInHand().getType() == Material.FISHING_ROD) {
player.setItemInHand(null);
}
LivingEntity kraken = (LivingEntity) world.spawnEntity(player.getEyeLocation(), (Misc.getRandom().nextInt(100) == 0 ? EntityType.CHICKEN : EntityType.SQUID));
Creature kraken = (Creature) world.spawnEntity(player.getEyeLocation(), (Misc.getRandom().nextInt(100) == 0 ? EntityType.CHICKEN : EntityType.SQUID));
kraken.setCustomName(AdvancedConfig.getInstance().getKrakenName());
if (!kraken.isValid()) {
@@ -177,7 +198,7 @@ public class FishingManager extends SkillManager {
}
// Make sure this is a body of water, not just a block of ice.
if (!Fishing.iceFishingBiomes.contains(block.getBiome()) && (block.getRelative(BlockFace.DOWN, 3).getType() != Material.WATER)) {
if (!Fishing.iceFishingBiomes.contains(block.getBiome()) && (block.getRelative(BlockFace.DOWN, 3).getType() != Material.STATIONARY_WATER)) {
return false;
}
@@ -236,16 +257,16 @@ public class FishingManager extends SkillManager {
return SkillUtils.handleFoodSkills(getPlayer(), skill, eventFoodLevel, Fishing.fishermansDietRankLevel1, Fishing.fishermansDietMaxLevel, rankChange);
}
public void iceFishing(FishHook hook, Block block) {
public void iceFishing(Fish hook, Block block) {
// Make a hole
block.setType(Material.WATER);
block.setType(Material.STATIONARY_WATER);
for (int x = -1; x <= 1; x++) {
for (int z = -1; z <= 1; z++) {
Block relative = block.getRelative(x, 0, z);
if (relative.getType() == Material.ICE) {
relative.setType(Material.WATER);
relative.setType(Material.STATIONARY_WATER);
}
}
}
@@ -254,7 +275,7 @@ public class FishingManager extends SkillManager {
EventUtils.callFakeFishEvent(getPlayer(), hook);
}
public void masterAngler(FishHook hook) {
public void masterAngler(Fish hook) {
Player player = getPlayer();
Location location = hook.getLocation();
double biteChance = hook.getBiteChance();
@@ -279,7 +300,7 @@ public class FishingManager extends SkillManager {
*/
public void handleFishing(Item fishingCatch) {
this.fishingCatch = fishingCatch;
int fishXp = ExperienceConfig.getInstance().getXp(SkillType.FISHING, fishingCatch.getItemStack().getType());
int fishXp = ExperienceConfig.getInstance().getFishXp(fishingCatch.getItemStack().getData());
int treasureXp = 0;
Player player = getPlayer();
FishingTreasure treasure = null;
@@ -373,57 +394,38 @@ public class FishingManager extends SkillManager {
// Extra processing depending on the mob and drop type
switch (target.getType()) {
case PLAYER:
Player targetPlayer = (Player) target;
switch (drop.getType()) {
case PLAYER_HEAD:
drop.setDurability((short) 3);
SkullMeta skullMeta = (SkullMeta) drop.getItemMeta();
skullMeta.setOwningPlayer(targetPlayer);
drop.setItemMeta(skullMeta);
break;
case BEDROCK:
if (TreasureConfig.getInstance().getInventoryStealEnabled()) {
PlayerInventory inventory = targetPlayer.getInventory();
int length = inventory.getContents().length;
int slot = Misc.getRandom().nextInt(length);
drop = inventory.getItem(slot);
if (drop == null) {
break;
}
if (TreasureConfig.getInstance().getInventoryStealStacks()) {
inventory.setItem(slot, null);
}
else {
inventory.setItem(slot, (drop.getAmount() > 1) ? new ItemStack(drop.getType(), drop.getAmount() - 1) : null);
drop.setAmount(1);
}
targetPlayer.updateInventory();
}
break;
default:
break;
}
break;
case SHEEP:
Sheep sheep = (Sheep) target;
if (drop.getType().name().endsWith("WOOL")) {
if (drop.getType() == Material.WOOL) {
if (sheep.isSheared()) {
return;
}
drop = new Wool(sheep.getColor()).toItemStack(drop.getAmount());
sheep.setSheared(true);
}
break;
case SKELETON:
if (((Skeleton) target).getSkeletonType() == SkeletonType.WITHER) {
switch (drop.getType()) {
case SKULL_ITEM:
drop.setDurability((short) 1);
break;
case ARROW:
drop.setType(Material.COAL);
break;
default:
break;
}
}
break;
default:
break;
break;
}
McMMOPlayerShakeEvent shakeEvent = new McMMOPlayerShakeEvent(getPlayer(), drop);
@@ -435,7 +437,7 @@ public class FishingManager extends SkillManager {
}
Misc.dropItem(target.getLocation(), drop);
CombatUtils.dealDamage(target, Math.max(target.getMaxHealth() / 4, 1), getPlayer()); // Make it so you can shake a mob no more than 4 times.
CombatUtils.dealDamage(target, Math.max(target.getMaxHealth() / 4, 1)); // Make it so you can shake a mob no more than 4 times.
applyXpGain(ExperienceConfig.getInstance().getFishingShakeXP(), XPGainReason.PVE);
}
}
@@ -447,18 +449,7 @@ public class FishingManager extends SkillManager {
*/
private FishingTreasure getFishingTreasure() {
double diceRoll = Misc.getRandom().nextDouble() * 100;
int luck;
if (getPlayer().getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) {
luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK);
}
else {
// We know something was caught, so if the rod wasn't in the main hand it must be in the offhand
luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK);
}
// Rather than subtracting luck (and causing a minimum 3% chance for every drop), scale by luck.
diceRoll *= (1.0 - luck * Config.getInstance().getFishingLureModifier() / 100);
diceRoll -= getPlayer().getItemInHand().getEnchantmentLevel(Enchantment.LUCK);
FishingTreasure treasure = null;
@@ -555,11 +546,6 @@ public class FishingManager extends SkillManager {
double dropRate = TreasureConfig.getInstance().getEnchantmentDropRate(getLootTier(), rarity);
if (diceRoll <= dropRate) {
// Make sure enchanted books always get some kind of enchantment. --hoorigan
if (treasureDrop.getType() == Material.ENCHANTED_BOOK) {
diceRoll = dropRate + 1;
continue;
}
fishingEnchantments = TreasureConfig.getInstance().fishingEnchantments.get(rarity);
break;
}
@@ -637,6 +623,6 @@ public class FishingManager extends SkillManager {
}
}
return 1;
return 0;
}
}

View File

@@ -1,17 +1,16 @@
package com.gmail.nossr50.skills.herbalism;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.material.SmoothBrick;
import java.util.HashSet;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.util.skills.SkillUtils;
public class Herbalism {
public static int farmersDietRankLevel1 = AdvancedConfig.getInstance().getFarmerDietRankChange();
public static int farmersDietRankLevel2 = farmersDietRankLevel1 * 2;
public static int farmersDietMaxLevel = farmersDietRankLevel1 * 5;
@@ -22,129 +21,56 @@ public class Herbalism {
/**
* Convert blocks affected by the Green Thumb & Green Terra abilities.
*
* @param blockState
* The {@link BlockState} to check ability activation for
* @param blockState The {@link BlockState} to check ability activation for
* @return true if the ability was successful, false otherwise
*/
protected static boolean convertGreenTerraBlocks(BlockState blockState) {
switch (blockState.getType()) {
case COBBLESTONE_WALL:
blockState.setType(Material.MOSSY_COBBLESTONE_WALL);
case COBBLE_WALL:
blockState.setRawData((byte) 0x1);
return true;
case STONE_BRICKS:
blockState.setType(Material.MOSSY_STONE_BRICKS);
case SMOOTH_BRICK:
((SmoothBrick) blockState.getData()).setMaterial(Material.MOSSY_COBBLESTONE);
return true;
case DIRT :
case GRASS_PATH :
blockState.setType(Material.GRASS_BLOCK);
case DIRT:
blockState.setType(Material.GRASS);
return true;
case COBBLESTONE :
case COBBLESTONE:
blockState.setType(Material.MOSSY_COBBLESTONE);
return true;
default :
default:
return false;
}
}
public static HashSet<Block> findChorusPlant(Block target) {
return findChorusPlant(target, new HashSet<Block>());
}
private static HashSet<Block> findChorusPlant(Block target, HashSet<Block> traversed) {
if (target.getType() != Material.CHORUS_PLANT) {
return traversed;
}
// Prevent any infinite loops, who needs more than 64 chorus anyways
if (traversed.size() > 64)
{
return traversed;
}
traversed.add(target);
Block relative = target.getRelative(BlockFace.UP, 1);
if (!traversed.contains(relative)) {
if (relative.getType() == Material.CHORUS_PLANT) {
traversed.addAll(findChorusPlant(relative, traversed));
}
}
relative = target.getRelative(BlockFace.NORTH, 1);
if (!traversed.contains(relative)) {
if (relative.getType() == Material.CHORUS_PLANT) {
traversed.addAll(findChorusPlant(relative, traversed));
}
}
relative = target.getRelative(BlockFace.SOUTH, 1);
if (!traversed.contains(relative)) {
if (relative.getType() == Material.CHORUS_PLANT) {
traversed.addAll(findChorusPlant(relative, traversed));
}
}
relative = target.getRelative(BlockFace.EAST, 1);
if (!traversed.contains(relative)) {
if (relative.getType() == Material.CHORUS_PLANT) {
traversed.addAll(findChorusPlant(relative, traversed));
}
}
relative = target.getRelative(BlockFace.WEST, 1);
if (!traversed.contains(relative)) {
if (relative.getType() == Material.CHORUS_PLANT) {
traversed.addAll(findChorusPlant(relative, traversed));
}
}
return traversed;
}
/**
* Calculate the drop amounts for multi block plants based on the blocks
* relative to them.
* Calculate the drop amounts for cacti & sugar cane based on the blocks above them.
*
* @param blockState
* The {@link BlockState} of the bottom block of the plant
* @param blockState The {@link BlockState} of the bottom block of the plant
* @return the number of bonus drops to award from the blocks in this plant
*/
protected static int calculateMultiBlockPlantDrops(BlockState blockState) {
protected static int calculateCatciAndSugarDrops(BlockState blockState) {
Block block = blockState.getBlock();
Material blockType = blockState.getType();
int dropAmount = mcMMO.getPlaceStore().isTrue(block) ? 0 : 1;
if (blockType == Material.CHORUS_PLANT) {
dropAmount = 1;
// Handle the two blocks above it - cacti & sugar cane can only grow 3 high naturally
for (int y = 1; y < 3; y++) {
Block relativeBlock = block.getRelative(BlockFace.UP, y);
if (block.getRelative(BlockFace.DOWN, 1).getType() == Material.END_STONE) {
HashSet<Block> blocks = findChorusPlant(block);
dropAmount = blocks.size();
/*
* for(Block b : blocks) {
* b.breakNaturally();
* }
*/
if (relativeBlock.getType() != blockType) {
break;
}
} else {
// Handle the two blocks above it - cacti & sugar cane can only grow 3 high naturally
for (int y = 1; y < 3; y++) {
Block relativeBlock = block.getRelative(BlockFace.UP, y);
if (relativeBlock.getType() != blockType) {
break;
}
if (mcMMO.getPlaceStore().isTrue(relativeBlock)) {
mcMMO.getPlaceStore().setFalse(relativeBlock);
} else {
dropAmount++;
}
if (mcMMO.getPlaceStore().isTrue(relativeBlock)) {
mcMMO.getPlaceStore().setFalse(relativeBlock);
}
else {
dropAmount++;
}
}
@@ -154,19 +80,17 @@ public class Herbalism {
/**
* Convert blocks affected by the Green Thumb & Green Terra abilities.
*
* @param blockState
* The {@link BlockState} to check ability activation for
* @param blockState The {@link BlockState} to check ability activation for
* @return true if the ability was successful, false otherwise
*/
protected static boolean convertShroomThumb(BlockState blockState) {
switch (blockState.getType()) {
case DIRT :
case GRASS_BLOCK:
case GRASS_PATH :
blockState.setType(Material.MYCELIUM);
case DIRT:
case GRASS:
blockState.setType(Material.MYCEL);
return true;
default :
default:
return false;
}
}
@@ -174,8 +98,7 @@ public class Herbalism {
/**
* Check if the block has a recently grown crop from Green Thumb
*
* @param blockState
* The {@link BlockState} to check green thumb regrown for
* @param blockState The {@link BlockState} to check green thumb regrown for
* @return true if the block is recently regrown, false otherwise
*/
public static boolean isRecentlyRegrown(BlockState blockState) {

View File

@@ -1,29 +1,42 @@
package com.gmail.nossr50.skills.herbalism;
import java.util.Collection;
import java.util.List;
import org.bukkit.CropState;
import org.bukkit.Material;
import org.bukkit.NetherWartsState;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.CocoaPlant.CocoaPlantSize;
import org.bukkit.material.Crops;
import org.bukkit.material.NetherWarts;
import org.bukkit.metadata.FixedMetadataValue;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.config.treasure.TreasureConfig;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.*;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.datatypes.treasure.HylianTreasure;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.skills.HerbalismBlockUpdaterTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.Ageable;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.Collection;
import java.util.List;
public class HerbalismManager extends SkillManager {
public HerbalismManager(McMMOPlayer mcMMOPlayer) {
@@ -36,17 +49,15 @@ public class HerbalismManager extends SkillManager {
public boolean canGreenThumbBlock(BlockState blockState) {
Player player = getPlayer();
ItemStack item = player.getInventory().getItemInMainHand();
return item.getAmount() > 0 && item.getType() == Material.WHEAT_SEEDS && BlockUtils.canMakeMossy(blockState) && Permissions.greenThumbBlock(player, blockState.getType());
return player.getItemInHand().getType() == Material.SEEDS && BlockUtils.canMakeMossy(blockState) && Permissions.greenThumbBlock(player, blockState.getType());
}
public boolean canUseShroomThumb(BlockState blockState) {
Player player = getPlayer();
PlayerInventory inventory = player.getInventory();
Material itemType = inventory.getItemInMainHand().getType();
Material itemType = player.getItemInHand().getType();
return (itemType == Material.BROWN_MUSHROOM || itemType == Material.RED_MUSHROOM) && inventory.contains(Material.BROWN_MUSHROOM, 1) && inventory.contains(Material.RED_MUSHROOM, 1) && BlockUtils.canMakeShroomy(blockState) && Permissions.secondaryAbilityEnabled(player, SecondaryAbility.SHROOM_THUMB);
return (itemType == Material.RED_MUSHROOM || itemType == Material.BROWN_MUSHROOM) && BlockUtils.canMakeShroomy(blockState) && Permissions.secondaryAbilityEnabled(player, SecondaryAbility.SHROOM_THUMB);
}
public boolean canUseHylianLuck() {
@@ -90,7 +101,7 @@ public class HerbalismManager extends SkillManager {
}
PlayerInventory playerInventory = player.getInventory();
ItemStack seed = new ItemStack(Material.WHEAT_SEEDS);
ItemStack seed = new ItemStack(Material.SEEDS);
if (!playerInventory.containsAtLeast(seed, 1)) {
player.sendMessage(LocaleLoader.getString("Herbalism.Ability.GTe.NeedMore"));
@@ -109,9 +120,8 @@ public class HerbalismManager extends SkillManager {
public void herbalismBlockCheck(BlockState blockState) {
Player player = getPlayer();
Material material = blockState.getType();
boolean oneBlockPlant = !(material == Material.CACTUS || material == Material.CHORUS_PLANT || material == Material.SUGAR_CANE);
boolean oneBlockPlant = !(material == Material.CACTUS || material == Material.SUGAR_CANE_BLOCK);
// Prevents placing and immediately breaking blocks for exp
if (oneBlockPlant && mcMMO.getPlaceStore().isTrue(blockState)) {
return;
}
@@ -134,20 +144,25 @@ public class HerbalismManager extends SkillManager {
}
}
else {
xp = ExperienceConfig.getInstance().getXp(skill, blockState.getBlockData());
if (Permissions.greenThumbPlant(player, material)) {
processGreenThumbPlants(blockState, greenTerra);
}
if (material == Material.DOUBLE_PLANT || material == Material.RED_ROSE || material == Material.LONG_GRASS) {
xp = ExperienceConfig.getInstance().getFlowerAndGrassXp(blockState.getData());
}
else {
xp = ExperienceConfig.getInstance().getXp(skill, material);
}
if (Config.getInstance().getDoubleDropsEnabled(skill, material) && Permissions.secondaryAbilityEnabled(player, SecondaryAbility.HERBALISM_DOUBLE_DROPS)) {
drops = blockState.getBlock().getDrops();
}
if (!oneBlockPlant) {
amount = Herbalism.calculateMultiBlockPlantDrops(blockState);
amount = Herbalism.calculateCatciAndSugarDrops(blockState);
xp *= amount;
}
if (Permissions.greenThumbPlant(player, material)) {
processGreenThumbPlants(blockState, greenTerra);
}
}
applyXpGain(xp, XPGainReason.PVE);
@@ -159,7 +174,7 @@ public class HerbalismManager extends SkillManager {
for (int i = greenTerra ? 2 : 1; i != 0; i--) {
if (SkillUtils.activationSuccessful(SecondaryAbility.HERBALISM_DOUBLE_DROPS, getPlayer(), getSkillLevel(), activationChance)) {
for (ItemStack item : drops) {
Misc.dropItems(Misc.getBlockCenter(blockState), item, amount);
Misc.dropItems(blockState.getLocation(), item, amount);
}
}
}
@@ -191,31 +206,44 @@ public class HerbalismManager extends SkillManager {
return false;
}
String friendly = StringUtils.getFriendlyConfigBlockDataString(blockState.getBlockData());
if (!TreasureConfig.getInstance().hylianMap.containsKey(friendly))
return false;
List<HylianTreasure> treasures = TreasureConfig.getInstance().hylianMap.get(friendly);
List<HylianTreasure> treasures;
switch (blockState.getType()) {
case DEAD_BUSH:
case LONG_GRASS:
case SAPLING:
treasures = TreasureConfig.getInstance().hylianFromBushes;
break;
case RED_ROSE:
case YELLOW_FLOWER:
if (mcMMO.getPlaceStore().isTrue(blockState)) {
mcMMO.getPlaceStore().setFalse(blockState);
return false;
}
treasures = TreasureConfig.getInstance().hylianFromFlowers;
break;
case FLOWER_POT:
treasures = TreasureConfig.getInstance().hylianFromPots;
break;
default:
return false;
}
Player player = getPlayer();
if (treasures.isEmpty()) {
if (treasures.isEmpty() || !EventUtils.simulateBlockBreak(blockState.getBlock(), player, false)) {
return false;
}
int skillLevel = getSkillLevel();
Location location = Misc.getBlockCenter(blockState);
for (HylianTreasure treasure : treasures) {
if (skillLevel >= treasure.getDropLevel() && SkillUtils.treasureDropSuccessful(getPlayer(), treasure.getDropChance(), activationChance)) {
if (!EventUtils.simulateBlockBreak(blockState.getBlock(), player, false)) {
return false;
}
blockState.setType(Material.AIR);
Misc.dropItem(location, treasure.getDrop());
player.sendMessage(LocaleLoader.getString("Herbalism.HylianLuck"));
return true;
}
}
return false;
blockState.setType(Material.AIR);
Misc.dropItem(blockState.getLocation(), treasures.get(Misc.getRandom().nextInt(treasures.size())).getDrop());
player.sendMessage(LocaleLoader.getString("Herbalism.HylianLuck"));
return true;
}
/**
@@ -227,13 +255,13 @@ public class HerbalismManager extends SkillManager {
public boolean processShroomThumb(BlockState blockState) {
Player player = getPlayer();
PlayerInventory playerInventory = player.getInventory();
if (!playerInventory.contains(Material.BROWN_MUSHROOM, 1)) {
if (!playerInventory.contains(Material.BROWN_MUSHROOM)) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)));
return false;
}
if (!playerInventory.contains(Material.RED_MUSHROOM, 1)) {
if (!playerInventory.contains(Material.RED_MUSHROOM)) {
player.sendMessage(LocaleLoader.getString("Skills.NeedMore", StringUtils.getPrettyItemString(Material.RED_MUSHROOM)));
return false;
}
@@ -257,45 +285,32 @@ public class HerbalismManager extends SkillManager {
* @param greenTerra boolean to determine if greenTerra is active or not
*/
private void processGreenThumbPlants(BlockState blockState, boolean greenTerra) {
if (!BlockUtils.isFullyGrown(blockState))
return;
Player player = getPlayer();
PlayerInventory playerInventory = player.getInventory();
Material seed = null;
ItemStack seed = null;
switch (blockState.getType()) {
case CARROTS:
seed = Material.CARROT;
case CARROT:
seed = new ItemStack(Material.CARROT_ITEM);
break;
case WHEAT:
seed = Material.WHEAT_SEEDS;
case CROPS:
seed = new ItemStack(Material.SEEDS);
break;
case NETHER_WART:
seed = Material.NETHER_WART;
case NETHER_WARTS:
seed = new ItemStack(Material.NETHER_STALK);
break;
case POTATOES:
seed = Material.POTATO;
break;
case BEETROOTS:
seed = Material.BEETROOT_SEEDS;
break;
case COCOA:
seed = Material.COCOA_BEANS;
case POTATO:
seed = new ItemStack(Material.POTATO_ITEM);
break;
default:
return;
break;
}
ItemStack seedStack = new ItemStack(seed);
if (!playerInventory.containsAtLeast(seedStack, 1)) {
if (!playerInventory.containsAtLeast(seed, 1)) {
return;
}
@@ -307,7 +322,7 @@ public class HerbalismManager extends SkillManager {
return;
}
playerInventory.removeItem(seedStack);
playerInventory.removeItem(seed);
player.updateInventory(); // Needed until replacement available
new HerbalismBlockUpdaterTask(blockState).runTaskLater(mcMMO.p, 0);
}
@@ -316,51 +331,74 @@ public class HerbalismManager extends SkillManager {
byte greenThumbStage = getGreenThumbStage();
blockState.setMetadata(mcMMO.greenThumbDataKey, new FixedMetadataValue(mcMMO.p, (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)));
Ageable crops = (Ageable) blockState.getBlockData();
switch (blockState.getType()) {
case POTATOES:
case CARROTS:
case WHEAT:
case CROPS:
Crops crops = (Crops) blockState.getData();
if (greenTerra) {
crops.setAge(3);
crops.setState(CropState.MEDIUM);
}
else {
crops.setAge(greenThumbStage);
switch (greenThumbStage) {
case 4:
crops.setState(CropState.SMALL);
break;
case 3:
crops.setState(CropState.VERY_SMALL);
break;
case 2:
crops.setState(CropState.GERMINATED);
break;
default:
crops.setState(CropState.SEEDED);
break;
}
}
break;
case BEETROOTS:
case NETHER_WART:
return true;
case CARROT:
case POTATO:
if (greenTerra) {
blockState.setRawData(CropState.MEDIUM.getData());
}
else {
blockState.setRawData(greenThumbStage);
}
return true;
case NETHER_WARTS:
NetherWarts warts = (NetherWarts) blockState.getData();
if (greenTerra || greenThumbStage > 2) {
crops.setAge(2);
warts.setState(NetherWartsState.STAGE_TWO);
}
else if (greenThumbStage == 2) {
crops.setAge(1);
warts.setState(NetherWartsState.STAGE_ONE);
}
else {
crops.setAge(0);
warts.setState(NetherWartsState.SEEDED);
}
break;
return true;
case COCOA:
CocoaPlant plant = (CocoaPlant) blockState.getData();
if (greenTerra || getGreenThumbStage() > 1) {
crops.setAge(1);
plant.setSize(CocoaPlantSize.MEDIUM);
}
else {
crops.setAge(0);
plant.setSize(CocoaPlantSize.SMALL);
}
break;
return true;
default:
return false;
}
blockState.setBlockData(crops);
return true;
}
private byte getGreenThumbStage() {

View File

@@ -1,13 +1,15 @@
package com.gmail.nossr50.skills.mining;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.util.Misc;
public class Mining {
/**
@@ -15,8 +17,9 @@ public class Mining {
*
* @param blockState The {@link BlockState} to check ability activation for
*/
public static int getBlockXp(BlockState blockState) {
int xp = ExperienceConfig.getInstance().getXp(SkillType.MINING, blockState.getType());
protected static int getBlockXp(BlockState blockState) {
Material blockType = blockState.getType();
int xp = ExperienceConfig.getInstance().getXp(SkillType.MINING, blockType != Material.GLOWING_REDSTONE_ORE ? blockType : Material.REDSTONE_ORE);
if (xp == 0 && mcMMO.getModManager().isCustomMiningBlock(blockState)) {
xp = mcMMO.getModManager().getBlock(blockState).getXpGain();
@@ -34,65 +37,39 @@ public class Mining {
Material blockType = blockState.getType();
switch (blockType) {
case END_STONE:
case TERRACOTTA:
case CLAY:
case ENDER_STONE:
case GOLD_ORE:
case HARD_CLAY:
case IRON_ORE:
case MOSSY_COBBLESTONE:
case NETHERRACK:
case OBSIDIAN:
case SANDSTONE:
case BLACK_GLAZED_TERRACOTTA:
case BLACK_TERRACOTTA:
case BLUE_GLAZED_TERRACOTTA:
case BLUE_TERRACOTTA:
case BROWN_GLAZED_TERRACOTTA:
case BROWN_TERRACOTTA:
case CYAN_GLAZED_TERRACOTTA:
case CYAN_TERRACOTTA:
case GRAY_GLAZED_TERRACOTTA:
case GRAY_TERRACOTTA:
case GREEN_GLAZED_TERRACOTTA:
case GREEN_TERRACOTTA:
case LIGHT_BLUE_GLAZED_TERRACOTTA:
case LIGHT_BLUE_TERRACOTTA:
case LIGHT_GRAY_GLAZED_TERRACOTTA:
case LIGHT_GRAY_TERRACOTTA:
case LIME_GLAZED_TERRACOTTA:
case LIME_TERRACOTTA:
case MAGENTA_GLAZED_TERRACOTTA:
case MAGENTA_TERRACOTTA:
case ORANGE_GLAZED_TERRACOTTA:
case ORANGE_TERRACOTTA:
case PINK_GLAZED_TERRACOTTA:
case PINK_TERRACOTTA:
case PURPLE_GLAZED_TERRACOTTA:
case PURPLE_TERRACOTTA:
case RED_GLAZED_TERRACOTTA:
case RED_TERRACOTTA:
case WHITE_GLAZED_TERRACOTTA:
case WHITE_TERRACOTTA:
case YELLOW_GLAZED_TERRACOTTA:
case YELLOW_TERRACOTTA:
case STAINED_CLAY:
handleMiningDrops(blockState);
return;
case GLOWING_REDSTONE_ORE:
if (Config.getInstance().getDoubleDropsEnabled(SkillType.MINING, Material.REDSTONE_ORE)) {
Misc.dropItem(blockState.getLocation(), new ItemStack(Material.REDSTONE_ORE));
}
return;
case COAL_ORE:
case DIAMOND_ORE:
case EMERALD_ORE:
case GLOWSTONE:
case LAPIS_ORE:
case PACKED_ICE:
case NETHER_QUARTZ_ORE:
case QUARTZ_ORE:
case REDSTONE_ORE:
case STONE:
case PRISMARINE:
Misc.dropItem(Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()));
Misc.dropItem(blockState.getLocation(), new ItemStack(blockType));
return;
default:
if (mcMMO.getModManager().isCustomMiningBlock(blockState)) {
Misc.dropItem(Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()));
Misc.dropItem(blockState.getLocation(), blockState.getData().toItemStack(1));
}
return;
}
@@ -108,10 +85,10 @@ public class Mining {
case COAL_ORE:
case DIAMOND_ORE:
case EMERALD_ORE:
case END_STONE:
case ENDER_STONE:
case GLOWSTONE:
case GOLD_ORE:
case TERRACOTTA:
case HARD_CLAY:
case IRON_ORE:
case LAPIS_ORE:
case MOSSY_COBBLESTONE:
@@ -120,46 +97,21 @@ public class Mining {
case PACKED_ICE:
case REDSTONE_ORE:
case SANDSTONE:
case BLACK_GLAZED_TERRACOTTA:
case BLACK_TERRACOTTA:
case BLUE_GLAZED_TERRACOTTA:
case BLUE_TERRACOTTA:
case BROWN_GLAZED_TERRACOTTA:
case BROWN_TERRACOTTA:
case CYAN_GLAZED_TERRACOTTA:
case CYAN_TERRACOTTA:
case GRAY_GLAZED_TERRACOTTA:
case GRAY_TERRACOTTA:
case GREEN_GLAZED_TERRACOTTA:
case GREEN_TERRACOTTA:
case LIGHT_BLUE_GLAZED_TERRACOTTA:
case LIGHT_BLUE_TERRACOTTA:
case LIGHT_GRAY_GLAZED_TERRACOTTA:
case LIGHT_GRAY_TERRACOTTA:
case LIME_GLAZED_TERRACOTTA:
case LIME_TERRACOTTA:
case MAGENTA_GLAZED_TERRACOTTA:
case MAGENTA_TERRACOTTA:
case ORANGE_GLAZED_TERRACOTTA:
case ORANGE_TERRACOTTA:
case PINK_GLAZED_TERRACOTTA:
case PINK_TERRACOTTA:
case PURPLE_GLAZED_TERRACOTTA:
case PURPLE_TERRACOTTA:
case RED_GLAZED_TERRACOTTA:
case RED_TERRACOTTA:
case WHITE_GLAZED_TERRACOTTA:
case WHITE_TERRACOTTA:
case YELLOW_GLAZED_TERRACOTTA:
case YELLOW_TERRACOTTA:
case STAINED_CLAY:
case STONE:
case NETHER_QUARTZ_ORE:
Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops());
case QUARTZ_ORE:
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
return;
case GLOWING_REDSTONE_ORE:
if (Config.getInstance().getDoubleDropsEnabled(SkillType.MINING, Material.REDSTONE_ORE)) {
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
return;
default:
if (mcMMO.getModManager().isCustomMiningBlock(blockState)) {
Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops());
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
return;
}

View File

@@ -1,5 +1,16 @@
package com.gmail.nossr50.skills.mining;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType;
@@ -7,7 +18,6 @@ import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.skills.AbilityCooldownTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.mining.BlastMining.Tier;
@@ -16,16 +26,6 @@ import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.inventory.ItemStack;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import java.util.ArrayList;
import java.util.List;
public class MiningManager extends SkillManager {
public MiningManager(McMMOPlayer mcMMOPlayer) {
@@ -39,7 +39,7 @@ public class MiningManager extends SkillManager {
public boolean canDetonate() {
Player player = getPlayer();
return canUseBlastMining() && player.isSneaking() && player.getInventory().getItemInMainHand().getType() == BlastMining.detonator && Permissions.remoteDetonation(player);
return canUseBlastMining() && player.isSneaking() && player.getItemInHand().getType() == BlastMining.detonator && Permissions.remoteDetonation(player);
}
public boolean canUseBlastMining() {
@@ -67,14 +67,14 @@ public class MiningManager extends SkillManager {
Material material = blockState.getType();
if (mcMMOPlayer.getAbilityMode(skill.getAbility())) {
SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), Config.getInstance().getAbilityToolDamage());
SkillUtils.handleDurabilityChange(getPlayer().getItemInHand(), Config.getInstance().getAbilityToolDamage());
}
if ((mcMMO.getModManager().isCustomMiningBlock(blockState) && !mcMMO.getModManager().getBlock(blockState).isDoubleDropEnabled()) || !Config.getInstance().getDoubleDropsEnabled(skill, material)) {
if ((mcMMO.getModManager().isCustomMiningBlock(blockState) && !mcMMO.getModManager().getBlock(blockState).isDoubleDropEnabled()) || material != Material.GLOWING_REDSTONE_ORE && !Config.getInstance().getDoubleDropsEnabled(skill, material)) {
return;
}
boolean silkTouch = player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH);
boolean silkTouch = player.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH);
for (int i = mcMMOPlayer.getAbilityMode(skill.getAbility()) ? 2 : 1; i != 0; i--) {
if (SkillUtils.activationSuccessful(SecondaryAbility.MINING_DOUBLE_DROPS, getPlayer(), getSkillLevel(), activationChance)) {
@@ -147,7 +147,7 @@ public class MiningManager extends SkillManager {
xp += Mining.getBlockXp(blockState);
}
Misc.dropItem(Misc.getBlockCenter(blockState), new ItemStack(blockState.getType())); // Initial block that would have been dropped
Misc.dropItem(blockState.getLocation(), blockState.getData().toItemStack(1)); // Initial block that would have been dropped
if (!mcMMO.getPlaceStore().isTrue(blockState)) {
for (int i = 1; i < dropMultiplier; i++) {
@@ -160,7 +160,7 @@ public class MiningManager extends SkillManager {
if (debrisYield > 0) {
for (BlockState blockState : debris) {
if (Misc.getRandom().nextFloat() < debrisYield) {
Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops());
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
}
}

View File

@@ -1,5 +1,17 @@
package com.gmail.nossr50.skills.repair;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.material.MaterialData;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
@@ -7,7 +19,6 @@ import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.repair.ArcaneForging.Tier;
import com.gmail.nossr50.skills.repair.repairables.Repairable;
@@ -16,16 +27,6 @@ import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.block.data.BlockData;
import java.util.Map;
import java.util.Map.Entry;
public class RepairManager extends SkillManager {
private boolean placedAnvil;
@@ -50,7 +51,7 @@ public class RepairManager extends SkillManager {
}
if (Config.getInstance().getRepairAnvilPlaceSoundsEnabled()) {
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_LAND, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
player.playSound(player.getLocation(), Sound.ANVIL_LAND, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
}
togglePlacedAnvil();
@@ -60,18 +61,13 @@ public class RepairManager extends SkillManager {
Player player = getPlayer();
Repairable repairable = mcMMO.getRepairableManager().getRepairable(item.getType());
if (item.getItemMeta().isUnbreakable()) {
player.sendMessage(LocaleLoader.getString("Anvil.Unbreakable"));
return;
}
// Permissions checks on material and item types
if (!Permissions.repairMaterialType(player, repairable.getRepairMaterialType())) {
player.sendMessage(LocaleLoader.getString("mcMMO.NoPermission"));
return;
}
if (!Permissions.repairItemType(player, repairable.getRepairItemType())) {
if (!Permissions.repairMaterialType(player, repairable.getRepairMaterialType())) {
player.sendMessage(LocaleLoader.getString("mcMMO.NoPermission"));
return;
}
@@ -89,7 +85,7 @@ public class RepairManager extends SkillManager {
Material repairMaterial = repairable.getRepairMaterial();
byte repairMaterialMetadata = repairable.getRepairMaterialMetadata();
ItemStack toRemove = new ItemStack(repairMaterial);
ItemStack toRemove = new MaterialData(repairMaterial, repairMaterialMetadata).toItemStack(1);
short startDurability = item.getDurability();
@@ -149,7 +145,7 @@ public class RepairManager extends SkillManager {
// BWONG BWONG BWONG
if (Config.getInstance().getRepairAnvilUseSoundsEnabled()) {
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_USE, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
player.playSound(player.getLocation(), Sound.ANVIL_USE, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
}
// Repair the item!
@@ -163,6 +159,9 @@ public class RepairManager extends SkillManager {
/**
* Check if the player has tried to use an Anvil before.
*
* @param anvilType The {@link Material} of the anvil block
* @param actualize determines if last anvil use should be actualized
*
* @return true if the player has confirmed using an Anvil
*/
public boolean checkConfirmation(boolean actualize) {
@@ -277,7 +276,7 @@ public class RepairManager extends SkillManager {
/**
* Handles removing & downgrading enchants.
*
* @param item Item being repaired
* @param item {@link ItemStack} being repaired
*/
private void addEnchants(ItemStack item) {
Player player = getPlayer();

View File

@@ -1,18 +1,8 @@
package com.gmail.nossr50.skills.salvage;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.salvage.Salvage.Tier;
import com.gmail.nossr50.skills.salvage.salvageables.Salvageable;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
@@ -20,10 +10,20 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.block.data.BlockData;
import org.bukkit.material.MaterialData;
import java.util.Map;
import java.util.Map.Entry;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.salvage.Salvage.Tier;
import com.gmail.nossr50.skills.salvage.salvageables.Salvageable;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
public class SalvageManager extends SkillManager {
private boolean placedAnvil;
@@ -48,7 +48,7 @@ public class SalvageManager extends SkillManager {
}
if (Config.getInstance().getSalvageAnvilPlaceSoundsEnabled()) {
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_LAND, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
player.playSound(player.getLocation(), Sound.ANVIL_LAND, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
}
togglePlacedAnvil();
@@ -59,11 +59,6 @@ public class SalvageManager extends SkillManager {
Salvageable salvageable = mcMMO.getSalvageableManager().getSalvageable(item.getType());
if (item.getItemMeta().isUnbreakable()) {
player.sendMessage(LocaleLoader.getString("Anvil.Unbreakable"));
return;
}
// Permissions checks on material and item types
if (!Permissions.salvageItemType(player, salvageable.getSalvageItemType())) {
player.sendMessage(LocaleLoader.getString("mcMMO.NoPermission"));
@@ -98,33 +93,27 @@ public class SalvageManager extends SkillManager {
salvageableAmount = Math.max((int) (salvageableAmount * getMaxSalvagePercentage()), 1); // Always get at least something back, if you're capable of salvaging it.
player.getInventory().setItemInMainHand(new ItemStack(Material.AIR));
location.add(0.5, 1, 0.5);
player.setItemInHand(new ItemStack(Material.AIR));
location.add(0, 1, 0);
Map<Enchantment, Integer> enchants = item.getEnchantments();
ItemStack enchantBook = null;
if (!enchants.isEmpty()) {
enchantBook = arcaneSalvageCheck(enchants);
ItemStack enchantBook = arcaneSalvageCheck(enchants);
if (enchantBook != null) {
Misc.dropItem(location, enchantBook);
}
}
ItemStack salvageResults = new ItemStack(salvageable.getSalvageMaterial(), salvageableAmount);
byte salvageMaterialMetadata = (salvageable.getSalvageMaterialMetadata() != (byte) -1) ? salvageable.getSalvageMaterialMetadata() : 0;
//Call event
if (EventUtils.callSalvageCheckEvent(player, item, salvageResults, enchantBook).isCancelled()) {
return;
}
if (enchantBook != null) {
Misc.dropItem(location, enchantBook);
}
Misc.dropItems(location, salvageResults, 1);
Misc.dropItems(location, new MaterialData(salvageable.getSalvageMaterial(), salvageMaterialMetadata).toItemStack(salvageableAmount), 1);
// BWONG BWONG BWONG - CLUNK!
if (Config.getInstance().getSalvageAnvilUseSoundsEnabled()) {
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_USE, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, 1.0F);
player.playSound(player.getLocation(), Sound.ANVIL_USE, Misc.ANVIL_USE_VOLUME, Misc.ANVIL_USE_PITCH);
player.playSound(player.getLocation(), Sound.ITEM_BREAK, 1.0F, 1.0F);
}
player.sendMessage(LocaleLoader.getString("Salvage.Skills.Success"));

View File

@@ -1,10 +1,13 @@
package com.gmail.nossr50.skills.smelting;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.mcMMO;
import org.bukkit.inventory.ItemStack;
public class Smelting {
// The order of the values is extremely important, a few methods depend on it to work properly
@@ -20,7 +23,7 @@ public class Smelting {
int numerical;
Tier(int numerical) {
private Tier(int numerical) {
this.numerical = numerical;
}
@@ -44,6 +47,9 @@ public class Smelting {
public static double fluxMiningChance = AdvancedConfig.getInstance().getFluxMiningChance();
protected static int getResourceXp(ItemStack smelting) {
return mcMMO.getModManager().isCustomOre(smelting.getType()) ? mcMMO.getModManager().getBlock(smelting.getType()).getSmeltingXpGain() : ExperienceConfig.getInstance().getXp(SkillType.SMELTING, smelting.getType());
MaterialData data = smelting.getData();
Material resourceType = smelting.getType();
return mcMMO.getModManager().isCustomOre(data) ? mcMMO.getModManager().getBlock(data).getSmeltingXpGain() : ExperienceConfig.getInstance().getXp(SkillType.SMELTING, resourceType != Material.GLOWING_REDSTONE_ORE ? resourceType : Material.REDSTONE_ORE);
}
}

View File

@@ -1,34 +1,24 @@
package com.gmail.nossr50.skills.smelting;
import com.gmail.nossr50.config.Config;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.events.skills.secondaryabilities.SecondaryAbilityWeightedActivationCheckEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.mining.Mining;
import com.gmail.nossr50.skills.smelting.Smelting.Tier;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
public class SmeltingManager extends SkillManager {
public SmeltingManager(McMMOPlayer mcMMOPlayer) {
@@ -73,51 +63,17 @@ public class SmeltingManager extends SkillManager {
if (item == null) {
return false;
}
if (!EventUtils.simulateBlockBreak(blockState.getBlock(), player, true)) {
return false;
}
// We need to distribute Mining XP here, because the block break event gets cancelled
applyXpGain(Mining.getBlockXp(blockState), XPGainReason.PVE);
SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), Config.getInstance().getAbilityToolDamage());
Misc.dropItems(Misc.getBlockCenter(blockState), item, isSecondSmeltSuccessful() ? 2 : 1);
Misc.dropItems(blockState.getLocation(), item, isSecondSmeltSuccessful() ? 2 : 1);
blockState.setType(Material.AIR);
if (Config.getInstance().getFluxPickaxeSoundEnabled()) {
player.playSound(blockState.getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, Misc.FIZZ_VOLUME, Misc.getFizzPitch());
}
ParticleEffectUtils.playFluxEffect(blockState.getLocation());
player.sendMessage(LocaleLoader.getString("Smelting.FluxMining.Success"));
return true;
}
return false;
}
public static ItemStack getFluxPickaxe(Material material, int amount) {
ItemStack itemStack = new ItemStack(material, amount);
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setDisplayName(ChatColor.GOLD + LocaleLoader.getString("Item.FluxPickaxe.Name"));
List<String> itemLore = itemMeta.hasLore() ? itemMeta.getLore() : new ArrayList<String>();
itemLore.add("mcMMO Item");
itemLore.add(LocaleLoader.getString("Item.FluxPickaxe.Lore.1"));
itemLore.add(LocaleLoader.getString("Item.FluxPickaxe.Lore.2", Smelting.fluxMiningUnlockLevel));
itemMeta.setLore(itemLore);
itemStack.setItemMeta(itemMeta);
return itemStack;
}
public static FurnaceRecipe getFluxPickaxeRecipe(Material material) {
return new FurnaceRecipe(getFluxPickaxe(material, 1), material);
}
/**
* Increases burn time for furnace fuel.
*

View File

@@ -83,7 +83,7 @@ public class SwordsManager extends SkillManager {
}
if (SkillUtils.activationSuccessful(SecondaryAbility.COUNTER, getPlayer(), getSkillLevel(), activationChance)) {
CombatUtils.dealDamage(attacker, damage / Swords.counterAttackModifier, getPlayer());
CombatUtils.dealDamage(attacker, damage / Swords.counterAttackModifier);
getPlayer().sendMessage(LocaleLoader.getString("Swords.Combat.Countered"));

View File

@@ -30,6 +30,10 @@ public class Taming {
public static int thickFurUnlockLevel = AdvancedConfig.getInstance().getThickFurUnlock();
public static double thickFurModifier = AdvancedConfig.getInstance().getThickFurModifier();
public static int wolfXp = ExperienceConfig.getInstance().getTamingXPWolf();
public static int ocelotXp = ExperienceConfig.getInstance().getTamingXPOcelot();
public static int horseXp = ExperienceConfig.getInstance().getTamingXPHorse();
public static boolean canPreventDamage(Tameable pet, AnimalTamer owner) {
return pet.isTamed() && owner instanceof Player && pet instanceof Wolf;
}

View File

@@ -1,8 +1,24 @@
package com.gmail.nossr50.skills.taming;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Ocelot;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
@@ -10,7 +26,6 @@ import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.events.fake.FakeEntityTameEvent;
import com.gmail.nossr50.events.skills.secondaryabilities.SecondaryAbilityWeightedActivationCheckEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.skills.BleedTimerTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.util.Misc;
@@ -19,14 +34,6 @@ import com.gmail.nossr50.util.StringUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TamingManager extends SkillManager {
public TamingManager(McMMOPlayer mcMMOPlayer) {
@@ -40,7 +47,7 @@ public class TamingManager extends SkillManager {
}
public boolean canUseEnvironmentallyAware() {
return getSkillLevel() >= Taming.environmentallyAwareUnlockLevel && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.ENVIRONMENTALLY_AWARE);
return getSkillLevel() >= Taming.environmentallyAwareUnlockLevel && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.ENVIROMENTALLY_AWARE);
}
public boolean canUseShockProof() {
@@ -73,7 +80,22 @@ public class TamingManager extends SkillManager {
* @param entity The LivingEntity to award XP for
*/
public void awardTamingXP(LivingEntity entity) {
applyXpGain(ExperienceConfig.getInstance().getTamingXP(entity.getType()), XPGainReason.PVE);
switch (entity.getType()) {
case HORSE:
applyXpGain(Taming.horseXp, XPGainReason.PVE);
return;
case WOLF:
applyXpGain(Taming.wolfXp, XPGainReason.PVE);
return;
case OCELOT:
applyXpGain(Taming.ocelotXp, XPGainReason.PVE);
return;
default:
return;
}
}
/**
@@ -110,7 +132,7 @@ public class TamingManager extends SkillManager {
BleedTimerTask.add(target, Taming.goreBleedTicks);
if (target instanceof Player) {
target.sendMessage(LocaleLoader.getString("Combat.StruckByGore"));
((Player) target).sendMessage(LocaleLoader.getString("Combat.StruckByGore"));
}
getPlayer().sendMessage(LocaleLoader.getString("Combat.Gore"));
@@ -234,7 +256,7 @@ public class TamingManager extends SkillManager {
private void callOfTheWild(EntityType type, int summonAmount) {
Player player = getPlayer();
ItemStack heldItem = player.getInventory().getItemInMainHand();
ItemStack heldItem = player.getItemInHand();
int heldItemAmount = heldItem.getAmount();
Location location = player.getLocation();
@@ -255,7 +277,6 @@ public class TamingManager extends SkillManager {
return;
}
location = Misc.getLocationOffset(location, 1);
LivingEntity entity = (LivingEntity) player.getWorld().spawnEntity(location, type);
FakeEntityTameEvent event = new FakeEntityTameEvent(entity, player);
@@ -303,9 +324,7 @@ public class TamingManager extends SkillManager {
ParticleEffectUtils.playCallOfTheWildEffect(entity);
}
ItemStack leftovers = new ItemStack(heldItem);
leftovers.setAmount(heldItemAmount - summonAmount);
player.getInventory().setItemInMainHand(heldItemAmount == summonAmount ? null : leftovers);
player.setItemInHand(heldItemAmount == summonAmount ? null : new ItemStack(heldItem.getType(), heldItemAmount - summonAmount));
String lifeSpan = "";
if (tamingCOTWLength > 0) {
@@ -313,7 +332,7 @@ public class TamingManager extends SkillManager {
}
player.sendMessage(LocaleLoader.getString("Taming.Summon.Complete") + lifeSpan);
player.playSound(location, Sound.ENTITY_FIREWORK_ROCKET_BLAST_FAR, 1F, 0.5F);
player.playSound(location, Sound.FIREWORK_LARGE_BLAST2, 1F, 0.5F);
}
private boolean rangeCheck(EntityType type) {

View File

@@ -1,27 +1,40 @@
package com.gmail.nossr50.skills.taming;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.UUID;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.ParticleEffectUtils;
public class TrackedTamingEntity extends BukkitRunnable {
private LivingEntity livingEntity;
private UUID id;
private int length;
private Player owner;
protected TrackedTamingEntity(LivingEntity livingEntity) {
this.livingEntity = livingEntity;
this.id = livingEntity.getUniqueId();
AnimalTamer tamer = ((Tameable)livingEntity).getOwner();
if (tamer != null && tamer instanceof Player) {
this.owner = (Player) tamer;
}
int tamingCOTWLength = Config.getInstance().getTamingCOTWLength(livingEntity.getType());
if (tamingCOTWLength > 0) {
@@ -34,12 +47,15 @@ public class TrackedTamingEntity extends BukkitRunnable {
public void run() {
if (livingEntity.isValid()) {
Location location = livingEntity.getLocation();
location.getWorld().playSound(location, Sound.BLOCK_FIRE_EXTINGUISH, 0.8F, 0.8F);
location.getWorld().playSound(location, Sound.FIZZ, 0.8F, 0.8F);
ParticleEffectUtils.playCallOfTheWildEffect(livingEntity);
CombatUtils.dealDamage(livingEntity, livingEntity.getMaxHealth(), DamageCause.SUICIDE, livingEntity);
}
TamingManager.removeFromTracker(this);
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(owner);
TamingManager tamingManager = mcMMOPlayer.getTamingManager();
tamingManager.removeFromTracker(this);
this.cancel();
}

View File

@@ -26,8 +26,7 @@ public class Unarmed {
if (inventory.containsAtLeast(dropStack, 1)) {
int nextSlot = 0;
ItemStack[] items = inventory.getStorageContents();
for (ItemStack itemstack : items) {
for (ItemStack itemstack : inventory) {
if (dropStack.isSimilar(itemstack)) {
int itemAmount = itemstack.getAmount();
int itemMax = itemstack.getMaxStackSize();
@@ -37,15 +36,13 @@ public class Unarmed {
if (dropAmount + itemAmount <= itemMax) {
drop.remove();
addStack.setAmount(dropAmount + itemAmount);
items[nextSlot] = addStack;
inventory.setStorageContents(items);
inventory.setItem(nextSlot, addStack);
return true;
}
addStack.setAmount(itemMax);
dropAmount = dropAmount + itemAmount - itemMax;
items[nextSlot] = addStack;
inventory.setStorageContents(items);
inventory.setItem(nextSlot, addStack);
}
if (dropAmount == 0) {
@@ -60,15 +57,13 @@ public class Unarmed {
if (firstEmpty == inventory.getHeldItemSlot()) {
int nextSlot = firstEmpty + 1;
ItemStack[] items = inventory.getStorageContents();
for (; nextSlot < items.length; nextSlot++) {
ItemStack itemstack = items[nextSlot];
for (Iterator<ItemStack> iterator = inventory.iterator(nextSlot); iterator.hasNext(); ) {
ItemStack itemstack = iterator.next();
if (itemstack == null) {
drop.remove();
dropStack.setAmount(dropAmount);
items[nextSlot] = dropStack;
inventory.setStorageContents(items);
inventory.setItem(nextSlot, dropStack);
return true;
}
@@ -76,14 +71,7 @@ public class Unarmed {
}
// Inventory is full - cancel the item pickup
if (dropStack.getAmount() == dropAmount) {
return false;
} else {
drop.remove();
dropStack.setAmount(dropAmount);
((Item) drop.getWorld().dropItem(drop.getLocation(), dropStack)).setPickupDelay(0);
return true;
}
return false;
}
else if (firstEmpty != -1) {
drop.remove();

View File

@@ -1,5 +1,15 @@
package com.gmail.nossr50.skills.unarmed;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.SmoothBrick;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType;
@@ -7,21 +17,12 @@ import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.ToolType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.block.data.BlockData;
public class UnarmedManager extends SkillManager {
public UnarmedManager(McMMOPlayer mcMMOPlayer) {
@@ -41,13 +42,13 @@ public class UnarmedManager extends SkillManager {
}
public boolean canDisarm(LivingEntity target) {
return target instanceof Player && ((Player) target).getInventory().getItemInMainHand().getType() != Material.AIR && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DISARM);
return target instanceof Player && ((Player) target).getItemInHand().getType() != Material.AIR && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DISARM);
}
public boolean canDeflect() {
Player player = getPlayer();
return ItemUtils.isUnarmed(player.getInventory().getItemInMainHand()) && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DEFLECT);
return player.getItemInHand().getType() == Material.AIR && Permissions.secondaryAbilityEnabled(getPlayer(), SecondaryAbility.DEFLECT);
}
public boolean canUseBlockCracker() {
@@ -59,15 +60,22 @@ public class UnarmedManager extends SkillManager {
return false;
}
BlockData data = blockState.getBlockData();
MaterialData data = blockState.getData();
switch (blockState.getType()) {
case STONE_BRICKS:
case SMOOTH_BRICK:
if (!Unarmed.blockCrackerSmoothBrick) {
return false;
}
blockState.setType(Material.CRACKED_STONE_BRICKS);
// Yes, this is awkward, but it's the *right* way to do it.
SmoothBrick smoothBrick = (SmoothBrick) data;
if (smoothBrick.getMaterial() != Material.STONE) {
return false;
}
smoothBrick.setMaterial(Material.COBBLESTONE);
return true;
default:
@@ -86,13 +94,13 @@ public class UnarmedManager extends SkillManager {
return;
}
Item item = Misc.dropItem(defender.getLocation(), defender.getInventory().getItemInMainHand());
Item item = Misc.dropItem(defender.getLocation(), defender.getItemInHand());
if (item != null && AdvancedConfig.getInstance().getDisarmProtected()) {
item.setMetadata(mcMMO.disarmedItemKey, UserManager.getPlayer(defender).getPlayerMetadata());
}
defender.getInventory().setItemInMainHand(new ItemStack(Material.AIR));
defender.setItemInHand(new ItemStack(Material.AIR));
defender.sendMessage(LocaleLoader.getString("Skills.Disarmed"));
}
}

View File

@@ -1,22 +1,24 @@
package com.gmail.nossr50.skills.woodcutting;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Tree;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class Woodcutting {
public static int leafBlowerUnlockLevel = AdvancedConfig.getInstance().getLeafBlowUnlockLevel();
public static int treeFellerThreshold = Config.getInstance().getTreeFellerThreshold();
@@ -26,7 +28,7 @@ public final class Woodcutting {
protected enum ExperienceGainMethod {
DEFAULT,
TREE_FELLER,
}
};
private Woodcutting() {}
@@ -38,11 +40,35 @@ public final class Woodcutting {
* @return Amount of experience
*/
protected static int getExperienceFromLog(BlockState blockState, ExperienceGainMethod experienceGainMethod) {
// Mushrooms aren't trees so we could never get species data from them
switch (blockState.getType()) {
case HUGE_MUSHROOM_1:
return ExperienceConfig.getInstance().getWoodcuttingXPHugeBrownMushroom();
case HUGE_MUSHROOM_2:
return ExperienceConfig.getInstance().getWoodcuttingXPHugeRedMushroom();
default:
break;
}
if (mcMMO.getModManager().isCustomLog(blockState)) {
return mcMMO.getModManager().getBlock(blockState).getXpGain();
}
return ExperienceConfig.getInstance().getXp(SkillType.WOODCUTTING, blockState.getType());
//TODO Remove this workaround when casting to Tree works again
TreeSpecies species = TreeSpecies.GENERIC;
if (blockState.getData() instanceof Tree) {
species = ((Tree) blockState.getData()).getSpecies();
}
int xp = ExperienceConfig.getInstance().getWoodcuttingTreeXP(species);
if (species == TreeSpecies.JUNGLE && experienceGainMethod == ExperienceGainMethod.TREE_FELLER) {
xp *= 0.5;
}
return xp;
}
/**
@@ -52,11 +78,17 @@ public final class Woodcutting {
*/
protected static void checkForDoubleDrop(BlockState blockState) {
if (mcMMO.getModManager().isCustomLog(blockState) && mcMMO.getModManager().getBlock(blockState).isDoubleDropEnabled()) {
Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops());
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
else {
if (Config.getInstance().getWoodcuttingDoubleDropsEnabled(blockState.getBlockData())) {
Misc.dropItems(Misc.getBlockCenter(blockState), blockState.getBlock().getDrops());
//TODO Remove this workaround when casting to Tree works again
TreeSpecies species = TreeSpecies.GENERIC;
if (blockState.getData() instanceof Tree) {
species = ((Tree) blockState.getData()).getSpecies();
}
if (Config.getInstance().getWoodcuttingDoubleDropsEnabled(species)) {
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
}
}

View File

@@ -1,5 +1,17 @@
package com.gmail.nossr50.skills.woodcutting;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Tree;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.AbilityType;
@@ -7,20 +19,14 @@ import com.gmail.nossr50.datatypes.skills.SecondaryAbility;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.datatypes.skills.XPGainReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.woodcutting.Woodcutting.ExperienceGainMethod;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.HashSet;
import java.util.Set;
public class WoodcuttingManager extends SkillManager {
public WoodcuttingManager(McMMOPlayer mcMMOPlayer) {
@@ -48,8 +54,8 @@ public class WoodcuttingManager extends SkillManager {
int xp = Woodcutting.getExperienceFromLog(blockState, ExperienceGainMethod.DEFAULT);
switch (blockState.getType()) {
case BROWN_MUSHROOM_BLOCK:
case RED_MUSHROOM_BLOCK:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
break;
default:
@@ -83,7 +89,7 @@ public class WoodcuttingManager extends SkillManager {
}
// If the tool can't sustain the durability loss
if (!Woodcutting.handleDurabilityLoss(treeFellerBlocks, player.getInventory().getItemInMainHand())) {
if (!Woodcutting.handleDurabilityLoss(treeFellerBlocks, player.getItemInHand())) {
player.sendMessage(LocaleLoader.getString("Woodcutting.Skills.TreeFeller.Splinter"));
double health = player.getHealth();
@@ -117,9 +123,9 @@ public class WoodcuttingManager extends SkillManager {
Material material = blockState.getType();
if (material == Material.BROWN_MUSHROOM_BLOCK || material == Material.RED_MUSHROOM_BLOCK) {
if (material == Material.HUGE_MUSHROOM_1 || material == Material.HUGE_MUSHROOM_2) {
xp += Woodcutting.getExperienceFromLog(blockState, ExperienceGainMethod.TREE_FELLER);
Misc.dropItems(Misc.getBlockCenter(blockState), block.getDrops());
Misc.dropItems(blockState.getLocation(), block.getDrops());
}
else if (mcMMO.getModManager().isCustomLog(blockState)) {
if (canGetDoubleDrops()) {
@@ -129,22 +135,35 @@ public class WoodcuttingManager extends SkillManager {
CustomBlock customBlock = mcMMO.getModManager().getBlock(blockState);
xp = customBlock.getXpGain();
Misc.dropItems(Misc.getBlockCenter(blockState), block.getDrops());
Misc.dropItems(blockState.getLocation(), block.getDrops());
}
else if (mcMMO.getModManager().isCustomLeaf(blockState)) {
Misc.dropItems(Misc.getBlockCenter(blockState), block.getDrops());
Misc.dropItems(blockState.getLocation(), block.getDrops());
}
else {
if (BlockUtils.isLog(blockState)) {
if (canGetDoubleDrops()) {
Woodcutting.checkForDoubleDrop(blockState);
}
xp += Woodcutting.getExperienceFromLog(blockState, ExperienceGainMethod.TREE_FELLER);
Misc.dropItems(Misc.getBlockCenter(blockState), block.getDrops());
//TODO Remove this workaround when casting to Tree works again
if (blockState.getData() instanceof Tree) {
Tree tree = (Tree) blockState.getData();
tree.setDirection(BlockFace.UP);
}
if (BlockUtils.isLeaves(blockState)) {
Misc.dropItems(Misc.getBlockCenter(blockState), block.getDrops());
switch (material) {
case LOG:
case LOG_2:
if (canGetDoubleDrops()) {
Woodcutting.checkForDoubleDrop(blockState);
}
xp += Woodcutting.getExperienceFromLog(blockState, ExperienceGainMethod.TREE_FELLER);
Misc.dropItems(blockState.getLocation(), block.getDrops());
break;
case LEAVES:
case LEAVES_2:
Misc.dropItems(blockState.getLocation(), block.getDrops());
break;
default:
break;
}
}

View File

@@ -1,26 +1,28 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.salvage.Salvage;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.Ageable;
import org.bukkit.block.data.BlockData;
import java.util.HashSet;
public final class BlockUtils {
import org.bukkit.CropState;
import org.bukkit.Material;
import org.bukkit.NetherWartsState;
import org.bukkit.block.BlockState;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.CocoaPlant.CocoaPlantSize;
import org.bukkit.material.Crops;
import org.bukkit.material.NetherWarts;
import org.bukkit.material.SmoothBrick;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.Repair;
import com.gmail.nossr50.skills.salvage.Salvage;
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
* @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) {
@@ -30,100 +32,40 @@ public final class BlockUtils {
/**
* 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
* @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 BLACK_BED:
case BLUE_BED:
case BROWN_BED:
case CYAN_BED:
case GRAY_BED:
case GREEN_BED:
case LIGHT_BLUE_BED:
case LIGHT_GRAY_BED:
case LIME_BED:
case MAGENTA_BED:
case ORANGE_BED:
case PINK_BED:
case PURPLE_BED:
case RED_BED:
case WHITE_BED:
case YELLOW_BED:
case BREWING_STAND :
case BOOKSHELF :
case CAKE:
case CHEST :
case DISPENSER :
case ENCHANTING_TABLE:
case ENDER_CHEST :
case OAK_FENCE_GATE:
case ACACIA_FENCE_GATE :
case DARK_OAK_FENCE_GATE :
case SPRUCE_FENCE_GATE :
case BIRCH_FENCE_GATE :
case JUNGLE_FENCE_GATE :
case FURNACE :
case JUKEBOX :
case LEVER :
case NOTE_BLOCK :
case STONE_BUTTON :
case OAK_BUTTON:
case BIRCH_BUTTON:
case ACACIA_BUTTON:
case DARK_OAK_BUTTON:
case JUNGLE_BUTTON:
case SPRUCE_BUTTON:
case ACACIA_TRAPDOOR:
case BIRCH_TRAPDOOR:
case DARK_OAK_TRAPDOOR:
case JUNGLE_TRAPDOOR:
case OAK_TRAPDOOR:
case SPRUCE_TRAPDOOR:
case WALL_SIGN :
case CRAFTING_TABLE:
case BEACON :
case ANVIL :
case DROPPER :
case HOPPER :
case TRAPPED_CHEST :
case IRON_DOOR :
case IRON_TRAPDOOR :
case OAK_DOOR:
case ACACIA_DOOR :
case SPRUCE_DOOR :
case BIRCH_DOOR :
case JUNGLE_DOOR :
case DARK_OAK_DOOR :
case OAK_FENCE:
case ACACIA_FENCE :
case DARK_OAK_FENCE :
case BIRCH_FENCE :
case JUNGLE_FENCE :
case SPRUCE_FENCE :
case ARMOR_STAND :
case BLACK_SHULKER_BOX :
case BLUE_SHULKER_BOX :
case BROWN_SHULKER_BOX :
case CYAN_SHULKER_BOX :
case GRAY_SHULKER_BOX :
case GREEN_SHULKER_BOX :
case LIGHT_BLUE_SHULKER_BOX :
case LIME_SHULKER_BOX :
case MAGENTA_SHULKER_BOX :
case ORANGE_SHULKER_BOX :
case PINK_SHULKER_BOX :
case PURPLE_SHULKER_BOX :
case RED_SHULKER_BOX :
case LIGHT_GRAY_SHULKER_BOX:
case WHITE_SHULKER_BOX :
case YELLOW_SHULKER_BOX :
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:
case DROPPER:
case HOPPER:
case TRAPPED_CHEST:
return false;
default :
default:
return !isMcMMOAnvil(blockState) && !mcMMO.getModManager().isCustomAbilityBlock(blockState);
}
}
@@ -131,35 +73,32 @@ public final class BlockUtils {
/**
* Check if a given block is an ore
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is an ore, false otherwise
*/
public static boolean isOre(BlockState blockState) {
return MaterialUtils.isOre(blockState.getType());
return MaterialUtils.isOre(blockState.getData());
}
/**
* Determine if a given block can be made mossy
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made mossy, false otherwise
*/
public static boolean canMakeMossy(BlockState blockState) {
switch (blockState.getType()) {
case COBBLESTONE :
case DIRT :
case GRASS_PATH :
case COBBLESTONE:
case DIRT:
return true;
case STONE_BRICKS:
return true;
case SMOOTH_BRICK:
return ((SmoothBrick) blockState.getData()).getMaterial() == Material.STONE;
case COBBLESTONE_WALL:
return true;
case COBBLE_WALL:
return blockState.getRawData() == (byte) 0x0;
default :
default:
return false;
}
}
@@ -167,78 +106,124 @@ public final class BlockUtils {
/**
* Determine if a given block should be affected by Green Terra
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Green Terra, false otherwise
*/
public static boolean affectedByGreenTerra(BlockState blockState) {
if (ExperienceConfig.getInstance().isSkillBlock(SkillType.HERBALISM, blockState.getBlockData())) {
return true;
}
switch (blockState.getType()) {
case BROWN_MUSHROOM:
case CACTUS:
case DOUBLE_PLANT:
case MELON_BLOCK:
case LONG_GRASS:
case PUMPKIN:
case RED_MUSHROOM:
case RED_ROSE:
case SUGAR_CANE_BLOCK:
case VINE:
case WATER_LILY:
case YELLOW_FLOWER:
return true;
return mcMMO.getModManager().isCustomHerbalismBlock(blockState);
case CARROT:
case POTATO:
return blockState.getRawData() == CropState.RIPE.getData();
case CROPS:
return ((Crops) blockState.getData()).getState() == CropState.RIPE;
case NETHER_WARTS:
return ((NetherWarts) blockState.getData()).getState() == NetherWartsState.RIPE;
case COCOA:
return ((CocoaPlant) blockState.getData()).getSize() == CocoaPlantSize.LARGE;
default:
return mcMMO.getModManager().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
* @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) {
if (ExperienceConfig.getInstance().isSkillBlock(SkillType.MINING, blockState.getBlockData()))
return true;
switch (blockState.getType()) {
case ENDER_STONE:
case GLOWSTONE:
case HARD_CLAY:
case MOSSY_COBBLESTONE:
case NETHERRACK:
case OBSIDIAN:
case PACKED_ICE:
case SANDSTONE:
case STAINED_CLAY:
case STONE:
return true;
return isOre(blockState) || mcMMO.getModManager().isCustomMiningBlock(blockState);
default:
return isOre(blockState) || mcMMO.getModManager().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
* @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) {
if (ExperienceConfig.getInstance().isSkillBlock(SkillType.EXCAVATION, blockState.getBlockData()))
return true;
return mcMMO.getModManager().isCustomExcavationBlock(blockState);
switch (blockState.getType()) {
case CLAY:
case DIRT:
case GRASS:
case GRAVEL:
case MYCEL:
case SAND:
case SNOW:
case SNOW_BLOCK:
case SOUL_SAND:
return true;
default:
return mcMMO.getModManager().isCustomExcavationBlock(blockState);
}
}
/**
* Check if a given block is a log
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a log, false otherwise
*/
public static boolean isLog(BlockState blockState) {
if (ExperienceConfig.getInstance().isSkillBlock(SkillType.WOODCUTTING, blockState.getBlockData()))
return true;
return mcMMO.getModManager().isCustomLog(blockState);
switch (blockState.getType()) {
case LOG:
case LOG_2:
case HUGE_MUSHROOM_1:
case HUGE_MUSHROOM_2:
return true;
default:
return mcMMO.getModManager().isCustomLog(blockState);
}
}
/**
* Check if a given block is a leaf
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a leaf, false otherwise
*/
public static boolean isLeaves(BlockState blockState) {
switch (blockState.getType()) {
case OAK_LEAVES:
case ACACIA_LEAVES:
case BIRCH_LEAVES:
case DARK_OAK_LEAVES:
case JUNGLE_LEAVES:
case SPRUCE_LEAVES:
case LEAVES:
case LEAVES_2:
return true;
default :
default:
return mcMMO.getModManager().isCustomLeaf(blockState);
}
}
@@ -246,17 +231,16 @@ public final class BlockUtils {
/**
* Determine if a given block should be affected by Flux Mining
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block should affected by Flux Mining, false otherwise
*/
public static boolean affectedByFluxMining(BlockState blockState) {
switch (blockState.getType()) {
case IRON_ORE :
case GOLD_ORE :
case IRON_ORE:
case GOLD_ORE:
return true;
default :
default:
return false;
}
}
@@ -264,20 +248,17 @@ public final class BlockUtils {
/**
* 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
* @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 GRASS_PATH :
case FARMLAND:
case DIRT:
case GRASS:
case SOIL:
return false;
default :
default:
return true;
}
}
@@ -285,17 +266,15 @@ public final class BlockUtils {
/**
* 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
* @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 STONE_BRICKS:
return true;
case SMOOTH_BRICK:
return ((SmoothBrick) blockState.getData()).getMaterial() == Material.STONE;
default :
default:
return false;
}
}
@@ -303,18 +282,16 @@ public final class BlockUtils {
/**
* Determine if a given block can be made into Mycelium
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block can be made into Mycelium, false otherwise
*/
public static boolean canMakeShroomy(BlockState blockState) {
switch (blockState.getType()) {
case DIRT :
case GRASS :
case GRASS_PATH :
case DIRT:
case GRASS:
return true;
default :
default:
return false;
}
}
@@ -322,8 +299,7 @@ public final class BlockUtils {
/**
* Determine if a given block is an mcMMO anvil
*
* @param blockState
* The {@link BlockState} of the block to check
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is an mcMMO anvil, false otherwise
*/
public static boolean isMcMMOAnvil(BlockState blockState) {
@@ -335,7 +311,7 @@ public final class BlockUtils {
public static boolean isPistonPiece(BlockState blockState) {
Material type = blockState.getType();
return type == Material.MOVING_PISTON || type == Material.AIR;
return type == Material.PISTON_MOVING_PIECE || type == Material.AIR;
}
/**
@@ -343,27 +319,15 @@ public final class BlockUtils {
*
* @return HashSet with the IDs of every transparent block
*/
public static HashSet<Material> getTransparentBlocks() {
HashSet<Material> transparentBlocks = new HashSet<Material>();
public static HashSet<Byte> getTransparentBlocks() {
HashSet<Byte> transparentBlocks = new HashSet<Byte>();
for (Material material : Material.values()) {
if (material.isTransparent()) {
transparentBlocks.add(material);
transparentBlocks.add((byte) material.getId());
}
}
return transparentBlocks;
}
public static boolean isFullyGrown(BlockState blockState) {
BlockData data = blockState.getBlockData();
if (data.getMaterial() == Material.CACTUS || data.getMaterial() == Material.SUGAR_CANE)
return true;
if (data instanceof Ageable)
{
Ageable ageable = (Ageable) data;
return ageable.getAge() == ageable.getMaximumAge();
}
return true;
}
}

View File

@@ -1,22 +1,27 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.items.ChimaeraWingWarmup;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.*;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.metrics.MetricsManager;
import com.gmail.nossr50.runnables.items.ChimaeraWingWarmup;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
public final class ChimaeraWing {
private static McMMOPlayer mcMMOPlayer;
@@ -34,7 +39,7 @@ public final class ChimaeraWing {
return;
}
ItemStack inHand = player.getInventory().getItemInMainHand();
ItemStack inHand = player.getItemInHand();
if (!ItemUtils.isChimaeraWing(inHand)) {
return;
@@ -86,7 +91,7 @@ public final class ChimaeraWing {
if (Config.getInstance().getChimaeraPreventUseUnderground()) {
if (location.getY() < player.getWorld().getHighestBlockYAt(location)) {
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(amount - Config.getInstance().getChimaeraUseCost())));
player.setItemInHand(new ItemStack(getChimaeraWing(amount - Config.getInstance().getChimaeraUseCost())));
player.sendMessage(LocaleLoader.getString("Item.ChimaeraWing.Fail"));
player.updateInventory();
player.setVelocity(new Vector(0, 0.5D, 0));
@@ -112,7 +117,7 @@ public final class ChimaeraWing {
public static void chimaeraExecuteTeleport() {
Player player = mcMMOPlayer.getPlayer();
if (Config.getInstance().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) {
if (player.getBedSpawnLocation() != null) {
player.teleport(player.getBedSpawnLocation());
}
else {
@@ -125,13 +130,17 @@ public final class ChimaeraWing {
}
}
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(player.getInventory().getItemInMainHand().getAmount() - Config.getInstance().getChimaeraUseCost())));
player.setItemInHand(new ItemStack(getChimaeraWing(player.getItemInHand().getAmount() - Config.getInstance().getChimaeraUseCost())));
player.updateInventory();
mcMMOPlayer.actualizeChimeraWingLastUse();
mcMMOPlayer.setTeleportCommenceLocation(null);
if (Config.getInstance().getStatsTrackingEnabled()) {
MetricsManager.chimeraWingUsed();
}
if (Config.getInstance().getChimaeraSoundEnabled()) {
player.playSound(location, Sound.ENTITY_BAT_TAKEOFF, Misc.BAT_VOLUME, Misc.BAT_PITCH);
player.playSound(location, Sound.BAT_TAKEOFF, Misc.BAT_VOLUME, Misc.BAT_PITCH);
}
player.sendMessage(LocaleLoader.getString("Item.ChimaeraWing.Pass"));
@@ -156,7 +165,7 @@ public final class ChimaeraWing {
Material ingredient = Config.getInstance().getChimaeraItem();
int amount = Config.getInstance().getChimaeraRecipeCost();
ShapelessRecipe chimeraWing = new ShapelessRecipe(new NamespacedKey(mcMMO.p, "Chimera"), getChimaeraWing(1));
ShapelessRecipe chimeraWing = new ShapelessRecipe(getChimaeraWing(1));
chimeraWing.addIngredient(amount, ingredient);
return chimeraWing;
}

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