Exemple #1
0
 public void addMySQLPlayer() {
   mcMMO.database.write(
       "INSERT INTO "
           + Config.getInstance().getMySQLTablePrefix()
           + "users (user, lastlogin) VALUES ('"
           + playerName
           + "',"
           + System.currentTimeMillis() / 1000
           + ")");
   userId =
       mcMMO.database.getInt(
           "SELECT id FROM "
               + Config.getInstance().getMySQLTablePrefix()
               + "users WHERE user = '******'");
   mcMMO.database.write(
       "INSERT INTO "
           + Config.getInstance().getMySQLTablePrefix()
           + "cooldowns (user_id) VALUES ("
           + userId
           + ")");
   mcMMO.database.write(
       "INSERT INTO "
           + Config.getInstance().getMySQLTablePrefix()
           + "skills (user_id) VALUES ("
           + userId
           + ")");
   mcMMO.database.write(
       "INSERT INTO "
           + Config.getInstance().getMySQLTablePrefix()
           + "experience (user_id) VALUES ("
           + userId
           + ")");
 }
Exemple #2
0
  private void checkModConfigs() {
    if (!Config.getInstance().getToolModsEnabled()) {
      getLogger()
          .info("MCPC+ implementation found, but the custom tool config for mcMMO is disabled!");
      getLogger().info("To enable, set Mods.Tool_Mods_Enabled to TRUE in config.yml.");
    }

    if (!Config.getInstance().getArmorModsEnabled()) {
      getLogger()
          .info("MCPC+ implementation found, but the custom armor config for mcMMO is disabled!");
      getLogger().info("To enable, set Mods.Armor_Mods_Enabled to TRUE in config.yml.");
    }

    if (!Config.getInstance().getBlockModsEnabled()) {
      getLogger()
          .info("MCPC+ implementation found, but the custom block config for mcMMO is disabled!");
      getLogger().info("To enable, set Mods.Block_Mods_Enabled to TRUE in config.yml.");
    }

    if (!Config.getInstance().getEntityModsEnabled()) {
      getLogger()
          .info("MCPC+ implementation found, but the custom entity config for mcMMO is disabled!");
      getLogger().info("To enable, set Mods.Entity_Mods_Enabled to TRUE in config.yml.");
    }
  }
