Java Code Examples for org.bukkit.GameMode

The following examples show how to use org.bukkit.GameMode. These examples are extracted from open source projects. 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
@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 2
@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 3
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 Project: PerWorldInventory   Source File: FlatFile.java    License: 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 5
Source Project: HubBasics   Source File: DoubleJump.java    License: 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 Project: Slimefun4   Source File: Splint.java    License: 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 Project: NyaaUtils   Source File: ExhibitionCommands.java    License: 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 Project: BetonQuest   Source File: QuestItemHandler.java    License: 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 Project: VoxelGamesLibv2   Source File: SpectatorFeature.java    License: 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 10
@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 11
@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 12
@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 13
@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 14
Source Project: AnnihilationPro   Source File: KitLoading.java    License: 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 Project: QualityArmory   Source File: Grenade.java    License: 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 16
Source Project: QualityArmory   Source File: QualityArmory.java    License: 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 17
Source Project: AnnihilationPro   Source File: GameMap.java    License: 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 18
Source Project: GriefDefender   Source File: CommonEntityEventHandler.java    License: 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 19
Source Project: AnnihilationPro   Source File: Areas.java    License: MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST,ignoreCancelled = true)
public void checkBreaks(BlockPlaceEvent e)
{
	if(e.getPlayer().getGameMode() != GameMode.CREATIVE)
	{
		Area a = this.getArea(new Loc(e.getBlock().getLocation(),false));
		if(a != null)
		{
			e.setCancelled(true);
		}
	}
}
 
Example 20
Source Project: ServerTutorial   Source File: CreateTutorial.java    License: MIT License 5 votes vote down vote up
@Override
public Prompt acceptInput(ConversationContext context, String input) {
    try {
        GameMode gm = GameMode.valueOf(input.toUpperCase());
        context.setSessionData("gamemode", gm.toString().toUpperCase());
        return new EndCommandTypeMessage();
    } catch (IllegalArgumentException e) {
        return new GamemodeMessage();
    }
}
 
Example 21
Source Project: Slimefun4   Source File: Research.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the {@link Player} can unlock this {@link Research}.
 * 
 * @param p
 *            The {@link Player} to check
 * @return Whether that {@link Player} can unlock this {@link Research}
 */
public boolean canUnlock(Player p) {
    if (!isEnabled()) {
        return true;
    }

    boolean creativeResearch = p.getGameMode() == GameMode.CREATIVE && SlimefunPlugin.getRegistry().isFreeCreativeResearchingEnabled();
    return creativeResearch || p.getLevel() >= cost;
}
 
Example 22
Source Project: AnnihilationPro   Source File: Signs.java    License: MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOW,ignoreCancelled = true)
public void signBreakCheck(BlockBreakEvent event)
{
	if(event.getBlock() != null && event.getPlayer().getGameMode() != GameMode.CREATIVE)
	{
		if(event.getBlock().getType() == Material.WALL_SIGN || event.getBlock().getType() == Material.SIGN_POST)
		{
			MapKey key = MapKey.getKey(event.getBlock().getLocation());
			if(this.signs.containsKey(key))
				event.setCancelled(true);
		}
	}
}
 
Example 23
Source Project: Transport-Pipes   Source File: DuctListener.java    License: MIT License 5 votes vote down vote up
private void decreaseHandItem(Player p, EquipmentSlot hand) {
    if (p.getGameMode() == GameMode.CREATIVE) {
        return;
    }
    ItemStack item = hand == EquipmentSlot.HAND ? p.getInventory().getItemInMainHand() : p.getInventory().getItemInOffHand();
    if (item != null) {
        if (item.getAmount() <= 1) {
            item = null;
        } else {
            item.setAmount(item.getAmount() - 1);
        }
        if (hand == EquipmentSlot.HAND) p.getInventory().setItemInMainHand(item);
        else p.getInventory().setItemInOffHand(item);
    }
}
 
Example 24
Source Project: Slimefun4   Source File: StormStaff.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void useItem(Player p, ItemStack item, Location loc) {
    loc.getWorld().strikeLightning(loc);

    if (p.getInventory().getItemInMainHand().getType() == Material.SHEARS) {
        return;
    }

    if (p.getGameMode() != GameMode.CREATIVE) {
        FoodLevelChangeEvent event = new FoodLevelChangeEvent(p, p.getFoodLevel() - 4);
        Bukkit.getPluginManager().callEvent(event);

        if (!event.isCancelled()) {
            p.setFoodLevel(event.getFoodLevel());
        }
    }

    ItemMeta meta = item.getItemMeta();
    int usesLeft = meta.getPersistentDataContainer().getOrDefault(usageKey, PersistentDataType.INTEGER, MAX_USES);

    if (usesLeft == 1) {
        p.playSound(p.getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1);
        item.setAmount(0);
    }
    else {
        usesLeft--;
        meta.getPersistentDataContainer().set(usageKey, PersistentDataType.INTEGER, usesLeft);

        List<String> lore = meta.getLore();
        lore.set(4, ChatColors.color("&e" + usesLeft + ' ' + (usesLeft > 1 ? "Uses" : "Use") + " &7left"));
        meta.setLore(lore);

        item.setItemMeta(meta);
    }
}
 
Example 25
Source Project: ShopChest   Source File: ClickType.java    License: MIT License 5 votes vote down vote up
public SelectClickType(GameMode gameMode, int amount, double buyPrice, double sellPrice, ShopType shopType) {
    super(EnumClickType.SELECT_ITEM);
    this.gameMode = gameMode;
    this.amount = amount;
    this.sellPrice = sellPrice;
    this.buyPrice = buyPrice;
    this.shopType = shopType;
}
 
Example 26
public InventoryLoadEvent(Player player, DeserializeCause cause, GameMode newGameMode, Group group) {
    this.player = player;
    this.cause = cause;
    this.newGameMode = newGameMode;
    this.group = group;
    this.cancelled = false;
}
 
Example 27
Source Project: PGM   Source File: GamemodeTool.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private GameMode getOppositeMode(GameMode mode) {
  switch (mode) {
    case CREATIVE:
      return GameMode.SPECTATOR;
    case SPECTATOR:
      return GameMode.CREATIVE;
    default:
      return mode;
  }
}
 
Example 28
Source Project: WorldGuardExtraFlagsPlugin   Source File: EssentialsListener.java    License: MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerChangedWorldEvent(PlayerChangedWorldEvent event)
{
	Player player = event.getPlayer();
	
	if (player.getGameMode() != GameMode.CREATIVE && !this.essentialsPlugin.getUser(player).isAuthorized("essentials.fly"))
	{
		//Essentials now turns off flight, fuck him
		Boolean value = this.plugin.getWorldGuardCommunicator().getSessionManager().get(player).getHandler(FlyFlagHandler.class).getCurrentValue();
		if (value != null)
		{
			player.setAllowFlight(value);
		}
	}
}
 
Example 29
Source Project: ServerTutorial   Source File: CreateTutorial.java    License: MIT License 5 votes vote down vote up
@Override
public String getPromptText(ConversationContext conversationContext) {
    String s = "&8>&7Choose a gamemode for the tutorial (it will be restored after the tutorial)\n";

    for (GameMode gm : GameMode.values()) {
        s += "&8>&6" + gm.toString().toUpperCase() + "\n";
    }

    s += "&8>&7>&6> &7Type a gamemode to continue:";
    return TutorialUtils.color(s);
}
 
Example 30
private void openBackpack(MarriagePlayer opener, MarriagePlayer partner)
{
	Player sender = opener.getPlayerOnline();
	if(sender.getGameMode() == GameMode.SURVIVAL || sender.hasPermission(Permissions.BYPASS_BACKPACK_GAME_MODE)) //TODO use minepacks settings
	{
		Player partnerPlayer = partner.getPlayerOnline();
		if(partnerPlayer == null || !partnerPlayer.isOnline())
		{
			((MarriageMaster) getMarriagePlugin()).messagePartnerOffline.send(sender);
		}
		else if(partner.isSharingBackpack())
		{
			if(getMarriagePlugin().isInRangeSquared(sender, partnerPlayer, range))
			{
				((MarriageMaster) getMarriagePlugin()).getBackpacksIntegration().openBackpack(sender, partnerPlayer, true);
				messageOpened.send(partnerPlayer);
			}
			else
			{
				((MarriageMaster) getMarriagePlugin()).messagePartnerNotInRange.send(sender);
			}
		}
		else
		{
			messageShareDenied.send(sender);
		}
	}
	else
	{
		messageOnlyInSurvival.send(sender);
	}
}