Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

[Resolved] Random Selection

Status
Not open for further replies.

Mac

Member

What would be the code to ask for a random item, weapon or armour in a certain area.... e.g.

Random Item(choice of random item id)
Code:
rand_item.id(1, 2 ,3 ,4 ,5 ,8, 20)

Hope thats understandable.
 

Anonymous

Guest

item = $data_items[rand($data_items.size)]
weapon = $data_weapons[rand($data_weapons.size)]
armor = $data_armors[rand($data_armors.size)]

Will give you one of those at random. If you only want one within a range of ids, try:

id_arr = [1, 2, 3, 4, 5, 8, 20]
item = $data_items[id_arr[rand(id_arr.size)]]
 
I tried to plug it in and got a syntax error too. I broke it down into more lines and it worked though:

id_arr = [1, 2, 3, 4, 5, 8, 20]
item_gained=id_arr[rand(id_arr.size)]
$game_party.gain_item(item_gained,1)
 
I prefer to use a method in the Array class for something like this.

Code:
class Array
  def random
    return self[rand(self.size)]
  end
end

Just add that in your scripts somewhere.

So if you wanted to gain a random item from a list of item ids
Code:
ids = [a, b, c, d]
$game_party.gain_item(ids.random, 1)

Simple, but effective.
 
Status
Not open for further replies.

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top