Java Code Examples for net.minecraft.util.text.TextComponentString

The following examples show how to use net.minecraft.util.text.TextComponentString. These examples are extracted from open source projects.
Example 1
Project: seppuku   File: PortalFinderModule.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void printPortalToChat(Vec3d portal) {
    final TextComponentString portalTextComponent = new TextComponentString("Portal found!");

    String overworld = "";
    String nether = "";

    if (Minecraft.getMinecraft().player.dimension == 0) { // overworld
        overworld = String.format("Overworld: X: %s, Y: %s, Z: %s", (int) portal.x, (int) portal.y, (int) portal.z);
        nether = String.format("Nether: X: %s, Y: %s, Z: %s", (int) portal.x / 8, (int) portal.y, (int) portal.z / 8);
    } else if (Minecraft.getMinecraft().player.dimension == -1) { // nether
        overworld = String.format("Overworld: X: %s, Y: %s, Z: %s", (int) portal.x * 8, (int) portal.y, (int) portal.z * 8);
        nether = String.format("Nether: X: %s, Y: %s, Z: %s", (int) portal.x, (int) portal.y, (int) portal.z);
    }

    int playerDistance = (int) Minecraft.getMinecraft().player.getDistance(portal.x, portal.y, portal.z);
    String distance = ChatFormatting.GRAY + "" + playerDistance + "m away";

    String hoverText = overworld + "\n" + nether + "\n" + distance;
    portalTextComponent.setStyle(new Style().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString(hoverText))));

    Seppuku.INSTANCE.logcChat(portalTextComponent);
}
 
Example 2
Project: Valkyrien-Skies   File: EventsCommon.java    License: Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPlayerTickEvent(PlayerTickEvent event) {
    if (!event.player.world.isRemote) {
        EntityPlayerMP p = (EntityPlayerMP) event.player;

        double[] pos = lastPositions.computeIfAbsent(p, k -> new double[3]);
        try {
            if (pos[0] != p.posX || pos[2] != p.posZ) { // Player has moved
                if (Math.abs(p.posX) > 27000000
                    || Math.abs(p.posZ) > 27000000) { // Player is outside of world
                    // border, tp them back
                    p.attemptTeleport(pos[0], pos[1], pos[2]);
                    p.sendMessage(new TextComponentString(
                        "You can't go beyond 27000000 blocks because airships are stored there!"));
                }
            }
        } catch (NullPointerException e) {
            logger.warn("Nullpointer EventsCommon.java:onPlayerTickEvent");
        }

        pos[0] = p.posX;
        pos[1] = p.posY;
        pos[2] = p.posZ;
    }
}
 
Example 3
Project: seppuku   File: HelpCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exec(String input) {
    if (!this.clamp(input, 1, 1)) {
        this.printUsage();
        return;
    }

    final int size = Seppuku.INSTANCE.getCommandManager().getCommandList().size();

    final TextComponentString msg = new TextComponentString("\2477Commands [" + size + "]\247f ");

    for (int i = 0; i < size; i++) {
        final Command cmd = Seppuku.INSTANCE.getCommandManager().getCommandList().get(i);

        msg.appendSibling(new TextComponentString("\247a" + cmd.getDisplayName() + "\2477" + ((i == size - 1) ? "" : ", "))
                .setStyle(new Style()
                        .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("\2476" + cmd.getDesc() + "\247f")
                                .appendSibling(new TextComponentString("\n" + cmd.getUsage()))))));
    }

    Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(msg);
}
 
Example 4
Project: GregTech   File: BlockSurfaceRockNew.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<ITextComponent> getMagnifyResults(IBlockAccess world, BlockPos pos, IBlockState blockState, EntityPlayer player) {
    TileEntitySurfaceRock tileEntity = getTileEntity(world, pos);
    if (tileEntity == null) {
        return Collections.emptyList();
    }
    List<Material> materials = tileEntity.getUndergroundMaterials();
    ITextComponent materialComponent = new TextComponentTranslation(tileEntity.getMaterial().getUnlocalizedName());
    materialComponent.getStyle().setColor(TextFormatting.GREEN);
    ITextComponent baseComponent = new TextComponentString("");
    ITextComponent separator = new TextComponentString(", ");
    separator.getStyle().setColor(TextFormatting.GRAY);
    for (int i = 0; i < materials.size(); i++) {
        ITextComponent extraComponent = new TextComponentTranslation(materials.get(i).getUnlocalizedName());
        extraComponent.getStyle().setColor(TextFormatting.YELLOW);
        baseComponent.appendSibling(extraComponent);
        if (i + 1 != materials.size()) baseComponent.appendSibling(separator);
    }
    ArrayList<ITextComponent> result = new ArrayList<>();
    result.add(new TextComponentTranslation("gregtech.block.surface_rock.material", materialComponent));
    result.add(new TextComponentTranslation("gregtech.block.surface_rock.underground_materials", baseComponent));
    return result;
}
 
Example 5
Project: GT-Classic   File: GTCommandTeleport.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] args)
		throws CommandException {
	if (!IC2.platform.isOp(sender.getCommandSenderEntity().getUniqueID())) {
		sender.sendMessage(new TextComponentString(TextFormatting.RED
				+ "You do not have permission to use this command"));
		return;
	}
	if (args.length < 1) {
		return;
	}
	String s = args[0];
	int dim;
	try {
		dim = Integer.parseInt(s);
	} catch (NumberFormatException e) {
		sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error parsing dimension!"));
		return;
	}
	if (sender instanceof EntityPlayer) {
		GTCommandTeleporter.teleportToDimension((EntityPlayer) sender, dim, 0, 100, 0);
	}
}
 
