org.bukkit.GameMode Java Examples

The following examples show how to use org.bukkit.GameMode. 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: QualityArmory.java    From QualityArmory with GNU General Public License v3.0 6 votes vote down vote up
public static boolean removeAmmoFromInventory(Player player, Ammo a, int amount) {
	int remaining = amount;
	if(player.getGameMode()==GameMode.CREATIVE)
		return true;
	for (int i = 0; i < player.getInventory().getSize(); i++) {
		ItemStack is = player.getInventory().getItem(i);
		if (is != null && QualityArmory.isAmmo(is)&&QualityArmory.getAmmo(is).equals(a)) {
			int temp = is.getAmount();
			if (remaining < is.getAmount()) {
				is.setAmount(is.getAmount() - remaining);
			} else {
				is.setType(Material.AIR);
			}
			remaining -= temp;
			player.getInventory().setItem(i, is);
			if (remaining <= 0)
				break;

		}
	}
	return remaining <= 0;
}
 
Example #2
Source File: FlatFile.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void saveToDatabase(Group group, GameMode gamemode, PWIPlayer player) {
    File file = getFile(gamemode, group, player.getUuid());
    ConsoleLogger.debug("Saving data for player '" + player.getName() + "' in file '" + file.getPath() + "'");

    try {
        createFileIfNotExists(file);
    } catch (IOException ex) {
        if (!(ex instanceof FileAlreadyExistsException)) {
            ConsoleLogger.severe("Error creating file '" + file.getPath() + "':", ex);
            return;
        }
    }

    ConsoleLogger.debug("Writing player data for player '" + player.getName() + "' to file");

    String data = playerSerializer.serialize(player);
    writeData(file, data);
}
 
Example #3
Source File: PWIPlayerManagerTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
private Player mockPlayer(String name, GameMode gameMode) {
    Player mock = mock(Player.class);
    PlayerInventory inv = mock(PlayerInventory.class);
    inv.setContents(new ItemStack[39]);
    inv.setArmorContents(new ItemStack[4]);

    Inventory enderChest = mock(Inventory.class);
    enderChest.setContents(new ItemStack[27]);

    given(mock.getInventory()).willReturn(inv);
    given(mock.getEnderChest()).willReturn(enderChest);
    given(mock.getName()).willReturn(name);
    given(mock.getUniqueId()).willReturn(TestHelper.TEST_UUID);
    given(mock.getGameMode()).willReturn(gameMode);
    AttributeInstance attribute = mock(AttributeInstance.class);
    given(mock.getAttribute(Attribute.GENERIC_MAX_HEALTH)).willReturn(attribute);
    given(attribute.getBaseValue()).willReturn(20.0);

    return mock;
}
 
Example #4
Source File: GameModeChangeProcessTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldNotBypassNoPermission() {
    // given
    Player player = mock(Player.class);

    Group group = mockGroup("world");

    GameMode newGameMode = GameMode.CREATIVE;
    given(permissionManager.hasPermission(player, PlayerPermission.BYPASS_GAMEMODE)).willReturn(false);
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(false);

    // when
    process.processGameModeChange(player, newGameMode, group);

    // then
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example #5
Source File: DoubleJump.java    From HubBasics with GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onJump(PlayerToggleFlightEvent event) {
    Player player = event.getPlayer();
    if (player.getGameMode() == GameMode.CREATIVE) return;
    if (!isEnabledInWorld(player.getWorld())) return;

    Section section = getWorldConfiguration(player.getWorld().getName());

    event.setCancelled(true);
    player.setAllowFlight(false);
    player.setFlying(false);
    Sound sound = FinderUtil.findSound(section.getString("Sound", "NOPE"));
    player.setVelocity(player.getLocation().getDirection().multiply(section.getDouble("Force", 1.0)).setY(1));
    if (sound != null) {
        player.playSound(player.getLocation(), sound, 1.0F, -5.0F);
    }
}
 
Example #6
Source File: Splint.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();

        // Player is neither burning nor injured
        if (p.getFireTicks() <= 0 && p.getHealth() >= p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()) {
            return;
        }

        if (p.getGameMode() != GameMode.CREATIVE) {
            ItemUtils.consumeItem(e.getItem(), false);
        }

        p.getWorld().playSound(p.getLocation(), Sound.ENTITY_SKELETON_HURT, 1, 1);
        p.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 0));

        e.cancel();
    };
}
 
