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

The following examples show how to use org.bukkit.entity.Player#setFallDistance() . 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: PlayerDeathListener.java    From PerWorldInventory with GNU General Public License v3.0 8 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Group group = groupManager.getGroupFromWorld(player.getLocation().getWorld().getName());

    if (!event.getKeepInventory()) {
        player.getInventory().clear();
    }

    if (!event.getKeepLevel()) {
        player.setExp(event.getNewExp());
        player.setLevel(event.getNewLevel());
    }

    player.setFoodLevel(20);
    player.setSaturation(5f);
    player.setExhaustion(0f);
    player.setFallDistance(0f);
    player.setFireTicks(0);
    for (PotionEffect effect : player.getActivePotionEffects()) {
        player.removePotionEffect(effect.getType());
    }

    playerManager.addPlayer(player, group);
}
 
Example 2
Source File: PlayerDeathListener.java    From PerWorldInventory with GNU General Public License v3.0 7 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Group group = groupManager.getGroupFromWorld(player.getLocation().getWorld().getName());

    if (!event.getKeepInventory()) {
        player.getInventory().clear();
    }

    if (!event.getKeepLevel()) {
        player.setExp(event.getNewExp());
        player.setLevel(event.getNewLevel());
    }

    player.setFoodLevel(20);
    player.setSaturation(5f);
    player.setExhaustion(0f);
    player.setFallDistance(0f);
    player.setFireTicks(0);
    for (PotionEffect effect : player.getActivePotionEffects()) {
        player.removePotionEffect(effect.getType());
    }

    playerManager.addPlayer(player, group);
}
 
Example 3
Source File: Portal.java    From CardinalPGM with MIT License 6 votes vote down vote up
private void tryTeleport(Player player, Location from, RegionModule destination, int dir) {
    if ((filter == null || filter.evaluate(player).equals(FilterState.ALLOW)) || ObserverModule.testObserver(player)) {
        if (destination != null) {
            from.setPosition(destination.getRandomPoint().getLocation().position());
        } else {
            from.setX(x.getLeft() ? from.getX() + (x.getRight() * dir) : x.getRight());
            from.setY(y.getLeft() ? from.getY() + (y.getRight() * dir) : y.getRight());
            from.setZ(z.getLeft() ? from.getZ() + (z.getRight() * dir) : z.getRight());
        }
        from.setYaw((float) (yaw.getLeft() ? from.getYaw() + (yaw.getRight() * dir) : yaw.getRight()));
        from.setPitch((float) (pitch.getLeft() ? from.getPitch() + (pitch.getRight() * dir) : pitch.getRight()));
        player.setFallDistance(0);
        player.teleport(from);
        if (sound) player.playSound(player.getLocation(), Sound.ENTITY_ENDERMEN_TELEPORT, 0.2F, 1);
    }
}
 
Example 4
Source File: Game.java    From Survival-Games with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void removeSpectator(Player p) {
	ArrayList < Player > players = new ArrayList < Player > ();
	players.addAll(activePlayers);
	players.addAll(inactivePlayers);

	if(p.isOnline()){
		for (Player pl: Bukkit.getOnlinePlayers()) {
			pl.showPlayer(p);
		}
	}
	restoreInv(p);
	p.setAllowFlight(false);
	p.setFlying(false);
	p.setFallDistance(0);
	p.setHealth(p.getMaxHealth());
	p.setFoodLevel(20);
	p.setSaturation(20);
	p.teleport(SettingsManager.getInstance().getLobbySpawn());
	// Bukkit.getServer().broadcastPrefixType("Removing Spec "+p.getName()+" "+spectators.size()+" left");
	spectators.remove(p.getName());
	// Bukkit.getServer().broadcastPrefixType("Removed");

	nextspec.remove(p);
}
 
Example 5
Source File: WindStaff.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ItemUseHandler getItemHandler() {
    return e -> {
        Player p = e.getPlayer();

        if (p.getFoodLevel() >= 2) {
            if (p.getInventory().getItemInMainHand().getType() != Material.SHEARS && p.getGameMode() != GameMode.CREATIVE) {
                FoodLevelChangeEvent event = new FoodLevelChangeEvent(p, p.getFoodLevel() - 2);
                Bukkit.getPluginManager().callEvent(event);
                p.setFoodLevel(event.getFoodLevel());
            }

            p.setVelocity(p.getEyeLocation().getDirection().multiply(4));
            p.getWorld().playSound(p.getLocation(), Sound.ENTITY_TNT_PRIMED, 1, 1);
            p.getWorld().playEffect(p.getLocation(), Effect.SMOKE, 1);
            p.setFallDistance(0F);
        }
        else {
            SlimefunPlugin.getLocalization().sendMessage(p, "messages.hungry", true);
        }
    };
}
 