Exemple #3
0
  private void loadConfigFiles() {
    // Force the loading of config files
    TreasureConfig.getInstance();
    HiddenConfig.getInstance();
    AdvancedConfig.getInstance();
    PotionConfig.getInstance();
    new ChildConfig();

    List<Repairable> repairables = new ArrayList<Repairable>();

    if (Config.getInstance().getToolModsEnabled()) {
      repairables.addAll(CustomToolConfig.getInstance().getLoadedRepairables());
    }

    if (Config.getInstance().getArmorModsEnabled()) {
      repairables.addAll(CustomArmorConfig.getInstance().getLoadedRepairables());
    }

    if (Config.getInstance().getBlockModsEnabled()) {
      CustomBlockConfig.getInstance();
    }

    if (Config.getInstance().getEntityModsEnabled()) {
      CustomEntityConfig.getInstance();
    }

    // Load repair configs, make manager, and register them at this time
    RepairConfigManager rManager = new RepairConfigManager(this);
    repairables.addAll(rManager.getLoadedRepairables());
    repairableManager = new SimpleRepairableManager(repairables.size());
    repairableManager.registerRepairables(repairables);
  }
  /**
   * Handle the Leaf Blower ability.
   *
   * @param player Player using the ability
   * @param block Block being broken
   */
  public static void leafBlower(Player player, Block block) {
    FakePlayerAnimationEvent armswing = new FakePlayerAnimationEvent(player);
    mcMMO.p.getServer().getPluginManager().callEvent(armswing);

    if (Config.getInstance().getWoodcuttingRequiresTool()) {
      Skills.abilityDurabilityLoss(
          player.getItemInHand(), Config.getInstance().getAbilityToolDamage());
    }

    if (mcMMO.spoutEnabled) {
      SpoutSounds.playSoundForPlayer(SoundEffect.POP, player, block.getLocation());
    }
  }
  private static int durabilityLossCalulate(ArrayList<Block> toBeFelled, int level) {
    int durabilityLoss = 0;
    for (Block x : toBeFelled) {
      if (random.nextInt(level + 1) > 0) {
      } // Don't add durabilityLoss, because Unbreaking enchantment does it's work.
      else if (x.getType().equals(Material.LOG)
          || (Config.getInstance().getBlockModsEnabled() && ModChecks.isCustomLogBlock(x))) {
        durabilityLoss = durabilityLoss + Config.getInstance().getAbilityToolDamage();
      }
    }

    return durabilityLoss;
  }
  /**
   * Check XP gain for woodcutting.
   *
   * @param player The player breaking the block
   * @param block The block being broken
   */
  public static void woodcuttingBlockCheck(Player player, Block block) {
    PlayerProfile profile = Users.getProfile(player);
    int xp = 0;

    if (mcMMO.placeStore.isTrue(block)) {
      return;
    }

    if (Config.getInstance().getBlockModsEnabled() && ModChecks.isCustomLogBlock(block)) {
      xp = ModChecks.getCustomBlock(block).getXpGain();
    } else {
      byte type = block.getData();

      if ((type & 0x4) == 0x4) type ^= 0x4;

      if ((type & 0x8) == 0x8) type ^= 0x8;

      TreeSpecies species = TreeSpecies.getByData(type);

      // Apparently species can be null in certain cases (custom server mods?)
      // https://github.com/mcMMO-Dev/mcMMO/issues/229
      if (species == null) return;

      switch (species) {
        case GENERIC:
          xp += Config.getInstance().getWoodcuttingXPOak();
          break;

        case REDWOOD:
          xp += Config.getInstance().getWoodcuttingXPSpruce();
          break;

        case BIRCH:
          xp += Config.getInstance().getWoodcuttingXPBirch();
          break;

        case JUNGLE:
          xp += Config.getInstance().getWoodcuttingXPJungle();
          break;

        default:
          break;
      }
    }

    WoodCutting.woodCuttingProcCheck(player, block);
    Skills.xpProcessing(player, profile, SkillType.WOODCUTTING, xp);
  }
  public void processAbilityActivation(SkillType skill) {
    if (Config.getInstance().getAbilitiesOnlyActivateWhenSneaking() && !player.isSneaking()) {
      return;
    }

    ItemStack inHand = player.getItemInHand();

    if (mcMMO.getModManager().isCustomTool(inHand)
        && !mcMMO.getModManager().getTool(inHand).isAbilityEnabled()) {
      return;
    }

    if (!getAbilityUse()) {
      return;
    }

    for (AbilityType abilityType : AbilityType.values()) {
      if (getAbilityMode(abilityType)) {
        return;
      }
    }

    AbilityType ability = skill.getAbility();
    ToolType tool = skill.getTool();

    /*
     * Woodcutting & Axes need to be treated differently.
     * Basically the tool always needs to ready and we check to see if the cooldown is over when the user takes action
     */
    if (ability.getPermissions(player) && tool.inHand(inHand) && !getToolPreparationMode(tool)) {
      if (skill != SkillType.WOODCUTTING && skill != SkillType.AXES) {
        int timeRemaining = calculateTimeRemaining(ability);

        if (!getAbilityMode(ability) && timeRemaining > 0) {
          player.sendMessage(LocaleLoader.getString("Skills.TooTired", timeRemaining));
          return;
        }
      }

      if (Config.getInstance().getAbilityMessagesEnabled()) {
        player.sendMessage(tool.getRaiseTool());
      }

      setToolPreparationMode(tool, true);
      new ToolLowerTask(this, tool)
          .runTaskLaterAsynchronously(mcMMO.p, 4 * Misc.TICK_CONVERSION_FACTOR);
    }
  }
Exemple #8
0
  public static void mcMMObackup() throws IOException {
    if (Config.getInstance().getUseMySQL()) {
      System.out.println("No Backup performed, in SQL Mode.");
      return;
    }

    try {
      if (BackupDir.mkdir()) {
        mcMMO.p.getLogger().info("Created Backup Directory.");
      }
    } catch (Exception e) {
      mcMMO.p.getLogger().severe(e.toString());
    }

    // Generate the proper date for the backup filename
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    File fileZip = new File(BackupDirectory + File.separator + dateFormat.format(date) + ".zip");

    // Create the Source List, and add directories/etc to the file.
    List<File> sources = new ArrayList<File>();
    sources.add(FlatFileDirectory);
    sources.add(ModFileDirectory);
    sources.add(UsersFile);
    sources.add(ConfigFile);
    sources.add(TreasuresFile);
    sources.add(Leaderboards);

    // Actually do something
    System.out.println("Backing up your mcMMO Configuration... ");

    packZip(fileZip, sources);
  }
