Java Code Examples for org.bukkit.entity.Player#giveExp()

The following examples show how to use org.bukkit.entity.Player#giveExp() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
public static void setTotalExperience(final Player player, final int exp) {
    if (exp < 0) {
        throw new IllegalArgumentException("Experience is negative!");
    }
    player.setExp(0);
    player.setLevel(0);
    player.setTotalExperience(0);

    int amount = exp;
    while (amount > 0) {
        final int expToLevel = getExpAtLevel(player.getLevel());
        amount -= expToLevel;
        if (amount >= 0) {
            // give until next level
            player.giveExp(expToLevel);
        } else {
            // give the rest
            amount += expToLevel;
            player.giveExp(amount);
            amount = 0;
        }
    }
}
 
Example 2
Source File: Experienced.java    From MineTinker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * The Effect of the modifier
 *
 * @param player    the Player
 * @param tool the Tool
 */
private void effect(Player player, ItemStack tool, Event event) {
	if (!player.hasPermission("minetinker.modifiers.experienced.use")) {
		return;
	}

	if (!modManager.hasMod(tool, this)) {
		return;
	}

	int level = modManager.getModLevel(tool, this);

	Random rand = new Random();
	int n = rand.nextInt(100);
	int c = this.percentagePerLevel * level;

	if (n <= c) {
		player.giveExp(this.amount);
	}
	ChatWriter.logModifier(player, event, this, tool, String.format("Chance(%d/%d)", n, c));
}
 
Example 3
Source File: CronusUtils.java    From TabooLib with MIT License 6 votes vote down vote up
public static void setTotalExperience(Player player, int exp) {
    player.setExp(0);
    player.setLevel(0);
    player.setTotalExperience(0);
    int amount = exp;
    while (amount > 0) {
        int expToLevel = getExpAtLevel(player);
        amount -= expToLevel;
        if (amount >= 0) {
            player.giveExp(expToLevel);
        } else {
            amount += expToLevel;
            player.giveExp(amount);
            amount = 0;
        }
    }
}
 
Example 4
Source File: ExpCapsuleCommands.java    From NyaaUtils with MIT License 6 votes vote down vote up
@SubCommand(value = "restore", permission = "nu.expcap.restore")
public void cmdRestoreExp(CommandSender sender, Arguments args) {
    Player p = asPlayer(sender);
    ItemStack item = getItemInHand(sender);
    Integer storedExp = getStoredExp(item);
    if (storedExp == null) throw new BadCommandException("user.expcap.not_enough_exp_cap");
    if (item.getAmount() > 1) throw new BadCommandException("user.expcap.not_stackable");

    int amount;
    if (args.top() == null) throw new BadCommandException();
    if ("ALL".equalsIgnoreCase(args.top())) {
        amount = storedExp;
        if (amount <= 0) throw new BadCommandException("user.expcap.not_enough_exp_cap");
    } else {
        amount = args.nextInt();
        if (amount <= 0) throw new BadCommandException("user.expcap.wrong_nbr");
        if (amount > storedExp) throw new BadCommandException("user.expcap.not_enough_exp_cap");
    }

    storedExp -= amount;
    p.giveExp(amount);
    setStoredExp(item, storedExp);
}
 
Example 5
Source File: SetExpFix.java    From PlayerSQL with GNU General Public License v2.0 6 votes vote down vote up
public static void setTotalExperience(final Player player, final int exp) {
    if (exp < 0) {
        throw new IllegalArgumentException("Experience is negative!");
    }
    player.setExp(0);
    player.setLevel(0);
    player.setTotalExperience(0);

    //This following code is technically redundant now, as bukkit now calulcates levels more or less correctly
    //At larger numbers however... player.getExp(3000), only seems to give 2999, putting the below calculations off.
    int amount = exp;
    while (amount > 0) {
        final int expToLevel = getExpAtLevel(player);
        amount -= expToLevel;
        if (amount >= 0) {
            // give until next level
            player.giveExp(expToLevel);
        } else {
            // give the rest
            amount += expToLevel;
            player.giveExp(amount);
            amount = 0;
        }
    }
}
 
