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

The following examples show how to use org.bukkit.entity.Player#setGameMode() . 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: ModeCoordinator.java    From StaffPlus with GNU General Public License v3.0 6 votes vote down vote up
private void unsetPassive(Player player)
{
	UUID uuid = player.getUniqueId();
	ModeDataVault modeData = modeUsers.get(uuid);
	
	if(options.modeOriginalLocation)
	{
		player.teleport(modeData.getPreviousLocation().setDirection(player.getLocation().getDirection()));
		message.send(player, messages.modeOriginalLocation, messages.prefixGeneral);
	}
	
	runModeCommands(player.getName(), false);
	player.getInventory().setContents(modeData.getItems());
	player.getInventory().setArmorContents(modeData.getArmor());
	player.updateInventory();
	player.setAllowFlight(modeData.hasFlight());
	player.setGameMode(modeData.getGameMode());
	
	if(modeData.getVanishType() == VanishType.NONE)
	{
		vanishHandler.removeVanish(player);
	}else vanishHandler.addVanish(player, modeData.getVanishType());
}
 
Example 2
Source File: LobbyMap.java    From AnnihilationPro with MIT License 6 votes vote down vote up
public void sendToSpawn(final Player player)
{
	if(spawn != null && player != null)
	{
		player.getInventory().clear();
		player.getInventory().setArmorContents(null);
		player.setHealth(player.getMaxHealth());
		player.setFoodLevel(20);
		player.setGameMode(GameVars.getDefaultGamemode());
		player.getInventory().addItem(CustomItem.KITMAP.toItemStack());
		player.getInventory().addItem(CustomItem.TEAMMAP.toItemStack());
		if(GameVars.getVoting())
			player.getInventory().addItem(CustomItem.VOTEMAP.toItemStack());
		player.teleport(getSpawn());
	}
}
 
Example 3
Source File: TutorialPlayer.java    From ServerTutorial with MIT License 6 votes vote down vote up
public void restorePlayer(Player player) {
    player.teleport(startLoc);
    player.getInventory().setContents(inventory);
    player.setFlying(flight);
    player.setAllowFlight(allowFlight);
    player.setExp(exp);
    player.setLevel(level);
    player.setFoodLevel(hunger);
    player.setHealth(health);
    player.setGameMode(gameMode);

    for (Player online : Bukkit.getServer().getOnlinePlayers()) {
        online.showPlayer(player);
        player.showPlayer(online);
    }
}
 
Example 4
Source File: CommonEntityEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
private void checkPlayerGameMode(GDPermissionUser user, GDClaim fromClaim, GDClaim toClaim) {
    if (user == null) {
        return;
    }
    final Player player = user.getOnlinePlayer();
    if (player == null) {
        // Most likely Citizens NPC
        return;
    }
    if (!GDOptions.isOptionEnabled(Options.PLAYER_GAMEMODE)) {
        return;
    }

    final GDPlayerData playerData = user.getInternalPlayerData();
    final GameMode currentGameMode = player.getGameMode();
    final GameModeType gameModeType = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(GameModeType.class), playerData.getSubject(), Options.PLAYER_GAMEMODE, toClaim);
    if (gameModeType == GameModeTypes.UNDEFINED && playerData.lastGameMode != GameModeTypes.UNDEFINED) {
        player.setGameMode(PlayerUtil.GAMEMODE_MAP.get(playerData.lastGameMode));
        return;
    }

    final boolean bypassOption = playerData.userOptionBypassPlayerGamemode;
    if (!bypassOption && gameModeType != null && gameModeType != GameModeTypes.UNDEFINED) {
        final GameMode newGameMode = PlayerUtil.GAMEMODE_MAP.get(gameModeType);
        if (currentGameMode != newGameMode) {
            playerData.lastGameMode = PlayerUtil.GAMEMODE_MAP.inverse().get(gameModeType);
            player.setGameMode(newGameMode);
            final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.OPTION_APPLY_PLAYER_GAMEMODE,
                    ImmutableMap.of(
                    "gamemode", gameModeType.getName()));
            GriefDefenderPlugin.sendMessage(player, message);
        }
    }
}
 
