Skip to content Skip to sidebar Skip to footer

How To Prevent Repeated Random Values?

The CPU and User is getting repeated cards. I've used the shuffle function, as well as pop. Is there a way to prevent useer and CPU from getting repeated cards. Here is an example

Solution 1:

Don't use randint() to pick cards at all. Construct a "deck", which is just a list of cards, use shuffle() to randomize it, and pop() to deal a card. Also, I'd recommend representing cards with numbers rather than strings. Strings are for humans. Numbers will make the rest of your code simpler and faster. Just translate to strings for the user when needed.

Something like:

theDeck = [];

defshuffle():
    theDeck = range(52)
    random.shuffle(theDeck)

defdealCard():
    return theDeck.pop()

defnameOfCard(c):
    return [ "Deuce", "Trey", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" ][c >> 2] + \
        " of " + [ "Clubs", "Diamonds", "Hearts", "Spades" ][c & 3];

Solution 2:

You would have to keep a list of all the cards that have been in play, and then check if the most recently generated card is in that list, and if it is, re-generate it.

generated_cards = []
...
card = random.randint(1,52)
while card in generated_cards:
    card = random.randint(1,52)
generated_cards.append(card)  # once the card is a new, unique one,# add it to the generated_cards list 

An easier way of handling this might be to generate the list of cards, shuffle them, and them pop them off the list one by one.

deck_of_cards = [x for x in range(0, 52)]
random.shuffle(deck_of_cards)
...
card = deck_of_cards.pop()  # this removes the item from the list # and puts it in the card variable

Solution 3:

Add played cards to list. Check if new random card already in this list and regenerate new card if so until it's not in list. Don't forget to check list have all the cards to avoid endless loop. P.S. Don't use this method, generating all list at once and shuffle it much more effective.

Post a Comment for "How To Prevent Repeated Random Values?"