Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Python code will not run due to invalid syntax when I ask the user for 5 variables, and try to store them as a list

Python code will not run due to invalid syntax when I ask the user for 5 variables, and try to store them as a list of objects. How can I fix this?

Here is the assignment:

The existing menu options will stay the same:

1. High Card

2. Deal Hand

3. Save Dream Hand

4. Display Dream Hand

5. Word Guess

6. Quit

Make sure you clean up your existing code.

You will implement the class Card and modify your program to work with the card as a class rather than just an integer.

The Card class will have the following:

Class name: Card

Data attributes: __value

Methods: __init__()

deal()

set_value()

get_value()

find_face_value()

__str__()

Additional instructions and hints:

There are several good examples in the book you can use as a guide.

Put the class definition in a separate file. You need to define this first.

At the top of your program file you will need an import statement: import yourClassFileName.

Be sure to import random at the top of your class definition file.

You will define a "deal" method in your class Card:

this method will deal one card (using the random number generator).

You will define a find_face_value method that will return the face value for the card object. You will remove the display_face_value function from your program.

Your main(), menu(), and make_change() functions will not change.

I would recommend you start modifying the high card function first, get that to work, then move to the other functions.

In the high_card function you will create two Card objects - one for each player:

player1_card = classFileName.Card()

player2_card = clasFileName.Card()

You will remove the code that assigns the random number and replace it with the call to the Class method that deals the card.

(you do not have to use the same identifier names as I have)

Your class will be called "Card", but use the file name you gave to the file that contains the class definition.

You will need to modify the way your high card function references the card values for purposes of comparing the cards.

ex:

if player1_card.get_value() > player2_card.get_value():

print("Payer 1 wins") etc.......

Once you get this to work, you will move on to your deal hand function.

Instead of putting the integer value for each card in a list, you will create an object of type Card, invoke the deal() method, then append it to your list.

There is a good example to refer to on page 516.

Your deal hand function will pass the list of objects to the display hand function and the hand stats function, so you will need to modify the code in each of those functions so they reference the data attributes in the object rather than just an integer value in a list like it currently does.

You will also have to modify your save dream hand and display dream hand functions: Save dream hand will read values from the user and store them in a list of objects rather than a list of integers.

Once you have read and stored all 5 cards, you will go through the list and store the integer value for each card into a file. The logic stays the same, you just change the way you store and access the card value.

Display dream hand will read the integer card values from the file and store them in a list of objects.

Then you will pass the list to the display hand function that will go through the list and display the face value of each card in the list.

Here is the code I have so far:

##################################################################

# COSC 1336 Lab 9 #

# Lab 9 Solution #

# #

# This program display a game menu: #

# 1. Make Change #

# 2. High Card #

# 3. Deal Hand #

# 4. Save Dream Hand #

# 5. Display Dream Hand #

# 6. Word Guess #

# 7. Quit #

# Prompts user for option and plays #

# the game chosen. #

# #

# Make Change: will read a purchase amount and a payment amount #

# and display the change due and the breakdown of the change #

# into number of dollars, quarters, dimes, nickels and pennies #

# #

# High Card: will deal one card to each of two players, display #

# who got which card and who wins #

# #

# Deal Hand: will deal a five card hand and display the face #

# value of each card, the total value of all the cards, and the #

# average. #

# #

# Save Dream Hand: will ask the user for 5 cards and save as a #

# list of objects #

# #

# Display Dream Hand: will read the integer card values from #

# the file and store them in a list of objects #

# #

# Word Guess: asks the user for the word, and prompts the user #

# enter letters to guess the word #

##################################################################

import random

import card

# Define global constants for the menu options

MAKE_CHANGE = 1

HIGH_CARD = 2

DEAL_HAND = 3

SAVE_DREAM_HAND = 4

DISPLAY_DREAM_HAND = 5

WORD_GUESS = 6

QUIT = 7

def main():

# Welcome the user

welcome()

# Get the first menu choice

choice = menu()

# Once the user chooses to quit, do not contiue

# to display the menu

while choice != QUIT:

# Check the choice and play the game chosen

if choice == MAKE_CHANGE:

make_change()

elif choice == HIGH_CARD:

high_card()

elif choice == DEAL_HAND:

deal_hand()

elif choice == SAVE_DREAM_HAND:

save_dream_hand()

elif choice == DISPLAY_DREAM_HAND:

display_dream_hand()

elif choice == WORD_GUESS:

word_guess()

# Get the next menu choice

choice = menu()

#############################################################

# Function: welcome #

# Inputs: none #

# Outputs: none #

# Description: This function welcomes the user and #

# displays a program description #

#############################################################

def welcome():

# Display program description

print(' ******************************************************')

print('* Welcome to the Lame Game computer gaming room *')

print('* *')

print('* This program display a game menu: *')

print('* 1. Make Change *')

print('* 2. High Card *')

print('* 3. Deal Hand *')

print('* 4. Save Dream Hand *')