Example 5
Source File: DragonRushListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onEntityDeath(EntityDeathEvent e){
    if (e.getEntityType() != EntityType.ENDER_DRAGON){
        return;
    }

    if (e.getEntity().getKiller() == null) {
        return;
    }

    Player killer = e.getEntity().getKiller();
    UhcPlayer uhcKiller = getPlayersManager().getUhcPlayer(killer);

    List<UhcPlayer> spectators = new ArrayList<>();

    for (UhcPlayer playingPlayer : getPlayersManager().getAllPlayingPlayers()){

        if (!playingPlayer.isInTeamWith(uhcKiller)){
            spectators.add(playingPlayer);
        }
    }

    for (UhcPlayer spectator : spectators){
        spectator.setState(PlayerState.DEAD);

        try {
            Player all = spectator.getPlayer();
            all.setGameMode(GameMode.SPECTATOR);
            all.teleport(killer);
        }catch (UhcPlayerNotOnlineException exeption){
            // Nothing
        }
    }

    getPlayersManager().checkIfRemainingPlayers();
}
 
Example 6
Source File: DGamePlayer.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
public DGamePlayer(DungeonsXL plugin, Player player, GameWorld world) {
    super(plugin, player, world);

    Game game = world.getGame();
    dGroup = (DGroup) plugin.getPlayerGroup(player);
    if (game == null) {
        game = new DGame(plugin, dGroup);
    }

    GameRuleContainer rules = game.getRules();
    player.setGameMode(GameMode.SURVIVAL);

    if (!rules.getState(GameRule.KEEP_INVENTORY_ON_ENTER)) {
        clearPlayerData();
    }
    player.setAllowFlight(rules.getState(GameRule.FLY));

    initialLives = rules.getState(GameRule.INITIAL_LIVES);
    lives = initialLives;

    resetClassInventoryOnRespawn = rules.getState(GameRule.RESET_CLASS_INVENTORY_ON_RESPAWN);

    Location teleport = world.getLobbyLocation();
    if (teleport == null) {
        player.teleport(world.getWorld().getSpawnLocation());
    } else {
        player.teleport(teleport);
    }

    if (!((DGameWorld) world).hasReadySign()) {
        MessageUtil.sendMessage(player, DMessage.ERROR_NO_READY_SIGN.getMessage(world.getName()));
    }
}
 
Example 7
Source File: PlayersManager.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public void setPlayerStartPlaying(UhcPlayer uhcPlayer){

		Player player;
		MainConfiguration cfg = GameManager.getGameManager().getConfiguration();

		if(!uhcPlayer.getHasBeenTeleportedToLocation()){
			uhcPlayer.setState(PlayerState.PLAYING);
			uhcPlayer.selectDefaultGlobalChat();

			try {
				player = uhcPlayer.getPlayer();
				clearPlayerInventory(player);
				player.setFireTicks(0);

				for(PotionEffect effect : player.getActivePotionEffects())
				{
					player.removePotionEffect(effect.getType());
				}
				player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 999999, 1), false);
				player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 999999, 40), false);
				player.setGameMode(GameMode.SURVIVAL);
				if(cfg.getEnableExtraHalfHearts()){
					VersionUtils.getVersionUtils().setPlayerMaxHealth(player, 20+((double) cfg.getExtraHalfHearts()));
					player.setHealth(20+((double) cfg.getExtraHalfHearts()));
				}
				UhcItems.giveGameItemTo(player, GameItem.COMPASS_ITEM);
				UhcItems.giveGameItemTo(player, GameItem.CUSTOM_CRAFT_BOOK);
				KitsManager.giveKitTo(player);

				if (!uhcPlayer.getStoredItems().isEmpty()){
					player.getInventory().addItem(uhcPlayer.getStoredItems().toArray(new ItemStack[]{}));
					uhcPlayer.getStoredItems().clear();
				}
			} catch (UhcPlayerNotOnlineException e) {
				// Nothing done
			}
		}
	}
 