Exemple #9
0
  /** Summon an ocelot to your side. */
  public void summonOcelot() {
    if (!Permissions.callOfTheWild(getPlayer(), EntityType.OCELOT)) {
      return;
    }

    callOfTheWild(EntityType.OCELOT, Config.getInstance().getTamingCOTWCost(EntityType.OCELOT));
  }
Exemple #10
0
  public PlayerProfile(String playerName, boolean addNew) {
    this.playerName = playerName;
    party = PartyManager.getInstance().getPlayerParty(playerName);

    for (AbilityType abilityType : AbilityType.values()) {
      skillsDATS.put(abilityType, 0);
    }

    for (SkillType skillType : SkillType.values()) {
      if (skillType != SkillType.ALL) {
        skills.put(skillType, 0);
        skillsXp.put(skillType, 0);
      }
    }

    if (Config.getInstance().getUseMySQL()) {
      if (!loadMySQL() && addNew) {
        addMySQLPlayer();
        loaded = true;
      }
    } else if (!load() && addNew) {
      addPlayer();
      loaded = true;
    }
  }
Exemple #11
0
  /** Summon a horse to your side. */
  public void summonHorse() {
    if (!Permissions.callOfTheWild(getPlayer(), EntityType.HORSE)) {
      return;
    }

    callOfTheWild(EntityType.HORSE, Config.getInstance().getTamingCOTWCost(EntityType.HORSE));
  }
  /**
   * Check if Tree Feller is being too aggressive.
   *
   * @param currentBlock The current block being felled
   * @param newBlock The next block to be felled
   * @return true if Tree Feller is too aggressive, false otherwise
   */
  private static boolean isTooAggressive(Block currentBlock, Block newBlock) {
    Material currentType = currentBlock.getType();
    Material newType = newBlock.getType();

    if ((currentType.equals(Material.LEAVES)
            || currentType.equals(Material.AIR)
            || (Config.getInstance().getBlockModsEnabled()
                && ModChecks.isCustomLeafBlock(currentBlock)))
        && (newType.equals(Material.LEAVES)
            || newType.equals(Material.AIR)
            || (Config.getInstance().getBlockModsEnabled()
                && ModChecks.isCustomLeafBlock(currentBlock)))) {
      return true;
    } else {
      return false;
    }
  }
  @Override
  protected void permissionsCheck() {
    Config configInstance = Config.getInstance();

    canTreeFell = permInstance.treeFeller(player);
    canDoubleDrop = permInstance.woodcuttingDoubleDrops(player);
    canLeafBlow = permInstance.leafBlower(player);
    doubleDropsDisabled = configInstance.woodcuttingDoubleDropsDisabled();
  }
Exemple #14
0
  public static void mcMMObackup() throws IOException {
    if (Config.getInstance().getUseMySQL()) {
      mcMMO.p.getLogger().info("This server is running in SQL Mode.");
      mcMMO.p.getLogger().info("Only config files will be backed up.");
    }

    try {
      if (BackupDir.mkdir()) {
        mcMMO.p.getLogger().info("Created Backup Directory.");
      }
    } catch (Exception e) {
      mcMMO.p.getLogger().severe(e.toString());
    }

    // Generate the proper date for the backup filename
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    File fileZip = new File(BackupDirectory + File.separator + dateFormat.format(date) + ".zip");

    // Create the Source List, and add directories/etc to the file.
    List<File> sources = new ArrayList<File>();
    if (!Config.getInstance().getUseMySQL()) {
      sources.add(FlatFileDirectory);
    }

    sources.add(ConfigFile);
    sources.add(TreasuresFile);
    sources.add(AdvancedConfigFile);
    sources.add(RepairFile);

    if (ModFileDirectory.exists()) {
      sources.add(ModFileDirectory);
    }

    if (SpoutFile.exists()) {
      sources.add(SpoutFile);
    }

    // Actually do something
    mcMMO.p.getLogger().info("Backing up your mcMMO Configuration... ");

    packZip(fileZip, sources);
  }