print('* 5. Display Dream Hand *')

print('* 6. Word guess *')

print('* 7. Quit *')

print('* *')

print('* Prompts for option and plays the game chosen. *')

print('****************************************************** ')

#############################################################

# Function: menu #

# Inputs: none #

# Outputs: a valid menu choice #

# Description: This function will display the game menu, #

# reads the choice, validates the choice #

# and returns it #

#############################################################

def menu():

# Initialize the user's choice

choice = 0

# Display the menu and read the choice

try:

print(" Welcome to the Lame Game Computer Game Room")

print("--------------------------------------------")

print("1. Make Change")

print("2. High Card")

print("3. Deal Hand")

print("4. Save Dream Hand")

print("5. Display Dream Hand")

print("6. Word Guess")

print("7. Quit")

choice = int(input(" Enter choice: "))

# Check for invalid input

while choice < MAKE_CHANGE or choice > QUIT:

print("Invalid option...")

# Display the menu and read the choice again

print(" Welcome to the Lame Game Computer Game Room")

print("--------------------------------------------")

print("1. Make Change")

print("2. High Card")

print("3. Deal Hand")

print("4. Save Dream Hand")

print("5. Display Dream Hand")

print("6. Word Guess")

print("7. Quit")

choice = int(input(" Enter choice again: "))

except ValueError:

print("Value can only be a number.")

# Pass back the user's choice

return choice

#############################################################

# Function: make_change #

# Inputs: none #

# Outputs: none #

# Description: This function will read a purchase amount #

# and a payment amount and display the change #

# due and the breakdown of the change into #

# number of dollars, quarters, dimes, nickels #

# and pennies #

#############################################################

def make_change():

# Read the amount of the purchase

price = float(input(' Enter the amount of the purchase '))

# Read the amount of the payment

paid = float(input('Enter the amount of payment '))

# Check to see if the payment is enough to cover the purchase

if paid < price:

print('You did not pay enough')

else:

# Calculate the change due

change = paid - price

# Display the change due

print(' Change due: ',format(change,'.2f'))

#print(' unformatted: ',change)

print('This breaks down into:')

# Calculate the number of dollars due