Example 8
Source File: PlayersManager.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public void setPlayerSpectateAtLobby(UhcPlayer uhcPlayer){

		uhcPlayer.setState(PlayerState.DEAD);
		uhcPlayer.sendPrefixedMessage(Lang.PLAYERS_WELCOME_BACK_SPECTATING);

		if(GameManager.getGameManager().getConfiguration().getSpectatingTeleport()) {
			uhcPlayer.sendPrefixedMessage(Lang.COMMAND_SPECTATING_HELP);
		}

		Player player;
		try {
			player = uhcPlayer.getPlayer();player.getEquipment().clear();
			clearPlayerInventory(player);
			player.setGameMode(GameMode.SPECTATOR);
			for(PotionEffect effect : player.getActivePotionEffects())
			{
				player.removePotionEffect(effect.getType());
			}
			if(GameManager.getGameManager().getGameState().equals(GameState.DEATHMATCH)){
				player.teleport(GameManager.getGameManager().getArena().getLoc());
			}else{
				player.teleport(GameManager.getGameManager().getLobby().getLoc());
			}
		} catch (UhcPlayerNotOnlineException e) {
			// Do nothing because DEAD is a safe state
		}
	}
 
Example 9
Source File: ModeCoordinator.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
private void setPassive(Player player, User user)
{
	if(options.modeFlight && !options.modeCreative)
	{
		player.setAllowFlight(true);
	}else if(options.modeCreative)
	{
		player.setGameMode(GameMode.CREATIVE);
	}
	
	runModeCommands(player.getName(), true);
	vanishHandler.addVanish(player, options.modeVanish);
	
	for(ModeItem modeItem : MODE_ITEMS)
	{
		if(!modeItem.isEnabled())
		{
			continue;
		}
		
		if(modeItem.getIdentifier().equals("vanish"))
		{
			modeItem.setItem(user.getVanishType() == options.modeVanish ? options.modeVanishItem : options.modeVanishItemOff);
		}
		
		player.getInventory().setItem(modeItem.getSlot(), StaffPlus.get().versionProtocol.addNbtString(modeItem.getItem(), modeItem.getIdentifier()));
	}
	
	for(ModuleConfiguration moduleConfiguration : options.moduleConfigurations.values())
	{
		player.getInventory().setItem(moduleConfiguration.getSlot(), StaffPlus.get().versionProtocol.addNbtString(moduleConfiguration.getItem(), moduleConfiguration.getIdentifier()));
	}
}
 
Example 10
Source File: AnnihilationMain.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOW)
public void onGameStart(GameStartEvent event)
{
       //Bukkit.getLogger().info("WELL WE GOT HERE!!!!");
	if(Game.getGameMap() != null)
	{
		for(AnniTeam t : AnniTeam.Teams)
		{
			t.setHealth(75);
		}
		GameMap map = Game.getGameMap();
		for(final AnniPlayer p : AnniPlayer.getPlayers())
		{
			final Player player = p.getPlayer();
			if(player != null && p.getTeam() != null)
			{
				player.setHealth(player.getHealth());
				player.setFoodLevel(20);
				player.setGameMode(GameVars.getDefaultGamemode());
				player.getInventory().clear();
				player.getInventory().setArmorContents(null);
				player.teleport(p.getTeam().getRandomSpawn());
				p.getKit().onPlayerSpawn(player);
				//Do the thing where we announce that the game has started
			}
		}
           AnnounceBar.getInstance().countDown(new Announcement(Lang.PHASEBAR.toStringReplacement(1) + " - {#}").setTime(map.getPhaseTime()).setCallback(new StandardPhaseHandler()));
		//MessageBar.countDown(Lang.PHASEBAR.toStringReplacement(1) + " - {#}", map.getPhaseTime(), new StandardPhaseHandler());
		map.setPhase(1);
		map.setCanDamageNexus(false);
	}
}
 
Example 11
Source File: Players.java    From CardinalPGM with MIT License 5 votes vote down vote up
public static void setObserver(Player player) {
    player.setGameMode(GameMode.CREATIVE);
    player.setAllowFlight(true);
    player.setFlying(true);
    canInteract(player, false);
    resetPlayer(player, false);
    player.closeInventory();
}
 