Exemple #15
0
  @Override
  public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (CommandUtils.noConsoleUsage(sender)) {
      return true;
    }

    switch (args.length) {
      case 0:
        McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName());
        Player player = mcMMOPlayer.getPlayer();

        if (Config.getInstance().getMcstatsScoreboardsEnabled()) {
          ScoreboardManager.setupPlayerScoreboard(player.getName());
          ScoreboardManager.enablePlayerStatsScoreboard(mcMMOPlayer);
        } else {
          player.sendMessage(LocaleLoader.getString("Stats.Own.Stats"));
          player.sendMessage(LocaleLoader.getString("mcMMO.NoSkillNote"));

          CommandUtils.printGatheringSkills(player);
          CommandUtils.printCombatSkills(player);
          CommandUtils.printMiscSkills(player);

          int powerLevelCap = Config.getInstance().getPowerLevelCap();

          if (powerLevelCap != Integer.MAX_VALUE) {
            player.sendMessage(
                LocaleLoader.getString(
                    "Commands.PowerLevel.Capped",
                    UserManager.getPlayer(player).getPowerLevel(),
                    powerLevelCap));
          } else {
            player.sendMessage(
                LocaleLoader.getString(
                    "Commands.PowerLevel", UserManager.getPlayer(player).getPowerLevel()));
          }
        }

        return true;

      default:
        return false;
    }
  }
  /**
   * Begins an experience gain. The amount will be affected by skill modifiers, global rate and
   * perks
   *
   * @param skill Skill being used
   * @param xp Experience amount to process
   */
  public void beginUnsharedXpGain(SkillType skill, float xp, XPGainReason xpGainReason) {
    applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason);

    if (party == null) {
      return;
    }

    if (!Config.getInstance().getPartyXpNearMembersNeeded()
        || !PartyManager.getNearMembers(this).isEmpty()) {
      party.applyXpGain(modifyXpGain(skill, xp));
    }
  }
Exemple #17
0
  private void checkForUpdates() {
    if (!Config.getInstance().getUpdateCheckEnabled()) {
      return;
    }

    Updater updater = new Updater(this, 31030, mcmmo, UpdateType.NO_DOWNLOAD, false);

    if (updater.getResult() != UpdateResult.UPDATE_AVAILABLE) {
      this.updateAvailable = false;
      return;
    }

    if (updater.getLatestType().equals("beta") && !Config.getInstance().getPreferBeta()) {
      this.updateAvailable = false;
      return;
    }

    this.updateAvailable = true;
    getLogger().info(LocaleLoader.getString("UpdateChecker.Outdated"));
    getLogger().info(LocaleLoader.getString("UpdateChecker.NewAvailable"));
  }
 public static void treeFeller(Block block, Player player) {
   PlayerProfile PP = Users.getProfile(player);
   int radius = 1;
   if (PP.getSkill("woodcutting") >= 500) radius++;
   if (PP.getSkill("woodcutting") >= 950) radius++;
   ArrayList<Block> blocklist = new ArrayList<Block>();
   ArrayList<Block> toAdd = new ArrayList<Block>();
   if (block != null) blocklist.add(block);
   while (isdone == false) {
     addBlocksToTreeFelling(blocklist, toAdd, radius);
   }
   // This needs to be a hashmap too!
   isdone = false;
   /*
    * Add blocks from the temporary 'toAdd' array list into the 'treeFeller' array list
    * We use this temporary list to prevent concurrent modification exceptions
    */
   for (Block x : toAdd) {
     if (!Config.getInstance().isTreeFellerWatched(x)) Config.getInstance().addTreeFeller(x);
   }
   toAdd.clear();
 }
 public void onPlayerChat(PlayerChatEvent event) {
   Player player = event.getPlayer();
   PlayerProfile PP = Users.getProfile(player);
   String x = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") ";
   String y = ChatColor.AQUA + "{" + ChatColor.WHITE + player.getName() + ChatColor.AQUA + "} ";
   if (Config.getInstance().isPartyToggled(player.getName())) {
     event.setCancelled(true);
     log.log(
         Level.INFO,
         "[P](" + PP.getParty() + ")" + "<" + player.getName() + "> " + event.getMessage());
     for (Player herp : plugin.getServer().getOnlinePlayers()) {
       if (Users.getProfile(herp).inParty()) {
         if (Party.getInstance().inSameParty(herp, player)) {
           herp.sendMessage(x + event.getMessage());
         }
       }
     }
     return;
   }
   if ((player.isOp() || mcPermissions.getInstance().adminChat(player))
       && Config.getInstance().isAdminToggled(player.getName())) {
     log.log(Level.INFO, "[A]" + "<" + player.getName() + "> " + event.getMessage());
     event.setCancelled(true);
     for (Player herp : plugin.getServer().getOnlinePlayers()) {
       if ((herp.isOp() || mcPermissions.getInstance().adminChat(herp))) {
         herp.sendMessage(y + event.getMessage());
       }
     }
     return;
   }
   /*
    * Remove from normal chat if toggled
   for(Player z : event.getRecipients()){
   	if(Users.getProfile(z.getName()).getPartyChatOnlyToggle() == true)
   		event.getRecipients().remove(z);
   }
   */
 }
Exemple #20
0
  private void scheduleTasks() {
    // Periodic save timer (Saves every 10 minutes by default)
    long saveIntervalTicks = Config.getInstance().getSaveInterval() * 1200;
    new SaveTimerTask().runTaskTimer(this, saveIntervalTicks, saveIntervalTicks);

    // Cleanup the backups folder
    new CleanBackupsTask().runTaskAsynchronously(mcMMO.p);

    // Bleed timer (Runs every two seconds)
    new BleedTimerTask()
        .runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR);

    // Old & Powerless User remover
    long purgeIntervalTicks =
        Config.getInstance().getPurgeInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;

    if (purgeIntervalTicks == 0) {
      new UserPurgeTask()
          .runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
    } else if (purgeIntervalTicks > 0) {
      new UserPurgeTask().runTaskTimer(this, purgeIntervalTicks, purgeIntervalTicks);
    }

    // Automatically remove old members from parties
    long kickIntervalTicks =
        Config.getInstance().getAutoPartyKickInterval() * 60 * 60 * Misc.TICK_CONVERSION_FACTOR;

    if (kickIntervalTicks == 0) {
      new PartyAutoKickTask()
          .runTaskLater(this, 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup.
    } else if (kickIntervalTicks > 0) {
      new PartyAutoKickTask().runTaskTimer(this, kickIntervalTicks, kickIntervalTicks);
    }

    // Update power level tag scoreboards
    new PowerLevelUpdatingTask()
        .runTaskTimer(this, 2 * Misc.TICK_CONVERSION_FACTOR, 2 * Misc.TICK_CONVERSION_FACTOR);
  }
  /**
   * Modifies an experience gain using skill modifiers, global rate and perks
   *
   * @param skillType Skill being used
   * @param xp Experience amount to process
   * @return Modified experience
   */
  private float modifyXpGain(SkillType skillType, float xp) {
    if (player.getGameMode() == GameMode.CREATIVE
        || (skillType.getMaxLevel() <= getSkillLevel(skillType))
        || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) {
      return 0;
    }

    xp =
        (float)
            (xp
                / skillType.getXpModifier()
                * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier());

    if (Config.getInstance().getToolModsEnabled()) {
      CustomTool tool = mcMMO.getModManager().getTool(player.getItemInHand());

      if (tool != null) {
        xp *= tool.getXpMultiplier();
      }
    }

    return PerksUtils.handleXpPerks(player, xp, skillType);
  }
Exemple #22
0
  /**
   * Handle triple drops from Giga Drill Breaker.
   *
   * @param player The player using the ability
   * @param block The block to check
   */
  public static void gigaDrillBreaker(Player player, Block block) {
    Skills.abilityDurabilityLoss(
        player.getItemInHand(), Config.getInstance().getAbilityToolDamage());

    if (!mcMMO.placeStore.isTrue(block)) {
      FakePlayerAnimationEvent armswing = new FakePlayerAnimationEvent(player);
      mcMMO.p.getServer().getPluginManager().callEvent(armswing);

      Excavation.excavationProcCheck(block, player);
      Excavation.excavationProcCheck(block, player);
    }

    if (mcMMO.p.spoutEnabled) {
      SpoutSounds.playSoundForPlayer(SoundEffect.POP, player, block.getLocation());
    }
  }