Example 6
Source File: Game.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
private void teleportPlayersToTeamSpawn() {
  for (Team team : this.teams.values()) {
    for (Player player : team.getPlayers()) {
      if (!player.getWorld().equals(team.getSpawnLocation().getWorld())) {
        this.getPlayerSettings(player).setTeleporting(true);
      }
      player.setVelocity(new Vector(0, 0, 0));
      player.setFallDistance(0.0F);
      player.teleport(team.getSpawnLocation());
      if (this.getPlayerStorage(player) != null) {
        this.getPlayerStorage(player).clean();
      }
    }
  }
}
 
Example 7
Source File: PlayerStateHolder.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Applies the default state to the player
 * and discards the current one<br><br>
 * 
 * Warning: This deletes the entire inventory
 * and all other various player attributes
 * 
 * It is recommended to save the player state
 * with {@link PlayerStateHolder#create(Player, GameMode)}
 * and store a reference to it before invoking this method
 * 
 * @param player
 */
public static void applyDefaultState(Player player, boolean adventureMode) {
	player.setGameMode(adventureMode ? GameMode.ADVENTURE : GameMode.SURVIVAL);
	player.getInventory().clear();
	player.getInventory().setArmorContents(new ItemStack[4]);
	player.setItemOnCursor(null);
	player.updateInventory();
       player.setMaxHealth(20.0);
	player.setHealth(20.0);
	player.setFoodLevel(20);
	player.setLevel(0);
	player.setExp(0f);
	player.setAllowFlight(false);
	player.setFlying(false);
	player.setFallDistance(0);
	player.setFireTicks(0);
	
	Collection<PotionEffect> effects = player.getActivePotionEffects();
	for (PotionEffect effect : effects) {
		player.removePotionEffect(effect.getType());
	}
	
	for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
		if (player.canSee(player)) {
			continue;
		}
		
		player.showPlayer(onlinePlayer);
	}
}
 
Example 8
Source File: PlayerEvents.java    From askyblock with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Protect players from damage when teleporting
 * @param e - event
 */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerTeleportDamage(EntityDamageEvent e){
    if(!(e.getEntity() instanceof Player)) return;

    Player p = (Player) e.getEntity();
    if (plugin.getPlayers().isInTeleport(p.getUniqueId())) {
        if (DEBUG)
            plugin.getLogger().info("DEBUG: protecting player from teleport damage");
        p.setFallDistance(0);
        e.setCancelled(true);
    }
}
 
Example 9
Source File: Utils.java    From PerWorldInventory with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set a player's stats to defaults, and optionally clear their inventory.
 *
 * @param plugin {@link PerWorldInventory} for econ.
 * @param player The player to zero.
 * @param clearInventory Clear the player's inventory.
 */
public static void zeroPlayer(PerWorldInventory plugin, Player player, boolean clearInventory) {
    if (clearInventory) {
        player.getInventory().clear();
        player.getEnderChest().clear();
    }

    player.setExp(0f);
    player.setFoodLevel(20);

    if (checkServerVersion(Bukkit.getVersion(), 1, 9, 0)) {
        player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
    } else {
        player.setHealth(player.getMaxHealth());
    }

    player.setLevel(0);
    for (PotionEffect effect : player.getActivePotionEffects()) {
        player.removePotionEffect(effect.getType());
    }
    player.setSaturation(5f);
    player.setFallDistance(0f);
    player.setFireTicks(0);

    if (plugin.isEconEnabled()) {
        Economy econ = plugin.getEconomy();
        econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).amount);
        econ.withdrawPlayer(player, econ.getBalance(player));
    }
}
 
Example 10
Source File: Utils.java    From PerWorldInventory with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set a player's stats to defaults, and optionally clear their inventory.
 *
 * @param plugin {@link PerWorldInventory} for econ.
 * @param player The player to zero.
 * @param clearInventory Clear the player's inventory.
 */
public static void zeroPlayer(PerWorldInventory plugin, Player player, boolean clearInventory) {
    if (clearInventory) {
        player.getInventory().clear();
        player.getEnderChest().clear();
    }

    player.setExp(0f);
    player.setFoodLevel(20);

    if (checkServerVersion(Bukkit.getVersion(), 1, 9, 0)) {
        player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
    } else {
        player.setHealth(player.getMaxHealth());
    }

    player.setLevel(0);
    for (PotionEffect effect : player.getActivePotionEffects()) {
        player.removePotionEffect(effect.getType());
    }
    player.setSaturation(5f);
    player.setFallDistance(0f);
    player.setFireTicks(0);

    if (plugin.isEconEnabled()) {
        Economy econ = plugin.getEconomy();
        econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).amount);
        econ.withdrawPlayer(player, econ.getBalance(player));
    }
}
 
