How would I go about removing duplicate draws from this card drawing program?
Problem Description:
#Imports random method
import random
#Gets the value of the card
def getCard():
global cards,cardSelect
#List of possible cards in an array
cards = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"]
#Selects a card
cardSelect = random.choice(cards)
#Gets the suit of the card
def getSuit():
global suits,suitSelect
#List of possible suits in an array
suits = ["Hearts","Spades","Clubs","Diamonds"]
#Selects a suit
suitSelect = random.choice(suits)
#Prints the cards
def buildCard():
global cards,suits,cardSelect,suitSelect
#Calls other functions
getCard()
getSuit()
#Chooses color randomly
color = random.randint(1,2)
#Defines randomly selected value to the name of a color : Red or Black
if color == 1:
color = "Red"
if color == 2:
color = "Black"
#Prints every card in a 52 deck
print("You drew a",color,cardSelect,"of",suitSelect)
#Calls BuildCard
while True:
input()
buildCard()
Essentially what I need this program to do is print a randomly generated card (as it does now) but keep score of what card has been generated to prevent duplicate card draws in the program. I was thinking there might be a way to do it using a set() or maybe remove() or pop()? Not sure because I’m still new to Python. Thanks!
Solution – 1
Consider building your deck first (non-randomly) and then shuffling the deck.
import random
cards = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"]
suits = ["Hearts","Spades","Clubs","Diamonds"]
deck=[]
for card in cards:
for suit in suits:
deck.append( ( card, suit ))
random.shuffle(deck)
for n,card in enumerate(deck):
print(n,card)
It should be noted that I left out the colors of the cards completely. After all, color is not random but rather just a function of the suit. And so, if you want to include the color information in your cards as well, you have a number of options:
- You can include the color in the suit name
- You can provide a dict to map suits to colors.
- You can provide the information in the suit names as a tuple.
Options 1 and 3 can be implemented with a change to a line of code:
Option 1:
Include color with suit name:
suits = ["Red Hearts","Black Spades","Black Clubs","Red Diamonds"]
Option 3:
Include color as a tuple:
import random
cards = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"]
suits = [("Hearts","Red"),("Spades","Black"),("Clubs","Black"),("Diamonds","Red")]
deck=[]
for card in cards:
for suit in suits:
deck.append( ( card, suit ))
random.shuffle(deck)
for n,card in enumerate(deck):
print(n,card)
Example output from Option 3 above:
0 (9, ('Spades', 'Black'))
1 (8, ('Spades', 'Black'))
2 (4, ('Diamonds', 'Red'))
3 (10, ('Spades', 'Black'))
...