Example 12
Source File: PlayerData.java    From SkyWarsReloaded with GNU General Public License v3.0 4 votes vote down vote up
public void restore(boolean playerQuit) {
if (!beingRestored) {
	beingRestored = true;
       final Player player = this.getPlayer();
       if (player == null) {
           return;
       }
       
	if (SkyWarsReloaded.getCfg().debugEnabled()) {
       	Util.get().logToFile(ChatColor.RED + "[skywars] " + ChatColor.YELLOW + "Restoring " + player.getName());
   	}
   	PlayerStat pStats = PlayerStat.getPlayerStats(player);
       player.closeInventory();
       player.setGameMode(GameMode.SURVIVAL);
       if (SkyWarsReloaded.getCfg().displayPlayerExeperience()) {
       	if (pStats != null) { Util.get().setPlayerExperience(player, pStats.getXp()); }
       }
       Util.get().clear(player);
       player.getInventory().clear();
       player.getInventory().setContents(inv.getContents());
       SkyWarsReloaded.getNMS().setMaxHealth(player, 20);
       if (health <= 0 || health > 20) {
		player.setHealth(20);
	} else {
		player.setHealth(health);
	}
       player.setFoodLevel(food);
       player.setSaturation(sat);
       player.resetPlayerTime();
       player.resetPlayerWeather();
       player.setAllowFlight(false);
       player.setFlying(false);
	if (!SkyWarsReloaded.getCfg().displayPlayerExeperience()) {
		player.setExp(xp);
	}
       
       player.setFireTicks(0);
       player.setScoreboard(sb);
       if (SkyWarsReloaded.getCfg().lobbyBoardEnabled() && !SkyWarsReloaded.getCfg().bungeeMode()) {
        PlayerStat.updateScoreboard(player);
       }
       
       final Location respawn = SkyWarsReloaded.getCfg().getSpawn();
       if (SkyWarsReloaded.get().isEnabled()) {
           if (playerQuit) {
                     player.teleport(respawn, TeleportCause.END_PORTAL);
                 } else {
                     new BukkitRunnable() {
                         @Override
                         public void run() {
                             player.teleport(respawn, TeleportCause.END_PORTAL);
                         }
                     }.runTaskLater(SkyWarsReloaded.get(), 2);
                 }
	} else {
		player.teleport(respawn, TeleportCause.END_PORTAL);
	}

       
   	if (SkyWarsReloaded.getCfg().debugEnabled()) {
       	Util.get().logToFile(ChatColor.RED + "[skywars] " + ChatColor.YELLOW + "Finished restoring " + player.getName() + ". Teleporting to Spawn");
   	}
	if (SkyWarsReloaded.getCfg().bungeeMode()) {
		new BukkitRunnable() {
			@Override
			public void run() {
				String uuid = player.getUniqueId().toString();
				SkyWarsReloaded.get().sendBungeeMsg(player, "Connect", SkyWarsReloaded.getCfg().getBungeeLobby());
				PlayerStat remove = PlayerStat.getPlayerStats(uuid);
				PlayerStat.getPlayers().remove(remove);
			}
		}.runTaskLater(SkyWarsReloaded.get(), 5);
	}
}
  }
 
Example 13
Source File: ServerTutorial.java    From ServerTutorial with MIT License 4 votes vote down vote up
/**
 * Starts tutorial
 *
 * @param tutorialName tutorial name
 * @param player       Player
 */
