mardi 4 mai 2021

how to pick a random enumeration value without it picking the same value twice? [duplicate]

I am making a blackjack app and I am currently stuck because first I made an array of the list of cards. Then I would pick randomly from that array and take out that card from the array, then once all the cards in the array were drawn and taken out I would add the contents of another array that was never touched and contained all the cards.

let cards = ["AC","AD","AH","AS","2C","2D","2H","2S","3C","3D","3H","3S","4C","4D","4H","4S","5C","5D","5H","5S","6C","6D","6H","6S","7C","7D","7H","7S","8C","8D","8H","8S","9C","9D","9H","9S","10C","10D","10H","10S","JC","JD","JH","JS","QC","QD","QH","QS","KC","KD","KH","KS",]
var inGameCards = ["AC","AD","AH","AS","2C","2D","2H","2S","3C","3D","3H","3S","4C","4D","4H","4S","5C","5D","5H","5S","6C","6D","6H","6S","7C","7D","7H","7S","8C","8D","8H","8S","9C","9D","9H","9S","10C","10D","10H","10S","JC","JD","JH","JS","QC","QD","QH","QS","KC","KD","KH","KS",]
func updateCard() {
    if inGameCards.count == 0 {
        inGameCards.append(contentsOf: cards)
    }
    let randomCard: String = inGameCards.randomElement()!
    print(randomCard)
    var numberOfCard = 0
    if let index = inGameCards.firstIndex(of: randomCard) {
        numberOfCard = index
    }
    inGameCards.remove(at: numberOfCard)
    print(inGameCards)
}

But then I faced the problem of getting the cards to have values, so I decided to use enums and switches. I had 62 case statements in two different switch statements in order to have the cards equal an int value and a string value for the pictures, the code I have to pick randomly is

enum CardChoice: CaseIterable {
    case AC,AD,AH,AS,TwoC,TwoD,TwoH,TwoS,ThreeC,ThreeD,ThreeH,ThreeS,FourC,FourD,FourH,FourS,FiveC,FiveD,FiveH,FiveS,SixC,SixD,SixH,SixS,SevenC,SevenD,SevenH,SevenS,EightC,EightD,EightH,EightS,NineC,NineD,NineH,NineS,TenC,TenD,TenH,TenS,JC,JD,JH,JS,QC,QD,QH,QS,KC,KD,KH,KS
    var value: Int {
        switch self {
        case .AC, .AD, .AH, .AS:
            return 1 ///I continued with the rest of the cards
}
}
var Text: String {
        switch self {
        case .AC:
            return "AC" ///I continued with the rest of the cards
}
}
}
func newCard()-> (first: Int, last: String) {
    let card = CardChoice.allCases.randomElement()
    return(first: card!.value, last: card!.Text)
}

but then with that new code I couldn't stop it from picking the same card multiple times in a single deck of cards.




Aucun commentaire:

Enregistrer un commentaire