Java Code Examples for net.minecraft.entity.player.EntityPlayerMP

The following examples show how to use net.minecraft.entity.player.EntityPlayerMP. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: malmo   Source File: ObservationFromServer.java    License: MIT License 6 votes vote down vote up
/** IMPORTANT: Call this from the onMessage method in the subclass. */
public IMessage processMessage(ObservationRequestMessage message, MessageContext ctx)
{
    IThreadListener mainThread = (WorldServer) ctx.getServerHandler().playerEntity.world;
    final EntityPlayerMP player = ctx.getServerHandler().playerEntity;
    final ObservationRequestMessage mess = message;
    mainThread.addScheduledTask(new Runnable()
    {
        @Override
        public void run()
        {
            JsonObject json = new JsonObject();
            buildJson(json, player, mess);
            // Send this message back again now we've filled in the json stats.
            Map<String, String> returnData = new HashMap<String, String>();
            returnData.put("json", json.toString());
            mess.addReturnData(returnData);
            MalmoMod.network.sendTo(new MalmoMod.MalmoMessage(MalmoMessageType.SERVER_OBSERVATIONSREADY, mess.id, returnData), player);
        }
    });
    return null; // no response in this case
}
 
Example 2
Source Project: Thermos   Source File: CraftPlayer.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void setExtraData(net.minecraft.nbt.NBTTagCompound nbttagcompound) {
    if (!nbttagcompound.hasKey("bukkit")) {
        nbttagcompound.setTag("bukkit", new net.minecraft.nbt.NBTTagCompound());
    }

    net.minecraft.nbt.NBTTagCompound data = nbttagcompound.getCompoundTag("bukkit");
    net.minecraft.entity.player.EntityPlayerMP handle = getHandle();
    data.setInteger("newExp", handle.newExp);
    data.setInteger("newTotalExp", handle.newTotalExp);
    data.setInteger("newLevel", handle.newLevel);
    data.setInteger("expToDrop", handle.expToDrop);
    data.setBoolean("keepLevel", handle.keepLevel);
    data.setLong("firstPlayed", getFirstPlayed());
    data.setLong("lastPlayed", System.currentTimeMillis());
    data.setString("lastKnownName", handle.getCommandSenderName());
}
 
Example 3
Source Project: Valkyrien-Skies   Source File: TileEntityShipHelm.java    License: Apache License 2.0 6 votes vote down vote up
@Override
void processControlMessage(PilotControlsMessage message, EntityPlayerMP sender) {
    double rotationDelta = 0;
    if (message.airshipLeft_KeyDown) {
        rotationDelta -= 12.5D;
    }
    if (message.airshipRight_KeyDown) {
        rotationDelta += 12.5D;
    }
    IBlockState blockState = this.getWorld().getBlockState(getPos());
    if (blockState.getBlock() instanceof BlockShipHelm) {
        EnumFacing facing = blockState.getValue(BlockShipHelm.FACING);
        if (this.isPlayerInFront(sender, facing)) {
            wheelRotation += rotationDelta;
        } else {
            wheelRotation -= rotationDelta;
        }
    }
    double max_rotation = 720D;
    wheelRotation = Math.min(Math.max(wheelRotation, -max_rotation), max_rotation);
}
 
Example 4
/**
 * Called when the block is right clicked by a player.
 */
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
    if (world.isRemote || !(playerIn instanceof EntityPlayerMP))
    {
        return true;
    }
    else
    {
        EntityPlayerMP entityplayermp = (EntityPlayerMP)playerIn;

        if (entityplayermp.connection.getNetworkManager().isChannelOpen() && entityplayermp.world == world && !entityplayermp.isPlayerSleeping())
        {
            
         if (playerIn.isRiding())
         {
         	playerIn.dismountRidingEntity();
         }

         playerIn.setPositionAndUpdate(world.rand.nextDouble()*2000000D-1000000D, 2550D, world.rand.nextDouble()*2000000D-1000000D);
         
        }
        return true;
    }
}
 
