Question

Please to indent and follow structure!!!!! Assignment 3 - The card game: War Due Date: June...

Please to indent and follow structure!!!!!

Assignment 3 - The card game: War Due Date: June 9th, 2018 @ 23:55

Percentage overall grade: 5% Penalties: No late assignments allowed

Maximum Marks: 10

Pedagogical Goal: Refresher of Python and hands-on experience with algorithm coding, input validation, exceptions, file reading, Queues, and data structures with encapsulation.

The card game War is a card game that is played with a deck of 52 cards. The goal is to be the first player to win all 52 cards. It is played by two players but can also be played with more. The deck, after being shuffled, is divided evenly between the players. When there are two players each one receives 26 cards, dealt one at a time, face down. So the cards and their order are unknown. Each player places their stack of cards face down. It may seem as a STACK as we know it, since the player takes and plays one card at a time from the top of this stack. However, it is more like a QUEUE, since as we shall see it, when a player wins cards, these are placed at the bottom of this stack of cards. How do we play the game Each player turns up a card at the same time and the player with the higher card takes both cards and puts them, face down, on the bottom of their stack. If the cards are the same rank, it is War. Each player turns up one, two, or three cards face down (so they are not seen) and one card face up. The player with the higher cards face-up at the end takes both piles (six, eight or ten cards). If the turned-up cards are again the same rank, it is War again and each player places another set of cards (one, two or three) face down and turns another card face up. The player with the higher card face-up at the end takes all placed cards, and so on. The game continues until one player has all 52 cards and is declared the winner. There are three versions of this game depending upon the number of cards we place face-down when there is War: one card, two cards, or three cards. It remains consistent throughout the game. A deck of cards: Suits A deck of 52 cards has four suits: diamonds, clubs, hearts, and spades). In each suit, we have the King, the Queen, the Jack, the Ace, and cards from 2 to 10. The Ace is the highest rank, followed respectively by the King, the Queen, the Jack then the cards 10 down to 2. Cards from different suits but with the same rank are equivalent. To display the cards on the screen, we use two characters to represent a card. The first character is the rank and the second the suit. The rank is either K for king, Q for queen, J for Jack, A for 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 of hearts. Card Deck Task 1 : Reading and Validating cards You are given a text file of 52 shuffled cards, each card is in a line coded on two characters as described above. You need to prompt the user for the name of the file, open the file and read it. Make sure the file exists and make sure the cards in the file are correctly formatted as described above. If the cards are in lower case, it is not an error as you can simply transform them in upper case. You can assume the cards are shuffled but don't assume they are formatted as specified or that there are exactly 52, or even that they are not repeated. Make sure all the standard 52 cards are there in the shuffled deck. You are not asked to correct the cards, but your program must raise and catch an exception if card validation does not go through. The program should then display an appropriate error message and terminate the program in case there is an issue with the cards. You are given a python program shuffleCards.py that generates the file shuffledDeck.txt as we described above with 52 lines constituting the shuffled deck. However, while this program generates a correct input to your program don't assume the input file is always correct. The assessment of your assignment may be made with a file that is incorrect. Task 2: Distributing cards Now that you have read the 52 cards from the file and you know you shuffled deck is complete and correct, distribute the cards to both players: the user and the computer. You may call them player1 and player2. You should give one card to each player repeatedly until all cards are distributed. You should start randomly with either player. The players keep their cards in such a way that the first card served is the first that will be played. In other words, the containers of these cards should receive the cards on one end and use them from the other end. Use the circular queue we saw and implemented in class to represent the player's hand. The capacity should be set to 52 since you will never have more than 52 cards. The Circular Queue class should be inside assignment3 file that you submit. Task 3: Asking user for data Ask the user whether they would like to play a war with one, two, or three cards face-down. validate the input from the user and don't proceed until a valid input is given. Example of a War with 3 cards down Task 4: Comparing cards You need a way to compare two cards. Write a function that given two correct cards returns 0 if the cards are of equal rank; 1 if the first card is of higher rank; and -1 if the second card is of higher rank. The ranks are explained above. Also, remember that the rank is the first character of the card and the cards are strings of two characters. Task 5: class OnTable We need to represent the cards on the table, the cards that are currently placed on the table by both players either face-up or face-down. Create an encapsulated class OnTable with the behaviour described below. We will use two simple lists: one list for the cards and one list to indicate whether they are face-up or face-down. The attributes of the class are: __cards which is a list that will contain the cards, and __faceUp with will have booleans to indicate if the __cards list in the same position in __cards is face-up or face-down. Cards put on the table by player 1 will be added on the left of self._cards. The cards put on the table by player 2 will be added on the right of self._cards. The interface of this class should include place(player, card, hidden), where player is either 1 or 2 for player 1 or player 2, card is the card being placed on the table, and hidden is False when the card is face-up and True when the card is face-down. This method should update the attributes of the class appropriately. The interface should also have the method cleanTable(). This method shuffles and then return a list of all cards on the table as stored in the attribute __cards and resets __cards and __faceUp. All cards returned this way are visible. Finally, also write the method __str__() that should allow the conversion of the cards on the table into a string to be displayed. We would like to display the cards as a list. However, cards that are face-down should be displayed as "XX". Moreover, player1 and player 2 cards should be separated by a vertical line.Please see sample output. Task 6: The Game Given the following algorithm and based on the previous tasks, implement the card game War. Obviously, there are details in the algorithm specific to the implementation in Python that are missing and it is up to you as an exercise to do the conversion from this pseudo-code to Python. There are other practical details to add to the algorithm. At the end of the game, we need to display who was the winner (player1, the user, or player2 the computer). As indicated in the algorithm, on line 45 and 46, after each round of the game, 60 dashes are displayed and the program will wait for the user to press enter before displaying the next round.

