2013-01-23 62 views
0

我對JS很新,但我想製作一個非常基本的RPG物品生成器,它受概率控制。這是我想出的。物品發生器控制的概率

我有一個itemtype部分的問題。在物品類型完成概率卷之後,我想隨機生成武器,配件和裝甲下的一組元素。

它應該是像稀有劍,罕見的工作人員,共同的手套,或共同的胸部。

我該如何解決這個問題?

var rarityNum = Math.floor(1 + Math.random() * 100); 
var itemNum = Math.floor(1 + Math.random() * 100); 

var rarity; 
if (rarityNum > 75) { rarity = "rare "; } 
else if (rarityNum > 65) { rarity = "uncommon "; } 
else { rarity = "common "; } 

var weapons =["sword","bow","staff"]; 
var armors =["chest","leggings","gloves"]; 

var itemtype; 
if (itemNum > 51) { itemtype = "weapons"; } 
else if (itemNum > 40) { itemtype = "accessories"; } 
else { itemtype = "armors"; } 

document.write (rarity); 
document.write (itemtype); 

回答

1
var item = { 
    "Weapon" : ["Sword", "Bow"], 
    "Armor" : ["Chest", "Leggings", "Gloves", "Helmet"], 
    "Access" : ["Ring", "Bracelet", "Amulet"] 
}; 

var rareness = Math.floor(1 + Math.random() * 100) 
    , item_type = Math.floor(1 + Math.random() * 100) 
;//randoms 

var rarity = 
    rareness > 75? "Rare"  : 
    rareness > 65? "Uncommon" : 
        "Common" ; 

var type = 
    item_type > 51? "Weapon" : 
    item_type > 40? "Access" : 
        "Armor" ; 

var item_list = item[type] 
    , item_index = Math.round(Math.random() * (item_list.length - 1)) 
;//items 

document.write(rarity + " " + item_list[item_index]); 
+0

但如果武器有超過裝甲不同的數組的長度? – user2002516

+0

我已更新代碼以向您展示如何處理可變長度的項目列表;-) – THEtheChad