Example 6
Source File: LootProtectListener.java    From NyaaUtils with MIT License 5 votes vote down vote up
private static void giveExp(Player p, int amount) {
    if (amount <= 0) return;
    List<ItemStack> candidate = new ArrayList<>(13);

    for (ItemStack item : new ItemStack[]{
            p.getInventory().getHelmet(),
            p.getInventory().getChestplate(),
            p.getInventory().getLeggings(),
            p.getInventory().getBoots(),
            p.getInventory().getItemInMainHand(),
            p.getInventory().getItemInOffHand()}) {
        if (item != null && item.hasItemMeta() && item.getItemMeta().hasEnchant(Enchantment.MENDING)) {
            if (item.getType().getMaxDurability() > 0 && ((Damageable) item.getItemMeta()).getDamage() > 0) {
                candidate.add(item);
            }
        }
    }

    ItemStack repair = null;
    if (candidate.size() > 0) {
        candidate.sort(LootProtectListener::compareByDamagePercentage);
        repair = candidate.get(0);
    }

    if (repair != null) {
        Damageable itemMeta = (Damageable) repair.getItemMeta();
        int durability = itemMeta.getDamage();
        int repairPoint = durability;
        if (amount * 2 < repairPoint) repairPoint = amount * 2;
        int expConsumption = ((repairPoint % 2) == 1) ? (repairPoint + 1) / 2 : repairPoint / 2;
        itemMeta.setDamage(durability - repairPoint);
        repair.setItemMeta((ItemMeta) itemMeta);
        amount -= expConsumption;
    }

    if (amount > 0) p.giveExp(amount);
    PlayerExpChangeEvent event = new PlayerExpChangeEvent(p, amount);
    Bukkit.getServer().getPluginManager().callEvent(event);
}
 
Example 7
Source File: EXPEvent.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    Player player = PlayerConverter.getPlayer(playerID);
    int amount = this.amount.getInt(playerID);
    if (level) {
        player.giveExpLevels(amount);
    } else {
        player.giveExp(amount);
    }
    return null;
}
 
Example 8
Source File: BonusXpSplitOnPickupListener.java    From MarriageMaster with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void splitWithPartner(PlayerExpChangeEvent event, Player partner, double xp, Object o, MarriagePlayer player, Marriage marriage)
{
	int xpPlayer = (int) Math.round((xp)), xpPartner = (int) xp;
	BonusXPSplitEvent xpSplitEvent = new BonusXPSplitEvent(player, marriage, xpPlayer);
	Bukkit.getServer().getPluginManager().callEvent(xpSplitEvent);
	if(!xpSplitEvent.isCancelled())
	{
		event.setAmount(xpSplitEvent.getAmount());
		if(xpPartner > 0) partner.giveExp(xpPartner); // If the partner is near he/she must also be online
	}
}
 
Example 9
Source File: Directing.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void effect(MTEntityDeathEvent event) {
	if (event.getPlayer().equals(event.getEvent().getEntity())) {
		return;
	}
	if (!this.workInPVP && event.getEvent().getEntity() instanceof Player) {
		return;
	}

	Player player = event.getPlayer();
	ItemStack tool = event.getTool();

	if (!player.hasPermission("minetinker.modifiers.directing.use")) {
		return;
	}

	if (!modManager.hasMod(tool, this)) {
		return;
	}

	List<ItemStack> drops = event.getEvent().getDrops();
	List<ItemStack> toremove = new ArrayList<>();

	for (ItemStack current : drops) {
		if (modManager.hasMod(current, Soulbound.instance())) {
			continue;
		}

		if (player.getInventory().addItem(current).size() != 0) { //adds items to (full) inventory
			player.getWorld().dropItem(player.getLocation(), current);
		} // no else as it gets added in if-clause
		toremove.add(current);
	}

	drops.removeAll(toremove);

	if (this.workOnXP && modManager.getModLevel(tool, this) >= this.minimumLevelForXP) {
		player.giveExp(event.getEvent().getDroppedExp());
		event.getEvent().setDroppedExp(0);
	}

	ChatWriter.logModifier(player, event, this, tool,
			"Entity(" + event.getEvent().getEntity().getType().toString() + ")");
}
 
Example 10
Source File: ExpManager.java    From Parties with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Distribute the experience to the player
 * @return Returns true if the distribution has been done
 */
