[1.8] Создание блока с GUI

Статус
В этой теме нельзя размещать новые ответы.
Собираюсь сделать блок торговый автомат, пока на бартере. Но не в этом суть, а в том, что не получается его запилить(ну там открытие-закрытие, и тому подобное). Хирург скинул некий туториал немца HyCraft HD, вот репо на гите, и его пример пашет, но есть одно но: у него GuiScreen, а у меня - GuiContainer. Помогите пожалуйста. А я пока пойду старые моды поворошу(оххх, сколько их - заброшенных проектов... бррр)
 
Так. Ща закину код, отдельным комментом, без слотов, без всего, с RussianCraft server mod выдрал коды MatterHandler'a. Но при добавлении слотов крашит.
 
Agravaine написал(а):
А какая разница?
В смысле? В коде? Ну, если не считать, что там было под 1.6 и 1.7 то никакой
[merge_posts_bbcode]Добавлено: 18.07.2015 01:39:26[/merge_posts_bbcode]

А, понял, ты про GuiScreen и GuiContainer. Ну, они передают разные параметры.

[merge_posts_bbcode]Добавлено: 18.07.2015 01:48:22[/merge_posts_bbcode]

Вот и код:
Блок
Код:
package ru.vovamaster99.rt.blocks;

import java.util.Iterator;

import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import ru.vovamaster99.rt.RegularThings;
import ru.vovamaster99.rt.tile.TETrademat;

public class Trademat extends Block{
    
    public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);

    public Trademat(Material materialIn) {
        super(materialIn);
        setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
    }
    
    /*@Override
    public TileEntity createNewTileEntity(World worldIn, int meta)
    {
        return new TETrademat();
    }*/
    
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
    {
        playerIn.openGui(RegularThings.INSTANCE, 1, worldIn, pos.getX(), pos.getY(), pos.getZ());
        return super.onBlockActivated(worldIn, pos, state, playerIn, side, hitX, hitY, hitZ);
    }
    
    
    /*-----------
    //---Facing--
    */
    public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
    {
        setDefaultFacing(worldIn, pos, state);
    }

     private void setDefaultFacing(World worldIn, BlockPos pos, IBlockState state)
     {
            if (!worldIn.isRemote)
            {
                Block block = worldIn.getBlockState(pos.north()).getBlock();
                Block block1 = worldIn.getBlockState(pos.south()).getBlock();
                Block block2 = worldIn.getBlockState(pos.west()).getBlock();
                Block block3 = worldIn.getBlockState(pos.east()).getBlock();
                EnumFacing enumfacing = (EnumFacing)state.getValue(FACING);

                if (enumfacing == EnumFacing.NORTH && block.isFullBlock() && !block1.isFullBlock())
                {
                    enumfacing = EnumFacing.SOUTH;
                }
                else if (enumfacing == EnumFacing.SOUTH && block1.isFullBlock() && !block.isFullBlock())
                {
                    enumfacing = EnumFacing.NORTH;
                }
                else if (enumfacing == EnumFacing.WEST && block2.isFullBlock() && !block3.isFullBlock())
                {
                    enumfacing = EnumFacing.EAST;
                }
                else if (enumfacing == EnumFacing.EAST && block3.isFullBlock() && !block2.isFullBlock())
                {
                    enumfacing = EnumFacing.WEST;
                }

                worldIn.setBlockState(pos, state.withProperty(FACING, enumfacing), 2);
            }
     }

     public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
     {
         return getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite());
     }

     public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
     {
         worldIn.setBlockState(pos, state.withProperty(FACING, placer.getHorizontalFacing().getOpposite()), 2);

        /*if (stack.hasDisplayName())
          {
              TileEntity tileentity = worldIn.getTileEntity(pos);

              if (tileentity instanceof TileEntityFurnace)
              {
                  ((TileEntityFurnace)tileentity).setCustomInventoryName(stack.getDisplayName());
              }
          }*/
     }
     
     public int getRenderType()
     {
         return 3;
     }
     
     @SideOnly(Side.CLIENT)
     public IBlockState getStateForEntityRender(IBlockState state)
     {
         return getDefaultState().withProperty(FACING, EnumFacing.SOUTH);
     }
     
     /**
         * Convert the given metadata into a BlockState for this Block
         */
        public IBlockState getStateFromMeta(int meta)
        {
            EnumFacing enumfacing = EnumFacing.getFront(meta);

            if (enumfacing.getAxis() == EnumFacing.Axis.Y)
            {
                enumfacing = EnumFacing.NORTH;
            }

            return this.getDefaultState().withProperty(FACING, enumfacing);
        }

        /**
         * Convert the BlockState into the correct metadata value
         */
        public int getMetaFromState(IBlockState state)
        {
            return ((EnumFacing)state.getValue(FACING)).getIndex();
        }

        protected BlockState createBlockState()
        {
            return new BlockState(this, new IProperty[] {FACING});
        }

        @SideOnly(Side.CLIENT)
        static final class SwitchEnumFacing
        {
            static final int[] FACING_LOOKUP = new int[EnumFacing.values().length];
            private static final String __OBFID = "CL_00002111";

            static
           {
                try
                {
                        FACING_LOOKUP[EnumFacing.WEST.ordinal()] = 1;
                    }
                    catch (NoSuchFieldError var4)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.EAST.ordinal()] = 2;
                    }
                    catch (NoSuchFieldError var3)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.NORTH.ordinal()] = 3;
                    }
                    catch (NoSuchFieldError var2)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.SOUTH.ordinal()] = 4;
                    }
                    catch (NoSuchFieldError var1)
                    {
                        ;
                    }
                }
            }

}

