2014-09-29 137 views
1

我想製作一個遊戲,您可以升級您的特定物品。新項目的質量將是隨機的,基於這樣的:選擇隨機數的快速概率?

10% worse - 35% better then current item level = 55% chance 
36% better to 90% better then current item level = 35% chance 
91% better to 200% better then current item level = 5% chance 
201% better to 500% better then current item level = 2.5% chance 
500% better to 2000% better then current item level = 2.5% chance 

我怎麼會去製作它,以便產生一個隨機數會有的,例如,55%的機會只有35%好?我有一個裂縫,想出了這個(忽略%數字,我只是用這個測試)。

let randomNumber = Int(arc4random_uniform(1000)) 


if randomNumber <= 700 { 
    println("hey") 
    var newLevel = (Double(Double(randomNumber)/700.00) + 0.1) * Double(pickDamage) 

} else if randomNumber <= 800 && randomNumber > 700 { 
    var newLevel = (Double(Double(randomNumber)/700.00) + 1.00) * Double(pickDamage) 
} else if randomNumber <= 1000 && randomNumber > 950 { 
    var newLevel = (Double(Double(randomNumber)/700.00) + 2.00) * Double(pickDamage) 
} 

但是,這並不是按照我想要的方式做到的。

+0

你無法產生隨機數,是你的問題嗎? – Suresh 2014-09-29 05:25:00

回答

4

爲什麼不使用斯威夫特switch語句與模式匹配相結合:

// create a random percent, with a precision of one decimal place 
func randomPercent() -> Double { 
    return Double(arc4random() % 1000)/10.0; 
} 

let randomNumber = randomPercent() 
switch(randomNumber) { 
case 0..<55: 
    println("10% worse - 35% better then current item level") 
case 55..<90: 
    println("36% better to 90% better then current item level") 
case 90..<95: 
    println("91% better to 200% better then current item level") 
case 95..<97.5: 
    println("201% better to 500% better then current item level") 
default: 
    println("500% better to 2000% better then current item level") 
} 

這使得該邏輯非常清晰。

4

我認爲統一與可啉的解決方案將是最好的:

func randomPermille() -> Int { 
    return Int(arc4Random(1000)) 
} 

let randomNumber = randomPermille() 
switch(randomNumber) { 
    case 0..<550: 
     println("10% worse - 35% better then current item level") 
    case 550<900: 
     ... and so on 

它通常是一個壞主意,Float S或Double我們比較,因爲漂浮在整個整數點古怪的Int秒。 (10.0的分割看起來特別令人擔憂,但最後可能並不重要)