Exemple #23
0
  private boolean rangeCheck(EntityType type) {
    double range = Config.getInstance().getTamingCOTWRange();
    Player player = getPlayer();

    if (range == 0) {
      return true;
    }

    for (Entity entity : player.getNearbyEntities(range, range, range)) {
      if (entity.getType() == type) {
        player.sendMessage(Taming.getCallOfTheWildFailureMessage(type));
        return false;
      }
    }

    return true;
  }
Exemple #24
0
  private boolean summonAmountCheck(EntityType entityType) {
    Player player = getPlayer();

    int maxAmountSummons = Config.getInstance().getTamingCOTWMaxAmount(entityType);

    if (maxAmountSummons <= 0) {
      return true;
    }

    List<TrackedTamingEntity> trackedEntities = getTrackedEntities(entityType);
    int summonAmount = trackedEntities == null ? 0 : trackedEntities.size();

    if (summonAmount >= maxAmountSummons) {
      player.sendMessage(LocaleLoader.getString("Taming.Summon.Fail.TooMany", maxAmountSummons));
      return false;
    }

    return true;
  }
Exemple #25
0
  public void purgeOldSQL() {
    plugin.getLogger().info("Purging old users...");
    long currentTime = System.currentTimeMillis();
    long purgeTime = 2630000000L * Config.getInstance().getOldUsersCutoff();
    HashMap<Integer, ArrayList<String>> usernames =
        read(
            "SELECT user FROM "
                + tablePrefix
                + "users WHERE (("
                + currentTime
                + " - lastlogin*1000) > "
                + purgeTime
                + ")");
    write(
        "DELETE FROM "
            + tablePrefix
            + "users WHERE "
            + tablePrefix
            + "users.id IN (SELECT * FROM (SELECT id FROM "
            + tablePrefix
            + "users WHERE (("
            + currentTime
            + " - lastlogin*1000) > "
            + purgeTime
            + ")) AS p)");

    int purgedUsers = 0;
    for (int i = 1; i <= usernames.size(); i++) {
      String playerName = usernames.get(i).get(0);

      if (playerName == null) {
        continue;
      }

      profileCleanup(playerName);
      purgedUsers++;
    }

    plugin.getLogger().info("Purged " + purgedUsers + " users from the database.");
  }
Exemple #26
0
  public static SkillType getSkill(String skillName) {
    if (!Config.getInstance().getLocale().equalsIgnoreCase("en_US")) {
      for (SkillType type : values()) {
        if (skillName.equalsIgnoreCase(
            LocaleLoader.getString(StringUtils.getCapitalized(type.name()) + ".SkillName"))) {
          return type;
        }
      }
    }

    for (SkillType type : values()) {
      if (type.name().equalsIgnoreCase(skillName)) {
        return type;
      }
    }

    if (!skillName.equalsIgnoreCase("all")) {
      mcMMO.p.getLogger().warning("Invalid mcMMO skill (" + skillName + ")"); // TODO: Localize
    }

    return null;
  }
  /**
   * Check the XP of a skill.
   *
   * @param skillType The skill to check
   */
  private void checkXp(SkillType skillType, XPGainReason xpGainReason) {
    if (getSkillXpLevelRaw(skillType) < getXpToLevel(skillType)) {
      return;
    }

    int levelsGained = 0;
    float xpRemoved = 0;

    while (getSkillXpLevelRaw(skillType) >= getXpToLevel(skillType)) {
      if (hasReachedLevelCap(skillType)) {
        setSkillXpLevel(skillType, 0);
        break;
      }

      xpRemoved += profile.levelUp(skillType);
      levelsGained++;
    }

    if (!EventUtils.handleLevelChangeEvent(
        player, skillType, levelsGained, xpRemoved, true, xpGainReason)) {
      return;
    }

    if (Config.getInstance().getLevelUpSoundsEnabled()) {
      player.playSound(
          player.getLocation(),
          Sound.ENTITY_EXPERIENCE_ORB_PICKUP,
          Misc.LEVELUP_VOLUME,
          Misc.LEVELUP_PITCH);
    }

    player.sendMessage(
        LocaleLoader.getString(
            StringUtils.getCapitalized(skillType.toString()) + ".Skillup",
            levelsGained,
            getSkillLevel(skillType)));
  }