Example 11
Source File: Game.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void playerWin(Player p) {
	if (GameMode.DISABLED == mode) return;
	Player win = activePlayers.get(0);
	// clearInv(p);
	win.teleport(SettingsManager.getInstance().getLobbySpawn());
	restoreInv(win);
	msgmgr.broadcastFMessage(PrefixType.INFO, "game.playerwin","arena-"+gameID, "victim-"+p.getName(), "player-"+win.getName());
	LobbyManager.getInstance().display(new String[] {
			win.getName(), "", "Won the ", "Survival Games!"
	}, gameID);

	mode = GameMode.FINISHING;
	if(config.getBoolean("reward.enabled", false)) {
		List<String> items = config.getStringList("reward.contents");
		for(int i=0; i<=(items.size() - 1); i++) {
			ItemStack item = ItemReader.read(items.get(i));
			win.getInventory().addItem(item);
		}
	}

	clearSpecs();
	win.setHealth(p.getMaxHealth());
	win.setFoodLevel(20);
	win.setFireTicks(0);
	win.setFallDistance(0);

	sm.playerWin(win, gameID, new Date().getTime() - startTime);
	sm.saveGame(gameID, win, getActivePlayers() + getInactivePlayers(), new Date().getTime() - startTime);

	activePlayers.clear();
	inactivePlayers.clear();
	spawns.clear();
	playerJoinTimes.clear();

	loadspawns();
	LobbyManager.getInstance().updateWall(gameID);
	MessageManager.getInstance().broadcastFMessage(PrefixType.INFO, "broadcast.gameend", "arena-"+gameID);

}
 
Example 12
Source File: MatchPlayer.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public void reset() {
    final Player bukkit = getBukkit();
    bukkit.closeInventory();
    clearInventory();
    bukkit.setExhaustion(0);
    bukkit.setFallDistance(0);
    bukkit.setFireTicks(0);
    bukkit.setFoodLevel(20); // full
    bukkit.setMaxHealth(20);
    bukkit.setHealth(bukkit.getMaxHealth());
    bukkit.setAbsorption(0);
    bukkit.setLevel(0);
    bukkit.setExp(0); // clear xp
    bukkit.setSaturation(5); // default
    bukkit.setFastNaturalRegeneration(false);
    bukkit.setSlowNaturalRegeneration(true);
    bukkit.setAllowFlight(false);
    bukkit.setFlying(false);
    bukkit.setSneaking(false);
    bukkit.setSprinting(false);
    bukkit.setFlySpeed(0.1f);
    bukkit.setKnockbackReduction(0);
    bukkit.setWalkSpeed(WalkSpeedKit.BUKKIT_DEFAULT);
    AttributeUtils.removeAllModifiers(bukkit);
    resetPotions();

    // we only reset bed spawn here so people don't have to see annoying messages when they respawn
    bukkit.setBedSpawnLocation(null);

    match.callEvent(new PlayerResetEvent(this));
}
 
Example 13
Source File: Island.java    From IridiumSkyblock with GNU General Public License v2.0 4 votes vote down vote up
public void teleportHome(Player p) {
    if (getHome() == null) home = getCenter();
    if (User.getUser(p).teleportingHome) {
        return;
    }
    if (isBanned(User.getUser(p)) && !members.contains(p.getUniqueId().toString())) {
        p.sendMessage(Utils.color(IridiumSkyblock.getMessages().bannedFromIsland.replace("%prefix%", IridiumSkyblock.getConfiguration().prefix)));
        return;
    }
    if (getSchematic() == null) {
        User u = User.getUser(p);
        if (u.getIsland().equals(this)) {
            if (IridiumSkyblock.getSchematics().schematics.size() == 1) {
                for (Schematics.FakeSchematic schematic : IridiumSkyblock.getSchematics().schematics) {
                    setSchematic(schematic.name);
                    setNetherschematic(schematic.netherisland);
                }
            } else {
                p.openInventory(getSchematicSelectGUI().getInventory());
            }
        }
        return;
    }
    p.setFallDistance(0);
    if (members.contains(p.getUniqueId().toString())) {
        p.sendMessage(Utils.color(IridiumSkyblock.getMessages().teleportingHome.replace("%prefix%", IridiumSkyblock.getConfiguration().prefix)));
    }
    if (Utils.isSafe(getHome(), this)) {
        p.teleport(getHome());
        sendBorder(p);
    } else {
        Location loc = Utils.getNewHome(this, this.home);
        if (loc != null) {
            this.home = loc;
            p.teleport(this.home);
            sendBorder(p);
        } else {
            User.getUser(p).teleportingHome = true;
            pasteSchematic(p, false);
        }
    }
}
 
