In: Computer Science
Instructions
Use your solution from Programming Assignment 5 (or use your instructor's solution) to create a modular Python application. Include a main function (and a top-level scope check),and at least one other non-trivial function (e.g., a function that deals the new card out of the deck). The main function should contain the loop which checks if the user wants to continue.
Include a shebang, and ID header, descriptive comments, and use constants where appropriate.
Sample Output (user input in red):
Welcome to the card dealer!
Here is your first card:
5 of hearts
Would you like another card? (y or n) y
King of hearts
Would you like another card? (y or n) y
Jack of clubs
Would you like another card? (y or n) y
King of spades
Would you like another card? (y or n) n
final hand value = 35
final hand: ['5 of hearts', 'King of hearts', 'Jack of clubs',
'King of spades']
Submission
Attach and submit your Python file to this assignment.
Python3 code:
#!/usr/bin/env python3
# Import the module
import random
# Global variables
value = 0
drawn = []
LETTER_CARD_VALUE = 10
# function to compute the total of the cards drawn
def compute_total(card):
global value
number = card.split()[0]
if len(number) == 1:
value += int(number)
else:
value += LETTER_CARD_VALUE
# function to draw a card from the deck
def draw_one():
global drawn
# list of 52 cards
cards = ["King of hearts", "Queen of hearts", "Jack of hearts", "Ace of hearts", "1 of hearts", "2 of hearts", "3 of hearts", "4 of hearts", "5 of hearts", "6 of hearts", "7 of hearts", "8 of hearts", "9 of hearts",
"King of clubs", "Queen of clubs", "Jack of clubs", "Ace of clubs", "1 of clubs", "2 of clubs", "3 of clubs", "4 of clubs", "5 of clubs", "6 of clubs", "7 of clubs", "8 of clubs", "9 of clubs",
"King of spades", "Queen of spades", "Jack of spades", "Ace of spades", "1 of spades", "2 of spades", "3 of spades", "4 of spades", "5 of spades", "6 of spades", "7 of spades", "8 of spades", "9 of spades",
"King of diamonds", "Queen of diamonds", "Jack of diamonds", "Ace of diamonds", "1 of diamonds", "2 of diamonds", "3 of diamonds", "4 of diamonds", "5 of diamonds", "6 of diamonds", "7 of diamonds", "8 of diamonds", "9 of diamonds"]
# remove drawn cards from the 52 cards
remaining_cards = list(set(cards)-set(drawn))
# randomly select one card
card = remaining_cards[random.randint(0, len(remaining_cards) - 1)]
drawn.append(card)
# call the function
compute_total(card)
return card
# main function
def main():
# draw first card
print("Here is your first card:")
print(draw_one())
# loop to ask the user whether he wants to draw the card
while 1:
c = input("Would you like another card? (y or n) ")
if c == 'y':
print(draw_one())
elif c == 'n':
break
# print the output
print("final hand value =", value)
print("final hand:", drawn)
if __name__ == "__main__":
main()
Please refer to the following pictures for the source code and its indentation:
Sample execution of the above code: