IOS Swift 2.0 Card shuffling function
本问题已经有最佳答案,请猛点这里访问。
不,我正在尝试用52张牌的标准牌组创建一个纸牌游戏。这是我想制作成func的代码,所以我不必每次都手工写出来。我正在创建5个不同的玩家,以便将其复制到其他玩家。
1 2 3 4 5 6 7 8 9 10 11 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 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 |
如果你还有其他问题,请告诉我。