Example 14
Source File: StatSerializer.java    From PerWorldInventory with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Apply stats to a player.
 *
 * @param player The Player to apply the stats to.
 * @param stats  The stats to apply.
 * @param dataFormat See {@link PlayerSerializer#serialize(PWIPlayer)}.
 */
public void deserialize(Player player,JsonObject stats, int dataFormat) {
    if (settings.getProperty(PwiProperties.LOAD_CAN_FLY) && stats.has("can-fly"))
        player.setAllowFlight(stats.get("can-fly").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_DISPLAY_NAME) && stats.has("display-name"))
        player.setDisplayName(stats.get("display-name").getAsString());
    if (settings.getProperty(PwiProperties.LOAD_EXHAUSTION) && stats.has("exhaustion"))
        player.setExhaustion((float) stats.get("exhaustion").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_EXP) && stats.has("exp"))
        player.setExp((float) stats.get("exp").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FLYING) && stats.has("flying") && player.getAllowFlight())
        player.setFlying(stats.get("flying").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_HUNGER) && stats.has("food"))
        player.setFoodLevel(stats.get("food").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_HEALTH) &&
            stats.has("max-health") &&
            stats.has("health")) {
        double maxHealth = stats.get("max-health").getAsDouble();
        if (bukkitService.shouldUseAttributes()) {
            player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth);
        } else {
            player.setMaxHealth(maxHealth);
        }

        double health = stats.get("health").getAsDouble();
        if (health > 0 && health <= maxHealth) {
            player.setHealth(health);
        } else {
            player.setHealth(maxHealth);
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_GAMEMODE) && (!settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)) && stats.has("gamemode")) {
        if (stats.get("gamemode").getAsString().length() > 1) {
            player.setGameMode(GameMode.valueOf(stats.get("gamemode").getAsString()));
        } else {
            int gm = stats.get("gamemode").getAsInt();
            switch (gm) {
                case 0:
                    player.setGameMode(GameMode.CREATIVE);
                    break;
                case 1:
                    player.setGameMode(GameMode.SURVIVAL);
                    break;
                case 2:
                    player.setGameMode(GameMode.ADVENTURE);
                    break;
                case 3:
                    player.setGameMode(GameMode.SPECTATOR);
                    break;
            }
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_LEVEL) && stats.has("level"))
        player.setLevel(stats.get("level").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_POTION_EFFECTS) && stats.has("potion-effects")) {
        if (dataFormat < 2) {
            PotionEffectSerializer.setPotionEffects(stats.get("potion-effects").getAsString(), player);
        } else {
            PotionEffectSerializer.setPotionEffects(stats.getAsJsonArray("potion-effects"), player);
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_SATURATION) && stats.has("saturation"))
        player.setSaturation((float) stats.get("saturation").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FALL_DISTANCE) && stats.has("fallDistance"))
        player.setFallDistance(stats.get("fallDistance").getAsFloat());
    if (settings.getProperty(PwiProperties.LOAD_FIRE_TICKS) && stats.has("fireTicks"))
        player.setFireTicks(stats.get("fireTicks").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_MAX_AIR) && stats.has("maxAir"))
        player.setMaximumAir(stats.get("maxAir").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_REMAINING_AIR) && stats.has("remainingAir"))
        player.setRemainingAir(stats.get("remainingAir").getAsInt());
}
 
Example 15
Source File: PWIPlayerManager.java    From PerWorldInventory with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a player from the cache, and apply the cached inventories and stats
 * to the actual player. If no matching player is found in the cache, nothing
 * happens and this method simply returns.
 *
 * @param group The {@link Group} the cached player was in.
 * @param gamemode The GameMode the cached player was in.
 * @param player The current actual player to apply the data to.
 * @param cause What triggered the inventory switch; passed on for post-processing.
 */