Screen%20Shot%202018-04-30%20at%205.47.1

Screen%20Shot%202018-04-30%20at%205.55.1

0 0
Add a comment Improve this question Transcribed image text
Answer #1

from random import shuffle

import time

class card:

def __init__(self, suit, rank):

self.suit = suit.lower() # make sure that the suit is spelled in all lowercase characters

self.rank = rank

def isBlackOrRed(self):

# Function to check if a card is black or red

# Hearts and Diamonds are red cards, all other are black cards

if self.suit == "hearts" or self.suit == "diamonds":

return "red"

else:

return "black"

def isFaceCard(self):

# Function to check if a card is a face card

# Face cards have the ranks 11, 12 and 13

# or, Jack, Queen and King

faceCards = [11, 12, 13]

for faceCard in faceCards:

if self.rank == faceCard:

return True

return False

def getDescription(self):

# Returns a two item list

return [self.rank, self.suit]

def __repr__(self):

# Returns a nice explanation of the card

# for example: "ace of diamonds"

rank = self.rank

if rank == 1:

rank = "ace"

elif rank == 11:

rank = "jack"

elif rank == 12:

rank = "queen"

elif rank == 13:

rank = "king"

return "{} of {}".format(rank, self.suit)

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

class cardStack:

# Class for both decks and hands

def __init__(self, name=""):

# Optional name variable, by default it's empty

self.stack = []

self.name = name

def giveFullDeck(self):

# Gives the stack a full set of cards (52 cards)

suits = ["clubs", "diamonds", "hearts", "spades"]

for suit in suits:

for rank in range(1, 14):

self.stack.append(card(suit, rank)) # Uses the card class to create cards

def stackSize(self):

# Return the length of the stack

return len(self.stack)

def shuffle(self, amount=1):

# Shuffle the stack, just for fun there's an optional

# parameter, for how often you want to shuffle the stack

# adds "realism" (default is one time)

for i in range(0, amount):

shuffle(self.stack)

def deal(self, amount, stack, position=-1):

# deal a card to another stack, optional

# parameter for where to deal the card, default is

# at the end of the stack (-1)

for i in range(0, amount):

dealt = self.stack[0:1]

self.stack = self.stack[1:]

for i in dealt:

stack.stack.insert(position, i)

def splitDeckIntoTwoStacks(self, stack1, stack2):

# Split the stack into two other stacks