Example 6
Project: Kettle   File: CraftHumanEntity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void openCustomInventory(Inventory inventory, EntityPlayerMP player, String windowType) {
    if (player.connection == null) return;
    Container container = new CraftContainer(inventory, this.getHandle(), player.getNextWindowIdCB());

    container = CraftEventFactory.callInventoryOpenEvent(player, container);
    if (container == null) return;

    String title = container.getBukkitView().getTitle();
    int size = container.getBukkitView().getTopInventory().getSize();

    // Special cases
    if (windowType.equals("minecraft:crafting_table")
            || windowType.equals("minecraft:anvil")
            || windowType.equals("minecraft:enchanting_table")
    ) {
        size = 0;
    }

    player.connection.sendPacket(new SPacketOpenWindow(container.windowId, windowType, new TextComponentString(title), size));
    getHandle().inventoryContainer = container;
    getHandle().inventoryContainer.addListener(player);
}
 
Example 7
Project: YouTubeModdingTutorial   File: BlockSuperchest.java    License: MIT License 6 votes vote down vote up
public static void toggleMultiBlock(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
    // Form or break the multiblock
    if (!world.isRemote) {
        SuperchestPartIndex formed = state.getValue(FORMED);
        if (formed == SuperchestPartIndex.UNFORMED) {
            if (MultiBlockTools.formMultiblock(SuperchestMultiBlock.INSTANCE, world, pos)) {
                player.sendStatusMessage(new TextComponentString(TextFormatting.GREEN + "Made a superchest!"), false);
            } else {
                player.sendStatusMessage(new TextComponentString(TextFormatting.RED + "Could not form superchest!"), false);
            }
        } else {
            if (!MultiBlockTools.breakMultiblock(SuperchestMultiBlock.INSTANCE, world, pos)) {
                player.sendStatusMessage(new TextComponentString(TextFormatting.RED + "Not a valid superchest!"), false);
            }
        }
    }
}
 
Example 8
Project: ForgeHax   File: AutoLog.java    License: MIT License 6 votes vote down vote up
@SubscribeEvent
public void onPacketRecieved(PacketEvent.Incoming.Pre event) {
  if (event.getPacket() instanceof SPacketSpawnPlayer) {
    if (disconnectOnNewPlayer.getAsBoolean()) {
      AutoReconnectMod.hasAutoLogged = true; // dont automatically reconnect
      UUID id = ((SPacketSpawnPlayer) event.getPacket()).getUniqueId();
      
      NetworkPlayerInfo info = MC.getConnection().getPlayerInfo(id);
      String name = info != null ? info.getGameProfile().getName() : "(Failed) " + id.toString();
      
      getNetworkManager()
          .closeChannel(new TextComponentString(name + " entered render distance"));
      disable();
    }
  }
}
 
Example 9
Project: Valkyrien-Skies   File: EventsCommon.java    License: Apache License 2.0 6 votes vote down vote up
@SubscribeEvent()
public void onPlayerSleepInBedEvent(PlayerSleepInBedEvent event) {
    EntityPlayer player = event.getEntityPlayer();
    BlockPos pos = event.getPos();
    Optional<PhysicsObject> physicsObject = ValkyrienUtils
        .getPhysicsObject(player.getEntityWorld(), pos);

    if (physicsObject.isPresent()) {
        if (player instanceof EntityPlayerMP) {
            EntityPlayerMP playerMP = (EntityPlayerMP) player;
            player.sendMessage(new TextComponentString("Spawn Point Set!"));
            player.setSpawnPoint(pos, true);
            event.setResult(SleepResult.NOT_POSSIBLE_HERE);
        }
    }
}
 
Example 10
Project: TofuCraftReload   File: TofuMain.java    License: MIT License 5 votes vote down vote up
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
    proxy.preInit(event);

    logger = event.getModLog();

    TofuEntityRegister.entitySpawn();

    TofuCompat.preInit();

    GameRegistry.registerWorldGenerator(new TofuOreGenerator(), 0);

    MapGenStructureIO.registerStructure(MapGenTofuVillage.Start.class,"TofuVillage");
    StructureTofuVillagePieces.registerVillagePieces();
    MapGenStructureIO.registerStructure(StructureTofuMineshaftStart.class,"TofuMineshaft");
    StructureTofuMineshaftPieces.registerStructurePieces();
    MapGenStructureIO.registerStructure(MapGenTofuCastle.Start.class, "TofuCastle");
    TofuCastlePiece.registerTofuCastlePiece();

    NetworkRegistry.INSTANCE.registerGuiHandler(this, new TofuGuiHandler());


    zunda = new DamageSource("zunda") {
        @Override
        public ITextComponent getDeathMessage(EntityLivingBase entityLivingBaseIn) {
            String s = "death.attack.zunda";
            String s1 = s + ".player";

            return new TextComponentString(entityLivingBaseIn.getDisplayName().getFormattedText() + " ").appendSibling(new TextComponentTranslation(s1, new Object[]{entityLivingBaseIn.getDisplayName()}));
        }
    }.setDamageIsAbsolute();

    TOFU_DIMENSION = DimensionType.register("Tofu World", "_tofu", TofuConfig.dimensionID, WorldProviderTofu.class, false);
    DimensionManager.registerDimension(TofuConfig.dimensionID, TOFU_DIMENSION);

    TofuVillages.register();
}
 