private void getDataFromCache(Group group, GameMode gamemode, Player player, DeserializeCause cause) {
    PWIPlayer cachedPlayer = getCachedPlayer(group, gamemode, player.getUniqueId());
    if (cachedPlayer == null) {
        ConsoleLogger.debug("No data for player '" + player.getName() + "' found in cache");

        return;
    }

    ConsoleLogger.debug("Player '" + player.getName() + "' found in cache! Setting their data");

    if (settings.getProperty(PwiProperties.LOAD_ENDER_CHESTS))
        player.getEnderChest().setContents(cachedPlayer.getEnderChest());
    if (settings.getProperty(PwiProperties.LOAD_INVENTORY)) {
        player.getInventory().setContents(cachedPlayer.getInventory());
        player.getInventory().setArmorContents(cachedPlayer.getArmor());
    }
    if (settings.getProperty(PwiProperties.LOAD_CAN_FLY))
        player.setAllowFlight(cachedPlayer.getCanFly());
    if (settings.getProperty(PwiProperties.LOAD_DISPLAY_NAME))
        player.setDisplayName(cachedPlayer.getDisplayName());
    if (settings.getProperty(PwiProperties.LOAD_EXHAUSTION))
        player.setExhaustion(cachedPlayer.getExhaustion());
    if (settings.getProperty(PwiProperties.LOAD_EXP))
        player.setExp(cachedPlayer.getExperience());
    if (settings.getProperty(PwiProperties.LOAD_FLYING) && player.getAllowFlight())
        player.setFlying(cachedPlayer.isFlying());
    if (settings.getProperty(PwiProperties.LOAD_HUNGER))
        player.setFoodLevel(cachedPlayer.getFoodLevel());
    if (settings.getProperty(PwiProperties.LOAD_HEALTH)) {
        if (bukkitService.shouldUseAttributes()) {
            player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(cachedPlayer.getMaxHealth());
        } else {
            player.setMaxHealth(cachedPlayer.getMaxHealth());
        }
        if (cachedPlayer.getHealth() > 0 && cachedPlayer.getHealth() <= cachedPlayer.getMaxHealth()) {
            player.setHealth(cachedPlayer.getHealth());
        } else {
            player.setHealth(cachedPlayer.getMaxHealth());
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_GAMEMODE) && (!settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)))
        player.setGameMode(cachedPlayer.getGamemode());
    if (settings.getProperty(PwiProperties.LOAD_LEVEL))
        player.setLevel(cachedPlayer.getLevel());
    if (settings.getProperty(PwiProperties.LOAD_POTION_EFFECTS)) {
        for (PotionEffect effect : player.getActivePotionEffects()) {
            player.removePotionEffect(effect.getType());
        }
        player.addPotionEffects(cachedPlayer.getPotionEffects());
    }
    if (settings.getProperty(PwiProperties.LOAD_SATURATION))
        player.setSaturation(cachedPlayer.getSaturationLevel());
    if (settings.getProperty(PwiProperties.LOAD_FALL_DISTANCE))
        player.setFallDistance(cachedPlayer.getFallDistance());
    if (settings.getProperty(PwiProperties.LOAD_FIRE_TICKS))
        player.setFireTicks(cachedPlayer.getFireTicks());
    if (settings.getProperty(PwiProperties.LOAD_MAX_AIR))
        player.setMaximumAir(cachedPlayer.getMaxAir());
    if (settings.getProperty(PwiProperties.LOAD_REMAINING_AIR))
        player.setRemainingAir(cachedPlayer.getRemainingAir());
    if (settings.getProperty(PwiProperties.USE_ECONOMY)) {
        Economy econ = plugin.getEconomy();
        if (econ == null) {
            ConsoleLogger.warning("Economy saving is turned on, but no economy found!");
            return;
        }

        EconomyResponse er = econ.withdrawPlayer(player, econ.getBalance(player));
        if (er.transactionSuccess()) {
            econ.depositPlayer(player, cachedPlayer.getBalance());
        } else {
            ConsoleLogger.warning("[ECON] Unable to withdraw currency from '" + player.getName() + "': " + er.errorMessage);
        }

        EconomyResponse bankER = econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).amount);
        if (bankER.transactionSuccess()) {
            econ.bankDeposit(player.getName(), cachedPlayer.getBankBalance());
        } else {
            ConsoleLogger.warning("[ECON] Unable to withdraw currency from bank of '" + player.getName() + "': " + er.errorMessage);
        }
    }

    InventoryLoadCompleteEvent event = new InventoryLoadCompleteEvent(player, cause);
    Bukkit.getPluginManager().callEvent(event);
}
 
