Коробочки с сюрпризом

Версия Minecraft
1.7.10
Использовал код из одной темы,впихнул вместо ванильных вещей , свои из мода,но оно не работает,выпадают только ванильные
Код:
public class rndbox extends Item {

    private ArrayList<DropsItem> list_drops = new ArrayList<DropsItem>();

    public rndbox() {
        super();
        setCreativeTab(CreativeTabs.tabMisc);
       this.setTextureName("testmod:rndbox");

        addItemWithChance(25F, Items.stick);
        addItemWithChance(25F, Items.beef);
       addItemWithChance(25F, Main.coin1);
       addItemWithChance(25F, Main.coin2);
    }

    @Override
    public ItemStack onItemRightClick(ItemStack is, World world, EntityPlayer player) {
        if (!world.isRemote) {
            float p = world.rand.nextFloat() * getChanceMax();
            ItemStack item_drop = null;
            if (list_drops != null)
                for (int i = 0; i < list_drops.size(); ++i) {
                    if (list_drops.get(i) != null) {
                        if (list_drops.get(i).getChanceA() <= p && list_drops.get(i).getChanceB() > p) {
                            item_drop = list_drops.get(i).getItem().copy();
                            //System.out.println("onItemRightClick - " + p + ",  " + item_drop);
                            break;
                        }
                    }
                }
            if (item_drop != null) {
                player.inventory.addItemStackToInventory(item_drop);
                --is.stackSize;
            }
        }
        return is;
    }

    public void addItemWithChance(float chance, Object item) {
        float a = 0F;
        if (list_drops != null && list_drops.size() > 0) {
            float b = -1F;
            for (int i = 0; i < list_drops.size(); ++i) {
                if (list_drops.get(i) != null) {
                    if (b < list_drops.get(i).getChanceB()) b = list_drops.get(i).getChanceB();
                    else continue;
                } else continue;
            }
            if (b != -1F) a = b;
        }
        list_drops.add(new DropsItem(a, a + chance, item));
    }

    public float getChanceMax() {
        float a = 0F;
        if (list_drops != null && list_drops.size() > 0) {
            float b = -1;
            for (int i = 0; i < list_drops.size(); ++i) {
                if (list_drops.get(i) != null) {
                    if (b < list_drops.get(i).getChanceB()) b = list_drops.get(i).getChanceB();
                    else continue;
                } else continue;
            }
            if (b != -1) a = b;
        }
        return a;
    }

    private static class DropsItem {

        private ItemStack item;
        private float chanceA;
        private float chanceB;

        private DropsItem(float chanceA, float chanceB, Object item) {
            if (item == null) return;
            if (item != null) {
                if (item instanceof Block) this.item = new ItemStack((Block)item);
                else if (item instanceof Item) this.item = new ItemStack((Item)item);
                else if (item instanceof ItemStack) this.item = (ItemStack)item;
                //this.item = item;
            }
            this.chanceA = chanceA;
            this.chanceB = chanceB;
        }

        public ItemStack getItem() {
            return item;
        }

        public float getChanceA() {
            return chanceA;
        }

        public float getChanceB() {
            return chanceB;
        }

    }

}
И еще вопрос,как сделать проверку на заполненность инвентаря,что бы если инвентарь заполнень ничего не происходило и выдавало в чат что то типо "Инвентарь переполнен"
 
Решение
Java:
public class ItemRandom extends Item {

