1

Noob here, I am trying to create a card game using a standard deck of 52 cards. Here is the code I would like to make into a func so I dont have to manually write it out every single time. I am creating 5 different players so this would be replicated to other players.

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)
}

Can someone let me know what I'm missing.

Paul
  • 227
  • 1
  • 3
  • 14
  • There are a _lot_ of card-shuffle Swift implementations shown on Stack Overflow. Please search before asking. – matt Mar 10 '16 at 18:05

1 Answers1

5

Not a direct answer to your question, but I think you'll want something like this:

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

Let me know if you have any other questions.

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63