Example 16
Source File: StatSerializer.java    From PerWorldInventory with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Apply stats to a player.
 *
 * @param player The Player to apply the stats to.
 * @param stats  The stats to apply.
 * @param dataFormat See {@link PlayerSerializer#serialize(PWIPlayer)}.
 */
public void deserialize(Player player,JsonObject stats, int dataFormat) {
    if (settings.getProperty(PwiProperties.LOAD_CAN_FLY) && stats.has("can-fly"))
        player.setAllowFlight(stats.get("can-fly").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_DISPLAY_NAME) && stats.has("display-name"))
        player.setDisplayName(stats.get("display-name").getAsString());
    if (settings.getProperty(PwiProperties.LOAD_EXHAUSTION) && stats.has("exhaustion"))
        player.setExhaustion((float) stats.get("exhaustion").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_EXP) && stats.has("exp"))
        player.setExp((float) stats.get("exp").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FLYING) && stats.has("flying") && player.getAllowFlight())
        player.setFlying(stats.get("flying").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_HUNGER) && stats.has("food"))
        player.setFoodLevel(stats.get("food").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_HEALTH) &&
            stats.has("max-health") &&
            stats.has("health")) {
        double maxHealth = stats.get("max-health").getAsDouble();
        if (bukkitService.shouldUseAttributes()) {
            player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth);
        } else {
            player.setMaxHealth(maxHealth);
        }

        double health = stats.get("health").getAsDouble();
        if (health > 0 && health <= maxHealth) {
            player.setHealth(health);
        } else {
            player.setHealth(maxHealth);
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_GAMEMODE) && (!settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)) && stats.has("gamemode")) {
        if (stats.get("gamemode").getAsString().length() > 1) {
            player.setGameMode(GameMode.valueOf(stats.get("gamemode").getAsString()));
        } else {
            int gm = stats.get("gamemode").getAsInt();
            switch (gm) {
                case 0:
                    player.setGameMode(GameMode.CREATIVE);
                    break;
                case 1:
                    player.setGameMode(GameMode.SURVIVAL);
                    break;
                case 2:
                    player.setGameMode(GameMode.ADVENTURE);
                    break;
                case 3:
                    player.setGameMode(GameMode.SPECTATOR);
                    break;
            }
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_LEVEL) && stats.has("level"))
        player.setLevel(stats.get("level").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_POTION_EFFECTS) && stats.has("potion-effects")) {
        if (dataFormat < 2) {
            PotionEffectSerializer.setPotionEffects(stats.get("potion-effects").getAsString(), player);
        } else {
            PotionEffectSerializer.setPotionEffects(stats.getAsJsonArray("potion-effects"), player);
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_SATURATION) && stats.has("saturation"))
        player.setSaturation((float) stats.get("saturation").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FALL_DISTANCE) && stats.has("fallDistance"))
        player.setFallDistance(stats.get("fallDistance").getAsFloat());
    if (settings.getProperty(PwiProperties.LOAD_FIRE_TICKS) && stats.has("fireTicks"))
        player.setFireTicks(stats.get("fireTicks").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_MAX_AIR) && stats.has("maxAir"))
        player.setMaximumAir(stats.get("maxAir").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_REMAINING_AIR) && stats.has("remainingAir"))
        player.setRemainingAir(stats.get("remainingAir").getAsInt());
}
 
Example 17
Source File: PWIPlayerManager.java    From PerWorldInventory with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a player from the cache, and apply the cached inventories and stats
 * to the actual player. If no matching player is found in the cache, nothing
 * happens and this method simply returns.
 *
 * @param group The {@link Group} the cached player was in.
 * @param gamemode The GameMode the cached player was in.
 * @param player The current actual player to apply the data to.
 * @param cause What triggered the inventory switch; passed on for post-processing.
 */
