Please help on this question: Python 3. Thanks :) Assignment Overview This assig
ID: 3907373 • Letter: P
Question
Please help on this question: Python 3. Thanks :)
Assignment Overview This assignment focuses on the design, implementation and testing of a Python program which uses classes to solve the problem described below. Note: you are using a class we provide; you are not designing a class It is worth 95 points (95% of course grade) and must be completed no later than 11:59 PM on Tuesday, June 26 Assignment Deliverable The deliverable for this assignment is the following file proj06.py the source code for your Python program Be sure to use the specified file name and to submit it for grading via the Mirmir system before the project deadline Assignment Background The goal of this project is to gain practice with use of classes and creating functions. You will design and implement a Python program which plays simplified Texas Hold'em Poker The program should deal two cards to two players (one card to each player, then a second card to each player), and then five community cards which players share to make their hands. A poker hand is the best five cards from the community cards plus the player's cards (i.e., best 5 out of 7 cards total). The goal of this assignment is to find the category of each player's hand and determine the winner. The rules of this game are relatively simple and you can find information about the game and about the poker hands in the links below. Keep in mind that you will only find the category of the hands and all nine cards can be dealt at once (a real poker game deals cards in stages to allow for betting, but we aren't betting). http://en.wikipedia.org/wiki/Texas holdem nd The categories in order from lowest to highest are: High card, 1 pair, 2 pair, 3 of a kind, straight, flush, full house, 4 of a kind, straight flush. You will not find a player's hand's value, but just the category of the hand. It is a tie if both players have hands in the same category. That is, if both of them have straights, it is considered a tie no matter who has the higher straight Our game is simplified in two ways We only compare categories to determine the winner, not the value of the hands. For example in a real poker game the winner of hands with exactly one pair would be determined by which 1.Explanation / Answer
**********************************************
cards.py
import random
"""
NOTE: If your terminal can't decode the unicode card suit symbols, set up the
bash terminal language environment to "en_US.utf8", like this --
export LANG=en_US.utf8
You might also want to put this in your ~/.bashrc to make the change
permanent accross the sessions.
For tcsh or zsh, there are similar methods exist, please look them up.
"""
class Card( object ):
""" Model a playing card. """
# Rank is an int (1-13), where aces are 1 and kings are 13.
# Suit is an int (1-4), where clubs are 1 and spades are 4.
# Value is an int (1-10), where aces are 1 and face cards are 10.
# List to map int rank to printable character (index 0 used for no rank)
rank_list = ['x','A','2','3','4','5','6','7','8','9','10','J','Q','K']
# List to map int suit to printable character (index 0 used for no suit)
# 1 is clubs, 2 is diamonds, 3 is hearts, and 4 is spades
# suit_list = ['x','c','d','h','s'] # for systems that cannot print Unicode symbols
suit_list = ['x','u2663','u2666','u2665','u2660']
def __init__( self, rank=0, suit=0 ):
""" Initialize card to specified rank (1-13) and suit (1-4). """
self.__rank = 0
self.__suit = 0
self.__face_up = None
# Verify that rank and suit are ints and that they are within
# range (1-13 and 1-4), then update instance variables if valid.
if type(rank) == int and type(suit) == int:
if rank in range(1,14) and suit in range(1,5):
self.__rank = rank
self.__suit = suit
self.__face_up = True
def rank( self ):
""" Return card's rank (1-13). """
return self.__rank
def value( self ):
""" Return card's value (1 for aces, 2-9, 10 for face cards). """
# Use ternary expression to determine value.
return self.__rank if self.__rank < 10 else 10
def suit( self ):
""" Return card's suit (1-4). """
return self.__suit
def is_face_up( self ):
""" Returns True if card is facing up."""
return self.__face_up
def flip_card( self ):
""" Flips card between face-up and face-down"""
self.__face_up = not self.__face_up
def __str__( self ):
""" Convert card into a string (usually for printing). """
# Use rank to index into rank_list; use suit to index into suit_list.
if self.__face_up:
return "{}{}".format( (self.rank_list)[self.__rank],
(self.suit_list)[self.__suit] )
else:
return "{}{}".format( "X", "X")
def __repr__( self ):
""" Convert card into a string for use in the shell. """
return self.__str__()
def __eq__( self, other ):
""" Return True, if Cards of equal rank and suit; False, otherwise. """
if not isinstance(other, Card):
return False
return self.rank() == other.rank() and self.suit() == other.suit()
class Deck( object ):
""" Model a deck of 52 playing cards. """
# Implement the deck as a list of cards. The last card in the list is
# defined to be at the top of the deck.
def __init__( self ):
""" Initialize deck--Ace of clubs on bottom, King of spades on top. """
self.__deck = [Card(r,s) for s in range(1,5) for r in range(1,14)]
def shuffle( self ):
""" Shuffle deck using shuffle method in random module. """
random.shuffle(self.__deck)
def deal( self ):
""" Return top card from deck (return None if deck empty). """
# Use ternary expression to guard against empty deck.
return self.__deck.pop() if len(self.__deck) else None
def is_empty( self ):
""" Return True if deck is empty; False, otherwise """
return len(self.__deck) == 0
def __len__( self ):
""" Return number of cards remaining in deck. """
return len(self.__deck)
def __str__( self ):
""" Return string representing deck (usually for printing). """
return ", ".join([str(card) for card in self.__deck])
def __repr__( self ):
""" Return string representing deck (for use in shell). """
return self.__str__()
def display( self, cols=13 ):
""" Column-oriented display of deck. """
for index, card in enumerate(self.__deck):
if index%cols == 0:
print()
print("{:3s} ".format(str(card)), end="" )
print()
print()
**********************************************
cardsDemo.py
import cards
''' The basic process is this:
1) You create a Deck instance, which is filled (automatically) with 52 Card instances
2) You can deal those cards out of the deck into hands, each hand a list of cards
3) You then manipulate cards as you add/remove them from a hand
'''
my_deck = cards.Deck()
print("======messy print a deck=====")
print(my_deck)
print("======pretty print a deck=====")
my_deck.display()
my_deck.shuffle()
print("======shuffled deck=====")
my_deck.display()
a_card = my_deck.deal()
print("Dealt card is:",a_card)
print('How many cards left:',len(my_deck))
print("Is the deck empty?",my_deck.is_empty())
# deal some hands and print
hand1_list=[]
hand2_list=[]
for i in range(5):
hand1_list.append(my_deck.deal())
hand2_list.append(my_deck.deal())
print(" Hand 1:", hand1_list)
print("Hand 2:", hand2_list)
print()
# take the last card dealt out of each hand
last_card_hand1 = hand1_list.pop()
last_card_hand2 = hand2_list.pop()
print("Hand1 threw down",last_card_hand1, ", Hand2 threw down", last_card_hand2)
print("Hands are now:",hand1_list, hand2_list)
# check the compares
if last_card_hand1 == last_card_hand2:
print(last_card_hand1, last_card_hand2, "of equal rank")
elif last_card_hand1.rank() > last_card_hand2.rank():
print(last_card_hand1.rank(), "of higher rank than",last_card_hand2.rank())
else:
print(last_card_hand2.rank(), "of higher rank than",last_card_hand1.rank())
if last_card_hand1.value() == last_card_hand2.value():
print(last_card_hand1, last_card_hand2, "of equal value")
elif last_card_hand1.value() > last_card_hand2.value():
print(last_card_hand1, "of higher value than",last_card_hand2)
else:
print(last_card_hand2, "of higher value than",last_card_hand1)
if last_card_hand1.suit() == last_card_hand2.suit():
print(last_card_hand1,'of equal suit with',last_card_hand2)
else:
print(last_card_hand1,'of different suit than',last_card_hand2)
# a foundation, a list of lists. 4 columns in this example
foundation_list = [[],[],[],[]]
column = 0
while not my_deck.is_empty():
foundation_list[column].append(my_deck.deal())
column += 1
if column % 4 == 0:
column = 0
for i in range(4):
print("foundation",i,foundation_list[i])
**********************************************
proj06.py
import cards
rank_list = ["High card", "one pair", "two pairs", "three of a kind", "straight", "flush","full house", "four of a kind", "straight flush"]
def less_than(c1,c2):
'''Return
True if c1 is smaller in rank,
True if ranks are equal and c1 has a 'smaller' suit
False otherwise'''
if c1.rank() < c2.rank():
return True
elif c1.rank() == c2.rank() and c1.suit() < c2.suit():
return True
return False
def min_in_list(L):
'''Return the index of the mininmum card in L'''
min_card = L[0] # first card
min_index = 0
for i,c in enumerate(L):
if less_than(c,min_card): # found a smaller card, c
min_card = c
min_index = i
return min_index
def cannonical(H):
''' Selection Sort: find smallest and swap with first in H,
then find second smallest (smallest of rest) and swap with second in H,
and so on...'''
for i,c in enumerate(H):
# get smallest of rest; +i to account for indexing within slice
min_index = min_in_list(H[i:]) + i
H[i], H[min_index] = H[min_index], c # swap
return H
def flush_7(H):
'''Return a list of 5 cards forming a flush,
if at least 5 of 7 cards form a flush in H, a list of 7 cards,
False otherwise.'''
color = []
for i,c in enumerate(H):
color.append(c.suit())
return_list = []
for s in color:
if color.count(s) >= 5:
for c in H:
if c.suit() == s:
return_list.append(c) # add to return list
if len(return_list) == 5: # if there collected all five cards,halt for loop
break
if len(return_list) == 5:
break
if return_list:
return return_list
else:
return False
def straight_7(H):
'''Return a list of 5 cards forming a straight,
if at least 5 of 7 cards form a straight in H, a list of 7 cards,
False otherwise.'''
H = cannonical(H)
return_list = []
returned_list = []
number = []
for i,c in enumerate(H):
number.append(c.rank())
number.sort()
min_rank = min(number)
while True:# add to return list
if min_rank in number and (min_rank + 1) in number and (min_rank + 2) in number and (min_rank + 3) in number and (min_rank + 4) in number :
for h in H:
if h.rank() == min_rank and h.rank() not in returned_list:
return_list.append(h)
returned_list.append(h.rank())
if h.rank() == min_rank + 1 and h.rank() not in returned_list:
return_list.append(h)
returned_list.append(h.rank())
if h.rank() == min_rank + 2 and h.rank() not in returned_list:
return_list.append(h)
returned_list.append(h.rank())
if h.rank() == min_rank + 3 and h.rank() not in returned_list:
return_list.append(h)
returned_list.append(h.rank())
if h.rank() == min_rank + 4 and h.rank() not in returned_list:
return_list.append(h)
returned_list.append(h.rank())
if min_rank + 4 == max(number) or len(return_list) == 5:
break
else:
min_rank += 1
if return_list:
return return_list
else:
return False
def straight_flush_7(H):
'''Return a list of 5 cards forming a straight flush,
if at least 5 of 7 cards form a straight flush in H, a list of 7 cards,
False otherwise.'''
if straight_7(H) == flush_7(H) :
return flush_7(H)
else:
return False
def four_7(H):
'''Return a list of 4 cards with the same rank,
if 4 of the 7 cards have the same rank in H, a list of 7 cards,
False otherwise.'''
number = []
for i,c in enumerate(H):
number.append(c.rank()) # get the all possible rank in the H
return_list = []
for s in number:
if number.count(s) == 4:
for c in H:
if c.rank() == s:
return_list.append(c) # add to return list
if len(return_list) == 4:
break
if len(return_list) == 4:
break
if return_list:
return return_list
else:
return False
def three_7(H):
'''Return a list of 3 cards with the same rank,
if 3 of the 7 cards have the same rank in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) is False.'''
color = []
for i,c in enumerate(H):
color.append(c.rank())
return_list = []
for s in color:
if color.count(s) == 3:
for c in H:
if c.rank() == s:
return_list.append(c) # add to return list
if len(return_list) == 3:
break
if len(return_list) == 3: # after add all three card, stop iterate the list
break
if return_list:
return return_list
else:
return False
def two_pair_7(H):
'''Return a list of 4 cards that form 2 pairs,
if there exist two pairs in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) and three_7(H) are both False.'''
dictionary_for_value = {}
for i in H:
if i.rank() not in dictionary_for_value:
dictionary_for_value[i.rank()] = 1
else:
dictionary_for_value[i.rank()] += 1
n_list = []
for d,v in dictionary_for_value.items():
if v == 2:
n_list.append(d) # for pair, add twice of same value
n_list.append(d)
return_list = []
if len(n_list) == 4:
i = 0
for n in n_list:
for h in H:
if h.rank() == n and h not in return_list:
return_list.append(h) # add to return list
return return_list
else:
return False
def one_pair_7(H):
'''Return a list of 2 cards that form a pair,
if there exists exactly one pair in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H), three_7(H) and two_pair(H) are False.'''
dictionary_for_value = {}
for i in H:
if i.rank() not in dictionary_for_value: # for the rank shows at the first time
dictionary_for_value[i.rank()] = 1
else:
dictionary_for_value[i.rank()] += 1
n_list = []
for d,v in dictionary_for_value.items():
if v == 2:
n_list.append(d)
n_list.append(d)
return_list = []
if len(n_list) == 2:
i = 0
for h in H:
if h.rank() == n_list[i]:
i+=1
return_list.append(h) # add to return list
if i == 2:
break
return return_list
else:
return False
def full_house_7(H):
'''Return a list of 5 cards forming a full house,
if 5 of the 7 cards form a full house in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) is False.'''
H_copy = H.copy() # create a shallow copy
color = []
for i,c in enumerate(H_copy):
color.append(c.rank())
return_list = []
for s in color:
if color.count(s) == 3:
for c in H_copy:
if c.rank() == s:
return_list.append(c) # add to return list
H_copy.remove(c) # remove the added card from the shallow copy
if len(return_list) == 3:
break
if len(return_list) == 3:
break
if len(return_list) == 3:
list2 = []
for o in H_copy:
list2.append(o.rank())
for l in list2:
if list2.count(l) == 2:
for h in H_copy:
if h.rank() == l:
return_list.append(h) # add to return list
if len(return_list) == 5:
break
if len(return_list) == 5:
break
if len(return_list) == 5:
return return_list
else:
return False
def main():
D = cards.Deck()
D.shuffle()
while True:
community_list = []
for i in range(5):
community_list.append(D.deal()) # create community cards
hand_1_list = []
hand_2_list = []
for i in range(2):
hand_1_list.append(D.deal())
for i in range(2):
hand_2_list.append(D.deal())
print("-"*40)
print("Let's play poker! ")
print("Community cards:",community_list)
print("Player 1:",hand_1_list)
print("Player 2:",hand_2_list)
print()
break
if __name__ == "__main__":
main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.