Тайл
Код:
package ru.vovamaster99.rt.tile;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IChatComponent;
import ru.vovamaster99.rt.blocks.Trademat;

public class TETrademat extends TileEntity implements IInventory {
    
    private ItemStack[] tradematContent = new ItemStack[27];
    private String customName;
    public int numPlayerUsing;
    

    @Override
    public int getSizeInventory() {
        return 27;
    }

    @Override
    public ItemStack getStackInSlot(int index) {
        return this.tradematContent[index];
    }

    @Override
    public ItemStack decrStackSize(int index, int count) {
        if (this.tradematContent[index] != null)
        {
            ItemStack stack;
            
            if (this.tradematContent[index].stackSize <= count)
            {
                stack = this.tradematContent[index];
                this.tradematContent[index] = null;
                this.markDirty();
                return stack;
            }
            else
            {
                stack = this.tradematContent[index].splitStack(count);
                
                if (this.tradematContent[index].stackSize == 0)
                {
                    this.tradematContent[index] = null;
                }
                
                this.markDirty();
                return stack;
            }
        }
        else
        {
            return null;
        }
    }

    @Override
    public ItemStack getStackInSlotOnClosing(int index) {
        if (this.tradematContent[index] != null)
        {
            ItemStack stack = this.tradematContent[index];
            this.tradematContent[index] = null;
            return stack;
        }
        else
        {
            return null;
        }
    }

    @Override
    public void setInventorySlotContents(int index, ItemStack stack) {
        this.tradematContent[index] = stack;
        
        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }
        
        this.markDirty();
    }

    @Override
    public int getInventoryStackLimit() {
        return 64;
    }

    @Override
    public boolean isUseableByPlayer(EntityPlayer player) {
        return this.worldObj.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
    }

    @Override
    public void openInventory(EntityPlayer player) {
        if (!player.isSpectator())
        {
            if (this.numPlayerUsing < 0)
            {
                this.numPlayerUsing = 0;
            }
            
            ++this.numPlayerUsing;
            this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayerUsing);
            this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType());
            this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType());
        }
    }

    @Override
    public void closeInventory(EntityPlayer player) {
        if (!player.isSpectator() && this.getBlockType() instanceof Trademat)
        {
            --this.numPlayerUsing;
            this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayerUsing);
            this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType());
            this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType());
        }
    }

    @Override
    public boolean isItemValidForSlot(int index, ItemStack stack) {
        return true;
    }

    @Override
    public int getField(int id) {
        return 0;
    }

    @Override
    public void setField(int id, int value) {
        
    }

    @Override
    public int getFieldCount() {
        return 0;
    }

    @Override
    public void clear() {
        for (int i = 0; i < this.tradematContent.length; ++i)
        {
            this.tradematContent[i] = null;
        }
    }

    @Override
    public String getName() {
        return this.hasCustomName() ? this.customName : "container.trademat";
    }

    @Override
    public boolean hasCustomName() {
        return this.customName != null && this.customName.length() > 0;
    }

    @Override
    public IChatComponent getDisplayName() {
        return null;
    }

 }