Example 5
Source Project: Artifacts   Source File: ComponentObscurity.java    License: MIT License 6 votes vote down vote up
@Override
	public boolean hitEntity(ItemStack itemStack, EntityLivingBase entityVictim, EntityLivingBase entityAttacker) {
		EntityPlayerMP player = UtilsForComponents.getPlayerFromUsername(entityAttacker.getCommandSenderName());
		
		if(player != null) {
			player.addPotionEffect(new PotionEffect(14, 600, 0));
			
			PacketBuffer out = new PacketBuffer(Unpooled.buffer());
			
			out.writeInt(PacketHandlerClient.OBSCURITY);
			SToCMessage packet = new SToCMessage(out);
			DragonArtifacts.artifactNetworkWrapper.sendTo(packet, player);
			
			//System.out.println("Cloaking player.");
			itemStack.damageItem(1, player);
//			UtilsForComponents.sendItemDamagePacket(entityAttacker, entityAttacker.inventory.currentItem, 1); //itemStack.damageItem(1, player);
//			itemStack.stackTagCompound.setInteger("onItemRightClickDelay", 200);
		}
		return false;
	}
 
Example 6
Source Project: malmo   Source File: ServerStateMachine.java    License: MIT License 6 votes vote down vote up
private void resetPlayerGameTypes()
{
    // Go through and set all the players to their correct game type:
    for (Map.Entry<String, String> entry : this.usernameToAgentnameMap.entrySet())
    {
        AgentSection as = getAgentSectionFromAgentName(entry.getValue());
        EntityPlayerMP player = getPlayerFromUsername(entry.getKey());
        if (as != null && player != null)
        {
            player.setGameType(GameType.getByName(as.getMode().name().toLowerCase()));
            // Also make sure we haven't accidentally left the player flying:
            player.capabilities.isFlying = false;
            player.sendPlayerAbilities();
        }
    }
}
 
Example 7
Source Project: NotEnoughItems   Source File: NEIServerUtils.java    License: MIT License 6 votes vote down vote up
public static void givePlayerItem(EntityPlayerMP player, ItemStack stack, boolean infinite, boolean doGive) {
    if (stack.getItem() == null) {
        player.sendMessage(setColour(new TextComponentTranslation("nei.chat.give.noitem"), TextFormatting.WHITE));
        return;
    }

    int given = stack.getCount();
    if (doGive) {
        if (infinite) {
            player.inventory.addItemStackToInventory(stack);
        } else {
            given -= InventoryUtils.insertItem(player.inventory, stack, false);
        }
    }

    sendNotice(player, new TextComponentTranslation("commands.give.success", stack.getTextComponent(), infinite ? "\u221E" : Integer.toString(given), player.getName()), "notify-item");
    player.openContainer.detectAndSendChanges();
}
 
Example 8
@Override
public IMessage onMessage(final MessageRequestPlayerCivilizationSync message, MessageContext ctx) {
	if (ctx.side != Side.SERVER) {
		return null;
	}

	final EntityPlayerMP player = ctx.getServerHandler().player;

	if (player == null) {
		return null;
	}

	final WorldServer worldServer = player.getServerWorld();

	worldServer.addScheduledTask(new Runnable() {
		@Override
		public void run() {
			PlayerCivilizationCapabilityImpl.get(player).syncClient();
		}
	});

	return null;
}
 
Example 9
@Override
public void handle(@NotNull MessageContext ctx) {
	EntityPlayerMP player = ctx.getServerHandler().player;

	ItemStack stack = player.getHeldItemMainhand();

	if (stack.getItem() instanceof IPearlStorageHolder) {
		IPearlStorageHolder holder = (IPearlStorageHolder) stack.getItem();
		int originalPearlCount = holder.getPearlCount(stack);

		ItemStack pearl = holder.removePearl(stack, index, true);
		player.addItemStackToInventory(pearl);

		int newPearlCount = holder.getPearlCount(stack);

		PacketHandler.NETWORK.sendTo(new PacketUpdatePearlGUI(originalPearlCount, newPearlCount, index, null, stack.getTagCompound()), player);
	}
}
 
Example 10
Source Project: bartworks   Source File: GT_TileEntity_BioVat.java    License: MIT License 6 votes vote down vote up
private void check_Chunk() {
    World aWorld = this.getBaseMetaTileEntity().getWorld();
    if (!aWorld.isRemote) {

        for (Object tObject : aWorld.playerEntities) {
            if (!(tObject instanceof EntityPlayerMP)) {
                break;
            }
            EntityPlayerMP tPlayer = (EntityPlayerMP) tObject;
            Chunk tChunk = aWorld.getChunkFromBlockCoords(this.getBaseMetaTileEntity().getXCoord(), this.getBaseMetaTileEntity().getZCoord());
            if (tPlayer.getServerForPlayer().getPlayerManager().isPlayerWatchingChunk(tPlayer, tChunk.xPosition, tChunk.zPosition)) {
                if (!this.playerMPHashSet.contains(tPlayer)) {
                    this.playerMPHashSet.add(tPlayer);
                    this.sendAllRequiredRendererPackets();
                }
            } else {
                this.playerMPHashSet.remove(tPlayer);
            }

        }
    }
}
 
Example 11
Source Project: ToroQuest   Source File: MessageQuestUpdate.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public IMessage onMessage(final MessageQuestUpdate message, MessageContext ctx) {
	if (ctx.side != Side.SERVER) {
		return null;
	}

	final EntityPlayerMP player = ctx.getServerHandler().player;

	if (player == null) {
		return null;
	}

	final WorldServer worldServer = player.getServerWorld();

	worldServer.addScheduledTask(new Runnable() {
		@Override
		public void run() {
			new Worker(message.action).work(message, player);
		}
	});

	return null;
}
 
Example 12
/**
 * Breaks the block as a player, and thus drops the item(s) from it
 */
public static void breakBlockAsPlayer(World world, BlockPos pos, EntityPlayerMP playerMP, ItemStack toolStack)
{
    PlayerInteractionManager manager = playerMP.interactionManager;
    int exp = ForgeHooks.onBlockBreakEvent(world, manager.getGameType(), playerMP, pos);

    if (exp != -1)
    {
        IBlockState stateExisting = world.getBlockState(pos);
        Block blockExisting = stateExisting.getBlock();

        blockExisting.onBlockHarvested(world, pos, stateExisting, playerMP);
        boolean harvest = blockExisting.removedByPlayer(stateExisting, world, pos, playerMP, true);

        if (harvest)
        {
            blockExisting.onPlayerDestroy(world, pos, stateExisting);
            blockExisting.harvestBlock(world, playerMP, pos, stateExisting, world.getTileEntity(pos), toolStack);
        }
    }
}
 
Example 13
public static boolean targetOutsideOfPlayerRange(ItemStack stack, EntityPlayer player)
{
    TargetData target = TargetData.getTargetFromSelectedModule(stack, ModuleType.TYPE_LINKCRYSTAL);

    if (target == null)
    {
        return true;
    }

    // We allow a max range of 64 blocks, to hopefully be on the safer side
    //return target.dimension != player.dimension || player.getDistanceSq(target.posX, target.posY, target.posZ) >= 4096.0d;

    WorldServer world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(target.dimension);

    if ((player instanceof EntityPlayerMP) == false || world == null ||
         world.getPlayerChunkMap().isPlayerWatchingChunk((EntityPlayerMP) player, target.pos.getX() >> 4, target.pos.getZ() >> 4) == false)
    {
        return true;
    }

    return false;
}
 
Example 14
@Override
public void execute(@NotNull MinecraftServer server, @NotNull ICommandSender sender, @NotNull String[] args) {
	Entity entity = sender.getCommandSenderEntity();
	if (entity instanceof EntityPlayerMP) {
		ItemStack item = new ItemStack(ModItems.PEARL_NACRE);


		List<ItemStack> recipe = new ArrayList<>();
		recipe.add(ModuleRegistry.INSTANCE.getModules(ModuleType.SHAPE).get(RandUtil.nextInt(ModuleRegistry.INSTANCE.getModules(ModuleType.SHAPE).size() - 1)).getItemStack());
		recipe.add(ModuleRegistry.INSTANCE.getModules(ModuleType.EFFECT).get(RandUtil.nextInt(ModuleRegistry.INSTANCE.getModules(ModuleType.EFFECT).size() - 1)).getItemStack());
		recipe.add(new ItemStack(ModItems.DEVIL_DUST));

		SpellBuilder builder = new SpellBuilder(recipe, 1);

		NBTTagList list = new NBTTagList();
		for (SpellRing spellRing : builder.getSpell())
			list.appendTag(spellRing.serializeNBT());
		NBTHelper.setList(item, NBTConstants.NBT.SPELL, list);
		NBTHelper.setBoolean(item, "infused", true);

		((EntityPlayerMP) entity).addItemStackToInventory(item);
		((EntityPlayerMP) entity).openContainer.detectAndSendChanges();
	} else notifyCommandListener(sender, this, "wizardry.command.notplayer");
}
 
Example 15
Source Project: Kettle   Source File: CraftEventFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static BlockBreakEvent callBlockBreakEvent(net.minecraft.world.World world, BlockPos pos, IBlockState state, EntityPlayerMP player) {
    Block bBlock = world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ());
    BlockBreakEvent bbe = new BlockBreakEvent(bBlock, player.getBukkitEntity());
    EntityPlayerMP playermp = player;
    net.minecraft.block.Block block = state.getBlock();
    if (!(playermp instanceof FakePlayer)) {
        boolean isSwordNoBreak = playermp.interactionManager.getGameType().isCreative() && !playermp.getHeldItemMainhand().isEmpty() && playermp.getHeldItemMainhand().getItem() instanceof ItemSword;
        if (!isSwordNoBreak) {
            int exp = 0;
            if (!(block == null || !player.canHarvestBlock(block.getDefaultState()) || block.canSilkHarvest(world, pos, block.getBlockState().getBaseState(), player) && EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, player.getHeldItemMainhand()) > 0)) {
                int bonusLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, player.getHeldItemMainhand());
                exp = block.getExpDrop(state, world, pos, bonusLevel);
            }
            bbe.setExpToDrop(exp);
        } else {
            bbe.setCancelled(true);
        }
    }

    world.getServer().getPluginManager().callEvent(bbe);
    return bbe;
}
 
Example 16
Source Project: OpenPeripheral-Addons   Source File: TerminalManagerServer.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGH)
public void onServerChatEvent(ServerChatEvent event) {
	final EntityPlayerMP player = event.player;
	final Optional<Long> guid = TerminalIdAccess.instance.getIdFrom(player);
	if (guid.isPresent()) {
		if (event.message.startsWith("$$")) {
			sendChatEvent(EVENT_CHAT_COMMAND, player, guid.get(), event.message.substring(2).trim());
			event.setCanceled(true);
		} else if (Config.listenToAllChat) {
			sendChatEvent(EVENT_CHAT_MESSAGE, player, guid.get(), event.message);
		}

	}
}
 
Example 17
Source Project: AgriCraft   Source File: PlayerConnectToServerHandler.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent
@SuppressWarnings("unused")
public void onConnect(PlayerEvent.PlayerLoggedInEvent event) {
    EntityPlayerMP player = (EntityPlayerMP) event.player;
    syncSoils(player);
    syncPlants(player);
    syncMutations(player);
}
 
Example 18
Source Project: CodeChickenCore   Source File: ContainerExtended.java    License: MIT License 5 votes vote down vote up
@Override
public void removeCraftingFromCrafters(ICrafting icrafting) {
    if (icrafting instanceof EntityPlayerMP)
        playerCrafters.remove(icrafting);
    else
        super.removeCraftingFromCrafters(icrafting);
}
 
Example 19
@Override
public void setPosition(Vector3D position) {
	if (wrapper instanceof EntityPlayerMP) {
		((EntityPlayerMP) wrapper).connection.setPlayerLocation(position.getX(), position.getY(), position.getZ(), wrapper.rotationYaw, wrapper.rotationPitch);
	} else {
		wrapper.setPosition(position.getX(), position.getY(), position.getZ());
	}
}
 
Example 20
protected void syncAllSlots(EntityPlayerMP player)
{
    for (int slot = 0; slot < this.inventorySlots.size(); slot++)
    {
        ItemStack stack = this.inventorySlots.get(slot).getStack();
        this.inventoryItemStacks.set(slot, stack.isEmpty() ? ItemStack.EMPTY : stack.copy());
        PacketHandler.INSTANCE.sendTo(new MessageSyncSlot(this.windowId, slot, stack), player);
    }
}
 
Example 21
@Override
public boolean interact(EntityPlayer entityplayer)
{

    if (super.interact(entityplayer)) { return false; }
    ItemStack itemstack = entityplayer.inventory.getCurrentItem();
    if ((itemstack != null) && !getIsTamed() && getHasEaten() && (itemstack.itemID == MoCreatures.medallion.itemID))
    {
        if (--itemstack.stackSize == 0)
        {
            entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, null);
        }
        if (MoCreatures.isServer())
        {
            MoCTools.tameWithName((EntityPlayerMP) entityplayer, this);
        }
        return true;
    }
    if ((itemstack != null) && getIsTamed() && (itemstack.itemID == MoCreatures.whip.itemID))
    {
        setSitting(!getIsSitting());
        return true;
    }
    if ((itemstack != null) && getIsTamed() && (itemstack.itemID == Item.porkRaw.itemID || itemstack.itemID == Item.fishRaw.itemID))
    {
        health = getMaxHealth();
        worldObj.playSoundAtEntity(this, "eating", 1.0F, 1.0F + ((rand.nextFloat() - rand.nextFloat()) * 0.2F));
        setHungry(false);
        //setEaten(true);
    }
    return false;

}
 
