(Solved) : Game Description Two Scenarios May Occur War Game Described Scenario 1 Normal Round Game P Q33346562 . . .
Game Description
There can be two scenarios that may occur in the War game. Theyare described below:
Scenario 1 Normal Round of the Game
Each player turns up a card faceup at the same time and theplayer with the higher card takes both cards and puts them,facedown, in random order, at the bottom of their pile of cards. Aplayer loses if they do not have any card left in their pile toparticipate in the normal round of the game. The winner in thiscase has all 52 cards.
Scenario 2 War
If the cards are the same rank in the normal round of game, itis War. This is different from the normal round of the game. Incase of War, each player places one, two, or three cards facedown(so they are not seen) and one card faceup. The player to win theround would be the one with the higher card faceup. This winningplayer will takes both piles (six, eight or ten cards) i.e ALLcards on the table including the ones that were initially placed.The winning player will put all these cards, facedown, in randomorder at the bottom of their pile of cards.During War, if thefaceup cards of both players happen to be of the same rank again,then it is War again and each player places another set of cards(one, two or three) facedown and a card faceup. This continuesuntil a player has a faceup card that is of a higher rank than theother player’s faceup card. At this point, the player with thehigher faceup card takes ALL cards placed on the table. Once WARhas been resolved, the players continue to play the game asdescribed in scenario 1.If any player is unable to participate inthe War due to lack of number of cards in their pile of cards, theother player will take all their cards and all the cards that areon the table at that time. In this case the player taking all thecards will have 52 cards and wins the game.
End of Game Condition
The game continues until one player has all 52 cards and isdeclared the winner.
There are three versions of this game depending upon the numberof cards that are placed facedown when there is War: one card, twocards, or three cards. The number is chosen at the start of thegame and it remains the same throughout the game
The Ace is the highest rank, followed respectively by the King,the Queen, the Jack then the cards 10 down to 2. Cards fromdifferent suits but with the same rank are equivalent.
To display the cards on the screen, we use two characters torepresent a card. The first character is the rank and the secondthe suit. The rank is either K for king, Q for queen, J for Jack, Afor Ace, then 2 to 9 for the numbers and 0 for 10. The suits are D,C, H, and S. Example 8D is eight of Diamond; 0H is 10 ofhearts.
Task 1 : Reading and Validating cards
Write a function calledread_and_validate_cards.
def read_and_validate_cards():
This function should prompt the user for the name of the file,that it tries to open in read mode. If the file does not exist, thefunction should raise an Exception. This exception should be caughtby the main function and the program should exit by reporting thefollowing error message:
Incorrect filename or file does not exist
If the file is found, the function proceed to read the file andvalidate the content of the file. In order to validate the contentof the file, the function should check the following items in thisorder:
This function should check if the number of cards in the file is52. If the number of cards is less than 52 or greater than 52, thefunction should raise an exception. For example if the file has 42cards instead of 52, the function should raise an exception thatshould be caught by the main function and the program should exitby reporting the following error message:
Error : Number of cards in the file is 42.
This function should also check if there are any duplicate cardsin the file. For example if 9D and QH appears more than once in thefile, the function should raise an exception and your main functionshould catch the exception and exit the program by reporting thefollowing error message:
Error:Duplicates found in the input file:QH,9D
This function should also check if each card in the file iscorrectly formatted or not. Each card is represented by 2characters. The first character is the rank and the second is thesuit. The rank is either K for king, Q for queen, J for Jack, A forAce, then 2 to 9 for the numbers and 0 for 10. The suits are D,C,H,and S. Example 8D is eight of Diamond; 0H is 10 of hearts. Forexample if there is a card in the file that has a format 1B thensince B is not one of the legal suit, therefore this card is notcorrectly formatted. In this case the function should raise anexception that should be caught by the main. The main should reportthe error message and exit the program. Similarly, if a card in thefile is 3QD, this is also not correct as the card must be representby 2 characters only. Please note that if only the card’s suit isin lower case then it is not considered as incorrect. It should bechanged to uppercase when reading in that card from the file andshould not raise an exception. For example a card represented by 2sshould not raise an exception.
If we have the following incorrectly formatted cards in our file:2B,1QD,17C,100Z, the main function should catch the exception andexit the program by reporting the following error message:
Error:Following cards not formattedcorrectly:2B,1QD,17C,100Z
You are given a python program shuffleCards.py that generatesthe file shuffledDeck.txt. A sample shuffledDeck.txt is also givenwith the assignment description. You can generate a newshuffledDeck.txt by running shuffleCards.py. The file will have 52distinct cards that are correctly formatted. However, while thisprogram generates a correct input for your program you cannotassume the input file is always correct. If the input file is notcorrectly formatted (has less or more cards or duplicate cards orincorrectly formatted cards) your program should report one of theappropriate error message that is given above and exit the program.The program that you submit maybe tested with a file with incorrectentries. In this case, your program should exit by displaying oneof the appropriate error message that is specified in the abovedescription.
Task 2: Distributing cards
Once you have read and validated the 52 cards from the file,distribute the cards to both players: player1 and player2. Thecards are distributed, one at a time, to each player. Thedistribution should start randomly with player 1 or player2. Inthis regard, write a function called distribute_cards that woulddistribute the cards:
def distribute_cards(cards)
The players keep their cards in such a way that the first cardserved is the first that will be played by the player. In otherwords, the containers of these cards should receive the cards atone end and use them from the other end. Use thecircular queue we saw and implemented in class to represent aplayer’s hand. The capacity should be set to 52 since you willnever have more than 52 cards. The Circular Queue class is given toyou in the file assignment3.py.
Task 3: Asking user for number of facedowncards
Write a function that would prompt the user to enter how theywould like to do war.
def get_user_input():
The input should be 1 or 2 or 3. This number represents thenumber of cards that will be placed facedown at the time of War.This function should validate whether the user has entered thecorrect value or not. The function should repeatedly ask the userto enter a value until the user enters the correct value. The valueentered by the user should be returned by the function.
Task 4: Comparing cards
You need a way to compare two cards. Write a function that giventwo correct cards returns 0 if the cards are of equal rank; 1 ifthe first card is of higher rank; and 2 if the second card is ofhigher rank. The ranks are explained above. Also, remember that therank is the first character of the card and the cards are stringsof two characters. Here is the function definition for thisfunction:
def compare_cards(card1,card2):
Task 5: Class OnTable
For the simulation of this game, we will consider the playersare sitting at the opposite ends of a table. Player1 places cardsat the left end of the table and player2 places cards at the rightend of the table. In this task you are required to create a classOnTable that represents this table. The instance attributes of theclass are:
cards_list – is an object of type list that will contain objectsof type str. Each str object represent a card.
faceUp_list – an object of type list that contain objects oftype bool. The bool object at a certain position in the faceUp_listis True if a card at the corresponding position in cards_list isfaceup and False if a card is facedown.
The OnTable class has the following methods:
place(player, card, hidden), where player is 1 for player 1 or 2or player 2, card is the card being placed on the table, and hiddenis False when the card is faceup and True when the card isfacedown. This method should update the cards_list and faceUp_list.Cards put on the table by player 1 will be added on the left of thecards_list. The cards put on the table by player 2 will be added onthe right of cards_list.
cleanTable(). This method shuffles and then returns a list ofall cards on the table as stored in the attribute cards_list andresets cards_list and faceUp_list.
__str__()This method should convert the cards on the table intoa string to be displayed. We can say this method returns thecurrent status of the table as a string. The string returned bythis method is similar to a list display. However, the cards thatare facedown on the table should be displayed as “XX”. Moreover,player1 and player2 cards should be separated by a vertical line.An example of what the string looks like when it is displayed onthe console is given below:
[QS, XX, XX, XX, AS | AD, XX, XX, XX, 8S]
In the above output QS, XX, XX, XX, AS are player1 cards and AD,XX, XX, XX, 8S are player2 cards.
Task 6: The Game
Given the following algorithm and based on the previous tasks,implement the simulation of the card game War. Obviously, there aredetails in the algorithm specific to the implementation in Pythonthat are missing and it is up to you to do the conversion from thispseudo-code to Python.
There are other practical details to add to the algorithm. Atthe end of the game, we need to display who was the winner player1or player2. As indicated in the algorithm, on line 45 and 46, aftereach round of the game, 60 dashes are displayed and the programwill wait for the user to press enter before displaying the nextround. Please note it make take many rounds before the gameends.
Sample Output
Part of output during game:
content of shuffleCards.py
##########################################################################################################
# Creates a deck of 52 shuffles cards and stores in fileshuffledDeck.txt
# each line of the file is a card. A card is 2 characters. thefirst is the rank, the second is the suit
# Suits are D, C, H, and S
# Ranks are: K, Q, J, A, 2, 3, 4, 5, 6, 7, 8, 9, 0
#
# Program by Osmar Zaiane
# Version 1.0 2018-02-25
##########################################################################################################
from random import shuffle
suits=[“D”, “C”, “H”, “S”]
ranks=[“K”,”Q”,”J”,”A”,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”0″]
cards=[]
for rank in ranks:
for suit in suits:
cards.append(rank+suit)
shuffle(cards)
try:
cardFile= open(“shuffledDeck.txt”, “w”)
for card in cards:
cardFile.write(card+”n”)
except IOError as e:
print (“I/O error({0}: {1}”.format(e.errno, e.strerror))
except:
print (“Unexpected error”)
finally:
cardFile.close()
print (“The following shuffled 52 card deck was saved inshuffledDeck.txt”)
print (cards)
The main code to be filled:
# START WRITING YOUR PROGRAM HERE
def read_and_validate_cards():
# TASK 1 Reading and Validating cards
# Three Conditions
# File Exists – raises Exception if it does not.
# 1.Exactly 52 2.Not repeated 3.Correct Format Raises Exception ifany of the
# above is not correct.
# TODO
pass
def distribute_cards(cards):
# Task 2 Distributing cards
# Creates Two circular Queues and return them
# – cards is a list of valid cards that has been read from thefile
# TODO
pass
def get_user_input():
# Task 3 Asking user for input
# prompt the user to enter the number of cards that would befacedown for war
# will repeatedly ask the user to enter a valid value if any numberother than 1 or 2 or 3
# is entered
# returns the number entered by the user
# TODO
pass
def compare_cards(card1,card2):
# Task 4 Comparing Cards
# compares card1 of player 1 with card2 of player2
# if card1 has higher rank return 1
# if card2 has higher rank return 2
# if card1 is equal to card2 reurn 0
# – card 1 is a string representing a card of player1
# – card 2 is a string representing a card of player2
# TODO
pass
class onTable:
# Task 5 Create a class to represent the table
# an instance of this class represents the table
def __init__(self):
# self is the onTable object
# TODO
pass
def place(self,player,card,hidden):
# places the given card on the table
# -self is the onTable object
# -player is an object of type int. It is 1 for player1 or 2 forplayer 2
# -card is an object of type str. It is the card being placed onthe table
# -hidden is an object of type bool. False when the card is faceupand True when facedown
# TODO
pass
def cleanTable(self):
# cleans the table by initializing the instance attributes
# -self is the onTable object
# TODO
pass
def __str__(self):
# returns the representation of the cards on the table
# -self is the onTable object
# TODO
pass
def main():
# TODO – IMPLEMENT ALGORITHM HERE
pass
main()
There is a Class CircularQueue in this file, but i donthave enough space to post it.
Expert Answer
Answer to Game Description Two Scenarios May Occur War Game Described Scenario 1 Normal Round Game P Q33346562 . . .
OR