private void getDataFromCache(Group group, GameMode gamemode, Player player, DeserializeCause cause) {
    PWIPlayer cachedPlayer = getCachedPlayer(group, gamemode, player.getUniqueId());
    if (cachedPlayer == null) {
        ConsoleLogger.debug("No data for player '" + player.getName() + "' found in cache");

        return;
    }

    ConsoleLogger.debug("Player '" + player.getName() + "' found in cache! Setting their data");

    if (settings.getProperty(PwiProperties.LOAD_ENDER_CHESTS))
        player.getEnderChest().setContents(cachedPlayer.getEnderChest());
    if (settings.getProperty(PwiProperties.LOAD_INVENTORY)) {
        player.getInventory().setContents(cachedPlayer.getInventory());
        player.getInventory().setArmorContents(cachedPlayer.getArmor());
    }
    if (settings.getProperty(PwiProperties.LOAD_CAN_FLY))
        player.setAllowFlight(cachedPlayer.getCanFly());
    if (settings.getProperty(PwiProperties.LOAD_DISPLAY_NAME))
        player.setDisplayName(cachedPlayer.getDisplayName());
    if (settings.getProperty(PwiProperties.LOAD_EXHAUSTION))
        player.setExhaustion(cachedPlayer.getExhaustion());
    if (settings.getProperty(PwiProperties.LOAD_EXP))
        player.setExp(cachedPlayer.getExperience());
    if (settings.getProperty(PwiProperties.LOAD_FLYING) && player.getAllowFlight())
        player.setFlying(cachedPlayer.isFlying());
    if (settings.getProperty(PwiProperties.LOAD_HUNGER))
        player.setFoodLevel(cachedPlayer.getFoodLevel());
    if (settings.getProperty(PwiProperties.LOAD_HEALTH)) {
        if (bukkitService.shouldUseAttributes()) {
            player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(cachedPlayer.getMaxHealth());
        } else {
            player.setMaxHealth(cachedPlayer.getMaxHealth());
        }
        if (cachedPlayer.getHealth() > 0 && cachedPlayer.getHealth() <= cachedPlayer.getMaxHealth()) {
            player.setHealth(cachedPlayer.getHealth());
        } else {
            player.setHealth(cachedPlayer.getMaxHealth());
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_GAMEMODE) && (!settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)))
        player.setGameMode(cachedPlayer.getGamemode());
    if (settings.getProperty(PwiProperties.LOAD_LEVEL))
        player.setLevel(cachedPlayer.getLevel());
    if (settings.getProperty(PwiProperties.LOAD_POTION_EFFECTS)) {
        for (PotionEffect effect : player.getActivePotionEffects()) {
            player.removePotionEffect(effect.getType());
        }
        player.addPotionEffects(cachedPlayer.getPotionEffects());
    }
    if (settings.getProperty(PwiProperties.LOAD_SATURATION))
        player.setSaturation(cachedPlayer.getSaturationLevel());
    if (settings.getProperty(PwiProperties.LOAD_FALL_DISTANCE))
        player.setFallDistance(cachedPlayer.getFallDistance());
    if (settings.getProperty(PwiProperties.LOAD_FIRE_TICKS))
        player.setFireTicks(cachedPlayer.getFireTicks());
    if (settings.getProperty(PwiProperties.LOAD_MAX_AIR))
        player.setMaximumAir(cachedPlayer.getMaxAir());
    if (settings.getProperty(PwiProperties.LOAD_REMAINING_AIR))
        player.setRemainingAir(cachedPlayer.getRemainingAir());
    if (settings.getProperty(PwiProperties.USE_ECONOMY)) {
        Economy econ = plugin.getEconomy();
        if (econ == null) {
            ConsoleLogger.warning("Economy saving is turned on, but no economy found!");
            return;
        }

        EconomyResponse er = econ.withdrawPlayer(player, econ.getBalance(player));
        if (er.transactionSuccess()) {
            econ.depositPlayer(player, cachedPlayer.getBalance());
        } else {
            ConsoleLogger.warning("[ECON] Unable to withdraw currency from '" + player.getName() + "': " + er.errorMessage);
        }

        EconomyResponse bankER = econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).amount);
        if (bankER.transactionSuccess()) {
            econ.bankDeposit(player.getName(), cachedPlayer.getBankBalance());
        } else {
            ConsoleLogger.warning("[ECON] Unable to withdraw currency from bank of '" + player.getName() + "': " + er.errorMessage);
        }
    }

    InventoryLoadCompleteEvent event = new InventoryLoadCompleteEvent(player, cause);
    Bukkit.getPluginManager().callEvent(event);
}
 
Example 18
Source File: PlayerEvents.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prevents visitors from getting damage if invinciblevisitors option is set to TRUE
 * @param e - event
 */
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onVisitorGetDamage(EntityDamageEvent e){
    if(!Settings.invincibleVisitors
            || !(e.getEntity() instanceof Player)
            || e.getCause().equals(DamageCause.ENTITY_ATTACK)) {
        return;
    }
    Player p = (Player) e.getEntity();
    if (!IslandGuard.inWorld(p) || plugin.getGrid().locationIsOnIsland(p, p.getLocation())) return;

    if (Settings.visitorDamagePrevention.contains(e.getCause())) e.setCancelled(true);

    if(e.getCause().equals(DamageCause.VOID)) {
        if (plugin.getPlayers().hasIsland(p.getUniqueId()) || plugin.getPlayers().inTeam(p.getUniqueId())) {
            Location safePlace = plugin.getGrid().getSafeHomeLocation(p.getUniqueId(), 1);
            if (safePlace != null) {
                unsetFalling(p.getUniqueId());
                p.teleport(safePlace);
                // Set their fall distance to zero otherwise they crash onto their island and die
                p.setFallDistance(0);
                e.setCancelled(true);
                return;
            }
        }
        if (plugin.getGrid().getSpawn() != null) {
            p.teleport(plugin.getGrid().getSpawnPoint());
            // Set their fall distance to zero otherwise they crash onto their island and die
            p.setFallDistance(0);
            e.setCancelled(true);
            return;
        } else if (!p.performCommand("spawn")) {
            // If this command doesn't work, let them die otherwise they may get trapped in the void forever
            return;
        } else {
            // Set their fall distance to zero otherwise they crash onto their island and die
            p.setFallDistance(0);
            e.setCancelled(true);
        }
    }
}
 