Example 11
Project: FastAsyncWorldedit   File: ForgePlayer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendMessage(String msg) {
    msg = BBC.color(msg);
    for (String line : msg.split("\n")) {
        this.parent.sendMessage(new TextComponentString(line));
    }
}
 
Example 12
Project: YUNoMakeGoodMap   File: NewSpawnPlatformCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
    if (args.length != 2)
        throw new WrongUsageException(getUsage(sender));

    EntityPlayer player = getPlayer(server, sender, args[1]);

    if (player != null)
    {
        PlacementSettings settings = new PlacementSettings();
        WorldServer world = (WorldServer) sender.getEntityWorld();

        int platformNumber = SpawnPlatformSavedData.get(world).addAndGetPlatformNumber();
        BlockPos pos = getPositionOfPlatform(world, platformNumber);

        Template temp = StructureUtil.loadTemplate(new ResourceLocation(args[0]), world, true);
        BlockPos spawn = StructureUtil.findSpawn(temp, settings);
        spawn = spawn == null ? pos : spawn.add(pos);

        sender.sendMessage(new TextComponentString("Building \"" + args[0] + "\" at " + pos.toString()));
        temp.addBlocksToWorld(world, pos, settings, 2); //Push to world, with no neighbor notifications!
        world.getPendingBlockUpdates(new StructureBoundingBox(pos, pos.add(temp.getSize())), true); //Remove block updates, so that sand doesn't fall!

        if (player instanceof EntityPlayerMP) {
            ((EntityPlayerMP) player).setPositionAndUpdate(spawn.getX() + 0.5, spawn.getY() + 1.6, spawn.getZ() + 0.5);
        }

        player.setSpawnChunk(spawn, true, world.provider.getDimension());
    }
    else
    {
        throw new WrongUsageException(getUsage(sender));
    }
}
 
Example 13
Project: seppuku   File: PortalFinderModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void printEndPortalToChat(Vec3d portal) {
    final TextComponentString portalTextComponent = new TextComponentString("End Portal found!");

    String coords = String.format("X: %s, Y: %s, Z: %s", (int) portal.x, (int) portal.y, (int) portal.z);
    int playerDistance = (int) Minecraft.getMinecraft().player.getDistance(portal.x, portal.y, portal.z);
    String distance = ChatFormatting.GRAY + "" + playerDistance + "m away";

    String hoverText = coords + "\n" + distance;
    portalTextComponent.setStyle(new Style().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString(hoverText))));

    Seppuku.INSTANCE.logcChat(portalTextComponent);
}
 
Example 14
Project: seppuku   File: NoLagModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Listener
public void renderWorld(EventRender3D event) {
    final Minecraft mc = Minecraft.getMinecraft();
    if (this.signs.getValue()) {
        for (TileEntity te : mc.world.loadedTileEntityList) {
            if (te instanceof TileEntitySign) {
                final TileEntitySign sign = (TileEntitySign) te;
                sign.signText = new ITextComponent[]{new TextComponentString(""), new TextComponentString(""), new TextComponentString(""), new TextComponentString("")};
            }
        }
    }
}
 
Example 15
Project: AdvancedRocketry   File: TileRocketBuilder.java    License: MIT License 5 votes vote down vote up
@Override
public boolean onLinkComplete(ItemStack item, TileEntity entity,
		EntityPlayer player, World world) {
	TileEntity tile = world.getTileEntity(ItemLinker.getMasterCoords(item));

	if(tile instanceof IInfrastructure) {
		HashedBlockPosition pos = new HashedBlockPosition(tile.getPos());
		if(!blockPos.contains(pos))
			blockPos.add(pos);

		if(getBBCache() == null) {
			bbCache = getRocketPadBounds(world, getPos());
		}

		if(getBBCache() != null) {

			List<EntityRocketBase> rockets = world.getEntitiesWithinAABB(EntityRocketBase.class, bbCache);
			for(EntityRocketBase rocket : rockets) {
				rocket.linkInfrastructure((IInfrastructure) tile);
			}
		}

		if(!world.isRemote) {
			player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.linker.success")));

			if(tile instanceof IMultiblock)
				((IMultiblock)tile).setMasterBlock(getPos());
		}

		ItemLinker.resetPosition(item);
		return true;
	}
	return false;
}
 
Example 16
Project: seppuku   File: AutoSignModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Listener
public void displayGui(EventDisplayGui event) {
    if (event.getScreen() != null && event.getScreen() instanceof GuiEditSign) {
        final GuiEditSign gui = (GuiEditSign) event.getScreen();

        final boolean shouldCancel = this.overflow.getValue() ? true : this.lines != null;

        if (gui != null && shouldCancel && gui.tileSign != null) {
            Minecraft.getMinecraft().player.connection.sendPacket(new CPacketUpdateSign(gui.tileSign.getPos(), new TextComponentString[]{new TextComponentString(""), new TextComponentString(""), new TextComponentString(""), new TextComponentString("")}));
            Minecraft.getMinecraft().displayGuiScreen(null);
            event.setCanceled(true);
        }
    }
}
 
Example 17
Project: OpenModsLib   File: GenericInventory.java    License: MIT License 5 votes vote down vote up
@Override
public ITextComponent getDisplayName() {
	final String name = getName();
	return hasCustomName()
			? new TextComponentString(name)
			: new TextComponentTranslation(name);
}
 
