Jump to content

Recommended Posts

Posted

Hello, I am having a bit of trouble giving the person right clicking my item, a random item out of the Minecraft Vanilla Items. Here's my code so far:

 

public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) {

	if (entityPlayer.capabilities.isCreativeMode) {
		return itemStack;
	}else {

		--itemStack.stackSize;

		entityPlayer.inventory.addItemStackToInventory(new ItemStack(itemRand, 1));

	}

	return itemStack;
}

}

 

itemRand is a variable inside of the Minecraft Item class.

Posted

Well, what are you trying to use this for, ultimately? If you change the item to a random one, then it will most likely end up being a vanilla item. And then you wouldn't be able to change it again from Item#onItemRightClick.

 

You could probably create a custom item that simply takes the texture of another item, changing that item randomly each time it is used.

I like to make mods, just like you. Here's one worth checking out

Posted

This item is essentially a "reward bag", when you right click the item, it deletes the bag, and gives you a random item.

 

I personally have no idea how to do this, since the itemRand in the Item class cannot be using in the ItemStack method.

Posted

itemRand is a Random object, meaning you use it to get random numbers - it's not an Item. You can use itemRand to get a random Item from the list of all registered items, or you could make your own list of items you want to give as rewards and select randomly from that. In either case, I suggest you start by brushing up on some basic Java, as it will make your journey much easier.

 

For starters, here is the documentation on the Random class. That will help you figure out how to get a random number ;)

Posted

I know basic Java. Just very new to modding, don't know how everything works. And yes, I know itemRand isn't an item. :P

 

I will take your advice and use the object to grab all of the registered items in Minecraft.

Posted

Osmthing you may be able to do is make a HashMap of all of the Items that can be awarded (this would filter out non-accessible items and give you more customization) Then you could get a random int, from itemRand and get the item stack that corresponds to that item in the HashMap.

Don't be afraid to ask question when modding, there are no stupid question! Unless you don't know java then all your questions are stupid!

Posted

i think this will work good 8)

add this and replace itemrand with stack

Random r = new Random();
ItemStack stack = new ItemStack(Item.itemList[r.nextInt(Item.itemList.length) + 1], r.next(3 /*MAX QUANTITY*/) /* this will generate random quantity */)

hope this work!

Posted

@Mecblader Thank you for your suggestion, I will try hash maps if I don't find a better solution to this.

 

@AlexStone There are a few issues with that code.

1. Where are you getting itemList from?

2. Where are you getting r.next from?

I'm guessing r.nextInt();

Posted

Yea, using a random each time crashes the game.

 

I tried using the code AlexStone provided, with a custom itemList I created. It does crash the game.

 

Even if I were to do:

 