dollars = int(change//1)

print('\tDollars:\t',dollars)

# Isolate the change amount and convert it to an integer.

# To account for precesion lost converting to an integer,

# force rounding of the 100ths digit by adding .005

# to the change portion

change = int(((change - dollars) + .005)* 100)

#print('change is now ',change)

# Calculate the number of quaters due

quarters = change // 25

print('\tQuarters:\t',quarters)

change = change - (quarters * 25)

# Calculate the number of dimes due

dimes = change // 10

print('\tDimes:\t\t',dimes)

change = change - (dimes * 10)

# Calculate the number of nickels due

nickels = change // 5

print('\tNickels:\t',nickels)

change = change - (nickels * 5)

# The number of pennies due will be all that is left

pennies = change

print('\tPennies:\t',pennies)

print()

#############################################################

# Function: high_card #

# Inputs: none #

# Outputs: none #

# Description: This function will read the name of each of #

# 2 players deal 2 cards to each player and #

# determine who wins: #

# the player with the highest card #

#############################################################

def high_card():

print("High Card")

print("----------")

# Prompt for user's names

player1 = input("What is your first name player one? ")

player2 = input("What is your first name player two? ")

# Create two instances of of the card class and eal the cards

card1 = card.Card()

card1.deal()

card2 = card.Card()

card2.deal()

# Display the cards

print(player1, "your card is:", card1.find_face_value())

print(player2, "your card is:", card2.find_face_value())

# Check to see which card was higher,

# or if the game is a draw

if card1.get_value() > card2.get_value():

print(player1, "you have the high card!")

elif card1.get_value() < card2.get_value():

print(player2, "you got the high card!")

else:

print("You tied!")

#############################################################

# Function: deal_hand #

# Inputs: none #

# Outputs: none #

# Description: This function will deal a five card hand #

# using a random number function then #

# displays the face value of each card #

#############################################################

def deal_hand():

print("Deal Hand")

print("------------")

i = 1

#Create a list

cards_list = []

#append number to the list

for n in range(5):

num = card.Card()

num.deal()

cards_list.append(num)

#Display face value of cards

print("The face value of the cards is:")

for item in cards_list:

print(i, item.find_face_value())

i +=1

print()

# Call hand_stats function to display the total and average of cards

hand_stats(cards_list)

#############################################################

# Function: save_dream_hand #

# Inputs: integer card value #

# Outputs: none #

# Description: This function ask the user for five cards #

# and save them to a file #

#############################################################

def save_dream_hand():

print("Save Dream Hand")

print("------------------")

try:

dream_cards = []

# Append dream cards to list

for n in range(5):

card = int(input("Enter a card between 1 and 13:"))

while card < 1 or card > 13:

print("The value of the card must be a number between 1 and 13.")

card = int(input("Enter a card between 1 and 13:")

num = card.Card()

num.set_value(card)

user_cards.append(num)

print()

#Get file name

file_name = input("Enter file name:")

# Open file

out_file = open(file_name, 'w')

# Write list to file

for item in dream_cards:

out_file.write(str(item.get_value()) + ' ')

# Close file

out_file.close

# Error trap for invalid value for card

except ValueError:

print("Error: Invalid input")

except Exception as error_msg:

print("Error:", error_msg)

#############################################################

# Function: display_dream_hand #

# Inputs: file name #

# Outputs: display face value of dream hand cards #

# Description: This function will display the face value #

# of a numeric card by opening file #

#############################################################

def display_dream_hand():

print("Display Dream Hand")

print("---------------------")

try:

i = 1

dream_list = []

# Get file name

file_name = input("Enter file name:")

# Open file

in_file = open(file_name, 'r')

# Get 5 cards from file and move them to a list

cards = in_file.readlines()

# Close file

in_file.clode()

# Append object to dream list

for index in range(5):

num = card.Card()

num.set_value(int(cards[index]))

dream_list.append(num)

# Display face value

print("The face value of the cards are:")

for item in dream_list:

print(i, iem.find_face_value())

i += 1

# Check for invalid file name

except FileNotFoundError:

print("Error: Invalid file name")

except Exception as error_msg:

print("Error:", error_msg)

#############################################

# Function: display_hand #

# Input: none #

# Outputs: display face value of card_list #

# Purpose: display face value of dream hand #

# card_list #

#############################################

def display_hand(card_list):

#Get list

dream_list = [card1, card2, card3, card4, card5]

# Call display_face_value function

display_face_value(dream_list)

#Display results

print(dream_list2)

#############################################

# Function: hand_stats #

# Input: none #

# Outputs: displays total and average of #

# dream hand card_list #

# Purpose: display the total and the average#

# of the dream hand cards #

#############################################

def hand_stats():

#Get list from deal_hand

card_list = [card1, card2, card3, card4, card5]

#Set accumulator

total = 0.0

#Calculate the total number of cards

for value in card_list:

total = total + value

#Calculate average of all the cards

average = total/5

# Display total and average of cards

print("The total of the cards is", total)

print("The average of the cards is", average)

#########################################

# Function: check #

# Input: none #

# Output: none #

# Purpose: check for guessed letters in #

# user_word #

#########################################

def check(letter_guess, guess, user_word):

# Iterating over string

for i in range(0, len(user_word)):

# Checking for existence of letters

if user_word[i] == letter_guess:

# Updating guess string

guess = guess[:i] + letter_guess + guess[i+1:];

# Return updated string

return guess;

###################################

# Function: word_guess #

# Input: Enter word to guess #

# Output: game displays whether #

# letters were guessed or not #

# Purpose: get word from user and #

# have them guess the letters #

# until all the letters are #

# guessed #

###################################

def word_guess():

# Get user word

user_word = input(" Enter a word: ");

# Printing new line

print(" " * 100);

# String that holds already guessed characters

guessed_letters = "";

# Storing word length

word_length = len(user_word);

# Forming guess string as a series of astreicks

guess = '*' * word_length;

# Iterate till entire word is guessed

while 1:

# Reading a letter

letter_guess = input(" Enter a letter: ");

# If already guessed

if letter_guess in guessed_letters:

print(" You have already guessed " + letter_guess + " ");

else:

# Checking word

guess = check(letter_guess, guess, user_word);

# Updating guessed Characters

guessed_letters = guessed_letters[:] + letter_guess

# Printing updated guess string

print(" So far you have: \t" + guess);

# If all letters are guessed correctly

if '*' not in guess:

# Printing Message

print(" Correct! ");

return;

main()

Here is the card file:

import random class Card:

def __init__(self): self.__value = 0

def deal(self): self.__value = random.randit(1,13)

def set_value(self, value): self.__value = value

def get_value(self): return self.__value

def find_face_value(self): if self.__value == 1: face_value = 'Ace' elif self.__value == 2: face_value = 'Two' elif self.__value == 3: face_value = 'Three' elif self.__value == 4: face_value = 'Four' elif self.__value == 5: face_value = 'Five' elif self.__value == 6: face_value = 'Six' elif self.__value == 7: face_value = 'Seven' elif self.__value == 8: face_value = 'Eight' elif self.__value == 9: face_value = 'Nine' elif self.__value == 10: face_value = 'Ten' elif self.__value == 11: face_value = 'Jack' elif self.__value == 12: face_value = 'Queen' else: face_value = 'King

return face_value

def __str__(self): return 'Value: ' + str(self.__value)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transactions On Large Scale Data And Knowledge Centered Systems Xxxviii Special Issue On Database And Expert Systems Applications Lncs 11250

Authors: Abdelkader Hameurlain ,Roland Wagner ,Sven Hartmann ,Hui Ma

1st Edition

3662583836, 978-3662583838

More Books

Students also viewed these Databases questions