Example 22
@Override
public void execute(MinecraftServer minecraftServer, ICommandSender sender, String[] args) throws CommandException {
    if ((sender instanceof EntityPlayerMP)) {
        EntityPlayerMP player = (EntityPlayerMP) sender;
        if (player.world.isRemote) {
            return;
        }
        FawePlayer<Object> fp = FawePlayer.wrap(player);
        cmd.executeSafe(fp, args);
    }
}
 
Example 23
public ChunkExtension(Chunk chunk, WorldExtension world)
{
    this.chunk = chunk;
    coord = chunk.getChunkCoordIntPair();
    this.world = world;
    watchedPlayers = new HashSet<EntityPlayerMP>();
}
 
Example 24
@Override
public void execute(MinecraftServer minecraftServer, ICommandSender sender, String[] args) throws CommandException {
    if ((sender instanceof EntityPlayerMP)) {
        EntityPlayerMP player = (EntityPlayerMP) sender;
        if (player.worldObj.isRemote) {
            return;
        }
        FawePlayer<Object> fp = FawePlayer.wrap(player);
        cmd.executeSafe(fp, args);
    }
}
 
Example 25
Source Project: EnderStorage   Source File: EnderStorageSPH.java    License: MIT License 5 votes vote down vote up
@Override
public void handlePacket(PacketCustom packet, EntityPlayerMP sender, INetHandlerPlayServer handler) {
    switch (packet.getType()) {
        case 1:
            TankSynchroniser.handleVisiblityPacket(sender, packet);
            break;
    }
}
 
Example 26
@Override
public void sendHeldItemUpdate() {
    for (IContainerListener listener : listeners) {
        EntityPlayerMP player = (EntityPlayerMP) listener;
        player.connection.sendPacket(new SPacketSetSlot(-1, -1, player.inventory.getItemStack()));
    }
}
 
Example 27
Source Project: MyTown2   Source File: PlotSelectionTool.java    License: The Unlicense 5 votes vote down vote up
@Override
public void onItemUse(BlockPos bp, int face) {
    Town town = MyTownUtils.getTownAtPosition(bp.getDim(), bp.getX() >> 4, bp.getZ() >> 4);

    if(!hasPermission(town)) {
        resetSelection(true, 0);
        return;
    }

    if (selectionFirst != null && selectionFirst.dim != bp.getDim()) {
        ChatManager.send(owner.getPlayer(), "mytown.cmd.err.plot.selection.otherDimension");
        return;
    }

    if (selectionFirst == null) {
        // selectionSecond = null;
        selectionFirst = new Selection(bp.getDim(), bp.getX(), bp.getY(), bp.getZ());
        // This is marked twice :P
        if(owner.getPlayer() instanceof EntityPlayerMP) {
            VisualsHandler.instance.markBlock(bp.getX(), bp.getY(), bp.getZ(), bp.getDim(), Blocks.redstone_block, (EntityPlayerMP) owner.getPlayer(), owner.getPlayer());
        }

    } else {
        selectionSecond = new Selection(bp.getDim(), bp.getX(), bp.getY(), bp.getZ());
        createPlotFromSelection();
    }
}
 
Example 28
@Override
public EnumActionResult onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, CuboidRayTraceResult hitResult) {
    if (!coverHolder.getWorld().isRemote) {
        openUI((EntityPlayerMP) playerIn);
    }
    return EnumActionResult.SUCCESS;
}
 
Example 29
@SubscribeEvent
public void on(PlayerEvent.PlayerLoggedInEvent e) {
    EntityPlayerMP p = (EntityPlayerMP) e.player;
    PacketHandler.INSTANCE.sendTo(new PacketUpdateGolemTypeOrder(GolemEnumHelper.getCurrentMapping()), p);
    PacketHandler.INSTANCE.sendTo(new PacketSyncConfigs(), p);
    ((DataFamiliar) SyncDataHolder.getDataServer("FamiliarData")).checkPlayerEquipment(p);
    ((DataAchromatic) SyncDataHolder.getDataServer("AchromaticData")).checkPotionEffect(p);
    SyncDataHolder.syncAllDataTo(p);
}
 
Example 30
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z){
    if(te instanceof TileEntityPressureTube) {
        ((TileEntityPressureTube)te).writeModulesToNBT(tag);
    }
    return tag;
}