By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,527 Members | 1,184 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,527 IT Pros & Developers. It's quick & easy.

JS - Item generator controlled by probability

P: 1
I'm pretty new to JS but I want to make a very basic RPG item generator that is controlled by probability. This is what I have come up with.

I have a problem with the itemtype part. After the probability roll is done for itemtype, I want to randomly generate a group of elements under weapons, accessories, and armors.

It should be something like Rare Sword, Uncommon staff, Common gloves, or Common Chest.

How do I go about this?

Expand|Select|Wrap|Line Numbers
  1. var rarityNum = Math.floor( 1 + Math.random() * 100 );
  2. var itemNum = Math.floor( 1 + Math.random() * 100 );
  3.  
  4. var rarity;
  5. if ( rarityNum > 75 ) { rarity = "rare "; }
  6. else if ( rarityNum > 65 ) { rarity = "uncommon "; }
  7. else { rarity = "common "; }
  8.  
  9. var weapons =["sword","bow","staff"];
  10. var armors =["chest","leggings","gloves"];
  11.  
  12. var itemtype;
  13. if ( itemNum > 51 ) { itemtype = "weapons"; }
  14. else if ( itemNum > 40 ) { itemtype = "accessories"; }
  15. else { itemtype = "armors"; }
  16.  
  17. document.write (rarity);
  18. document.write (itemtype);
  19.  
Jan 23 '13 #1
Share this Question
Share on Google+
2 Replies


Rabbit
Expert Mod 10K+
P: 12,430
I'm confused by what your question is because, from the code you have, it looks like you know how to pick an item by probability. Perhaps not in the way I would do it but you're doing it nonetheless.
Jan 23 '13 #2

Dormilich
Expert Mod 5K+
P: 8,639
I think the problem is not about choosing, but how to combine each chosen category.

currently what is missing is that you have not chosen which of the weapons/accessories/armors to use.

for that I’d also recomment to couple your data more, instead of using globals (not to mention that document.write() will shoot you in the foot sooner than later).

Expand|Select|Wrap|Line Numbers
  1. var itemStore = {
  2.   rarity: ["rare", "uncommon", "common"],
  3.   type: {
  4.     weapons: ["sword", "bow", "staff"],
  5.     armors:  ["chest", "leggings", "gloves"],
  6.     accessories: [/* ... */]
  7. };
then you only need to break down the probabilities to indices and you can combine.
Expand|Select|Wrap|Line Numbers
  1. // say you have randomly chosen:
  2. // rarity_index  1
  3. // item_type     "weapons"
  4. // item_index    2
  5. var chosenItem = itemStore.rarity[rarity_index] + " " + itemStore[item_type][type_index];
  6.  
  7. // which would get you: "uncommon staff"
Jan 25 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.