- 39
- 2
Привет, есть такой прекрасный гайд [1.7.10] Создание аддона для IC2
Решил сделать себе мехи с 2/3/6/12 слотами ну и как ожидалось для етого надо кастомный GUI в котором надо поставить координаты того же инвентаря.
Но тут такой прикол

Вот вам и дублированый инв, из-за чего не могу понять уже 2 день)
Tile
GUI
Container
Решил сделать себе мехи с 2/3/6/12 слотами ну и как ожидалось для етого надо кастомный GUI в котором надо поставить координаты того же инвентаря.
Но тут такой прикол

Вот вам и дублированый инв, из-за чего не могу понять уже 2 день)
Tile
Kotlin:
package com.heros.wlmod.tile
import com.heros.wlmod.container.ContainerMy2SlotsMacerator
import com.heros.wlmod.gui.GuiMy2SlotsMacerator
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import ic2.api.recipe.Recipes
import ic2.core.ContainerBase
import ic2.core.IC2
import ic2.core.IHasGui
import ic2.core.block.invslot.*
import ic2.core.block.machine.tileentity.TileEntityElectricMachine
import ic2.core.upgrade.IUpgradableBlock
import ic2.core.upgrade.IUpgradeItem
import ic2.core.upgrade.UpgradableProperty
import net.minecraft.client.gui.GuiScreen
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.nbt.NBTTagCompound
import java.util.*
// Аргументы для конструктора TileEntityElectricMachine. 1 - максимальное количество энергии, 2 - уровень машины
class TileEntityMy2SlotsMacerator: TileEntityElectricMachine(256000, 2, 2), IHasGui, IUpgradableBlock {
private var progress: Short = 0
val inputSlotA: InvSlotProcessable
val inputSlotB: InvSlotProcessable
val outputSlotA: InvSlotOutput
val outputSlotB: InvSlotOutput
val upgradeSlot: InvSlotUpgrade
init {
// Если хотите добавить еще слотов, создаете еще переменные, но при инициализации третий аргумент должен быть на один больше предыдущего, это - индекс.
this.inputSlotA = InvSlotProcessableGeneric(this, "inputA", 0, 1, Recipes.macerator) // Первый входной слот
this.inputSlotB = InvSlotProcessableGeneric(this, "inputB", 1, 1, Recipes.macerator) // Второй входной слот
this.outputSlotA = InvSlotOutput(this, "outputA", 3, 1) // Первый выходной слот
this.outputSlotB = InvSlotOutput(this, "outputB", 4, 1) // Второй выходной слот
this.upgradeSlot = InvSlotUpgrade(this, "upgrade", 5, 2) // Слот для улучшения. Обратите внимание на последний аргумент. Это - количество слотов.
}
override fun getInventoryName(): String = if(IC2.platform.isRendering) "My 2 Slots Macerator" else "My2SlotsMacerator" // Имя инвентаря
override fun getWrenchDropRate(): Float = 0.80f // Шанс успешного выбадения машины. Иначе падает механизм. От 0.0 до 1.0. 0.0 - 0%, 1.0 - 100%. За наводку спасибо Merisen
override fun getGuiContainer(entityPlayer: EntityPlayer): ContainerBase<TileEntityMy2SlotsMacerator> = ContainerMy2SlotsMacerator(entityPlayer, this) // Указываем контейнер
@SideOnly(Side.CLIENT)
override fun getGui(entityPlayer: EntityPlayer, isAdmin: Boolean): GuiScreen = GuiMy2SlotsMacerator(ContainerMy2SlotsMacerator(entityPlayer, this), entityPlayer.inventory) // Указываем GUI с переданным playerInventory
// Чтение прогресса из NBT
override fun readFromNBT(nbttagcompound: NBTTagCompound) {
super.readFromNBT(nbttagcompound)
this.progress = nbttagcompound.getShort("progress")
}
// Запись прогресса в NBT
override fun writeToNBT(nbttagcompound: NBTTagCompound) {
super.writeToNBT(nbttagcompound)
nbttagcompound.setShort("progress", this.progress)
}
fun gaugeProgressScaled(i: Int): Int = i * this.progress / 4000 // Прогресс
// Цикл для работы.
override fun updateEntityServer() {
super.updateEntityServer()
var needsInvUpdate = false
var newActive = this.active
if(this.progress >= 4000) { // 4000 - максимальный прогресс, если хотите сдеалть работу быстрее или медленнее уменьшаете или увеличиваете соответственно.
this.operate()
needsInvUpdate = true
this.progress = 0
newActive = false
}
val canOperate = this.canOperate()
if(this.energy > 0.0 && canOperate) {
--this.energy
newActive = true
}
if(newActive && this.progress.toInt() != 0) {
if(!canOperate || this.energy < 15.0) {
if(!canOperate) {
this.progress = 0
}
newActive = false
}
} else if(canOperate) {
if(this.energy >= 15.0) {
newActive = true
}
} else {
this.progress = 0
}
if(newActive && canOperate) {
this.progress = (this.progress + 300).toShort() // Работа. Если хотите сдеалть работу быстрее или медленнее увеличиваете или уменьшаете соответственно
this.energy -= 256.0 // Потребление энергии за тик
}
if(needsInvUpdate) {
this.markDirty()
}
if(newActive != this.active) {
this.active = newActive
}
for(i in 0 until this.upgradeSlot.size()) {
val stack = this.upgradeSlot.get(i)
if(stack != null && stack.item is IUpgradeItem && (stack.item as IUpgradeItem).onTick(stack, this)) {
super.markDirty()
}
}
}
// Работа со слотами. Забираем из входного, помещаем в выходной
private fun operate() {
this.operate(this.inputSlotA, this.outputSlotA)
this.operate(this.inputSlotB, this.outputSlotB)
}
private fun operate(inputSlot: InvSlotProcessable, outputSlot: InvSlotOutput) {
if(this.canOperate(inputSlot, outputSlot)) {
outputSlot.add(inputSlot.process().items)
inputSlot.consume()
}
}
// Можно ли положить предмет в выходной слот или забрать из входного.
private fun canOperate(): Boolean = this.canOperate(this.inputSlotA, this.outputSlotA) || this.canOperate(this.inputSlotB, this.outputSlotB)
private fun canOperate(inputSlot: InvSlotProcessable, outputSlot: InvSlotOutput): Boolean = if(inputSlot.isEmpty) { false } else { val output = inputSlot.process(); if(output == null) false else outputSlot.canAdd(output.items) }
override fun onGuiClosed(entityPlayer: EntityPlayer) {}
override fun getEnergy(): Double = this.energy
override fun useEnergy(amount: Double): Boolean = if(this.energy >= amount) { this.energy -= amount; true } else { false }
override fun getUpgradableProperties(): Set<UpgradableProperty> = EnumSet.of(UpgradableProperty.RedstoneSensitive, UpgradableProperty.ItemConsuming, UpgradableProperty.ItemProducing, UpgradableProperty.Augmentable)
}
Kotlin:
package com.heros.wlmod.gui
import com.heros.wlmod.container.ContainerMy2SlotsMacerator
import com.heros.wlmod.tile.TileEntityMy2SlotsMacerator
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.gui.inventory.GuiContainer
import net.minecraft.entity.player.InventoryPlayer
import net.minecraft.util.ResourceLocation
import net.minecraft.util.StatCollector
@SideOnly(Side.CLIENT)
class GuiMy2SlotsMacerator(container: ContainerMy2SlotsMacerator, private val playerInventory: InventoryPlayer) : GuiContainer(container) {
private val guiWidth = 214
private val guiHeight = 211
private val tileEntity: TileEntityMy2SlotsMacerator = container.base
init {
this.xSize = guiWidth
this.ySize = guiHeight
}
override fun initGui() {
super.initGui()
this.guiLeft = (this.width - this.guiWidth) / 2
this.guiTop = (this.height - this.guiHeight) / 2
}
override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) {
this.mc.textureManager.bindTexture(ResourceLocation("wlmod", "textures/gui/GUIX6Macerator.png"))
this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize)
val chargeLevel = Math.round(tileEntity.chargeLevel * 14.0f)
this.drawTexturedModalRect(this.guiLeft + 56, this.guiTop + 36 + 14 - chargeLevel, 176, 14 - chargeLevel, 14, chargeLevel)
val i1 = tileEntity.gaugeProgressScaled(24)
this.drawTexturedModalRect(this.guiLeft + 79, this.guiTop + 34, 176, 14, i1 + 1, 16)
}
override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) {
val s = StatCollector.translateToLocal("myic2addon.My2SlotsMachine.gui.name")
this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752)
this.fontRendererObj.drawString(StatCollector.translateToLocal("container.inventory"), 8, this.ySize - 96 + 2, 4210752)
}
}
Container
Kotlin:
package com.heros.wlmod.container
import com.heros.wlmod.tile.TileEntityMy2SlotsMacerator
import ic2.core.ContainerFullInv
import ic2.core.slot.SlotInvSlot
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.inventory.Slot
import net.minecraft.entity.player.InventoryPlayer
class ContainerMy2SlotsMacerator(entityPlayer: EntityPlayer, tileEntity: TileEntityMy2SlotsMacerator) : ContainerFullInv<TileEntityMy2SlotsMacerator>(entityPlayer, tileEntity, 166) {
init {
this.addSlotToContainer(SlotInvSlot(tileEntity.inputSlotA, 0, 47, 17))
this.addSlotToContainer(SlotInvSlot(tileEntity.inputSlotB, 0, 63, 17))
this.addSlotToContainer(SlotInvSlot(tileEntity.outputSlotA, 0, 113, 35))
this.addSlotToContainer(SlotInvSlot(tileEntity.outputSlotB, 0, 131, 35))
for (i in 0..1) {
this.addSlotToContainer(SlotInvSlot(tileEntity.upgradeSlot, i, 153, 26 + i * 18))
}
bindPlayerInventory(entityPlayer.inventory)
}
protected fun bindPlayerInventory(inventoryPlayer: InventoryPlayer?) {
val playerInvX = 26
var playerInvY = 132
for (i in 0 until 3) {
for (j in 0..8) {
this.addSlotToContainer(Slot(inventoryPlayer, j + i * 9 + 9, playerInvX + j * 18, playerInvY + i * 18))
}
}
playerInvY = 190
for (i in 0 until 9) {
this.addSlotToContainer(Slot(inventoryPlayer, i, playerInvX + i * 18, playerInvY))
}
}
override fun getNetworkedFields(): List<String> {
val ret = super.getNetworkedFields()
ret.add("progress")
return ret
}
}