Example 18
Project: seppuku   File: CalcStrongholdCommand.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Listener
public void onUpdate(EventPlayerUpdate event) {
    if (event.getStage() == EventStageable.EventStage.PRE) {
        if (this.firstStart != null && this.firstEnd != null && this.secondStart != null && this.secondEnd != null) {
            final double[] start = new double[]{this.secondStart.x, this.secondStart.z, this.secondEnd.x, this.secondEnd.z};
            final double[] end = new double[]{this.firstStart.x, this.firstStart.z, this.firstEnd.x, this.firstEnd.z};
            final double[] intersection = MathUtil.calcIntersection(start, end);

            if (Double.isNaN(intersection[0]) || Double.isNaN(intersection[1]) || Double.isInfinite(intersection[0]) || Double.isInfinite(intersection[1])) {
                Seppuku.INSTANCE.errorChat("Error lines are parallel");
                Seppuku.INSTANCE.getEventManager().removeEventListener(this);
                return;
            }

            final double dist = Minecraft.getMinecraft().player.getDistance(intersection[0], Minecraft.getMinecraft().player.posY, intersection[1]);

            final TextComponentString component = new TextComponentString("Stronghold found " + ChatFormatting.GRAY + (int) dist + "m away");
            final String coords = String.format("X: %s, Y: ?, Z: %s\nClick to add a Waypoint", (int) intersection[0], (int) intersection[1]);
            final CommandsModule cmds = (CommandsModule) Seppuku.INSTANCE.getModuleManager().find(CommandsModule.class);

            if (cmds != null) {
                component.setStyle(new Style().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString(coords))).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmds.prefix.getValue() + "Waypoints add Stronghold " + intersection[0] + " " + Minecraft.getMinecraft().player.posY + " " + intersection[1])));
            }

            Seppuku.INSTANCE.logcChat(component);
            Seppuku.INSTANCE.getNotificationManager().addNotification("", "Stronghold found " + ChatFormatting.GRAY + (int) dist + "m away");
            this.firstStart = null;
            this.firstEnd = null;
            this.secondStart = null;
            this.secondEnd = null;
            Seppuku.INSTANCE.getEventManager().removeEventListener(this);
        }
    }
}
 
Example 19
Project: pycode-minecraft   File: MyEntityPlayer.java    License: MIT License 5 votes vote down vote up
public void chat(Object... args) {
    if (this.entity.worldObj == null || !this.entity.worldObj.isRemote) return;
    StringBuilder sbStr = new StringBuilder();
    for (Object arg : args) {
        if (arg != args[0]) sbStr.append(" ");
        sbStr.append(arg);
    }
    ((EntityPlayer) this.entity).addChatComponentMessage(new TextComponentString(sbStr.toString()));
}
 
Example 20
Project: FastAsyncWorldedit   File: ForgePlayer.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void sendColorized(String msg, TextFormatting formatting) {
    for (String part : msg.split("\n")) {
        TextComponentString component = new TextComponentString(part);
        component.getStyle().setColor(formatting);
        this.player.sendMessage(component);
    }
}
 
Example 21
Project: CommunityMod   File: WhatAreThose.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@SubscribeEvent
public static void onEquipEvent(TickEvent.PlayerTickEvent event) {
    if (rand.nextInt(1000) < 1) {
        EntityPlayer player = event.player;
        BlockPos pos = new BlockPos(player.posX, player.posY, player.posZ);
        IBlockState state = player.world.getBlockState(pos.add(0, -1, 0));
        if (player.onGround) {
            for (ItemStack stack : player.inventory.armorInventory) {
                if (stack.getItem() instanceof ItemArmor && ((ItemArmor) stack.getItem()).getEquipmentSlot() == EntityEquipmentSlot.FEET && state == Blocks.DIAMOND_BLOCK) {
                    player.sendMessage(new TextComponentString("What are THOOOOOSE!?"));
                }
            }
        }
    }
}
 
Example 22
Project: CommunityMod   File: CommandFindBiome.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static BlockPos spiralOutwardsLookingForBiome(ICommandSender sender, World world, Biome biomeToFind, double startX, double startZ, int timeout) {
	double a = 16 / Math.sqrt(Math.PI);
	double b = 2 * Math.sqrt(Math.PI);
	double x;
	double z;
	double dist = 0;
	int n;
	long start = System.currentTimeMillis();
	BlockPos.PooledMutableBlockPos pos = BlockPos.PooledMutableBlockPos.retain();
	int previous = 0;
	int i = 0;
	for (n = 0; dist < Integer.MAX_VALUE; ++n) {
		if ((System.currentTimeMillis() - start) > timeout) {
			return null;
		}
		double rootN = Math.sqrt(n);
		dist = a * rootN;
		x = startX + (dist * Math.sin(b * rootN));
		z = startZ + (dist * Math.cos(b * rootN));
		pos.setPos(x, 0, z);
		if (sender instanceof EntityPlayer) {
			if (previous == 3)
				previous = 0;
			String s = (previous == 0 ? "." : previous == 1 ? ".." : "...");
			((EntityPlayer) sender).sendStatusMessage(new TextComponentString("Scanning" + s), true);
			if (i == 1501) {
				previous++;
				i = 0;
			}
			i++;
		}
		if (world.getBiome(pos).equals(biomeToFind)) {
			pos.release();
			if (sender instanceof EntityPlayer)
				((EntityPlayer) sender).sendStatusMessage(new TextComponentString("Found Biome"), true);
			return new BlockPos((int) x, 0, (int) z);
		}
	}
	return null;
}
 