ItemStack stack = new ItemStack(ItemList.itemList[r.nextInt()];

It would still end up crashing the game.

 

I will try a few other things, see if they work.

Posted

I haven't tested this code yet, so yeah:

public static Item getRandomItem() {
	Item i = null;
	Object[] objects = Item.itemRegistry.getKeys().toArray();
	Object select = objects[utilRF.RANDOM.nextInt(objects.length)];
	if(select instanceof Item) {
		i = (Item) select;
	} else {
		return getRandomItem();
	}
	return i;
}

 

UtilRF.RANDOM is a Random object.

Kain

Posted

It only returns it if the object isn't an instance of an item, which is unlikely.

For some reason it returns it everytime. And, why is there:

UtilRF.RANDOM.nextInt()?

Instead of UtilRF.nextInt()

Posted

While it is nice to use elegant coding, or impressive to use tricky coding, sometimes I think it is best to just do something simple and "brute force".  Why not just do use a random int to pick from a case statement and just list out all the items you want to have possible.  Sure it will be fairly long list (although not really that long), but it will work very simply and should perform well too.  The nice thing is that it is gives full control and won't have any weird occasional issues where you pick some unusable item out of the gameregistry.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

When you right click this bag, I want it to give you 1 item. The item is chosen from every single item in the game, it would be much more convenient to not have to make 300+ item stacks. :P

Posted

Define a new List where you store/cache all possible items:

private List<Item> filteredItems = null;

 

In your onItemUse method, do this:

- If the list is uninitialized, initialize it and fill the array with all items:

        if( filteredItems == null ) {
            filteredItems = new ArrayList<Item>();
            Iterators.addAll(filteredItems, Iterators.filter(Iterators.forArray(Item.itemsList), Predicates.notNull()));
        }

The last statement in the block is basically, it filters the itemsList array by throwing out any null value which are in there (basically all unassigned/free items) and adds them to your filteredItems list.

 

- After that, get a random element from your filteredItems list and make a new ItemStack out of that element:

        ItemStack stack = null;
        if( items.size() > 0 ) {
            stack = new ItemStack(items.get(par2EntityPlayer.getRNG().nextInt(items.size())), 1);
        }

 

The only problem I see is that some items have multiple metadata values as subtypes (dyes and potions are the most prominent example) and you'll get only the first item subtype

Don't ask for support per PM! They'll get ignored! | If a post helped you, click the "Thank You" button at the top right corner of said post! |

mah twitter

This thread makes me sad because people just post copy-paste-ready code when it's obvious that the OP has little to no programming experience. This is not how learning works.

Posted

It only returns it if the object isn't an instance of an item, which is unlikely.

For some reason it returns it everytime. And, why is there:

UtilRF.RANDOM.nextInt()?

Instead of UtilRF.nextInt()

 

I don't use UtilRF.nextInt() because UtilRF doesn't have a method called nextInt. I keep a static Random object in the class whenever I need to use one.

Kain

Posted

Ok, I've gotten the method to work. It also returns blocks too, since each block has an ItemBlock version.

public static Item getRandomItem() {
	Item i = null;
	int length = Item.itemRegistry.getKeys().toArray().length;
	Object select = Item.itemRegistry.getObjectById(UtilRF.RANDOM.nextInt(length));
	if(select != null && select instanceof Item) {
		i = (Item) select;
	} else {
		return getRandomItem();
	}
	return i;
}

 

100% sure to work, tested.

Kain

Posted

Ok, I've gotten the method to work. It also returns blocks too, since each block has an ItemBlock version.

public static Item getRandomItem() {
	Item i = null;
	int length = Item.itemRegistry.getKeys().toArray().length;
	Object select = Item.itemRegistry.getObjectById(UtilRF.RANDOM.nextInt(length));
	if(select != null && select instanceof Item) {
		i = (Item) select;
	} else {
		return getRandomItem();
	}
	return i;
}

 

100% sure to work, tested.

I got confused on that UtilRF.RANDOM part, I wasn't thinking...lol

Didn't know UtilRF was the class. lol

 

Anyways, testing the code.

 

Doesn't seem as if the code is working, does nothing actually, here is my class:

package com.hex.lootbag;

import java.util.Random;

import com.hex.hexcore.HexCore;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

public class ItemLootBag extends Item {

public ItemLootBag() {

	setUnlocalizedName("itemLootBag");
	setCreativeTab(CreativeTabs.tabAllSearch);
	setTextureName("lootbag:ItemLootBag");
	setMaxStackSize(1);

}

public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) {

	System.out.println("Working!");

	if (player.capabilities.isCreativeMode) {
		getRandomItem();
		return item;
	}else{
		--item.stackSize;
		getRandomItem();
		return item;
	}
}

static Random RANDOM = new Random();

public static Item getRandomItem() {
	Item i = null;
	int length = Item.itemRegistry.getKeys().toArray().length;
	Object select = Item.itemRegistry.getObjectById(ItemLootBag.RANDOM.nextInt(length));
	if(select != null && select instanceof Item) {
		i = (Item) select;
	} else {
		return getRandomItem();
	}
	return i;
}

}

Posted

FTFY

package com.hex.lootbag;

import java.util.Random;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

public class ItemLootBag extends Item {

public ItemLootBag() {

	setUnlocalizedName("itemLootBag");
	setCreativeTab(CreativeTabs.tabAllSearch);
	setTextureName("lootbag:ItemLootBag");
	setMaxStackSize(1);

}

public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) {

	System.out.println("Working!");

	if (player.capabilities.isCreativeMode) {
		player.dropPlayerItemWithRandomChoice(new ItemStack(getRandomItem(), 1), false);
		return item;
	}else{
		--item.stackSize;
		player.dropPlayerItemWithRandomChoice(new ItemStack(getRandomItem(), 1), false);
		return item;
	}
}