public void startTutorial(String tutorialName, Player player) {
    String name = player.getName();
    UUID uuid = Caching.getCaching().getUUID(player);
    if (DataLoading.getDataLoading().getData().getConfigurationSection("tutorials") == null) {
        player.sendMessage(ChatColor.RED + "You need to set up a tutorial first! /tutorial create <name>");
        return;
    }
    Tutorial tut = TutorialManager.getManager().getTutorial(tutorialName);
    if (tut == null) {
        player.sendMessage("Invalid tutorial");
        return;
    }
    if (DataLoading.getDataLoading().getData().getConfigurationSection("tutorials." + tutorialName + ".views") ==
            null) {
        player.sendMessage(ChatColor.RED + "You need to set up a view first! /tutorial addview <name>");
        return;
    }

    addPlayertoTemp(player);
    TutorialPlayer tutorialPlayer = new TutorialPlayer(player);
    tutorialPlayer.clearPlayer(player);
    addTutorialPlayer(uuid, tutorialPlayer);

    player.setGameMode(tut.getGameMode());
    this.initializeCurrentView(name);
    TutorialManager.getManager().addCurrentTutorial(name, tutorialName);
    TutorialManager.getManager().addToTutorial(name);

    Caching.getCaching().setTeleport(player, true);
    player.teleport(TutorialManager.getManager().getTutorialView(tutorialName, name).getLocation());
    if (TutorialManager.getManager().getTutorial(tutorialName).getViewType() == ViewType.TIME) {
        TutorialManager.getManager().getTutorialTimeTask(tutorialName, name);
    }
    TutorialUtils.getTutorialUtils().messageUtils(player);
    StartTutorialEvent event = new StartTutorialEvent(player, TutorialManager.getManager().getTutorial(tutorialName));
    this.getServer().getPluginManager().callEvent(event);

    DataLoading.getDataLoading().getPlayerData().set("players." + uuid + ".tutorials." + tutorialName, "false");
    DataLoading.getDataLoading().savePlayerData();
}
 
Example 14
Source File: SilentOpenChest.java    From SuperVanish with Mozilla Public License 2.0 4 votes vote down vote up
private void restoreState(StateInfo stateInfo, Player p) {
    p.setGameMode(stateInfo.gameMode);
    p.setAllowFlight(stateInfo.canFly);
    p.setFlying(stateInfo.isFlying);
}
 
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: ASkyBlock.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Resets a player's inventory, armor slots, equipment, enderchest and
 * potion effects
 *
 * @param player - player
 */
@SuppressWarnings("deprecation")
public void resetPlayer(Player player) {
    // getLogger().info("DEBUG: clear inventory = " +
    // Settings.clearInventory);
    if (Settings.clearInventory
            && (player.getWorld().getName().equalsIgnoreCase(Settings.worldName) || player.getWorld().getName()
                    .equalsIgnoreCase(Settings.worldName + "_nether"))) {
        // Clear their inventory and equipment and set them as survival
        player.getInventory().clear(); // Javadocs are wrong - this does not
        // clear armor slots! So...
        player.getInventory().setArmorContents(null);
        player.getInventory().setHelmet(null);
        player.getInventory().setChestplate(null);
        player.getInventory().setLeggings(null);
        player.getInventory().setBoots(null);
        player.getEquipment().clear();
    }
    if (!player.isOp()) {
        player.setGameMode(GameMode.SURVIVAL);
    }
    if (Settings.resetChallenges) {
        // Reset the player's challenge status
        players.resetAllChallenges(player.getUniqueId(), false);
    }
    // Reset the island level
    players.setIslandLevel(player.getUniqueId(), 0);
    // Clear the starter island
    players.clearStartIslandRating(player.getUniqueId());
    // Save the player
    players.save(player.getUniqueId());
    topTen.topTenAddEntry(player.getUniqueId(), 0);
    // Update the inventory
    player.updateInventory();
    if (Settings.resetEnderChest) {
        // Clear any Enderchest contents
        final ItemStack[] items = new ItemStack[player.getEnderChest().getContents().length];
        player.getEnderChest().setContents(items);
    }
    // Clear any potion effects
    for (PotionEffect effect : player.getActivePotionEffects())
        player.removePotionEffect(effect.getType());
}
 