Example 23
Project: CommunityMod   File: CommandFindBiome.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
	Biome biome = null;
	if (args.length == 0) {
		sender.sendMessage(new TextComponentString("No biome specified"));
		return;
	}
	for (Biome b : ForgeRegistries.BIOMES.getValues()) {
		String name = b.getRegistryName().toString().replaceAll(" ", "_").toLowerCase();
		if (args[0].equalsIgnoreCase(name)) {
			biome = b;
		}
	}
	if (biome == null) {
		sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! Biome '" + args[0] + "' cannot be found!"));
		return;
	}
	long start = System.currentTimeMillis();
	final Biome finalBiome = biome;
	new Thread(() -> {
		BlockPos pos = spiralOutwardsLookingForBiome(sender, sender.getEntityWorld(), finalBiome, sender.getPosition().getX(), sender.getPosition().getZ(), TraverseConfig.findBiomeCommandTimeout);
		if (pos == null) {
			server.addScheduledTask(() -> sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! Biome '" + args[0] + "' could not be found after " + TextFormatting.GRAY + TraverseConfig.findBiomeCommandTimeout + "ms" + TextFormatting.RED + ".")));
			return;
		}
		if (sender instanceof EntityPlayerMP) {
			server.addScheduledTask(() -> {
				EntityPlayerMP playerMP = (EntityPlayerMP) sender;
				playerMP.connection.setPlayerLocation(pos.getX(), 150, pos.getZ(), 0, 0);
				sender.sendMessage(new TextComponentString(TextFormatting.WHITE + "Found '" + finalBiome.getRegistryName().toString() + "' Biome! " + TextFormatting.GRAY + "(" + (System.currentTimeMillis() - start) + "ms)"));
			});
			return;
		}
		server.addScheduledTask(() -> sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! An unknown error occurred.")));
	}, "Biome Finder - Traverse").start();
}
 
Example 24
Project: CommunityMod   File: SentientBread.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@SubscribeEvent
public static void onClientTick(TickEvent.ClientTickEvent event)
{
    Minecraft mc = Minecraft.getMinecraft();

    if (!isLoaded)
    {
        return;
    }

    if (event.phase == TickEvent.Phase.END && mc.world != null && !mc.isGamePaused())
    {
        ItemStack stack = mc.player.getActiveItemStack();

        if (!stack.isEmpty() && stack.getItem() == Items.BREAD)
        {
            Random rand = mc.player.world.rand;

            if (rand.nextFloat() < 0.04)
            {
                String msg = MESSAGES_STOP[rand.nextInt(MESSAGES_STOP.length)];
                int i = mc.gameSettings.narrator;

                if (NARRATOR.active() && (i == 0 || i == 3)) // Don't narrate if the setting is already turned on
                {
                    NARRATOR.clear();
                    NARRATOR.say(msg);
                }

                mc.player.sendMessage(stack.getTextComponent().appendSibling(new TextComponentString(": " + msg)));
            }
        }
    }
}
 
Example 25
Project: Valkyrien-Skies   File: PhysicsObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates the new chunks
 */
public TickSyncCompletableFuture<Void> assembleShipAsOrderedByPlayer(EntityPlayer player) {
    if (world().isRemote) {
        throw new IllegalStateException("This method cannot be invoked on client side!");
    }
    if (!(world() instanceof WorldServer)) {
        throw new IllegalStateException("The world " + world() + " wasn't an instance of WorldServer");
    }

    BlockPos centerInWorld = new BlockPos(getWrapperEntity().posX,
        getWrapperEntity().posY, getWrapperEntity().posZ);

    // The thread the tick sync will execute on.
    IThreadListener worldServerThread = (WorldServer) world();

    return TickSyncCompletableFuture
        .supplyAsync(() -> DetectorManager.getDetectorFor(getDetectorID(), centerInWorld, world(),
            VSConfig.maxShipSize + 1, true))
        .thenAcceptTickSync(detector -> {
            if (detector.foundSet.size() > VSConfig.maxShipSize || detector.cleanHouse) {
                System.err.println("Ship too big or bedrock detected!");
                if (player != null) {
                    player.sendMessage(new TextComponentString(
                        "Ship construction canceled because its exceeding the ship size limit; "
                            +
                            "or because it's attached to bedrock. " +
                            "Raise it with /physsettings maxshipsize [number]"));
                }
                getWrapperEntity().setDead();
                return;
            }
            assembleShip(player, detector, centerInWorld);

            markFullyLoaded();
        }, worldServerThread);
}
 
Example 26
Project: YUNoMakeGoodMap   File: GuiCustomizeWorld.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void clickHeader(int x, int y)
{
    int offset = y;
    if (logoPath != null) {
      offset -= logoDims.height + 10;
    }
    if (offset <= 0)
        return;

    int lineIdx = offset / 10;
    if (lineIdx >= lines.size())
        return;

    ITextComponent line = lines.get(lineIdx);
    if (line != null)
    {
        int k = -4;
        for (ITextComponent part : line)
        {
            if (!(part instanceof TextComponentString))
                continue;
            k += GuiCustomizeWorld.this.fontRenderer.getStringWidth(((TextComponentString)part).getText());
            if (k >= x)
            {
                GuiCustomizeWorld.this.handleComponentClick(part);
                break;
            }
        }
    }
}
 
Example 27
Project: FastAsyncWorldedit   File: ForgePlayer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendMessage(String msg) {
    msg = BBC.color(msg);
    for (String line : msg.split("\n")) {
        this.parent.addChatMessage(new TextComponentString(line));
    }
}
 
Example 28
Project: CommunityMod   File: EntityPenguin.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean processInteract(EntityPlayer player, EnumHand hand) {
	boolean ret = super.processInteract(player, hand);
	if (player.world.isRemote && hand == EnumHand.MAIN_HAND) {
		player.sendMessage(new TextComponentString(
				"If you like these penguins, you'll like the full version more!"));
		player.sendMessage(new TextComponentString("Click [here] to download it on CurseForge.")
				.setStyle(new Style().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,
						"https://minecraft.curseforge.com/projects/penguins"))));
	}
	return ret;
}
 