Контейнер
Код:
  package ru.vovamaster99.rt.inventory;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import ru.vovamaster99.rt.tile.TETrademat;

public class ContainerTrademat extends Container {
    
    private TETrademat tile;
    private EntityPlayer player;
    
    public ContainerTrademat(EntityPlayer p)
    {
        player = p;
                //Перекроил весь код + убрал слоты, т.к. крашат. А так работает
    }
    
    @Override
    public ItemStack transferStackInSlot(EntityPlayer player, int index) { return null; }
    
    @Override
    public boolean canInteractWith(EntityPlayer player) { return true; }
    

}

Гуи
Код:
package ru.vovamaster99.rt.gui;

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import ru.vovamaster99.rt.inventory.ContainerTrademat;
import ru.vovamaster99.rt.tile.TETrademat;

public class GuiTrademat extends GuiContainer {
    
    private static final ResourceLocation GUI_TEXTURE = new ResourceLocation("rt:textures/gui/container/def.png");
    
    private TETrademat tile;
    
    public GuiTrademat(EntityPlayer player)
    {
        super(new ContainerTrademat(player));
        xSize = 176;
        ySize = 206;
    }
    
    @Override
    protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3)
    {
        int zX = (width - xSize) / 2;
        int zY = (height - ySize) / 2;
        mc.getTextureManager().bindTexture(GUI_TEXTURE);
        drawTexturedModalRect(zX, zY, 0, 0, xSize, ySize);
    }
}
Весь код основан на костылях
 
Код:
package ru.vovamaster99.rt.init;

import ru.vovamaster99.rt.tile.TETrademat;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class RegularTiles {

    public static void register()
    {
        GameRegistry.registerTileEntity(TETrademat.class, "TileEntityTrademat");
    }

}
 
1,990
18
105
Регистрация тут ни при чём, тайл передаётся из GuiHandler'а при создании контейнера.
 
Код:
package ru.vovamaster99.rt.handlers;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import ru.vovamaster99.rt.gui.GuiTrademat;
import ru.vovamaster99.rt.tile.TETrademat;

public class RegularGuiHandler implements IGuiHandler {

    /*public RegularGuiHandler() {
        // TODO Auto-generated constructor stub
    }*/

    @Override
    public Object getServerGuiElement(int ID, EntityPlayer player, World world,
            int x, int y, int z) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object getClientGuiElement(int ID, EntityPlayer player, World world,
            int x, int y, int z) {
        switch (ID) {
        case 1:
            return new GuiTrademat(player);
        default:
            return null;
        }
    }

}
 
1,239
2
24
Код:
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int X, int Y, int Z) {
      TileEntity te = world.getTileEntity(X, Y, Z);
      return te != null?(te instanceof TileEntityMachine?((TileEntityMachine)te).getGuiContainer(player.inventory):null):null;
   }

   public Object getClientGuiElement(int ID, EntityPlayer player, World world, int X, int Y, int Z) {
      TileEntity te = world.getTileEntity(X, Y, Z);
      return te != null?(te instanceof TileEntityMachine?new GuiMachine(player.inventory, (TileEntityMachine)te):null):null;
   }
 
