IOS Swift 2.0卡改组功能

时间:2016-03-10 17:34:03

标签: ios swift function

Noob在这里,我正在尝试使用52张牌的标准牌创建纸牌游戏。这是我想要成为一个函数的代码所以我不必每次都手动写出来。我正在创建5个不同的玩家,所以这将被复制到其他玩家。

func firstPlayerCardShuffle() {
var firstPlayerCard1Num = (Int(arc4random_uniform(UInt32(13)) + 2))
var firstPlayerCard1Suit = suits[Int(arc4random_uniform(UInt32(suits.count)))]
var firstPlayerCard1 = "\(firstPlayerCard1Num) of \(firstPlayerCard1Suit)"

var firstPlayerCard2Num = (Int(arc4random_uniform(UInt32(13)) + 2))
var firstPlayerCard2Suit = suits[Int(arc4random_uniform(UInt32(suits.count)))]
var firstPlayerCard2 = "\(firstPlayerCard2Num) of \(firstPlayerCard2Suit)"

return(firstPlayerCard1,firstPlayerCard2)
}

有人能让我知道我失踪的是什么。

1 个答案:

答案 0 :(得分:4)

不能直接回答你的问题,但我认为你会想要这样的事情:

enum Number: String {
    case Two = "two"
    case Three = "three"
    case Four = "four"
    case Five = "five"
    case Six = "six"
    case Seven = "seven"
    case Eight = "eight"
    case Nine = "nine"
    case Ten = "ten"
    case Jack = "jack"
    case Queen = "queen"
    case King = "king"
    case Ace = "ace"

    static var randomNumber: Number {
        return [Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace][Int(arc4random_uniform(13))]

    }
}

enum Suit: String {
    case Spades = "spades"
    case Hearts = "hearts"
    case Diamonds = "diamonds"
    case Clubs = "clubs"

    static var randomSuit: Suit {
        return [Spades, Hearts, Diamonds, Clubs][Int(arc4random_uniform(4))]
    }
}

struct Card: CustomStringConvertible, Equatable {
    let number: Number
    let suit: Suit

    var description: String {
        return "\(number.rawValue) of \(suit.rawValue)"
    }

    static var randomCard: Card {
        return Card(number: Number.randomNumber, suit: Suit.randomSuit)
    }

    static func randomCards(count count: Int) -> [Card] {
        guard count > 0 else {
            return []
        }
        guard count <= 52 else {
            fatalError("There only are 52 unique cards.")
        }
        let cards = randomCards(count: count - 1)
        while true {
            let card = randomCard
            if !cards.contains(card) {
                return cards + [card]
            }
        }
    }
}

func == (left: Card, right: Card) -> Bool {
    return left.number == right.number && left.suit == right.suit
}

let randomCards = Card.randomCards(count: 5)
print(randomCards)
// prints five random cards

如果您有任何其他问题,请告诉我。