Example 29
Project: AdvancedRocketry   File: ItemSealDetector.java    License: MIT License 5 votes vote down vote up
@Override
public EnumActionResult onItemUse(EntityPlayer player,
		World world, BlockPos pos, EnumHand hand, EnumFacing facing,
		float hitX, float hitY, float hitZ) {
       if (!world.isRemote)
       {
           if (SealableBlockHandler.INSTANCE.isBlockSealed(world, pos))
           {
               player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.sealed")));
           }
           else
           {
           	IBlockState state = world.getBlockState(pos);
               Material mat = state.getMaterial();
               if (SealableBlockHandler.INSTANCE.isMaterialBanned(mat))
               {
                   player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.notsealmat")));
               }
               else if (SealableBlockHandler.INSTANCE.isBlockBanned(state.getBlock()))
               {
                   player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.notsealblock")));
               }
               else if (SealableBlockHandler.isFulBlock(world, pos))
               {
                   player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.notfullblock")));
               }
               else if (state.getBlock() instanceof IFluidBlock)
               {
                   player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.fluid")));
               }
               else
               {
                   player.sendMessage(new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.sealdetector.other")));
               }
           }
       }
       return EnumActionResult.SUCCESS;
}
 
Example 30
Project: CommunityMod   File: ModGenuinePeoplePersonalities.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean generateComplaint(StringType type, EntityPlayer player, ItemStack stack, EventData data) {
    switch (type) {
        case ACTIVATE:
            if (stack.getItem() == Items.APPLE) {
                switch (data.random.nextInt(5)) {
                    case 0:
                        player.sendMessage(new TextComponentString(obnoxious + "The apple screams, \"No! Think of my children!\""));
                        break;
                    case 1:
                        player.sendMessage(new TextComponentString(obnoxious + "The apple sobs mournfully as it is devoured."));
                        break;
                    case 2:
                        player.sendMessage(new TextComponentString(obnoxious + "The apple seems resigned to its oncoming demise."));
                        break;
                    case 3:
                    case 4:
                        player.sendMessage(new TextComponentString(obnoxious + "The apple seems resigned to its oncoming demise."));
                        break;
                }
                return true;
            } else if (stack.getItem() == Items.FISH || stack.getItem() == Items.PORKCHOP || stack.getItem() == Items.MUTTON || stack.getItem() == Items.BEEF) {
                player.sendMessage(new TextComponentString(obnoxious + String.format("The %s yells, \"Serves you right if you get sick! Bastard.\"", stack.getDisplayName())));
                return true;
            }
    }
    return false;
}
 
Example 31
Project: Kettle   File: CraftHumanEntity.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void openInventory(InventoryView inventory) {
    if (!(getHandle() instanceof EntityPlayerMP)) return; // TODO: NPC support?
    if (((EntityPlayerMP) getHandle()).connection == null) return;
    if (getHandle().inventoryContainer != getHandle().inventoryContainer) {
        // fire INVENTORY_CLOSE if one already open
        ((EntityPlayerMP) getHandle()).connection.processCloseWindow(new CPacketCloseWindow(getHandle().inventoryContainer.windowId));
    }
    EntityPlayerMP player = (EntityPlayerMP) getHandle();
    Container container;
    if (inventory instanceof CraftInventoryView) {
        container = ((CraftInventoryView) inventory).getHandle();
    } else {
        container = new CraftContainer(inventory, this.getHandle(), player.getNextWindowIdCB());
    }

    // Trigger an INVENTORY_OPEN event
    container = CraftEventFactory.callInventoryOpenEvent(player, container);
    if (container == null) {
        return;
    }

    // Now open the window
    InventoryType type = inventory.getType();
    String windowType = CraftContainer.getNotchInventoryType(type);
    String title = inventory.getTitle();
    int size = inventory.getTopInventory().getSize();
    player.connection.sendPacket(new SPacketOpenWindow(container.windowId, windowType, new TextComponentString(title), size));
    player.inventoryContainer = container;
    player.inventoryContainer.addListener(player);
}
 
Example 32
Project: HoloInventory   File: ServerEventHandler.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onRightClick(PlayerInteractEvent.RightClickBlock event)
{
    if (catchNext == Type.NONE) return;
    boolean ban = catchNext == Type.BAN;
    catchNext = Type.NONE;
    event.setCanceled(true);

    TileEntity te = event.getWorld().getTileEntity(event.getPos());

    if (te == null)
    {
        event.getEntityPlayer().sendMessage(new TextComponentString("That block does not have a TileEntity.").setStyle(new Style().setColor(TextFormatting.RED)));
        return;
    }

    if (ban)
    {
        if (Helper.banned.add(te.getClass().getCanonicalName()))
            event.getEntityPlayer().sendMessage(new TextComponentString("Banned " + te.getClass().getCanonicalName()).setStyle(new Style().setColor(TextFormatting.GREEN)));
        else
            event.getEntityPlayer().sendMessage(new TextComponentString(te.getClass().getCanonicalName() + " is already banned.").setStyle(new Style().setColor(TextFormatting.RED)));
    }
    else
    {
        boolean wasBanned = Helper.banned.remove(te.getClass().getCanonicalName());
        if (wasBanned)
            event.getEntityPlayer().sendMessage(new TextComponentString("Unbanned " + te.getClass().getCanonicalName()).setStyle(new Style().setColor(TextFormatting.GREEN)));
        else
            event.getEntityPlayer().sendMessage(new TextComponentString(te.getClass().getCanonicalName() + " is not banned. Perhaps it is banned on the " + (FMLCommonHandler.instance().getSide().isClient() ? "server" : "client") + "?").setStyle(new Style().setColor(TextFormatting.RED)));
    }

    HoloInventory.getInstance().saveBanned();
}
 
Example 33
Project: AdvancedRocketry   File: WorldCommand.java    License: MIT License 5 votes vote down vote up
private void printStarHelp(ICommandSender sender) {
	sender.sendMessage(new TextComponentString("star list"));
	sender.sendMessage(new TextComponentString("star get temp <star id>"));
	sender.sendMessage(new TextComponentString("star get planets <star id>"));
	sender.sendMessage(new TextComponentString("star get pos <star id>"));
	sender.sendMessage(new TextComponentString("star set temp <star id> <temperature>"));
	sender.sendMessage(new TextComponentString("star set pos <star id> <x> <y>"));
	sender.sendMessage(new TextComponentString("star generate <name> <temp> <x> <y>"));
}
 
Example 34
@SuppressWarnings("deprecation")
public static void processRequest(MinecraftServer server, NetworkManager networkManager) {
    StandardPaperServerListPingEventImpl event = new StandardPaperServerListPingEventImpl(server, networkManager, server.getServerStatusResponse());
    server.server.getPluginManager().callEvent(event);

    // Close connection immediately if event is cancelled
    if (event.isCancelled()) {
        networkManager.closeChannel(null);
        return;
    }

    // Setup response
    ServerStatusResponse ping = new ServerStatusResponse();

    // Description
    ping.setServerDescription(new TextComponentString(event.getMotd()));

    // Players
    if (!event.shouldHidePlayers()) {
        ping.setPlayers(new ServerStatusResponse.Players(event.getMaxPlayers(), event.getNumPlayers()));
        ping.getPlayers().setPlayers(event.getPlayerSampleHandle());
    }

    // Version
    ping.setVersion(new ServerStatusResponse.Version(event.getVersion(), event.getProtocolVersion()));

    // Favicon
    if (event.getServerIcon() != null) {
        ping.setFavicon(event.getServerIcon().getData());
    }

    // Send response
    networkManager.sendPacket(new SPacketServerInfo(ping));
}
 
Example 35
Project: YouTubeModdingTutorial   File: ItemWand.java    License: MIT License 5 votes vote down vote up
public void toggleMode(EntityPlayer player, ItemStack stack) {
    WandMode mode = getMode(stack);
    if (mode == WandMode.SPHERE) {
        mode = WandMode.LEVITATE;
    } else {
        mode = WandMode.SPHERE;
    }
    player.sendStatusMessage(new TextComponentString(TextFormatting.GREEN + "Switched to " + mode.name()), false);
    if (!stack.hasTagCompound()) {
        stack.setTagCompound(new NBTTagCompound());
    }
    stack.getTagCompound().setInteger("mode", mode.ordinal());
}
 
Example 36
Project: BakaDanmaku   File: ChatMsgHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 发送普通弹幕
 *
 * @param e 发送弹幕事件
 */
@SubscribeEvent
public static void receiveDanmaku(DanmakuEvent e) {
    EntityPlayer player = Minecraft.getMinecraft().player;
    Pattern readDanmakuUser = Pattern.compile(BakaDanmakuConfig.blockFunction.blockPlayer); // 屏蔽弹幕发送者
    Pattern readDanmakuMsg = Pattern.compile(BakaDanmakuConfig.blockFunction.blockDanmaku); // 屏蔽弹幕关键词

    // 先判定是否开启弹幕显示
    if (player != null && BakaDanmakuConfig.chatMsg.showDanmaku) {
        // 获取弹幕信息
        String msg = e.getMsg();

        // 进行格式符消除,关键词屏蔽
        if (BakaDanmakuConfig.blockFunction.blockFormatCode) {
            // 替换消除格式符,更有效的祛除格式符
            msg = e.getMsg().replaceAll("(?:§(?=§*(\\1?+[0-9a-fk-or])))+\\1", "");

            // 如果不为空,消除关键词
            if (!BakaDanmakuConfig.blockFunction.blockKeyword.isEmpty())
                msg = msg.replaceAll(BakaDanmakuConfig.blockFunction.blockKeyword, "*");
        }

        // 进行指定玩家屏蔽,指定弹幕屏蔽
        Matcher mUser = readDanmakuUser.matcher(e.getUser());
        Matcher mMsg = readDanmakuMsg.matcher(msg);
        // 没找到,或者对应列表为空
        if ((!mUser.find() || BakaDanmakuConfig.blockFunction.blockPlayer.isEmpty())
                && (!mMsg.find() || BakaDanmakuConfig.blockFunction.blockDanmaku.isEmpty())) {
            player.sendMessage(new TextComponentString(String.format(BakaDanmakuConfig.chatMsg.danmakuStyle,
                    e.getPlatform(), e.getUser(), msg)));
        }
    }
}
 
Example 37
Project: AdvancedRocketry   File: TileEntityFuelingStation.java    License: MIT License 5 votes vote down vote up
@Override
public boolean onLinkStart(ItemStack item, TileEntity entity,
		EntityPlayer player, World world) {

	ItemLinker.setMasterCoords(item, pos);

	if(this.linkedRocket != null) {
		this.linkedRocket.unlinkInfrastructure(this);
		this.unlinkRocket();
	}

	if(player.world.isRemote)
		Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage((new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.fuelingStation.link") + ": " + this.pos.getX() + " " + this.pos.getY() + " " + this.pos.getZ())));
	return true;
}
 
Example 38
Project: Traverse-Legacy-1-12-2   File: CommandFindBiome.java    License: MIT License 5 votes vote down vote up
public static BlockPos spiralOutwardsLookingForBiome(ICommandSender sender, World world, Biome biomeToFind, double startX, double startZ, int timeout) {
	double a = 16 / Math.sqrt(Math.PI);
	double b = 2 * Math.sqrt(Math.PI);
	double x;
	double z;
	double dist = 0;
	int n;
	long start = System.currentTimeMillis();
	BlockPos.PooledMutableBlockPos pos = BlockPos.PooledMutableBlockPos.retain();
	int previous = 0;
	int i = 0;
	for (n = 0; dist < Integer.MAX_VALUE; ++n) {
		if ((System.currentTimeMillis() - start) > timeout) {
			return null;
		}
		double rootN = Math.sqrt(n);
		dist = a * rootN;
		x = startX + (dist * Math.sin(b * rootN));
		z = startZ + (dist * Math.cos(b * rootN));
		pos.setPos(x, 0, z);
		if (sender instanceof EntityPlayer) {
			if (previous == 3)
				previous = 0;
			String s = (previous == 0 ? "." : previous == 1 ? ".." : "...");
			((EntityPlayer) sender).sendStatusMessage(new TextComponentString("Scanning" + s), true);
			if (i == 1501) {
				previous++;
				i = 0;
			}
			i++;
		}
		if (world.getBiome(pos).equals(biomeToFind)) {
			pos.release();
			if (sender instanceof EntityPlayer)
				((EntityPlayer) sender).sendStatusMessage(new TextComponentString("Found Biome"), true);
			return new BlockPos((int) x, 0, (int) z);
		}
	}
	return null;
}
 
Example 39
Project: Traverse-Legacy-1-12-2   File: CommandFindBiome.java    License: MIT License 5 votes vote down vote up
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
	Biome biome = null;
	if (args.length == 0) {
		sender.sendMessage(new TextComponentString("No biome specified"));
		return;
	}
	for (Biome b : ForgeRegistries.BIOMES.getValues()) {
		String name = b.getRegistryName().toString().replaceAll(" ", "_").toLowerCase();
		if (args[0].equalsIgnoreCase(name)) {
			biome = b;
		}
	}
	if (biome == null) {
		sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! Biome '" + args[0] + "' cannot be found!"));
		return;
	}
	long start = System.currentTimeMillis();
	final Biome finalBiome = biome;
	new Thread(() -> {
		BlockPos pos = spiralOutwardsLookingForBiome(sender, sender.getEntityWorld(), finalBiome, sender.getPosition().getX(), sender.getPosition().getZ(), TraverseConfig.findBiomeCommandTimeout);
		if (pos == null) {
			server.addScheduledTask(() -> sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! Biome '" + args[0] + "' could not be found after " + TextFormatting.GRAY + TraverseConfig.findBiomeCommandTimeout + "ms" + TextFormatting.RED + ".")));
			return;
		}
		if (sender instanceof EntityPlayerMP) {
			server.addScheduledTask(() -> {
				EntityPlayerMP playerMP = (EntityPlayerMP) sender;
				playerMP.connection.setPlayerLocation(pos.getX(), 150, pos.getZ(), 0, 0);
				sender.sendMessage(new TextComponentString(TextFormatting.WHITE + "Found '" + finalBiome.getRegistryName().toString() + "' Biome! " + TextFormatting.GRAY + "(" + (System.currentTimeMillis() - start) + "ms)"));
			});
			return;
		}
		server.addScheduledTask(() -> sender.sendMessage(new TextComponentString(TextFormatting.RED + "Error! An unknown error occurred.")));
	}, "Biome Finder - Traverse").start();
}
 
Example 40
Project: AdvancedRocketry   File: TileEntityMoniteringStation.java    License: MIT License 5 votes vote down vote up
@Override
public boolean onLinkComplete(ItemStack item, TileEntity entity,
		EntityPlayer player, World world) {
	if(player.world.isRemote)
		Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage((new TextComponentString(LibVulpes.proxy.getLocalizedString("msg.linker.error.firstMachine"))));
	return false;
}