Example 17
Source File: SpectatorTools.java    From CardinalPGM with MIT License 4 votes vote down vote up
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
    ItemStack item = event.getCurrentItem();
    Player player = (Player) event.getWhoClicked();
    String locale = player.getLocale();
    if (item == null) return;
    if (event.getInventory().getName().equals(getSpectatorMenuTitle(event.getActor().getLocale()))) {
        if (item.isSimilar(getTeleportItem(locale))) {
            player.openInventory(getTeamsMenu(player));
        } else if (item.isSimilar(getVisibilityItem(locale))) {
            Bukkit.dispatchCommand(player, "toggle obs");
            player.closeInventory();
        } else if (item.isSimilar(getElytraItem(locale))) {
            Bukkit.dispatchCommand(player, "toggle elytra");
            player.closeInventory();
        } else if (item.isSimilar(getEffectsItem(locale))) {
            player.openInventory(getEffectsMenu(player));
        } else if (item.isSimilar(getGamemodeItem(locale))) {
            player.setGameMode(player.getGameMode().equals(GameMode.CREATIVE) ? GameMode.SPECTATOR : GameMode.CREATIVE);
            if (player.getGameMode().equals(GameMode.CREATIVE)) Bukkit.dispatchCommand(player, "!");
            player.closeInventory();
        }
    } else if (event.getInventory().getName().equals(getTeamsMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getSpectatorMenu(player));
        } else if (item.getType().equals(Material.LEATHER_HELMET) && item.getItemMeta().hasDisplayName() && !item.isSimilar(TeamPicker.getTeamPicker(locale))){
            TeamModule team = Teams.getTeamByName(ChatColor.stripColor(Strings.removeLastWord(item.getItemMeta().getDisplayName()))).orNull();
            if (team != null) {
                player.openInventory(getTeleportMenu(player, team));
            }
        }
    } else if (event.getInventory().getName().equals(getTeleportMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getTeamsMenu(player));
        } else if (item.getType().equals(Material.SKULL_ITEM) && item.getItemMeta().hasDisplayName()) {
            Player teleport = Bukkit.getPlayer(((SkullMeta) item.getItemMeta()).getOwner());
            if (teleport != null) {
                player.teleport(teleport);
                player.closeInventory();
            }
        }
    } else if (event.getInventory().getName().equals(getEffectsMenuTitle(locale))) {
        if (item.isSimilar(getGoBackItem(locale))) {
            player.openInventory(getSpectatorMenu(player));
        } else if (item.isSimilar(getNightVisionItem(player.getLocale()))) {
            if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
                player.removePotionEffect(PotionEffectType.NIGHT_VISION);
            } else {
                player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 0, false, false));
            }
            player.closeInventory();
        } else if (item.getType().equals(Material.SUGAR) && item.getItemMeta().hasDisplayName()) {
            int value = event.getSlot();
            Setting setting = Settings.getSettingByName("Speed");
            Bukkit.dispatchCommand(player, "set speed " + setting.getValues().get(value).getValue());
            player.closeInventory();
        }
    }
}
 
Example 18
Source File: GameModeKit.java    From CardinalPGM with MIT License 4 votes vote down vote up
@Override
public void apply(Player player, Boolean force) {
    player.setGameMode(gameMode);
}
 
Example 19
Source File: FlagSpectate.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public boolean spectate(SpleefPlayer player, Game game) {
	SpectateEnterEvent enterEvent = new SpectateEnterEvent(game, player);
	game.getEventBus().callEvent(enterEvent);

	if (enterEvent.isCancelled()) {
		return false;
	}
	
	final Player bukkitPlayer = player.getBukkitPlayer();
	
	PlayerStateHolder holder = new PlayerStateHolder();
	holder.setLocation(bukkitPlayer.getLocation());
	holder.setGamemode(bukkitPlayer.getGameMode());
	
	bukkitPlayer.setGameMode(GameMode.SURVIVAL);
	player.teleport(getValue());
	
	holder.updateState(bukkitPlayer, false, holder.getGamemode());
	player.savePlayerState(this, holder);

       boolean adventureMode = config.getGeneralSection().isAdventureMode();
	PlayerStateHolder.applyDefaultState(bukkitPlayer, adventureMode);
	
	spectators.add(player);
	
	Bukkit.getScheduler().runTask(game.getHeavySpleef().getPlugin(), new Runnable() {
		@Override
		public void run() {
               addLeaveItem(bukkitPlayer);
		}
	});

       boolean showScoreboard = config.getSpectateSection().isShowScoreboard();
       Scoreboard scoreboard = getScoreboard();

       if (showScoreboard && scoreboard != null) {
           player.getBukkitPlayer().setScoreboard(scoreboard);
       }
	
	SpectateEnteredEvent enteredEvent = new SpectateEnteredEvent(game, player);
	game.getEventBus().callEvent(enteredEvent);
	return true;
}
 
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);
}