XuPuPG написал(а):
Код:
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int X, int Y, int Z) {
      TileEntity te = world.getTileEntity(X, Y, Z);
      return te != null?(te instanceof TileEntityMachine?((TileEntityMachine)te).getGuiContainer(player.inventory):null):null;
   }

   public Object getClientGuiElement(int ID, EntityPlayer player, World world, int X, int Y, int Z) {
      TileEntity te = world.getTileEntity(X, Y, Z);
      return te != null?(te instanceof TileEntityMachine?new GuiMachine(player.inventory, (TileEntityMachine)te):null):null;
   }
в 1.8 x, y, z вызывает ошибку - они требуют BlockPos передавать. А как его получать не находясь в нужном блоке - хз.
 
1,239
2
24
Возьми какой нибудь мод на 1.8 с гуи и посмотри там.Или жди пока ответят тут.
 
1,990
18
105
.____________________.
BlockPos - просто обёртка для трёх координат.
Пытался хоть в класс заглянуть?
Код:
BlockPos blockPos = new BlockPos(x, y, z);

Координаты тебе передаются нужные.
 
Oldestkon написал(а):
.____________________.
BlockPos - просто обёртка для трёх координат.
Пытался хоть в класс заглянуть?
Код:
BlockPos blockPos = new BlockPos(x, y, z);

Координаты тебе передаются нужные.
Видимо дауном меня надо звать :|. Слишком я все усложняю вечно
[merge_posts_bbcode]Добавлено: 18.07.2015 18:33:57[/merge_posts_bbcode]

Все сделал, но - краш, причем понятно, что из-за меня, но ссылок на свои файлы не нашел
[17:32:22] [pool-2-thread-1/WARN]: Couldn't look up profile properties for com.mojang.authlib.GameProfile@2ee17b74[id=dcea94fd-efa4-3c29-93d8-2d56666245c7,name=Player367,properties={},legacy=false]
com.mojang.authlib.exceptions.AuthenticationException: The client has sent too many requests within a certain amount of time
at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:65) ~[YggdrasilAuthenticationService.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillGameProfile(YggdrasilMinecraftSessionService.java:158) [YggdrasilMinecraftSessionService.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:53) [YggdrasilMinecraftSessionService$1.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:50) [YggdrasilMinecraftSessionService$1.class:?]
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache.get(LocalCache.java:3934) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4827) [guava-17.0.jar:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillProfileProperties(YggdrasilMinecraftSessionService.java:148) [YggdrasilMinecraftSessionService.class:?]
at net.minecraft.client.resources.SkinManager$3.run(SkinManager.java:138) [SkinManager$3.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_45]
at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_45]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
[17:32:22] [Server thread/FATAL] [FML]: Exception caught executing FutureTask: java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(Unknown Source) ~[?:1.8.0_45]
at java.util.concurrent.FutureTask.get(Unknown Source) ~[?:1.8.0_45]
at net.minecraftforge.fml.common.FMLCommonHandler.callFuture(FMLCommonHandler.java:715) [FMLCommonHandler.class:?]
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:727) [MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:669) [MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:171) [IntegratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:540) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
at net.minecraft.inventory.Slot.getStack(Slot.java:79) ~[Slot.class:?]
at net.minecraft.inventory.Container.getInventory(Container.java:75) ~[Container.class:?]
at net.minecraft.inventory.Container.addCraftingToCrafters(Container.java:61) ~[Container.class:?]
at net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.openGui(FMLNetworkHandler.java:92) ~[FMLNetworkHandler.class:?]
at net.minecraft.entity.player.EntityPlayer.openGui(EntityPlayer.java:2577) ~[EntityPlayer.class:?]
at ru.vovamaster99.rt.blocks.Trademat.onBlockActivated(Trademat.java:44) ~[Trademat.class:?]
at net.minecraft.server.management.ItemInWorldManager.activateBlockOrUseItem(ItemInWorldManager.java:476) ~[ItemInWorldManager.class:?]
at net.minecraft.network.NetHandlerPlayServer.processPlayerBlockPlacement(NetHandlerPlayServer.java:624) ~[NetHandlerPlayServer.class:?]
at net.minecraft.network.play.client.C08PacketPlayerBlockPlacement.processPacket(C08PacketPlayerBlockPlacement.java:67) ~[C08PacketPlayerBlockPlacement.class:?]
at net.minecraft.network.play.client.C08PacketPlayerBlockPlacement.processPacket(C08PacketPlayerBlockPlacement.java:114) ~[C08PacketPlayerBlockPlacement.class:?]
at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:24) ~[PacketThreadUtil$1.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_45]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_45]
at net.minecraftforge.fml.common.FMLCommonHandler.callFuture(FMLCommonHandler.java:714) ~[FMLCommonHandler.class:?]
... 5 more
[17:32:22] [Server thread/ERROR]: Encountered an unexpected exception
net.minecraft.util.ReportedException: Ticking entity
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:781) ~[MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:669) ~[MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:171) ~[IntegratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:540) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
at net.minecraft.inventory.Slot.getStack(Slot.java:79) ~[Slot.class:?]
at net.minecraft.inventory.Container.detectAndSendChanges(Container.java:97) ~[Container.class:?]
at net.minecraft.entity.player.EntityPlayerMP.onUpdate(EntityPlayerMP.java:263) ~[EntityPlayerMP.class:?]
at net.minecraft.world.World.updateEntityWithOptionalForce(World.java:2031) ~[World.class:?]
at net.minecraft.world.WorldServer.updateEntityWithOptionalForce(WorldServer.java:758) ~[WorldServer.class:?]
at net.minecraft.world.World.updateEntity(World.java:1997) ~[World.class:?]
at net.minecraft.world.World.updateEntities(World.java:1823) ~[World.class:?]
at net.minecraft.world.WorldServer.updateEntities(WorldServer.java:587) ~[WorldServer.class:?]
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:775) ~[MinecraftServer.class:?]
... 4 more

[merge_posts_bbcode]Добавлено: 18.07.2015 18:36:17[/merge_posts_bbcode]

Handler
Код:
public class RegularGuiHandler implements IGuiHandler {

    /*public RegularGuiHandler() {
        // TODO Auto-generated constructor stub
    }*/

    @Override
    public Object getServerGuiElement(int ID, EntityPlayer player, World world,
            int x, int y, int z) {
        BlockPos bPos = new BlockPos(x, y, z);
        TileEntity tile = world.getTileEntity(bPos);
        switch (ID) {
        case 1:
            return new ContainerTrademat(player, (TETrademat)tile);
        default:
            return null;
        }
    }

    @Override
    public Object getClientGuiElement(int ID, EntityPlayer player, World world,
            int x, int y, int z) {
        BlockPos bPos = new BlockPos(x, y, z);
        TileEntity tile = world.getTileEntity(bPos);
        switch (ID) {
        case 1:
            return new GuiTrademat(player, (TETrademat)tile);
        default:
            return null;
        }
    }

}

GuiContainer
Код:
public class GuiTrademat extends GuiContainer {
    
    private static final ResourceLocation GUI_TEXTURE = new ResourceLocation("rt:textures/gui/container/def.png");
    
    private TETrademat tile;
    
    public GuiTrademat(EntityPlayer player, TETrademat te)
    {
        super(new ContainerTrademat(player, te));
        tile = te;
        xSize = 176;
        ySize = 206;
    }
    
    @Override
    protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3)
    {
        int zX = (width - xSize) / 2;
        int zY = (height - ySize) / 2;
        mc.getTextureManager().bindTexture(GUI_TEXTURE);
        drawTexturedModalRect(zX, zY, 0, 0, xSize, ySize);
    }
}

Container
Код:
public class ContainerTrademat extends Container {
    
    private TETrademat tile;
    private EntityPlayer player;
    
    public ContainerTrademat(EntityPlayer p, TETrademat te)
    {
        player = p; tile = te;
        addSlotToContainer(new Slot(tile, 0, 56, 35));
    }
    
    @Override
    public ItemStack transferStackInSlot(EntityPlayer player, int index) { return null; }
    
    @Override
    public boolean canInteractWith(EntityPlayer player) { return true; }
    

}
[merge_posts_bbcode]Добавлено: 18.07.2015 18:40:42[/merge_posts_bbcode]