# Will try to split it 50/50

while len(self.stack) > 0:

self.deal(1, stack1)

self.deal(1, stack2)

def splitStack(self, stack):

# Does a similar thing to "splitDeckIntoTwoStacks"

# but this just splits itself into one other stack

while len(self.stack) > len(self.stack)/2:

self.deal(1, stack)

def __str__(self):

spaces = ""

print(self.name)

for card in self.stack:

print(spaces, card)

spaces += " "

return ""

def highPlay(mainDeck):

play1 = deck.stack[0].rank

print(" You played:", deck.stack[0])

play2 = deck.stack[1].rank

print("Your opponent played:", deck.stack[1])

if play1 > play2:

return "play1"

elif play2 > play1:

return "play2"

else:

return "draw"

# Lay out the things befoe the game

deck = cardStack() # Create a stack to be the main deck

deck.giveFullDeck() # give this stack a full deck of cards

deck.shuffle(amount=5) # shuffle this full deck of cards

player1Hand = cardStack() # give player1Hand a stack (empty)

player2Hand = cardStack() # Same for player2Hand

deck.splitDeckIntoTwoStacks(player1Hand, player2Hand) # Split the full deck of cards to player1Hand and player2Hand (26 cards)

round = 0

# Explain the rules for the game

print()

print(" W E L C O M E T O W A R !")

print()

print()

print(" The rules are simple, play a card and pray to god that it is a")

print("higher rank than your opponents card.")

print(" If you play the same card rank as your opponent, it's WAR")

print("You and your opponent will play two cards, only the second one")

print("needs to be higher rank than your opponents second card")

print("if it is, you get all the cards played that round")

print()

print(" L E T ' S B E G I N !")

wait = input(" press ENTER to start") # all "wait" variables, are just there to wait for the player to input something

# main game loop

while True:

# shuffle the players' deck at the start of each round

player1Hand.shuffle()

player2Hand.shuffle()

round += 1 # add to round timer by 1

print()

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

print()

print("this is round:", round) # tell the player what round it is

print("and you have", len(player1Hand.stack), "cards") # tell the player how many cards he has

deck.stack = [] # empty the main deck stack, should in theory always be empty at the start of a round

# but to be safe, it's forced emptied here

wait = input("press ENTER to play a card")

print()

# loop for the rounds

player1Hand.deal(1, deck) # Deal one card into the deck

player2Hand.deal(1, deck) # Deal one card into the deck

while True:

highestPlay = highPlay(deck) # Get who played the highest card, or if it was a draw

# Give the cards to the player that played the highest rank or

# start the code for a draw

if highestPlay == "play1":

print("YOU WON THE ROUND!")

print("You won the following cards:")

print(deck)

deck.deal(len(deck.stack), player1Hand)

break

elif highestPlay == "play2":

print("Sadly, your opponent won the round")

print("He won the following cards:")

print(deck)

deck.deal(len(deck.stack), player2Hand)

break

elif highestPlay == "draw":

print("AND IT'S A DRAW!")

wait = input("press ENTER to play a card facedown")

player1Hand.deal(1, deck) # deal the card to the back of the deck list (default)

wait = input("press ENTER to play a card faceup")

print()

player1Hand.deal(1, deck, 0) # deal the card to the front of the deck list

player2Hand.deal(1, deck)

player2Hand.deal(1, deck, 0)

print("Your opponent played two cards")

if len(player1Hand.stack) == 0: # if player1Hand.stack has no cards in it, player1Hand lost the game

print("Sadly, you lost the war")

wait = input("the game is over, press ENTER to quit")

break

elif len(player2Hand.stack) == 0: # if player2Hand.stack has no cards in it, player1Hand won the game

print("YOU ANNHILATED YOUR OPPONENT!")

wait = input("the game is over, press ENTER to quit")

break

