我在一个应用程序中有一个方法,我正在创建玩战争,纸牌游戏,这是故障。它应该随机生成一个arc4random_均匀的数字,然后用这个数字来确定玩家拥有的牌的套牌、等级和价值。接下来,套装和等级用于显示卡图像。这是有效的,除了它只显示从8到王牌。我想这和我打字的兰卡德有关,因为我在逻辑上找不到其他问题。
@IBAction func showPlayerCard(sender: AnyObject) {
var randCard = arc4random_uniform(52)+1
var suit = ""
var rank = ""
var value = 0
if(randCard <= 13){
suit = " of Clubs"
}else if(randCard <= 26){
suit = " of Diamonds"
value = (Int)(randCard)/2
}else if(randCard <= 39){
suit = " of Hearts"
value = (Int)(randCard)/3
}else if(randCard <= 52){
suit = " of Spades"
value = (Int)(randCard)/4
}
switch value {
case 1:
rank = "2"
value = 2
case 2:
rank = "3"
value = 3
case 3:
rank = "4"
value = 4
case 4:
rank = "5"
value = 5
case 5:
rank = "6"
value = 6
case 6:
rank = "7"
value = 7
case 7:
rank = "8"
value = 8
case 8:
rank = "9"
value = 9
case 9:
rank = "10"
value = 10
case 10:
rank = "Jack"
value = 11
case 11:
rank = "Queen"
value = 12
case 12:
rank = "King"
value = 13
case 13:
rank = "Ace"
value = 14
default:
rank = ""
value = 0
}
var cardName = rank + suit
if(rank == ""){
cardName = "Ace" + suit
}
self.firstCardImageView.image = UIImage(named: cardName)
如果有人对如何解决这个问题有建议,我们将不胜感激。
哦,我忘了加上,我放在底部的if(rank==”),因为有时候随机生成的卡会是空白的;我相信这是默认情况被触发的结果。
最佳答案
这个问题与类型转换无关。
从1范围内的随机数计算value
的逻辑。。。五十二
是错误的。不用除以1、2、3或4,你得减去
偏移量。(想象一下value = (Int)(randCard)/4
如果randCard
在40范围内。。。52.)
更简单的方法是使用“余数运算符”%
:
let randCard = Int(arc4random_uniform(52)) // 0, 1, ..., 51
let suit = randCard / 13 + 1 // 1, 2, 3, 4
let value = randCard % 13 + 1 // 1, 2, ..., 13
或者只是
let suit = Int(arc4random_uniform(4)) + 1 // 1, 2, 3, 4
let value = Int(arc4random_uniform(13)) + 1 // 1, 2, ..., 13
关于ios - 在Swift中类型转换arc4random_uniform(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34374188/