static Random RANDOM = new Random();

public static Item getRandomItem() {
	Item i = null;
	int length = Item.itemRegistry.getKeys().toArray().length;
	Object select = Item.itemRegistry.getObjectById(ItemLootBag.RANDOM.nextInt(length));
	if(select != null && select instanceof Item) {
		i = (Item) select;
	} else {
		return getRandomItem();
	}
	return i;
}

}

Posted

You didn't give the player anything. The method returns an item, it doesn't automatically give the player the item.

Sorry, was spacing out, was like 2AM when I looked at that code. :P

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Minecraft 1.21.4 requires a new model definition file for each item, which you don't have. These can be created through Data Generation, specifically the ModelProvider, BlockModelGenerators and ItemModelGenerators classes.
    • Hi,  I'm using Forge 47.3.0 for Minecraft 1.20.1 I apologise if this is obvious I am very new to modding for Minecraft. I sucessfully made a mod that launched without errors or crashes (without it doing anything) but in order to add the features I need, I need to add "Custom Portal API [Forge]" as a dependency. However no matter the way I've tried to acheive this, it crashes. I am pretty sure it's not the way I'm putting it in the repositories, the dependencies or the way I'm refrencing it, as I've a hundred diffrent combinations and multiple Maven methods. And on all those diffrent variations I still get this crash: pastebin.com/UhumzZCZ Any tips would be invaluable as I've been loosing my mind over this!
    • Hi, i'm really having problems trying to set the texture to my custom item. I thought i'm doing everything correctly, but all i see is the missing texture block for my item. I am trying this for over a week now and getting really frustrated. The only time i could make the texture work, was when i used an older Forge version (52.0.1) for Minecraft (1.21.4). Was there a fundamental change for textures and models somewhere between versions that i'm missing? I started with Forge 54.1.0 and had this problem, so in my frustration i tried many things: Upgrading to Forge 54.1.1, created multiple new projects, workspaces, redownloaded everything and setting things up multiple times, as it was suggested in an older thread. Therea are no errors in the console logs, but maybe i'm blind, so i pasted the console logs to pastebin anyway: https://pastebin.com/zAM8RiUN The only time i see an error is when i change the models JSON file to an incorrect JSON which makes sense and that suggests to me it is actually reading the JSON file.   I set the github repository to public, i would be so thankful if anyone could take a look and tell me what i did wrong: https://github.com/xLorkin/teleport_pug_forge   As a note: i'm pretty new to modding, this is my first mod ever. But i'm used to programming. I had some up and downs, but through reading the documentation, using google and experimenting, i could solve all other problems. I only started modding for Minecraft because my son is such a big fan and wanted this mod.
    • Please read the FAQ (link in orange bar at top of page), and post logs as described there.
    • Hello fellow Minecrafters! I recently returned to Minecraft and realized I needed a wiki that displays basic information easily and had great user navigation. That’s why I decided to build: MinecraftSearch — a site by a Minecraft fan, for Minecraft fans. Key Features So Far Straight-to-the-Point Info: No extra fluff; just the essentials on items, mobs, recipes, loot and more. Clean & Intuitive Layout: Easy navigation so you spend less time scrolling and more time playing. Optimized Search: Search for anything—items, mobs, blocks—and get results instantly. What I’m Thinking of Adding More data/information: Catch chances for fishing rod, traveling villager trades, biomes info and a lot more. The website is still under development and need a lot more data added. Community Contributions: Potential for user-uploaded tips for items/mobs/blocks in the future. Feature Requests Welcome: Your ideas could shape how the wiki evolves! You can see my roadmap at the About page https://minecraftsearch.com/about I’d love for you to check out MinecraftSearch and see if it helps you find the info you need faster. Feedback is crucial—I want to develop this further based on what the community needs most, so please let me know what you think. Thanks, and happy crafting!
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.