Example 19
Source File: MatchPlayerImpl.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void reset() {
  getMatch().callEvent(new PlayerResetEvent(this));

  setFrozen(false);
  Player bukkit = getBukkit();
  bukkit.closeInventory();
  resetInventory();
  bukkit.setArrowsStuck(0);
  bukkit.setExhaustion(0);
  bukkit.setFallDistance(0);
  bukkit.setFireTicks(0);
  bukkit.setFoodLevel(20); // full
  bukkit.setHealth(bukkit.getMaxHealth());
  bukkit.setLevel(0);
  bukkit.setExp(0); // clear xp
  bukkit.setSaturation(5); // default
  bukkit.setAllowFlight(false);
  bukkit.setFlying(false);
  bukkit.setSneaking(false);
  bukkit.setSprinting(false);
  bukkit.setFlySpeed(0.1f);
  bukkit.setKnockbackReduction(0);
  bukkit.setWalkSpeed(WalkSpeedKit.BUKKIT_DEFAULT);

  for (PotionEffect effect : bukkit.getActivePotionEffects()) {
    if (effect.getType() != null) {
      bukkit.removePotionEffect(effect.getType());
    }
  }

  for (Attribute attribute : ATTRIBUTES) {
    AttributeInstance attributes = bukkit.getAttribute(attribute);
    if (attributes == null) continue;

    for (AttributeModifier modifier : attributes.getModifiers()) {
      attributes.removeModifier(modifier);
    }
  }

  NMSHacks.setAbsorption(bukkit, 0);

  // we only reset bed spawn here so people don't have to see annoying messages when they respawn
  bukkit.setBedSpawnLocation(null);
}
 
Example 20
Source File: PlayerStateHolder.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public void apply(Player player, boolean teleport) {
	PlayerInventory playerInv = player.getInventory();
	boolean is1_9 = MinecraftVersion.getImplementationVersion().compareTo(MinecraftVersion.V1_9) >= 0;
       boolean isSimpleSize = playerInv.getContents().length <= SIMPLE_INVENTORY_SIZE;

       ItemStack[] inventoryContents = new ItemStack[is1_9 && !isSimpleSize ? playerInv.getSize() : SIMPLE_INVENTORY_SIZE];
       System.arraycopy(inventory, 0, inventoryContents, 0, inventoryContents.length);

       if (!is1_9 || isSimpleSize) {
           ItemStack[] armorContents = new ItemStack[ARMOR_INVENTORY_SIZE];
           System.arraycopy(inventory, inventory.length - ARMOR_INVENTORY_SIZE, armorContents, 0, armorContents.length);
           playerInv.setArmorContents(armorContents);
       }
	
	playerInv.setContents(inventoryContents);

	player.setItemOnCursor(null);
	Map<Integer, ItemStack> exceeded = playerInv.addItem(onCursor);
	for (ItemStack stack : exceeded.values()) {
           if (stack.getType() == Material.AIR) {
               continue;
           }
           
		player.getWorld().dropItem(player.getLocation(), stack);
	}
	
	player.updateInventory();

       player.setMaxHealth(maxHealth);
	player.setHealth(health);
	player.setFoodLevel(foodLevel);
	player.setLevel(level);
	player.setExp(experience);
	player.setAllowFlight(allowFlight);
	player.setFlying(isFlying);
	
	/* Remove current potion effects */
	Collection<PotionEffect> effects = player.getActivePotionEffects();
	for (PotionEffect effect : effects) {
		player.removePotionEffect(effect.getType());
	}
	player.addPotionEffects(activeEffects);
	
	player.setExhaustion(exhaustion);
	player.setSaturation(saturation);
	player.setFallDistance(fallDistance);
	player.setFireTicks(fireTicks);
	
	if (scoreboard != player.getScoreboard()) {
		Scoreboard showBoard = scoreboard;
		if (scoreboard == null) {
			showBoard = Bukkit.getScoreboardManager().getMainScoreboard();
		}
		
		player.setScoreboard(showBoard);
	}
	
	if (teleport) {
		player.teleport(location);
	}
	
	Location compassTarget = this.compassTarget;
	
	if (compassTarget == null) {
		compassTarget = player.getWorld().getSpawnLocation();
	}
	
	player.setCompassTarget(compassTarget);
	
	for (WeakReference<Player> ref : cantSee) {
		Player cantSeePlayer = ref.get();
		
		if (cantSeePlayer == null) {
			// Player object has been garbage-collected
			continue;
		}
		
		if (!cantSeePlayer.isOnline()) {
			continue;
		}
		
		player.hidePlayer(cantSeePlayer);
	}
	
	player.setGameMode(gamemode);
}