Код:
public class ContainerTrademat extends Container {
    
    private TETrademat tile;
    private EntityPlayer player;
    
    public ContainerTrademat(EntityPlayer p, TETrademat te)
    {
        player = p; tile = te;
        addSlotToContainer(new Slot(player.inventory, 0, 56, 35));
    }
    
    @Override
    public ItemStack transferStackInSlot(EntityPlayer player, int index) { return null; }
    
    @Override
    public boolean canInteractWith(EntityPlayer player) { return true; }
    

}
А когда tile меняю на player.inventory все открывается
 
тайл
Код:
package ru.vovamaster99.rt.tile;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IChatComponent;
import ru.vovamaster99.rt.blocks.Trademat;

public class TETrademat extends TileEntity implements IInventory {
    
    private ItemStack[] tradematContent = new ItemStack[27];
    private String customName;
    public int numPlayerUsing;
    

    @Override
    public int getSizeInventory() {
        return 27;
    }

    @Override
    public ItemStack getStackInSlot(int index) {
        return this.tradematContent[index];
    }

    @Override
    public ItemStack decrStackSize(int index, int count) {
        if (this.tradematContent[index] != null)
        {
            ItemStack stack;
            
            if (this.tradematContent[index].stackSize <= count)
            {
                stack = this.tradematContent[index];
                this.tradematContent[index] = null;
                this.markDirty();
                return stack;
            }
            else
            {
                stack = this.tradematContent[index].splitStack(count);
                
                if (this.tradematContent[index].stackSize == 0)
                {
                    this.tradematContent[index] = null;
                }
                
                this.markDirty();
                return stack;
            }
        }
        else
        {
            return null;
        }
    }

    @Override
    public ItemStack getStackInSlotOnClosing(int index) {
        if (this.tradematContent[index] != null)
        {
            ItemStack stack = this.tradematContent[index];
            this.tradematContent[index] = null;
            return stack;
        }
        else
        {
            return null;
        }
    }

    @Override
    public void setInventorySlotContents(int index, ItemStack stack) {
        this.tradematContent[index] = stack;
        
        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }
        
        this.markDirty();
    }

    @Override
    public int getInventoryStackLimit() {
        return 64;
    }

    @Override
    public boolean isUseableByPlayer(EntityPlayer player) {
        return this.worldObj.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
    }

    @Override
    public void openInventory(EntityPlayer player) {
        if (!player.isSpectator())
        {
            if (this.numPlayerUsing < 0)
            {
                this.numPlayerUsing = 0;
            }
            
            ++this.numPlayerUsing;
            this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayerUsing);
            this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType());
            this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType());
        }
    }

    @Override
    public void closeInventory(EntityPlayer player) {
        if (!player.isSpectator() && this.getBlockType() instanceof Trademat)
        {
            --this.numPlayerUsing;
            this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayerUsing);
            this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType());
            this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType());
        }
    }

    @Override
    public boolean isItemValidForSlot(int index, ItemStack stack) {
        return true;
    }

    @Override
    public int getField(int id) {
        return 0;
    }

    @Override
    public void setField(int id, int value) {
        
    }

    @Override
    public int getFieldCount() {
        return 0;
    }

    @Override
    public void clear() {
        for (int i = 0; i < this.tradematContent.length; ++i)
        {
            this.tradematContent[i] = null;
        }
    }

    @Override
    public String getName() {
        return this.hasCustomName() ? this.customName : "container.trademat";
    }

    @Override
    public boolean hasCustomName() {
        return this.customName != null && this.customName.length() > 0;
    }

    @Override
    public IChatComponent getDisplayName() {
        return null;
    }

   
}

блок
Код:
package ru.vovamaster99.rt.blocks;

import java.util.Iterator;

import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import ru.vovamaster99.rt.RegularThings;
import ru.vovamaster99.rt.tile.TETrademat;

public class Trademat extends Block{
    
