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. 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: seppuku   Source 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
Source Project: Valkyrien-Skies   Source 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
Source Project: seppuku   Source 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
@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
@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
Source Project: Kettle   Source 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
Source Project: YouTubeModdingTutorial   Source 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
Source Project: ForgeHax   Source 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
Source Project: Valkyrien-Skies   Source 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
Source Project: TofuCraftReload   Source 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
@Override
public void sendMessage(String msg) {
    msg = BBC.color(msg);
    for (String line : msg.split("\n")) {
        this.parent.sendMessage(new TextComponentString(line));
    }
}
 
Example 12
Source Project: YUNoMakeGoodMap   Source 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
Source Project: seppuku   Source 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
Source Project: seppuku   Source 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
Source Project: AdvancedRocketry   Source 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
Source Project: seppuku   Source 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
Source Project: OpenModsLib   Source 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
@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
Source Project: pycode-minecraft   Source 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
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
@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
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
@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
@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
Source Project: Valkyrien-Skies   Source 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
Source Project: YUNoMakeGoodMap   Source 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
@Override
public void sendMessage(String msg) {
    msg = BBC.color(msg);
    for (String line : msg.split("\n")) {
        this.parent.addChatMessage(new TextComponentString(line));
    }
}
 
Example 28
@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
Source Project: AdvancedRocketry   Source 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
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;
}