vendredi 4 janvier 2019

Using a while loop to indefinitely reassign a variable, until that variable no longer belongs to a list?

The purpose of this program is to deal out one 5-card hand from a standard 52-card deck.

I'm new to Python. Eventually I'd like to write a 5-card draw poker program, but first would like to know how to deal out 5 random non-repeating cards. The cards get dealt out and printed back to the user fine, but it is sometimes dealing duplicates. ie, the hand I'm dealt is Ah 2d 8h Ah Jc. Can't have two ace of hearts.

I'm trying to use a while True: construction to ensure that the same card isn't dealt twice. I studied C for awhile before Python and am confused here in syntax/construction. A do-while loop would seem to be handy, where it indefinitely reassigns the card to a random int as long as that card hasn't been drawn yet.

The code is also super long and I've just shown the process for assigning the first few cards. Using 52 if statements seems to a problem, but first I'd like to see if it can run with this construction, just fixing the while loop.

import random


# track a list of cards used
drawn_cards = ["Joker", "Joker2"]

for n in range (5):
    # generate a random int between 1 and 52 representing card
    card = random.randint(1,52)

    #check to see if this card has already been drawn, and if so 
redraw
    while True:
        if card in drawn_cards:
            card = random.randint(1,52)
        else:
            break


    #assign each random int generation to a specific card in the 
    deck,
    #and add the new card to drawn_cards

    #spades
    if card == 1:
        card = str(card)
        card = 'As'
        drawn_cards.append(card)
    if card == 2:
        card = str(card)
        card = '2s'
        drawn_cards.append(card)
    if card == 3:
        card = str(card)
        card = '3s'
        drawn_cards.append(card)
    if card == 4:
        card = str(card)
        card = '4s'
        drawn_cards.append(card)
    if card == 5:
        card = str(card)
        card = '5s'
        drawn_cards.append(card)
    if card == 6:
        card = str(card)
        card = '6s'
        drawn_cards.append(card)

I expect the program to return 5 unique non - repeating playing cards to the user, but it sometimes returns (deals) the same card twice in the same hand.




Aucun commentaire:

Enregistrer un commentaire