public boolean distributeExp(ExpDrop drop) {
	boolean ret = false;
	
	// Flags used to messages
	int totalParty = 0;
	int totalNormal = 0;
	int totalSkillapi = 0;
	
	PartyImpl party = plugin.getPartyManager().getParty(drop.getKiller().getPartyName());
	
	if (party != null) {
		plugin.getLoggerManager().logDebug(PartiesConstants.DEBUG_EXP_RECEIVED
				.replace("{normal}", Integer.toString(drop.getNormal()))
				.replace("{skillapi}", Integer.toString(drop.getSkillApi())), true);
		
		Player player = Bukkit.getPlayer(drop.getKiller().getPlayerUUID());
		User user = plugin.getPlayer(drop.getKiller().getPlayerUUID());
		
		if (player != null && user != null) {
			if (drop.getNormal() > 0) {
				switch (convertNormal) {
					case PARTY:
						totalParty += drop.getNormal();
						break;
					case NORMAL:
						totalNormal += drop.getNormal();
						break;
					case SKILLAPI:
						totalSkillapi += drop.getNormal();
						break;
					default:
						// Convert option not set
						return false;
				}
				ret = true;
			}
			if (drop.getSkillApi() > 0) {
				switch (convertSkillapi) {
					case PARTY:
						totalParty += drop.getSkillApi();
						break;
					case NORMAL:
						totalNormal += drop.getSkillApi();
						break;
					case SKILLAPI:
						totalSkillapi += drop.getSkillApi();
						break;
					default:
						// Convert option not set
						return false;
				}
				ret = true;
			}
			
			// Send experience
			if (totalParty > 0) {
				// If sent to the party, don't share experience
				party.giveExperience(totalParty);
				
				user.sendMessage(plugin.getMessageUtils().convertPlayerPlaceholders(BukkitMessages.ADDCMD_EXP_PARTY_GAINED
						.replace("%exp%", Integer.toString(totalParty)), drop.getKiller()), true);
			}
			if (totalNormal > 0 && !shareExperience(totalNormal, drop.getKiller(), party, drop.getEntityKilled(), ExpConvert.NORMAL)) {
				player.giveExp(totalNormal);
			}
			if (totalSkillapi > 0 && !shareExperience(totalSkillapi, drop.getKiller(), party, drop.getEntityKilled(), ExpConvert.SKILLAPI)) {
				SkillAPIHandler.giveExp(player.getUniqueId(), totalSkillapi);
			}
		}
	}
	return ret;
}
 
Example 11
Source File: ChallengeLogic.java    From uSkyBlock with GNU General Public License v3.0 4 votes vote down vote up
private boolean giveReward(Player player, Challenge challenge) {
    String challengeName = challenge.getName();
    player.sendMessage(tr("\u00a7aYou have completed the {0} challenge!", challenge.getDisplayName()));
    PlayerInfo playerInfo = plugin.getPlayerInfo(player);
    Reward reward;
    boolean isFirstCompletion = playerInfo.checkChallenge(challengeName) == 0;
    if (isFirstCompletion) {
        reward = challenge.getReward();
    } else {
        reward = challenge.getRepeatReward();
    }
    player.giveExp(reward.getXpReward());
    boolean wasBroadcast = false;
    if (defaults.broadcastCompletion && isFirstCompletion) {
        Bukkit.getServer().broadcastMessage(FormatUtil.normalize(config.getString("broadcastText")) + tr("\u00a79{0}\u00a7f has completed the \u00a79{1}\u00a7f challenge!", player.getName(), challenge.getDisplayName()));
        wasBroadcast = true;
    }
    player.sendMessage(tr("\u00a7eItem reward(s): \u00a7f{0}", reward.getRewardText()));
    player.sendMessage(tr("\u00a7eExp reward: \u00a7f{0,number,#.#}", reward.getXpReward()));
    if (defaults.enableEconomyPlugin) {
        float rewBonus = 1;
        Perk perk = plugin.getPerkLogic().getPerk(player);
        rewBonus += perk.getRewBonus();
        float currencyReward = reward.getCurrencyReward() * rewBonus;
        double percentage = (rewBonus - 1.0) * 100.0;

        plugin.getHookManager().getEconomyHook().ifPresent((hook) -> {
            hook.depositPlayer(player, currencyReward);

            player.sendMessage(tr("\u00a7eCurrency reward: \u00a7f{0,number,###.##} {1} \u00a7a ({2,number,##.##})%",
                currencyReward, hook.getCurrenyName(), percentage));
        });
    }
    if (reward.getPermissionReward() != null) {
        List<String> perms = Arrays.asList(reward.getPermissionReward().trim().split(" "));
        if (isIslandSharing()) {
            // Give all members
            IslandInfo islandInfo = playerInfo.getIslandInfo();
            for (UUID memberUUID : islandInfo.getMemberUUIDs()) {
                if (memberUUID == null) {
                    continue;
                }
                PlayerInfo pi = plugin.getPlayerInfo(memberUUID);
                if (pi != null) {
                    pi.addPermissions(perms);
                }
            }
        } else {
            // Give only player
            playerInfo.addPermissions(perms);
        }
    }
    HashMap<Integer, ItemStack> leftOvers = player.getInventory().addItem(reward.getItemReward().toArray(new ItemStack[0]));
    for (ItemStack item : leftOvers.values()) {
        player.getWorld().dropItem(player.getLocation(), item);
    }
    if (!leftOvers.isEmpty()) {
        player.sendMessage(tr("\u00a7eYour inventory is \u00a74full\u00a7e. Items dropped on the ground."));
    }
    for (String cmd : reward.getCommands()) {
        String command = cmd.replaceAll("\\{challenge\\}", Matcher.quoteReplacement(challenge.getName()));
        command = command.replaceAll("\\{challengeName\\}", Matcher.quoteReplacement(challenge.getDisplayName()));
        plugin.execCommand(player, command, true);
    }
    playerInfo.completeChallenge(challengeName, wasBroadcast);
    return true;
}