    @Override
    public ItemStack onItemRightClick(ItemStack is, World world, EntityPlayer player) {

        ArrayList<ItemWithChanceEvent.ItemWithChance> list_rate_drops = new ArrayList<ItemWithChanceEvent.ItemWithChance>();

        //Даём конструктору эвента аргументы.
        //Give the constructor event's arguments.
        ItemWithChanceEvent event = new ItemWithChanceEvent(list_rate_drops, is, player);

        //Добаваяем предметы с шансом.
        //Adding items with chance.
        event.addItemWithChance(30F, Items.diamond);
        event.addItemWithChance(30F, SMTMagic.item.teleport);
        event.addItemWithChance(30F, SMTTechnology.item.itemsTechnology)...

timaxa007

Модератор
5,831
409
672
На первый вопрос был подобный вопрос и подобный ответ. Твои предметы который ты указывал зарегистрированы, после твоей "коробки с сюрпризом".
На второй вопрос, просто пройтись циклом по инвентарю, если каждый слот != null, то ни чего не делать.
 
timaxa007 написал(а):
На первый вопрос был подобный вопрос и подобный ответ. Твои предметы который ты указывал зарегистрированы, после твоей "коробки с сюрпризом".
На второй вопрос, просто пройтись циклом по инвентарю, если каждый слот != null, то ни чего не делать.

пример на 1 слот и конечное действие можно?
 

timaxa007

Модератор
5,831
409
672
Java:
public class ItemRandom extends Item {

    @Override
    public ItemStack onItemRightClick(ItemStack is, World world, EntityPlayer player) {

        ArrayList<ItemWithChanceEvent.ItemWithChance> list_rate_drops = new ArrayList<ItemWithChanceEvent.ItemWithChance>();

        //Даём конструктору эвента аргументы.
        //Give the constructor event's arguments.
        ItemWithChanceEvent event = new ItemWithChanceEvent(list_rate_drops, is, player);

        //Добаваяем предметы с шансом.
        //Adding items with chance.
        event.addItemWithChance(30F, Items.diamond);
        event.addItemWithChance(30F, SMTMagic.item.teleport);
        event.addItemWithChance(30F, SMTTechnology.item.itemsTechnology);
        event.addItemWithChance(25F, new ItemStack(Items.coal, 1, 0));
        event.addItemWithChance(25F, new ItemStack(Items.coal, 1, 1));

        //После инстанций эвентов.
        //Post instance events.
        MinecraftForge.EVENT_BUS.post(event);

        //Если эвент отменён, то продолжать выполнять код не должен.
        //If the event is canceled, then continue to execute code should not.
        if (event.isCanceled()) return is;

        if (!world.isRemote) {

            //Переделываем ItemWithChance для ChanceDropItem.
            //Remake ItemWithChance for ChanceDropItem.
            ArrayList<ChanceDropItem> list_drops_item = new ArrayList<ChanceDropItem>();
            if (!list_rate_drops.isEmpty())
                for (ItemWithChanceEvent.ItemWithChance cdi : list_rate_drops)
                    addItemWithChance(list_drops_item, cdi.getChance(), cdi.getItem());

            if (!list_drops_item.isEmpty()) {
                float maxChance = getChanceMax(list_drops_item);
                float p = world.rand.nextFloat() * maxChance;
                ItemStack item_drop = null;
                for (int i = 0; i < list_drops_item.size(); ++i) {
                    if (list_drops_item.get(i) != null) {
                        if (list_drops_item.get(i).getChanceStart() <= p && list_drops_item.get(i).getChanceEnd() > p) {
                            item_drop = list_drops_item.get(i).getItem().copy();
                            System.out.println("Item: " + item_drop + " (" + p + " / " + maxChance + ")");
                            break;
                        }
                    }
                }
                if (item_drop != null) {
                    --is.stackSize;
                    //Если нельзя положить в инвентарь предмет, то
                    if (!player.inventory.addItemStackToInventory(item_drop))
                        //То бросаеться в мир (если эвент позволит).
                        player.dropPlayerItemWithRandomChoice(item_drop, false);//Второй аргумент безполезен.
                   
                }
            }
        }
        return super.onItemRightClick(is, world, player);
    }

    private static void addItemWithChance(ArrayList<ChanceDropItem> list_drops, float chance, Object item) {
        if (list_drops == null || item == null || chance <= 0F) return;
        float tempChance = 0F;
        if (!list_drops.isEmpty()) {
            for (int i = 0; i < list_drops.size(); ++i) {
                if (list_drops.get(i) != null) {
                    if (tempChance < list_drops.get(i).getChanceEnd()) tempChance = list_drops.get(i).getChanceEnd();
                    else continue;
                } else continue;
            }
        }
        list_drops.add(new ChanceDropItem(tempChance, tempChance + chance, item));
    }

    private static float getChanceMax(ArrayList<ChanceDropItem> list_drops) {
        float maxChance = 0F;
        if (list_drops != null && !list_drops.isEmpty()) {
            for (int i = 0; i < list_drops.size(); ++i) {
                if (list_drops.get(i) == null) continue;
                if (maxChance < list_drops.get(i).getChanceEnd()) maxChance = list_drops.get(i).getChanceEnd();
                else continue;
            }
        }
        return maxChance;
    }

    private static class ChanceDropItem {

        private ItemStack item;
        private float chanceStart;
        private float chanceEnd;

        public ChanceDropItem(float chanceStart, float chanceEnd, Object item) {
            if (item == null) return;
            else if (item instanceof Block) this.item = new ItemStack((Block)item);
            else if (item instanceof Item) this.item = new ItemStack((Item)item);
            else if (item instanceof ItemStack) this.item = (ItemStack)item;
            else return;
            this.chanceStart = chanceStart;
            this.chanceEnd = chanceEnd;
        }

        public ItemStack getItem() {
            return item;
        }

        public float getChanceStart() {
            return chanceStart;
        }

        public float getChanceEnd() {
            return chanceEnd;
        }

    }

}
Java:
public class ItemWithChanceEvent extends PlayerEvent {

    /**
    С помощью какого предмета будет выпадать "предмет с шансом".</br>
    With the help of some item will drop "item with chance".
    **/
    public final ItemStack item_use;
    /**
    Список "предмет с шансом".</br>
    List "item with chance".
    **/
    public ArrayList<ItemWithChance> list_drops;

    public ItemWithChanceEvent(ArrayList<ItemWithChance> list_drops, ItemStack item_use, EntityPlayer player) {
        super(player);
        this.item_use = item_use;
        this.list_drops = list_drops;
    }

    public void addItemWithChance(float chance, Object item) {
        if (item == null || chance <= 0F) return;
        this.list_drops.add(new ItemWithChance(chance, item));
    }

    public static class ItemWithChance {

        private ItemStack item;
        private float chance;

        public ItemWithChance(float chance, Object item) {
            if (item == null) return;
            else if (item instanceof Block) this.item = new ItemStack((Block)item);
            else if (item instanceof Item) this.item = new ItemStack((Item)item);
            else if (item instanceof ItemStack) this.item = (ItemStack)item;
            else return;
            if (chance <= 0F) return;
            else this.chance = chance;
        }

        public ItemStack getItem() {
            return item;
        }

        public float getChance() {
            return chance;
        }

    }

}
Java:
MinecraftForge.EVENT_BUS.register(new EventsForge());
Java:
public class EventsForge {
    @SubscribeEvent
    public void changeItemWithChance(ItemWithChanceEvent event) {
        //Добавляем, с помощью эвента, "предмет с шансом".
        //Adding through event, "item with chance".
        event.addItemWithChance(15F, Items.nether_star);
        //Алмаз(-ы) будет(-ут) убран(-ы).
        //Diamond(-s) will be removed.
        if (!event.list_drops.isEmpty())
            for (int i = 0; i < event.list_drops.size(); ++i) {
                ItemWithChanceEvent.ItemWithChance iwc = event.list_drops.get(i);
                if (iwc.getItem() != null && iwc.getItem().getItem() != null) {
                    if (iwc.getItem().getItem() == Items.diamond) event.list_drops.remove(i);
                }
            }
        //Если игрок будет в воде, то эвент будет отменён.
        //If a player is in water, then the event will be canceled.
        if (event.entityPlayer.isInWater()) event.setCanceled(true);

        boolean isFull = true;
        for (ItemStack is : event.entityPlayer.inventory.mainInventory) {
            if (is == null) {
                isFull = false;
                break;
            }
        }
        if (isFull) event.setCanceled(true);//Если инвентарь полон, то эвент будет отменён.
    }

}
 
Последнее редактирование:

timaxa007

Модератор
5,831
409
672
Dankis написал(а):
а последние 2 кода куда?
Первый к примеру в preInit. Второй это класс.

Dankis написал(а):
Пожалуйста.

Dankis написал(а):
как при выпадении определенного предмета написать всем в чат и вызвать феерверк ?
При определённом предмете, писать в чат от имени сервера, если не ошибаюсь, и заспавнить фейерверки.
 
timaxa007 написал(а):
Dankis написал(а):
а последние 2 кода куда?
Первый к примеру в preInit. Второй это класс.

Dankis написал(а):
Пожалуйста.

Dankis написал(а):
как при выпадении определенного предмета написать всем в чат и вызвать феерверк ?
При определённом предмете, писать в чат от имени сервера, если не ошибаюсь, и заспавнить фейерверки.

Как и где выцепить что выпал именно этот предмет
 

timaxa007

Модератор
5,831
409
672
В предмете:
Код:
if (item_drop != null) {
	--is.stackSize;
	//Если нельзя положить в инвентарь предмет, то
	if (!player.inventory.addItemStackToInventory(item_drop))
		//То бросаеться в мир (если эвент позволит).
		player.dropPlayerItemWithRandomChoice(item_drop, false);//Второй аргумент безполезен.
}


Проверяешь у item_drop.
 
Сверху