    public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);

    public Trademat(Material materialIn) {
        super(materialIn);
        setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
    }
    
    /*@Override
    public TileEntity createNewTileEntity(World worldIn, int meta)
    {
        return new TETrademat();
    }*/
    
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
    {
        playerIn.openGui(RegularThings.INSTANCE, 1, worldIn, pos.getX(), pos.getY(), pos.getZ());
        return super.onBlockActivated(worldIn, pos, state, playerIn, side, hitX, hitY, hitZ);
    }
    
    
    /*-----------
    //---Facing--
    */
    public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
    {
        setDefaultFacing(worldIn, pos, state);
    }

     private void setDefaultFacing(World worldIn, BlockPos pos, IBlockState state)
     {
            if (!worldIn.isRemote)
            {
                Block block = worldIn.getBlockState(pos.north()).getBlock();
                Block block1 = worldIn.getBlockState(pos.south()).getBlock();
                Block block2 = worldIn.getBlockState(pos.west()).getBlock();
                Block block3 = worldIn.getBlockState(pos.east()).getBlock();
                EnumFacing enumfacing = (EnumFacing)state.getValue(FACING);

                if (enumfacing == EnumFacing.NORTH && block.isFullBlock() && !block1.isFullBlock())
                {
                    enumfacing = EnumFacing.SOUTH;
                }
                else if (enumfacing == EnumFacing.SOUTH && block1.isFullBlock() && !block.isFullBlock())
                {
                    enumfacing = EnumFacing.NORTH;
                }
                else if (enumfacing == EnumFacing.WEST && block2.isFullBlock() && !block3.isFullBlock())
                {
                    enumfacing = EnumFacing.EAST;
                }
                else if (enumfacing == EnumFacing.EAST && block3.isFullBlock() && !block2.isFullBlock())
                {
                    enumfacing = EnumFacing.WEST;
                }

                worldIn.setBlockState(pos, state.withProperty(FACING, enumfacing), 2);
            }
     }

     public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
     {
         return getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite());
     }

     public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
     {
         worldIn.setBlockState(pos, state.withProperty(FACING, placer.getHorizontalFacing().getOpposite()), 2);

        /*if (stack.hasDisplayName())
          {
              TileEntity tileentity = worldIn.getTileEntity(pos);

              if (tileentity instanceof TileEntityFurnace)
              {
                  ((TileEntityFurnace)tileentity).setCustomInventoryName(stack.getDisplayName());
              }
          }*/
     }
     
     public int getRenderType()
     {
         return 3;
     }
     
     @SideOnly(Side.CLIENT)
     public IBlockState getStateForEntityRender(IBlockState state)
     {
         return getDefaultState().withProperty(FACING, EnumFacing.SOUTH);
     }
     
     /**
         * Convert the given metadata into a BlockState for this Block
         */
        public IBlockState getStateFromMeta(int meta)
        {
            EnumFacing enumfacing = EnumFacing.getFront(meta);

            if (enumfacing.getAxis() == EnumFacing.Axis.Y)
            {
                enumfacing = EnumFacing.NORTH;
            }

            return this.getDefaultState().withProperty(FACING, enumfacing);
        }

        /**
         * Convert the BlockState into the correct metadata value
         */
        public int getMetaFromState(IBlockState state)
        {
            return ((EnumFacing)state.getValue(FACING)).getIndex();
        }

        protected BlockState createBlockState()
        {
            return new BlockState(this, new IProperty[] {FACING});
        }

        @SideOnly(Side.CLIENT)
        static final class SwitchEnumFacing
        {
            static final int[] FACING_LOOKUP = new int[EnumFacing.values().length];
            private static final String __OBFID = "CL_00002111";

            static
           {
                try
                {
                        FACING_LOOKUP[EnumFacing.WEST.ordinal()] = 1;
                    }
                    catch (NoSuchFieldError var4)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.EAST.ordinal()] = 2;
                    }
                    catch (NoSuchFieldError var3)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.NORTH.ordinal()] = 3;
                    }
                    catch (NoSuchFieldError var2)
                    {
                        ;
                    }

                    try
                    {
                        FACING_LOOKUP[EnumFacing.SOUTH.ordinal()] = 4;
                    }
                    catch (NoSuchFieldError var1)
                    {
                        ;
                    }
                }
            }

}
 
Develance написал(а):
Oldestkon написал(а):
Код:
    /*@Override
    public TileEntity createNewTileEntity(World worldIn, int meta)
    {
        return new TETrademat();
    }*/
И удивляется, чего это ему нулл кидает.
XD
*здесь были нехорошие слова*
[merge_posts_bbcode]Добавлено: 19.07.2015 00:32:39[/merge_posts_bbcode]

вот я лох
Хотя кто бы сомневался

[merge_posts_bbcode]Добавлено: 19.07.2015 00:35:45[/merge_posts_bbcode]

[23:35:08] [Server thread/FATAL] [FML]: Exception caught executing FutureTask: java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(Unknown Source) ~[?:1.8.0_45]
at java.util.concurrent.FutureTask.get(Unknown Source) ~[?:1.8.0_45]
at net.minecraftforge.fml.common.FMLCommonHandler.callFuture(FMLCommonHandler.java:715) [FMLCommonHandler.class:?]
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:727) [MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:669) [MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:171) [IntegratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:540) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
at net.minecraft.inventory.Slot.getStack(Slot.java:79) ~[Slot.class:?]
at net.minecraft.inventory.Container.getInventory(Container.java:75) ~[Container.class:?]
at net.minecraft.inventory.Container.addCraftingToCrafters(Container.java:61) ~[Container.class:?]
at net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.openGui(FMLNetworkHandler.java:92) ~[FMLNetworkHandler.class:?]
at net.minecraft.entity.player.EntityPlayer.openGui(EntityPlayer.java:2577) ~[EntityPlayer.class:?]
at ru.vovamaster99.rt.blocks.Trademat.onBlockActivated(Trademat.java:43) ~[Trademat.class:?]
at net.minecraft.server.management.ItemInWorldManager.activateBlockOrUseItem(ItemInWorldManager.java:476) ~[ItemInWorldManager.class:?]
at net.minecraft.network.NetHandlerPlayServer.processPlayerBlockPlacement(NetHandlerPlayServer.java:624) ~[NetHandlerPlayServer.class:?]
at net.minecraft.network.play.client.C08PacketPlayerBlockPlacement.processPacket(C08PacketPlayerBlockPlacement.java:67) ~[C08PacketPlayerBlockPlacement.class:?]
at net.minecraft.network.play.client.C08PacketPlayerBlockPlacement.processPacket(C08PacketPlayerBlockPlacement.java:114) ~[C08PacketPlayerBlockPlacement.class:?]
at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:24) ~[PacketThreadUtil$1.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_45]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_45]
at net.minecraftforge.fml.common.FMLCommonHandler.callFuture(FMLCommonHandler.java:714) ~[FMLCommonHandler.class:?]
... 5 more
[23:35:08] [Server thread/ERROR]: Encountered an unexpected exception
net.minecraft.util.ReportedException: Ticking entity
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:781) ~[MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:669) ~[MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:171) ~[IntegratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:540) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
at net.minecraft.inventory.Slot.getStack(Slot.java:79) ~[Slot.class:?]
at net.minecraft.inventory.Container.detectAndSendChanges(Container.java:97) ~[Container.class:?]
at net.minecraft.entity.player.EntityPlayerMP.onUpdate(EntityPlayerMP.java:263) ~[EntityPlayerMP.class:?]
at net.minecraft.world.World.updateEntityWithOptionalForce(World.java:2031) ~[World.class:?]
at net.minecraft.world.WorldServer.updateEntityWithOptionalForce(WorldServer.java:758) ~[WorldServer.class:?]
at net.minecraft.world.World.updateEntity(World.java:1997) ~[World.class:?]
at net.minecraft.world.World.updateEntities(World.java:1823) ~[World.class:?]
at net.minecraft.world.WorldServer.updateEntities(WorldServer.java:587) ~[WorldServer.class:?]
at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:775) ~[MinecraftServer.class:?]
... 4 more
 
Статус
В этой теме нельзя размещать новые ответы.
Сверху