cse homeworks for prof washington
project 6/cards.py
import random class Card( object ): """ Model a playing card. """ # Rank is an integer (1-13), where aces are 1 and kings are 13. # Suit is an integer (1-4), where clubs are 1 and spades are 4. # Value is an integer (1-10), where aces are 1 and face cards are 10. # List to map integer 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 integer suit to printable character (index 0 used for no suit) # The commented-out list prints symbols rather than characters. You may use either. suit_list = ['x','c','d','h','s'] #suit_list = ['x',u'\u2660',u'\u2665',u'\u2666',u'\u2663'] def __init__( self, rank=0, suit=0 ): """ Initialize card to specified rank (1-13) and suit (1-4). """ self.__rank = 0 self.__suit = 0 # Verify that rank and suit are integers 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 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 __eq__( self, other ): """ Return True if ranks are equal. """ return self.__rank == other.__rank def __ne__( self, other ): """ Return True if ranks are not equal. """ return self.__rank != other.__rank def __le__( self, other ): """ Return True if rank of self <= rank of other. """ return self.rank() <= other.rank() def __lt__( self, other ): """ Return True if rank of self < rank of other. """ return self.rank() < other.rank() def __ge__( self, other ): """ Return True if rank of self >= rank of other. """ return self.rank() >= other.rank() def __gt__( self, other ): """ Return True if rank of self > rank of other. """ return self.rank() > other.rank() 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. return "{}{}".format( (self.rank_list)[self.__rank], (self.suit_list)[self.__suit] ) def __repr__( self ): """ Convert card into a string for use in the shell. """ return self.__str__() 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. """ 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()
project 6/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.pretty_print() my_deck.shuffle() print("======shuffled deck=====") my_deck.pretty_print() a_card = my_deck.deal() print("Dealt card is:",a_card) print('How many cards left:',my_deck.cards_count()) 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("\nHand 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.equal_rank(last_card_hand2): print(last_card_hand1, last_card_hand2, "of equal rank") elif last_card_hand1.get_rank() > last_card_hand2.get_rank(): print(last_card_hand1, "of higher rank than",last_card_hand2) else: print(last_card_hand2, "of higher rank than",last_card_hand1) if last_card_hand1.equal_value(last_card_hand2): print(last_card_hand1, last_card_hand2, "of equal value") elif last_card_hand1.get_value() > last_card_hand2.get_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.equal_suit(last_card_hand2): 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])
project 6/cardsDemo_updated.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("\nHand 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 > last_card_hand2: print(last_card_hand1, "of higher rank than",last_card_hand2) else: print(last_card_hand2, "of higher rank than",last_card_hand1) 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])
project 6/project06.pdf
CSE 231 Summer 2016 Programming Project #6
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 (9.5% of course grade) and must be completed no later than 11:59 PM on Monday, June 27. 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 handin 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 http://en.wikipedia.org/wiki/Poker_hands
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:
1. 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 pair had the highest card rank. That is, a pair of 10s wins over a pair of 3s. In our game, two hands with exactly one pair is considered a tie with no consideration given to the card ranks.
2. The Card class ranks an Ace as the lowest card in a suit; whereas traditional poker ranks an Ace
as highest. For simplicity, we will keep Aces as the lowest ranked card because we are only comparing categories not values. In particular, the cards 10h, Jh, Qh, Kh, Ah are not considered to make a straight in our game (they would under normal poker rules).
Assignment Specifications
1. Your program will use the Card and Deck classes found in the file named cards.py. You may not modify the contents of that file: we will test your project using our copy of cards.py. We have included a cardsDemo.py program to illustrate how to use the Card and Deck classes.
2. Your program will be subdivided into meaningful functions. Use a function for each category (except that “high-card” doesn’t need a function). See hints below.
3. Your program will display each player’s dealt cards, the community cards, and announce the
winner of the hand. Also, your program will display the winning combination (or either of the winning combinations, if a tie) as well as the category of the winning hand (see sample output below). For example, if the winning combination is “four-of-a-kind”, those four cards will be displayed; the fifth card in the hand will not be displayed. The display will be appropriately labeled and formatted.
4. After each run, the program will prompt the user if they want to see another hand: “do you want to continue: y or n”. The program should continue if user enters “y” or “Y”; otherwise, the program should halt. Also, if there are fewer than 9 cards left in the deck, the program should halt. Do not shuffle between hands; only shuffle at the beginning of the program.
5. Using dictionaries in this assignment is very useful as you can find how many cards have the same suit, or how many of them have the same rank. Most of my functions used a dictionary that had rank as the key, so I created a separate function to build such a dictionary from a hand.
Hints
1. There are 9 categories of hands. For each category (except high-card), I wrote a function that would take as an argument a list of 7 cards and return either a sub-list of cards that satisfied that category or an empty list. That design let me use the functions in Boolean expressions since an empty list evaluates to False whereas a non-empty list evaluates to True. Returning a list of cards also allowed me to use functions within functions, e.g., a straight flush must be a flush. Returning a list of cards also made testing easier because I could see not only that the function had found a combination of that type, but I also could easily check that it was correct. By the way, the function to find a straight was the hardest function to write.
2. Finding a winner is simple: start with the highest category and work your way down the categories in a cascade of “if” and “elif” statements. The result is a long, but repetitive structure. (You do not need to check all possible combinations of hands because you are only trying to find the highest category that a hand fits.)
3. Think strategically for testing. Custom build a set of hands for testing by creating particular
cards, e.g. H1 = [5c, 2c, 5h, 4s, 3d, 2h, 5d] can be used to test for a full house (I had to create each card first, e.g. c1 = cards.Card(5,1) to create the 5c card in H1. It took many lines to create the testing hands, but once built they proved useful.) Test each category function separately using the custom hands you created for testing. For example, result = full_house(H1) should yield a result [5c, 5h, 5d, 2c, 2h].
4. I found dictionaries useful within functions. Sometimes using the rank as key worked best; other
times using the suit as key was best. 5. In order for sort() and sorted() to work on any data type the less-than operation must be defined.
That operation is not defined in the Cards class so neither sort() nor sorted() work on Cards. (We tried to make the Cards class as generic as possible to work with a wide variety of card games, and the ordering of cards considering both rank and suit varies across card games.)
Sample Output (Note that this output uses the default suit_list from cards.py: suit_list = ['x','c','d','h','s'] ) ---------------------------------------- Let's play poker! Community cards: [9d, 3d, 6s, 2s, 2d] Player 1: [4h, 5c] Player 2: [9c, 5h] Player 1 wins with a straight: [2s, 3d, 4h, 5c, 6s] Do you wish to play another hand?(Y or N) y ---------------------------------------- Let's play poker! Community cards: [Ks, 6d, Kc, 5s, 9h] Player 1: [4c, 10s] Player 2: [7s, Qc] TIE with one pair: [Ks, Kc] Do you wish to play another hand?(Y or N) y ---------------------------------------- Let's play poker! Community cards: [Jc, 8h, Jd, Js, 3c] Player 1: [3h, 4d] Player 2: [As, 7c] Player 1 wins with a full house: [Jc, Jd, Js, 3h, 3c] Do you wish to play another hand?(Y or N) y ---------------------------------------- Let's play poker!
Community cards: [Qs, 4s, 8d, 2h, Qd] Player 1: [7d, 6c] Player 2: [2c, 8s] Player 2 wins with two pairs: [8s, 8d, 2c, 2h] Do you wish to play another hand?(Y or N) y ---------------------------------------- Let's play poker! Community cards: [10h, 7h, 10d, Kh, Ah] Player 1: [9s, Ad] Player 2: [Ac, 3s] TIE with two pairs: [10h, 10d, Ad, Ah] Deck has too few cards so game is done.