Example #7
Source File: ExhibitionCommands.java    From NyaaUtils with MIT License 6 votes vote down vote up
@SubCommand(value = "set", permission = "nu.exhibition.set")
public void commandSet(CommandSender sender, Arguments args) {
    Player p = asPlayer(sender);
    ExhibitionFrame f = ExhibitionFrame.fromPlayerEye(p);
    if (f == null) {
        msg(sender, "user.exhibition.no_item_frame");
        return;
    }
    if (!f.hasItem()) {
        msg(sender, "user.exhibition.no_item");
        return;
    }
    if (f.isSet()) {
        msg(sender, "user.exhibition.already_set");
        return;
    }
    if (p.getGameMode() == GameMode.SURVIVAL) {
        p.getWorld().dropItem(p.getEyeLocation(), f.getItemFrame().getItem());
    }
    f.set(p);
}
 
Example #8
Source File: QuestItemHandler.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onItemFrameClick(final PlayerInteractEntityEvent event) {
    if (event.getPlayer().getGameMode() == GameMode.CREATIVE) {
        return;
    }
    // this prevents the journal from being placed inside of item frame
    if (event.getRightClicked() instanceof ItemFrame) {
        ItemStack item = null;
        item = (event.getHand() == EquipmentSlot.HAND) ? event.getPlayer().getInventory().getItemInMainHand()
                : event.getPlayer().getInventory().getItemInOffHand();

        final String playerID = PlayerConverter.getID(event.getPlayer());
        if (Journal.isJournal(playerID, item) || Utils.isQuestItem(item)) {
            event.setCancelled(true);
        }
    }
}
 
