在Swift中进行类型转换arc4random_uniform()

时间:2015-12-19 18:48:58

标签: ios swift

我在应用程序中有一个方法,我正在创建玩战争,卡片游戏,这是故障。它应该随机生成一个带有arc4random_uniform的数字,然后使用该数字来确定玩家拥有的牌的套装,等级和值。在此之后,套装和等级用于显示卡片图像。这样做除了它只显示从8到Ace的卡片。我认为它与randCard的类型转换有关,因为我在逻辑上找不到任何其他错误。

@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 个答案:

答案 0 :(得分:4)

问题与类型转换无关。 您从1 ... 52范围内的随机数计算value的逻辑 是错的。你必须减去,而不是除以1,2,3或4 抵消。 (想象一下可能的结果是什么 如果value = (Int)(randCard)/4在40 ... 52范围内,则为randCard。)

更简单的方法是使用“余数运算符”%

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