Exemple #28
0
  /** Things to be run when the plugin is disabled. */
  @Override
  public void onDisable() {
    try {
      Alchemy
          .finishAllBrews(); // Finish all partially complete AlchemyBrewTasks to prevent vanilla
                             // brewing continuation on restart
      UserManager.saveAll(); // Make sure to save player information if the server shuts down
      PartyManager.saveParties(); // Save our parties
      ScoreboardManager.teardownAll();
      formulaManager.saveFormula();
      placeStore.saveAll(); // Save our metadata
      placeStore.cleanUp(); // Cleanup empty metadata stores
    } catch (NullPointerException e) {
    }

    getServer().getScheduler().cancelTasks(this); // This removes our tasks
    HandlerList.unregisterAll(this); // Cancel event registrations

    if (Config.getInstance().getBackupsEnabled()) {
      // Remove other tasks BEFORE starting the Backup, or we just cancel it straight away.
      try {
        ZipLibrary.mcMMOBackup();
      } catch (IOException e) {
        getLogger().severe(e.toString());
      } catch (Throwable e) {
        if (e instanceof NoClassDefFoundError) {
          getLogger().severe("Backup class not found!");
          getLogger().info("Please do not replace the mcMMO jar while the server is running.");
        } else {
          getLogger().severe(e.toString());
        }
      }
    }

    debug("Was disabled."); // How informative!
  }
Exemple #29
0
  @Override
  public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    switch (args.length) {
      case 1:
        if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) {
          ScoreboardManager.setupPlayerScoreboard(sender.getName());
        }

        String playerName = Misc.getMatchedPlayerName(args[0]);
        McMMOPlayer mcMMOPlayer = UserManager.getPlayer(playerName, true);

        // 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) {
          PlayerProfile profile =
              mcMMO.getDatabaseManager().loadPlayerProfile(playerName, false); // Temporary Profile

          if (CommandUtils.inspectOffline(sender, profile, Permissions.inspectOffline(sender))) {
            return true;
          }

          if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) {
            ScoreboardManager.enablePlayerInspectScoreboardOffline((Player) sender, profile);
            return true;
          }

          sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", playerName));

          sender.sendMessage(LocaleLoader.getString("Stats.Header.Gathering"));
          for (SkillType skill : SkillType.GATHERING_SKILLS) {
            sender.sendMessage(CommandUtils.displaySkill(profile, skill));
          }

          sender.sendMessage(LocaleLoader.getString("Stats.Header.Combat"));
          for (SkillType skill : SkillType.COMBAT_SKILLS) {
            sender.sendMessage(CommandUtils.displaySkill(profile, skill));
          }

          sender.sendMessage(LocaleLoader.getString("Stats.Header.Misc"));
          for (SkillType skill : SkillType.MISC_SKILLS) {
            sender.sendMessage(CommandUtils.displaySkill(profile, skill));
          }

        } else {
          Player target = mcMMOPlayer.getPlayer();

          if (CommandUtils.hidden(sender, target, Permissions.inspectHidden(sender))) {
            if (!Permissions.inspectOffline(sender)) {
              sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
              return true;
            }
          } else if (CommandUtils.tooFar(sender, target, Permissions.inspectFar(sender))) {
            return true;
          }

          if (sender instanceof Player && Config.getInstance().getInspectScoreboardEnabled()) {
            ScoreboardManager.enablePlayerInspectScoreboardOnline((Player) sender, mcMMOPlayer);
            return true;
          }

          sender.sendMessage(LocaleLoader.getString("Inspect.Stats", target.getName()));
          CommandUtils.printGatheringSkills(target, sender);
          CommandUtils.printCombatSkills(target, sender);
          CommandUtils.printMiscSkills(target, sender);
          sender.sendMessage(
              LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel()));
        }

        return true;

      default:
        return false;
    }
  }
Exemple #30
0
 public int getMaxLength() {
   return Config.getInstance().getMaxLength(this);
 }