Example #9
Source File: GameModeChangeProcessTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldNotBypassBecauseBypassDisabled() {
    // given
    Player player = mock(Player.class);

    Group group = mockGroup("world");

    GameMode newGameMode = GameMode.CREATIVE;
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(true);

    // when
    process.processGameModeChange(player, newGameMode, group);

    // then
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example #10
Source File: InventoryChangeProcessTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldNotBypassBecauseBypassDisabled() {
    // given
    Player player = mock(Player.class);
    given(player.getName()).willReturn("Bob");
    given(player.getGameMode()).willReturn(GameMode.SURVIVAL);
    Group from = mockGroup("test_group", GameMode.SURVIVAL, true);
    Group to = mockGroup("other_group", GameMode.SURVIVAL, true);
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(true);

    // when
    process.processWorldChange(player, from, to);

    // then
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example #11
Source File: InventoryChangeProcessTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldChangeInventoryEvenIfGroupsNotConfigured() {
    // given
    Player player = mock(Player.class);
    given(player.getName()).willReturn("Bob");
    given(player.getGameMode()).willReturn(GameMode.SURVIVAL);
    Group from = mockGroup("test_group", GameMode.SURVIVAL, false);
    Group to = mockGroup("other_group", GameMode.SURVIVAL, false);
    given(settings.getProperty(PwiProperties.SHARE_IF_UNCONFIGURED)).willReturn(false);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(false);
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(permissionManager.hasPermission(player, PlayerPermission.BYPASS_WORLDS)).willReturn(false);

    // when
    process.processWorldChange(player, from, to);

    // then
    verify(permissionManager).hasPermission(player, PlayerPermission.BYPASS_WORLDS);
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example #12
Source File: GroupManagerTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void addGroupWithUppercaseNameLowercaseGet() {
    // given
    groupManager.clearGroups(); // Clear any existing groups
    String name = "TeSt";
    Set<String> worlds = new HashSet<>();
    worlds.add(name);
    GameMode gameMode = GameMode.SURVIVAL;

    // when
    groupManager.addGroup(name, worlds, gameMode);

    // then
    Group expected = mockGroup(name, worlds, gameMode);
    Group actual = groupManager.getGroup("test");

    assertThat(actual.getName(), equalTo(expected.getName()));
    assertThat(actual.getWorlds(), equalTo(expected.getWorlds()));
    assertThat(actual.getGameMode(), equalTo(expected.getGameMode()));
}
 
Example #13
Source File: SpectatorFeature.java    From VoxelGamesLibv2 with MIT License 6 votes vote down vote up
@GameEvent(filterPlayers = false, filterSpectators = true)
public void onJoin(GameJoinEvent event) {
    event.getUser().getPlayer().setGameMode(GameMode.SPECTATOR);

    // spawn
    Optional<SpawnFeature> spawnFeature = getPhase().getOptionalFeature(SpawnFeature.class);
    if (spawns.size() > 0) {
        Location location = spawns.get(ThreadLocalRandom.current().nextInt(spawns.size()))
                .toLocation(map.getLoadedName(getPhase().getGame().getUuid())).add(0.5, 0, 0.5);
        event.getUser().getPlayer().teleportAsync(location);
    } else if (spawnFeature.isPresent()) {
        event.getUser().getPlayer().teleportAsync(spawnFeature.get().getSpawn(event.getUser().getUuid()));
    } else if (event.getGame().getPlayers().size() > 0) {
        event.getUser().getPlayer().teleportAsync(event.getGame().getPlayers().get(0).getPlayer().getLocation());
    } else {
        log.warning("Could not figure out a spectator spawn point");
    }
}
 
Example #14
Source File: KitLoading.java    From AnnihilationPro with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void ClassChanger(final PlayerPortalEvent event)
{
	if(Game.isGameRunning() && event.getPlayer().getGameMode() != GameMode.CREATIVE)
	{
		AnniPlayer p = AnniPlayer.getPlayer(event.getPlayer().getUniqueId());
		if(p != null)
		{
			event.setCancelled(true);
			if(p.getTeam() != null)
			{
				final Player pl = event.getPlayer();
				pl.teleport(p.getTeam().getRandomSpawn());
				Bukkit.getScheduler().runTaskLater(AnnihilationMain.getInstance(), new Runnable(){

					@Override
					public void run()
					{
						openKitMap(pl);
					}}, 40);
			}
		}
	}
}
 
Example #15
Source File: InventoryChangeProcessTest.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldNotBypassBecauseBypassDisabled() {
    // given
    Player player = mock(Player.class);
    given(player.getName()).willReturn("Bob");
    given(player.getGameMode()).willReturn(GameMode.SURVIVAL);
    Group from = mockGroup("test_group", GameMode.SURVIVAL, true);
    Group to = mockGroup("other_group", GameMode.SURVIVAL, true);
    given(settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)).willReturn(true);
    given(settings.getProperty(PwiProperties.DISABLE_BYPASS)).willReturn(true);

    // when
    process.processWorldChange(player, from, to);

    // then
    verify(bukkitService).callEvent(any(InventoryLoadEvent.class));
}
 
Example #16
Source File: Grenade.java    From QualityArmory with GNU General Public License v3.0 6 votes vote down vote up
public void removeGrenade(Player player) {
	if (player.getGameMode() != GameMode.CREATIVE) {
		int slot = -56;
		ItemStack stack = null;
		for (int i = 0; i < player.getInventory().getContents().length; i++) {
			if ((stack = player.getInventory().getItem(i)) != null && MaterialStorage.getMS(stack) == getItemData()) {
				slot = i;
				break;
			}
		}
		if (slot >= -1) {
			if (stack.getAmount() > 1) {
				stack.setAmount(stack.getAmount() - 1);
			} else {
				stack = null;
			}
			player.getInventory().setItem(slot, stack);
		}
	}
}
 
Example #17
Source File: ExprGameMode.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public Class<?>[] acceptChange(final ChangeMode mode) {
	if (mode == ChangeMode.SET || mode == ChangeMode.RESET)
		return CollectionUtils.array(GameMode.class);
	return null;
}
 
Example #18
Source File: SilentOpenChest.java    From SuperVanish with Mozilla Public License 2.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onGameModeChange(PlayerGameModeChangeEvent e) {
    Player p = e.getPlayer();
    if (playerStateInfoMap.containsKey(p) && e.getNewGameMode() != GameMode.SPECTATOR) {
        // Don't let low-priority event listeners cancel the gamemode change
        if (e.isCancelled()) e.setCancelled(false);
    }
}
 
Example #19
Source File: PlayerGameModeChangeListenerTest.java    From PerWorldInventory with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldDoNothingEventCancelled() {
    // given
    PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(mock(Player.class), GameMode.CREATIVE);
    event.setCancelled(true);

    // when
    listener.onPlayerGameModeChange(event);

    // then
    verifyZeroInteractions(groupManager);
    verifyZeroInteractions(playerManager);
    verifyZeroInteractions(bukkitService);
}
 
Example #20
Source File: DEditPlayer.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
public DEditPlayer(DungeonsXL plugin, Player player, EditWorld world) {
    super(plugin, player, world);
    editWorld = world;

    // Set gamemode a few ticks later to avoid incompatibilities with plugins that force a gamemode
    new BukkitRunnable() {
        @Override
        public void run() {
            player.setGameMode(GameMode.CREATIVE);
        }
    }.runTaskLater(plugin, 10L);

    clearPlayerData();

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

    // Permission bridge
    if (plugin.getPermissionProvider() != null) {
        for (String permission : plugin.getMainConfig().getEditPermissions()) {
            plugin.getPermissionProvider().playerAddTransient(world.getName(), player, permission);
        }
    }
}
 
Example #21
Source File: Tutorial.java    From ServerTutorial with MIT License 5 votes vote down vote up
public Tutorial(String name, Map<Integer, TutorialView> tutorialViews, ViewType viewType, int timeLength, String
        endMessage, String command, CommandType commandType, GameMode gamemode) {
    this.name = name;
    this.tutorialViews = tutorialViews;
    this.viewType = viewType;
    this.timeLength = timeLength;
    this.endMessage = endMessage;
    this.command = command;
    this.commandType = commandType;
    this.gamemode = gamemode;
}
 
Example #22
Source File: PlayerInventory.java    From CS-CoreLib with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static void consumeItemInHand(Player p) {
	if (p.getGameMode() != GameMode.CREATIVE) {
 		ItemStack item = p.getItemInHand().clone();
 		item.setAmount(item.getAmount() - 1);
  		p.setItemInHand(item.getAmount() > 0 ? item: null);
	}
}
 
Example #23
Source File: GameMap.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void blockPlaceCheck(BlockPlaceEvent event)
{
	if(event.getPlayer().getGameMode() != GameMode.CREATIVE)
	{
		Block b = event.getBlock();
		UnplaceableBlock block = this.unplaceableBlocks.get(b.getType());
		if(block != null)
		{
			if(block.isData((byte)-1) || block.isData(b.getData()))
				event.setCancelled(true);
		}
	}
}
 
Example #24
Source File: BlockBreakReach.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void check(BlockDigEvent e) {
    Player p = e.getPlayer();
    HawkPlayer pp = e.getHawkPlayer();

    Location bLoc = e.getBlock().getLocation();
    Vector min = bLoc.toVector();
    Vector max = bLoc.toVector().add(new Vector(1, 1, 1));
    AABB targetAABB = new AABB(min, max);

    Vector ppPos;
    if(pp.isInVehicle()) {
        ppPos = hawk.getLagCompensator().getHistoryLocation(ServerUtils.getPing(p), p).toVector();
        ppPos.setY(ppPos.getY() + p.getEyeHeight());
    }
    else {
        ppPos = pp.getHeadPosition();
    }

    double maxReach = pp.getPlayer().getGameMode() == GameMode.CREATIVE ? MAX_REACH_CREATIVE : MAX_REACH;
    double dist = targetAABB.distanceToPosition(ppPos);

    if (dist > maxReach) {
        punish(pp, 1, true, e, new Placeholder("distance", MathPlus.round(dist, 2)));
    } else {
        reward(pp);
    }
}
 
Example #25
Source File: BlockBreakSpeedSurvival.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
private void checkEvent(BlockDigEvent e) {
    Player p = e.getPlayer();
    HawkPlayer pp = e.getHawkPlayer();
    if(p.getGameMode() == GameMode.CREATIVE)
        return;

    if (e.getDigAction() == BlockDigEvent.DigAction.START) {
        targetBlockMap.put(p.getUniqueId(), e.getBlock());
        blockDamageCumulativeMap.put(p.getUniqueId(), 0F);
        interactTick.put(p.getUniqueId(), pp.getCurrentTick());
        tickDig(pp);
        return;
    }

    if (e.getDigAction() == BlockDigEvent.DigAction.COMPLETE) {
        float totalDamage = blockDamageCumulativeMap.getOrDefault(p.getUniqueId(), 0F);

        if(totalDamage < 1 || (PREVENT_SAME_TICK && pp.getCurrentTick() == interactTick.getOrDefault(p.getUniqueId(), 0L))) {
            double speedFactor = 1 / totalDamage;
            double vl = Math.min((speedFactor - 1) * 10, 10);
            Block b = e.getBlock();
            punish(pp, vl, true, e, new Placeholder("block", b.getType()), new Placeholder("speed", MathPlus.round(speedFactor, 2) + "x"));
            e.resync();
        }
        else {
            reward(pp);
        }

        targetBlockMap.put(p.getUniqueId(), null);
        blockDamageCumulativeMap.put(p.getUniqueId(), 0F);
    }
}
 
Example #26
Source File: DoubleJumpFeature.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@GameEvent
public void e(@Nonnull PlayerToggleFlightEvent event) {
    final Player player = event.getPlayer();
    if (player.getGameMode() != GameMode.CREATIVE) {
        if (!disabled.contains(player.getUniqueId())) {
            event.setCancelled(true);
            player.setAllowFlight(false);
            player.setFlying(false);
            player.setVelocity(player.getLocation().getDirection().multiply(1.6).setY(1));
            player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDER_DRAGON_FLAP, 4, 1);
        }
    }
}
 
Example #27
Source File: EntityInteractReach.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void check(InteractEntityEvent e) {
    Entity victimEntity = e.getEntity();
    if (!(victimEntity instanceof Player) && !CHECK_OTHER_ENTITIES)
        return;
    int ping = ServerUtils.getPing(e.getPlayer());
    if (PING_LIMIT > -1 && ping > PING_LIMIT)
        return;
    Player p = e.getPlayer();
    HawkPlayer att = e.getHawkPlayer();

    Location victimLocation;
    if (LAG_COMPENSATION)
        victimLocation = hawk.getLagCompensator().getHistoryLocation(ping, victimEntity);
    else
        victimLocation = victimEntity.getLocation();

    AABB victimAABB = WrappedEntity.getWrappedEntity(victimEntity).getHitbox(victimLocation.toVector());

    Vector attackerPos;
    if(att.isInVehicle()) {
        attackerPos = hawk.getLagCompensator().getHistoryLocation(ServerUtils.getPing(p), p).toVector();
        attackerPos.setY(attackerPos.getY() + p.getEyeHeight());
    }
    else {
        attackerPos = att.getHeadPosition();
    }

    double maxReach = att.getPlayer().getGameMode() == GameMode.CREATIVE ? MAX_REACH_CREATIVE : MAX_REACH;
    double dist = victimAABB.distanceToPosition(attackerPos);

    if (dist > maxReach) {
        punish(att, 1, true, e, new Placeholder("distance", MathPlus.round(dist, 2)));
    } else {
        reward(att);
    }
}
 
Example #28
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 #29
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 #30
Source File: Alive.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public void die(@Nullable ParticipantState killer) {
    player.setDead(true);

    // Setting a player's gamemode resets their fall distance.
    // We need the fall distance for the death message.
    // We set the fall distance back to 0 when we refresh the player.
    float fallDistance = bukkit.getFallDistance();
    bukkit.setGameMode(GameMode.CREATIVE);
    bukkit.setFallDistance(fallDistance);

    playDeathEffect(killer);

    transition(new Dead(player));
}