Add a comment
Know the answer?
Add Answer to:
Please to indent and follow structure!!!!! Assignment 3 - The card game: War Due Date: June...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ program This program involves writing a VERY simplified version of the card game War. You...

    C++ program This program involves writing a VERY simplified version of the card game War. You may know this game or not but my rules are these 1. Split the deck between player1 and player2. Only the face values matter (2-14) and not the suits 2. Each player puts a card down on the table. The higher face value wins that hand. If the card values match, you will simply indicate tie and neither player wins.The original rules would require...

  • I am just curious about this question... please can you answer with applying indent and space...

    I am just curious about this question... please can you answer with applying indent and space clearly. Furthermore, can you make answer shortly as possible..? This is a python question Question 6.34 The two-player card game war is played with a standard deck of 52 cards. A shuffled deck is evenly split among the two players who keep their decks face-down. The game consists of battles until one of the players runs out of cards. In a battle, each player...

  • War—A Card game Playing cards are used in many computer games, including versions of such classic...

    War—A Card game Playing cards are used in many computer games, including versions of such classics as solitaire, hearts, and poker. War:    Deal two Cards—one for the computer and one for the player—and determine the higher card, then display a message indicating whether the cards are equal, the computer won, or the player won. (Playing cards are considered equal when they have the same value, no matter what their suit is.) For this game, assume the Ace (value 1) is...

  • the card game Acey Deucey, which is also known by several other names. In general, the...

    the card game Acey Deucey, which is also known by several other names. In general, the game is played with three or more people that continue to gamble for a pot of money. The pot grows and shrinks depending on how much General description of the game ● Two cards are dealt face up to a player from a shuffled deck of cards. ○ If the face of each card is the same then the player adds $1 into the...

  • I need to build the card game of War in C++. It will be a 2...

    I need to build the card game of War in C++. It will be a 2 player game. Each player will have their own deck of 52 cards. 2-10, Jack=11, Queen=12, King=13, Ace=14. Each player will draw one card from their deck. The player with the higher card wins both cards. If the card drawn is the same, then each player will draw 3 cards and on the 4th card drawn will show it. The player that shows the higher...

  • Program 4: C++ The Game of War The game of war is a card game played by children and budding comp...

    Program 4: C++ The Game of War The game of war is a card game played by children and budding computer scientists. From Wikipedia: The objective of the game is to win all cards [Source: Wikipedia]. There are different interpretations on how to play The Game of War, so we will specify our SMU rules below: 1) 52 cards are shuffled and split evenly amongst two players (26 each) a. The 26 cards are placed into a “to play” pile...

  • 2 A Game of UNO You are to develop an interactive game of UNO between a...

    2 A Game of UNO You are to develop an interactive game of UNO between a number of players. The gameplay for UNO is described at https://www.unorules.com/. Your program should operate as follows. 2.1 Setup 1. UNO cards are represented as variables of the following type: typedef struct card_s { char suit[7]; int value; char action[15]; struct card_s *pt; } card; You are allowed to add attributes to this definition, but not to remove any. You can represent colors by...

  • Instructions for Question: We are creating a new card game with a new deck. Unlike the...

    Instructions for Question: We are creating a new card game with a new deck. Unlike the normal deck that has 13 ranks (Ace through King) and 4 Suits (hearts, diamonds, spades, and clubs), our deck will be made up of the following. Each card will have: i) One rank from 1 to 11. ii) One of 9 different suits. Hence, there are 99 cards in the deck with 11 ranks for each of the 9 different suits, and none of...

  • Suppose, we have 3 players and they are playing a card game. In the card game,...

    Suppose, we have 3 players and they are playing a card game. In the card game, the deck contains 10 cards where there are 3 kings, 3 aces, and 4 jacks. Each player gets a card from the deck randomly. The winner of the game is determined based on the strength of the card where a king has 10 strength, an ace has 15 strength and a jack has 20 strength. Your task is to write a function called playgame()...

  • Need a blackjack code for my assignment its due in 3 hours: it has to include...

    Need a blackjack code for my assignment its due in 3 hours: it has to include classes and object C++. Create a fully functioning Blackjack game in three separate phases. A text based version with no graphics, a text based object oriented version and lastly an object oriented 2D graphical version. Credits (money) is kept track of throughout the game by placing a number next to the player name. Everything shown to the user will be in plain text. No...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT