我正在尝试制作一款可以升级您特定项目的游戏。新项目的质量将是随机的,基于以下内容:
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 :(得分:6)
为什么不将Swift 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")
}
这使得逻辑非常明确。
答案 1 :(得分:4)
我认为用ColinE统一你的解决方案是最好的:
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
或Double
s与Int
s进行比较通常是一个坏主意,因为整个整数周围的浮点很奇怪。 (10.0的划分对我来说似乎特别令人担忧,但最终可能并不重要)