class Player: def __init__(self): self.hand = Hand() self.trumpSuit = JOKER self.tNumber = 0 self.cardinal = 0 def giveCard(self, card): self.hand.add(card) self.hand.sort(self.trumpSuit, self.tNumber) def declaredTrump(self, suit, num): self.trumpSuit = suit self.cardinal = num print "Someone declared %d with %d cards" % (suit, num) def bury(self, n): i = n while i > 0: bc = input("Choose what card(s) to bury: ") for k in range(len(self.hand.cardList)): if self.hand.cardList[i].toString == bc: self.hand.cardList.pop(i) i = i - 1 break
def split(hand1): hand2 = Hand("HAND 2", hand1.wager, False) hand1.was_split = True hand2.was_split = True hand1.cards.pop() hand1.calc_total() hand2.add_card(hand1.cards[0]) if hand2.cards[0] == "A": hand2.ace_list.append("A") return hand2
def __init__(self,screen,seat,cards): Hand.__init__(self,cards) self.name=seat[0].lower() self.human=False self.dummy=False self.humanspartner=False self.contractowner=False self.bgcolor=COLORS['tablelight'] self.orient='h' self.winsize=[373,370] # self.winsize=[cs[0]+12*self.dx,cs[1]+12*self.dy] self.x,self.y,self.dx,self.dy=10,10,25,25 sr=screen.get_rect() cs=DECKDEFS.cardsize seatx=[sr.centerx, sr.right-cs[0]/2, sr.centerx, cs[0]/2] seaty=[cs[1]/2, sr.bottom-self.winsize[1]/2, sr.bottom-cs[1]/2, sr.bottom-self.winsize[1]/2] for iseat in range(len(DECKDEFS.seats)): if self.name==DECKDEFS.seats[iseat].lower()[0]: self.orient=('h','v')[iseat%2] self.x=seatx[iseat] self.y=seaty[iseat] break if self.orient=='v': self.surf=pygame.Surface((cs[0],self.winsize[1]),1).convert() else: self.surf=pygame.Surface((self.winsize[0],cs[1]),1).convert() self.rect=self.surf.get_rect() self.rect.centerx=self.x self.rect.centery=self.y self.clear(screen) w,h=75,75 if self.name=='n': x=sr.centerx-w/2 y=cs[1] self.offset=(0,-10) elif self.name=='e': x=sr.right-w-cs[0] y=sr.centery-h/2 self.offset=(-10,0) elif self.name=='s': x=sr.centerx-w/2 y=sr.bottom-cs[1]-h self.offset=(0,10) elif self.name=='w': x=cs[0] y=sr.centery-h/2 self.offset=(10,0) # self.info=TextBox(None,(x,y),(w,h),14,COLORS['tablelight'],COLORS['yellow']) self.info=TextBox(None,(x,y),(w,h),14,COLORS['grey'],COLORS['yellow']) self.info.centeredy=False self.updateInfo()
class Player: def __init__(self,name = "Anonymous", chips = 1000 , face_up = False): self.name = name self._cards = [] self._hand = Hand(name) self._chips = chips self._face_up = face_up def add_card(self, card): self._cards.append(card) def add_card_to_hand(self,cards): for card in cards: self._hand._all_cards.append(card) def get_hand_name(self): return self._hand._hand_name def reset_player_cards(self): self._cards = [] self._hand = Hand(self.name) def display_cards(self): if self._face_up == True: print self.name , "has :" , self._cards else: print self.name , "has : [X,X]" def display_all_cards(self): print self.name , "has :" , self._cards def get_chips(self): return self._chips def add_chips(self, more_chips): self._chips += more_chips def set_chips(self, amount): self._chips = amount def get_cards(self): return self._cards def evaluate(self): if len(self._hand._all_cards) == 7: self._hand.evaluateHand() else: print "player cards:" , self._cards raw_input("Player does not have 7 cards") quit() def get_hand_category(self): return self._hand._category def get_hand_five_cards(self): return self._hand._five_cards def get_hand_name(self): return self._hand._hand_name
def find_best_hand(cardlist): combos = itertools.combinations(cardlist, 5) best_hand = None for c in combos: if best_hand is None: best_hand = Hand(c) else: compare = best_hand.compare_to_hand(Hand(c)) if compare == 1: continue elif compare == -1: best_hand = Hand(c) elif compare == 0: continue return best_hand
def __init__(self): self.moves = ["hit","stand","double","split"] self.deck = Deck() self.player = Player() self.player_hand = [] self.player_hand.append(Hand()) self.dealer_hand = Hand()
def __init__(self, name, initcards): ''' Constructs a new Player ''' self._name = name self._hand = Hand() for card in initcards: self._hand.addCard(card)
def find_best_plo_hand(player_cards, shared_cards): combos = select_combinations([ (player_cards, 2), (shared_cards, 3), ]) best_hand = None for c in combos: if best_hand is None: best_hand = Hand(list(c)) else: compare = best_hand.compare_to_hand(Hand(list(c))) if compare == 1: continue elif compare == -1: best_hand = Hand(list(c)) elif compare == 0: continue return best_hand
def __init__(self): self.hand = Hand() self.cardinal = 0 # How many cards were declared trump self.trumpSuit = JOKER self.tNumber = 0 self.trumps = 0 self.jokers = 0 self.spades = 0 self.hearts = 0 self.diamonds = 0 self.clubs = 0
class Player(object): def __init__(self, hand=None, cash=None, holds=None): self.hand = Hand() self.cash = 100 self.holds = [0, 0, 0, 0, 0] def add_card(self, card): for k in range(5): if self.hand[k].get_suite() == -1: self.hand.pop(k) self.hand.insert(k, card) break def hold_card(self, selection): self.holds[selection] = 1 def add_holds(self, holds): self.holds = holds def submit_play(self, temp=None): temp = DiscardPile() for k in range(len(self.holds)): if self.holds[k] == 0: temp.append(self.hand.get_card(k)) self.hand[k] = Card(-1, -1) # self.clear_holds() return temp def get_hand(self): return self.hand def get_holds(self): return self.holds def clear_holds(self): temp = [0, 0, 0, 0, 0] self.holds = list(temp) def print_holds(self): for k in range(5): print self.holds[k]
def calculateRound(self): #### TODO : Calculate Winning points and Tie ############################################################### for b in self.POOL: self.R_RESULT.append({'bot':b,'hand':Hand.getPowerHand(Hand,b.getHand())}) self.R_RESULT= sorted(self.R_RESULT,key=lambda k:k['hand']) #print(self.R_RESULT) for b in self.POOL: if isinstance(b,Player):continue b.setLastGameWin(self.R_RESULT[0]['hand']) ###### This happens when all players have [1,2,3,4,5] hand uHand = [1,2,3,4,5] count = 0 for b in self.R_RESULT: if b['hand'] == uHand: count+=1 if count == 5: for b in self.POOL: b.tieGame() return if count == 3: for i in range(2): self.R_RESULT[i]['bot'].winGame() if self.R_RESULT[3]['bot'] == self.FLIPPER: self.R_RESULT[3]['bot'].loseGame() self.R_RESULT[4]['bot'].notWin() if self.R_RESULT[4]['bot'] == self.FLIPPER: self.R_RESULT[3]['bot'].notWin() self.R_RESULT[4]['bot'].loseGame() return ###################################################################### f_idx = 99 for x in self.R_RESULT: if x['bot'] == self.FLIPPER: f_idx = self.R_RESULT.index(x) if self.R_RESULT[0]['hand'] == self.R_RESULT[1]['hand']: if self.R_RESULT[0]['bot'] != self.FLIPPER and self.R_RESULT[1]['bot'] != self.FLIPPER: self.R_RESULT.append(self.R_RESULT.pop(f_idx)) self.R_RESULT[0]['bot'].winGame() self.R_RESULT[1]['bot'].winGame() self.R_RESULT[2]['bot'].notWin() self.R_RESULT[3]['bot'].notWin() self.R_RESULT[4]['bot'].loseGame() else: if self.R_RESULT[0]['bot'] != self.FLIPPER: self.R_RESULT.append(self.R_RESULT.pop(f_idx)) self.R_RESULT[0]['bot'].winGame() self.R_RESULT[1]['bot'].notWin() self.R_RESULT[2]['bot'].notWin() self.R_RESULT[3]['bot'].notWin() self.R_RESULT[4]['bot'].loseGame()
def nextHand(self): bet = self.r.randint(0,self.getSum(self.currentHandValue)) handValue = 0 if(bet < self.history[self.currentHandValue][0]): handValue = 0 elif (bet < self.history[self.currentHandValue][0] + self.history[self.currentHandValue][1]): handValue = 1 else: handValue = 2 self.prevHandValue = self.currentHandValue self.currentHandValue = handValue return Hand.getHand(handValue)
class Player: def __init__(self, name, auto=False): self.name = name self.hand = Hand() self.score = 0 self.tricksWon = [] def addCard(self, card): self.hand.addCard(card) def getInput(self, option): card = None while card is None: card = raw_input(self.name + ", select a card to " + option + ": ") return card def play(self, option='play', c=None, auto=False): if auto: card = self.hand.getRandomCard() elif c is None: card = self.getInput(option) else: card = c if not auto: card = self.hand.playCard(card) return card def trickWon(self, trick): self.score += trick.points def hasSuit(self, suit): return len(self.hand.hand[suit.iden]) > 0 def removeCard(self, card): self.hand.removeCard(card) def discardTricks(self): self.tricksWon = [] def hasOnlyHearts(self): return self.hand.hasOnlyHearts()
class HandTest(unittest.TestCase): def setUp(self): self.hand = Hand() self.hand.addToHand(Card(2, 'hearts')) self.hand.addToHand(Card(9, 'hearts')) def test_numOfCards(self): self.assertEqual(2, self.hand.numOfCards()) def test_getValue1(self): self.assertEquals(11, self.hand.getValue()) def test_aceGetValue(self): hand = Hand() hand.addToHand(Card('A', 'spades')) hand.addToHand(Card('A', 'diamonds')) self.assertEquals(12, hand.getValue()) def test_resetHand(self): self.hand.resetHand() self.assertEquals(0, self.hand.numOfCards())
class ComputerAI: def __init__(self): self.hand = Hand() self.cardinal = 0 # How many cards were declared trump self.trumpSuit = JOKER self.tNumber = 0 self.trumps = 0 self.jokers = 0 self.spades = 0 self.hearts = 0 self.diamonds = 0 self.clubs = 0 def giveHand(self, h): self.hand = h # Reinitialize suit numbers self.trumps = 0 self.jokers = 0 self.spades = 0 self.hearts = 0 self.diamonds = 0 self.clubs = 0 for c in h: if c.suit == JOKER: self.jokers = self.jokers + 1 self.trumps = self.trumps + 1 elif c.number == self.tNumber: self.trumps = self.trumps + 1 elif c.suit == SPADES: self.spades = self.spades + 1 elif c.suit == HEARTS: self.hearts = self.hearts + 1 elif c.suit == DIAMONDS: self.diamonds = self.diamonds + 1 elif c.suit == CLUBS: self.clubs = self.clubs + 1 def declaredTrump(self, suit, num): # Sets trumps self.trumpSuit = suit self.cardinal = num def giveCard(self, c): # Adds the card into hand and then choose a card to declare, if appropriate self.hand.add(c) self.hand.sort(self.trumpSuit, self.tNumber) if c.suit == JOKER: self.jokers = self.jokers + 1 self.trumps = self.trumps + 1 elif c.number == self.tNumber: self.trumps = self.trumps + 1 elif c.suit == SPADES: self.spades = self.spades + 1 elif c.suit == HEARTS: self.hearts = self.hearts + 1 elif c.suit == DIAMONDS: self.diamonds = self.diamonds + 1 elif c.suit == CLUBS: self.clubs = self.clubs + 1 def avg(s): # returns a float that is the average value of the cards in a specific suit sum = 0 count = 0 for c in self.hand.cardList: if c.suit == s: sum = sum + c.number count = count + 1 if count > 0: return float(sum) / count else: return 0 def checkPairs(): # returns a float value that indicates how many pairs/triples in the hand count = 0 for c in self.hand.cardList: partial = 0.5 for d in self.hand.cardList: if c.equals(d): partial = partial + 0.5 if partial >= 1: count = count + partial return count # Logic for deciding card suit if self.trumps > self.cardinal: if self.cardinal == 0: temp = None count = 0 count_trump = 0 jpair = False for i in range(len(self.hand.cardList)): c = self.hand.cardList[i] if c.suit == JOKER: index = i how_many = 1 while index + 1 < len(self.hand.cardList) and self.hand.cardList[index + 1].equals(c): how_many = how_many + 1 index = index + 1 if how_many > 1 and (self.trumps > 4 or checkPairs() > 4): jpair = True temp = JOKER count = how_many count_trump = self.trumps elif c.number == self.tNumber: index = i how_many = 1 while index + 1 < len(self.hand.cardList) and self.hand.cardList[index + 1].equals(c): how_many = how_many + 1 index = index + 1 if len(self.hand.cardList) < 16: if c.suit == SPADES and self.spades > count_trump and self.spades > float(len(self.hand.cardList)) / 2: return SPADES + 5 * (how_many - 1) elif c.suit == HEARTS and self.hearts > count_trump and self.hearts > float(len(self.hand.cardList)) / 2: return HEARTS + 5 * (how_many - 1) elif c.suit == CLUBS and self.clubs > count_trump and self.clubs > float(len(self.hand.cardList)) / 2: return CLUBS + 5 * (how_many - 1) elif c.suit == DIAMONDS and self.diamonds > count_trump and self.diamonds > float(len(self.hand.cardList)) / 2: return DIAMONDS + 5 * (how_many - 1) else: return None else: if c.suit == SPADES and self.spades > count_trump and self.spades > float(len(self.hand.cardList)) / 4 and self.spades + self.trumps > float(len(self.hand.cardList)) / 3: temp = SPADES count = how_many count_trump = self.spades elif c.suit == HEARTS and self.hearts > count_trump and self.hearts > float(len(self.hand.cardList)) / 4 and self.hearts + self.trumps > float(len(self.hand.cardList)) / 3: temp = HEARTS count = how_many count_trump = self.hearts elif c.suit == CLUBS and self.clubs > count_trump and self.clubs > float(len(self.hand.cardList)) / 4 and self.clubs + self.trumps > float(len(self.hand.cardList)) / 3: temp = CLUBS count = how_many count_trump = self.clubs elif c.suit == DIAMONDS and self.diamonds > count_trump and self.diamonds > float(len(self.hand.cardList)) / 4 and self.diamonds + self.trumps > float(len(self.hand.cardList)) / 3: temp = DIAMONDS count = how_many count_trump = self.diamonds # end of for loop if jpair and temp == JOKER and count > 1: return temp + 5 * count elif count > 0 and count_trump > 0 and temp != JOKER: return temp + 5 * (count - 1) else: return None ############################# end of cardinal == 0 elif self.cardinal == 1: temp = None count = 0 count_trump = 0 jpair = False for i in range(len(self.hand.cardList)): c = self.hand.cardList[i] if c.suit == JOKER: index = i how_many = 1 while index + 1 < len(self.hand.cardList) and self.hand.cardList[index + 1].equals(c): how_many = how_many + 1 index = index + 1 if how_many > 1 and self.trumps > 4 and checkPairs() > 4 and avg(SPADES) + avg(HEARTS) + avg(DIAMONDS) + avg(CLUBS) > 34: jpair = True temp = JOKER count = how_many count_trump = self.trumps elif c.number == self.tNumber: index = i how_many = 1 while index + 1 < len(self.hand.cardList) and self.hand.cardList[index + 1].equals(c): how_many = how_many + 1 index = index + 1 if how_many > 1 and self.spades > count_trump: p = checkPairs() l = float(len(self.hand.cardList)) if c.suit == SPADES: if self.spades + self.trumps > l / 2.5 and p > 4: temp = SPADES count = how_many count_trump = self.spades elif self.spades + self.trumps > l / 2 and p > 2 and avg(HEARTS) + avg(DIAMONDS) + avg(CLUBS) > 27: temp = SPADES count = how_many count_trump = self.spades elif self.spades + self.trumps > l / 3 and p > 5: temp = SPADES count = how_many count_trump = self.spades elif c.suit == HEARTS: if self.hearts + self.trumps > l / 2.5 and p > 4: temp = HEARTS count = how_many count_trump = self.hearts elif self.hearts + self.trumps > l / 2 and p > 2 and avg(SPADES) + avg(DIAMONDS) + avg(CLUBS) > 27: temp = HEARTS count = how_many count_trump = self.hearts elif self.hearts + self.trumps > l / 3 and p > 5: temp = HEARTS count = how_many count_trump = self.hearts elif c.suit == CLUBS: if self.clubs + self.trumps > l / 2.5 and p > 4: temp = CLUBS count = how_many count_trump = self.clubs elif self.clubs + self.trumps > l / 2 and p > 2 and avg(SPADES) + avg(DIAMONDS) + avg(HEARTS) > 27: temp = CLUBS count = how_many count_trump = self.clubs elif self.clubs + self.trumps > l / 3 and p > 5: temp = CLUBS count = how_many count_trump = self.clubs elif c.suit == DIAMONDS: if self.diamonds + self.trumps > l / 2.5 and p > 4: temp = DIAMONDS count = how_many count_trump = self.diamonds elif self.diamonds + self.trumps > l / 2 and p > 2 and avg(SPADES) + avg(HEARTS) + avg(CLUBS) > 27: temp = DIAMONDS count = how_many count_trump = self.diamonds elif self.diamonds + self.trumps > l / 3 and p > 5: temp = DIAMONDS count = how_many count_trump = self.diamonds if jpair and temp == JOKER and count > 1: return temp + 5 * count elif count > 1 and count_trump > 0 and temp != JOKER: return temp + 5 * (count - 1) else: return None else: return None def bury(self, n): def checkPairs(x): count = 0 for c in self.hand.cardList: if c.suit == x: p = 1 for d in self.hand.cardList: if not c is d and d.suit == x and c.number != self.tNumber and c.equals(d): p = p + 1 if p > 1: count = count + p return count def countPoints(suit): sum = 0 for c in self.hand.cardList: if c.suit == suit and suit != 0 and c.number != self.tNumber: if c.number == 5: sum = sum + 5 elif c.number == 10 or c.number == 13: sum = sum + 10 elif suit == 0 and c.number == self.tNumber: if c.number == 5: sum = sum + 5 elif c.number == 10 or c.number == 13: sum = sum + 10 return sum def suitSingle(card): for c in self.hand.cardList: if not c is card and c.equals(card): return True return False tlist = [(1, self.spades), (2, self.hearts), (3, self.clubs), (4, self.diamonds)] tlist.sort(key = lambda x: x[1]) buriedCards = [] print tlist i = 0 while i < 4 and len(buriedCards) < n: if tlist[i][0] == self.trumpSuit: i = i + 1 pass # Check that the suit with the least number of cards contains points or pairs/triples. If those pairs and triples can be # subtracted from the total count of the suit to be less than the treasure card count, then we can proceed to bury them. x = countPoints(tlist[i][0]) y = checkPairs(tlist[i][0]) print x print y if x <= 10 * self.jokers and tlist[i][1] - y <= n: for c in self.hand.cardList: if c.suit == tlist[i][0] and c.number != self.tNumber and c.number != 14 and suitSingle(c): self.hand.remove(c) print "Got Here 1" buriedCards.append(c) print len(buriedCards) i = i + 1 if len(buriedCards) < n: print "F****d up!" else: return buriedCards
# Hand.py class Hand(object): def __init__(self, label=""): self.label = label self.cards = [] def add(self, card): self.cards.append(card) def dump(self): print(self.label + "'s Cards:") for c in self.cards: print(" ", c) from Hand import Hand from Card import Card h = Hand("North") h.add(Card(5, "c")) h.add(Card(10, "d")) h.add(Card(13, "s")) h.dump()
def test_trick_winner_winner_lower_than_2sluffs(hearts, playOrder): board = Hand(inputString=("8H 9H QC KS")) assert hearts.determineTrickWinner(board, playOrder).getName() == 'Bob'
def __init__(self): self._constructs = Hand() self._heroes = []
#test_hand.py # # by David M. Reed and John Zelle # from Data Structures and Algorithms Using Python and C++ # downloaded from publisher's website: # https://www.fbeedle.com/content/data-structures-and-algorithms-using-python-and-c # on July 23, 2014 from Hand import Hand from Card import Card h = Hand("North") h.add(Card(5, "c")) h.add(Card(10, "d")) h.add(Card(13, "s")) h.dump() h.sort() h.dump()
def test_compute_trick_points_qs(hearts): board = Hand(inputString=("6C 7C QS QC")) assert hearts.computeTrickPoints(board) == 13
def showAllHands(self): for b in self.POOL: print("#{} hand {} {}".format(b.getName(), b.getHand(), Hand.getPowerHand(Hand, b.getHand())))
def dealHand(self, num_cards): player_hand = Hand() player_hand.deal(num_cards, self) return player_hand
def doSplit(self, hand): self.hasSplit = True self.addHand(Hand([self.getHands()[hand].popCard()]))
class Player(object): ''' Player Constructor Set the players name, initializes the players hand, initializes list of hands, initializes players' bank roll and bet amount. @param: name @return: NONE ''' def __init__(self, name): self.__name = name self.__current_hand = Hand() self.__list_of_hands = [] self.__poker_hands = [] self.__bank_roll = 0 self.__bet_amount = 0 self.__current_hand_size = 0 # Poker Hand Utility object which evaluates any 5 card hand self.__poker_hand_utility = PokerHandUtility() ''' Players Destructor clears the list of hands LIST @param: self @return: NONE ''' def __del__(self): del self.__list_of_hands[:] def get_poker_hand_utility(self): return self.__poker_hand_utility def get_poker_hands(self): return self.__poker_hands ''' add_card Add input new card object to the Players' hand @param: new_card - input Card object @return: NONE ''' def add_card(self, new_card): self.__current_hand.add_card(new_card) self.__current_hand_size = self.__current_hand_size + 1 ''' add_funds Adds the specified amount to the player's funds @param: new_funds: The amount to be added to the player's funds @return: NONE ''' def add_funds(self, new_funds): self.__bank_roll = self.__bank_roll + float(new_funds) ''' remove_funds Removes the specified amount from the player's funds @param: amount_of_funds: The amount to be removed from the player's funds @return: NONE ''' def remove_funds(self, amount_of_funds): # probably should check to make sure the player as enough funds in their # bank roll before blindly deduction cash from the account. # we dont want our account to go in the red or become negative self.__bank_roll = self.__bank_roll - float(amount_of_funds) ''' get_funds Retrieves the player's funds @param: self @return: int: The integer amount of funds the player has ''' def get_funds(self): return self.__bank_roll ''' get_bet_amount Retrieves the bet amount @param: self @return: int: The amount of money the player bet ''' def get_bet_amount(self): return self.__bet_amount ''' set_bet_amount Sets the bet amount @param: bet_amount : The amount of money the player is betting @return: NONE ''' def set_bet_amount(self, bet_amount): self.__bet_amount = bet_amount ''' get_name Retrieves the player's name @param: self @return string: The player's name ''' def get_name(self): return self.__name ''' five_card_stud_hand get_hand Retrieves the player's current hand @param: self @return: LIST : The player's hand ''' def get_hand(self): #return self.__current_hand.get_cards() return self.__current_hand def get_current_hand_size(self): return len(self.__current_hand.get_cards()) def show_hand(self): if self.__current_hand.get_cards(): for card in self.__current_hand.get_cards(): card.print_card() else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def show_hand_by_index(self): ''' The pythonic way to do it is from the PEP 8 style guide: https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty ''' if self.__current_hand.get_cards(): index = 0 for card in self.__current_hand.get_cards(): card.print_card_by_index(index) index = index + 1 else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def show_hand_ver1(self): if self.__current_hand.get_cards(): idx = 0 for card in self.__current_hand.get_cards(): self.__current_hand.get_cards()[idx].print_card() idx = idx + 1 else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def get_card_at_index(self, position): return self.__current_hand[position] def show_hand_single_card_format(self): if self.__current_hand.get_cards(): for card in self.__current_hand.get_cards(): card.print_single_card() else: print "PLAYERS HAND IS EMPTY NO CARDS ARE IN THE HAND\n" def draw(self, deck): self.__current_hand.add_card(deck.draw_card()) return self ''' reset Resets the player's bet and hand @param: self @return: NONE ''' def reset(self): # reset the bet amount self.__bet_amount = 0 # clear the players' current hand self.__current_hand.clear() ''' get_list_of_players_hands Retrieves the players' history of list of hands @param: self @return: LIST : the list of players previous hands while playing poker ''' def get_list_of_players_hands(self): return self.__list_of_hands ''' add_hand_to_list_of_players_hands Add the latest current hand to the list of players hands This can be used to study the players hands later @param: self @param: list : five_stud_hand @return: NONE ''' def add_hand_to_list_of_players_hands(self, five_stud_hand): self.__list_of_hands.append(five_stud_hand) def get_list_of_players_hands_size(self): return len(self.__list_of_hands) ''' This was done to make the Card class iterable ''' def __eq__(self, other): return self.__dict__ == other.__dict__ ''' toString method @return - String respresentation in a customized card hand order ''' def toString(self): return "Hand: \t\t{} Test\t| {} | {} | {} | {}".format( self.__current_hand.get_cards()[0].print_card(), self.__current_hand.get_cards()[1].print_card(), self.__current_hand.get_cards()[2].print_card(), self.__current_hand.get_cards()[3].print_card(), self.__current_hand.get_cards()[4].print_card())
def test_resolve_hands(self): # SCENARIO 1 - p1 busts, p2 wins normally p1 = Player() p2 = Player(Hand([Card('HJ'), Card('H9')])) p1.hands[0].status = 'busted' p2.hands[0].status = 'stand' self.assertEqual(p1.recent_winloss, []) self.assertEqual(p2.recent_winloss, []) dealer_cards = [Card('HJ'), Card('C7')] # no bust Jack.resolve_hands(p1, dealer_cards) Jack.resolve_hands(p2, dealer_cards) self.assertEqual(len(p1.recent_winloss), 1) self.assertEqual(len(p2.recent_winloss), 1) self.assertEqual(p1.recent_winloss[0], 0) self.assertEqual(p2.recent_winloss[0], 2) # SCENARIO 2 - p1 blackjacks, p2 push, dealer does not bust p1 = Player(Hand([Card('HJ'), Card('HA')])) p2 = Player(Hand([Card('HJ'), Card('C7')])) p1.hands[0].status = 'blackjack' p2.hands[0].status = 'stand' self.assertEqual(p1.recent_winloss, []) self.assertEqual(p2.recent_winloss, []) dealer_cards = [Card('HJ'), Card('C7')] # no bust Jack.resolve_hands(p1, dealer_cards) Jack.resolve_hands(p2, dealer_cards) self.assertEqual(len(p1.recent_winloss), 1) self.assertEqual(len(p2.recent_winloss), 1) self.assertEqual(p1.recent_winloss[0], 2.5) self.assertEqual(p2.recent_winloss[0], 1) # SCENARIO 3 - p1 push, p2 loses normally p1 = Player(Hand([Card('H9'), Card('H9')])) p2 = Player(Hand([Card('H2'), Card('C3')])) p1.hands[0].status = 'stand' p2.hands[0].status = 'stand' self.assertEqual(p1.recent_winloss, []) self.assertEqual(p2.recent_winloss, []) dealer_cards = [Card('H9'), Card('C9')] # no bust Jack.resolve_hands(p1, dealer_cards) Jack.resolve_hands(p2, dealer_cards) self.assertEqual(len(p1.recent_winloss), 1) self.assertEqual(len(p2.recent_winloss), 1) self.assertEqual(p1.recent_winloss[0], 1) self.assertEqual(p2.recent_winloss[0], 0) # SCENARIO 4 - p1 blackjack push, p2 unnat blackjack (loss), dealer blackjacks p1 = Player(Hand([Card('HA'), Card('D10')])) p2 = Player(Hand([Card('H2'), Card('C3'), Card('C10'), Card('D6')])) p1.hands[0].status = 'blackjack' p2.hands[0].status = 'unnat' self.assertEqual(p1.recent_winloss, []) self.assertEqual(p2.recent_winloss, []) dealer_cards = [Card('HA'), Card('C10')] # no bust Jack.resolve_hands(p1, dealer_cards) Jack.resolve_hands(p2, dealer_cards) self.assertEqual(len(p1.recent_winloss), 1) self.assertEqual(len(p2.recent_winloss), 1) self.assertEqual(p1.recent_winloss[0], 1) self.assertEqual(p2.recent_winloss[0], 0)
def test_compute_trick_points_heart_qs_jd(hearts): board = Hand(inputString=("6H QS JD TH")) assert hearts.computeTrickPoints(board) == 5
def test_compute_trick_points_jd(hearts): board = Hand(inputString=("6C JD 7C QC")) assert hearts.computeTrickPoints(board) == -10
def calculate_value(seven_cards): five_cards_formations = combinations(seven_cards, 5) hands = [Hand(formation) for formation in five_cards_formations] return max(hands)
class Game: # Constructor def __init__(self): pass # Function to run the whole Blackjack game def runGame(self): # Create stats for player print("Welcome to Blackjack!") playerName = input("What is your name? ") cashAmount = int(input("How much money would you like to play with? ")) playerWins = 0 playerLosses = 0 ties = 0 # Infinite loop to keep game going for as long as the player wants to keepPlaying = True while keepPlaying: # Ask for bet amount print("The maximum amount you can bet is ", cashAmount) betAmount = int(input("How much would you like to bet? ")) cashAmount -= betAmount # Create deck and shuffle it self.deck = Deck() self.deck.shuffle() # Create hand objects for dealer and player self.playersHand = Hand(isDealer=False) self.dealersHand = Hand(isDealer=True) # Deal 2 cards each to dealer and player for i in range(2): self.playersHand.addCard(self.deck.hit()) self.dealersHand.addCard(self.deck.hit()) # Show hands of dealer and player print("Dealer's hand is: ") self.dealersHand.showHand() print() print("Your hand is: ") self.playersHand.showHand() # Loop for players turn stopGame = False while not stopGame: # Ask player if they want to hit or stand choice = input( "Do you want to hit or stand? (h/hit or s/stand) ") choice = choice.lower() while choice not in ["h", "s", "hit", "stand"]: choice = input( "That is not a valid input! Please choose to hit or stand: " ) choice = choice.lower() # Deal card if player chooses to hit if choice == "hit" or choice == "h": self.playersHand.addCard(self.deck.hit()) self.playersHand.showHand() # Check if player has busted after adding card if self.playersHand.getHandValue() > 21: print("You busted and therefore have lost!") stopGame = True # Option if player chose to stand else: # Display both hands and values playerHandValue = self.playersHand.getHandValue() dealerHandValue = self.dealersHand.getHandValue() print("Dealer's hand: ") for card in self.dealersHand.cards: print(card) print("Dealer's hand value: ", dealerHandValue) print("Your hand: ") for card in self.playersHand.cards: print(card) print("Your hand value: ", playerHandValue) # Win, loss, or tie checker if playerHandValue > dealerHandValue: print("You win and the dealer loses!") playerWins += 1 cashAmount += betAmount * 2 elif playerHandValue == dealerHandValue: print("Tie!") ties += 1 cashAmount += betAmount else: print("You lose and the dealer wins!") playerLosses += 1 # Print stats print(playerName) print("Wins: ", playerWins) print("Losses: ", playerLosses) print("Ties: ", ties) print("Cash: ", cashAmount) print() print("Dealer") print("Wins: ", playerLosses) print("Losses: ", playerWins) print("Ties: ", ties) stopGame = True # Check if player wants to continue playing playAgain = input("Do you want to play again? (y/yes or n/no) ") playAgain = playAgain.lower() while playAgain not in ["y", "yes", "n", "no"]: playAgain = input( "This is not a valid input! Please enter y or n: ") playAgain = playAgain.lower() if playAgain == "y": gameOver = True else: print("Game will now end. Thank you!") keepPlaying = False
import Utils playing = True player_chips = Chip() #the game while True: print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n\ Dealer hits until she reaches 17. Aces count as 1 or 11.') deck = Deck() deck.shuffle() player_hand = Hand() dealer_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) Utils.take_bet(player_chips) Utils.show_some(player_hand,dealer_hand)
def __init__(self): self.hand = Hand()
def clearCards(self): self.hand = Hand()
def detect_hand(frame, hist): detected_hand, masked, raw = locate_object(frame, hist) return Hand(detected_hand, masked, raw, frame)
def test_four_of_a_kind(self): myHand = Hand("Vu") myCards = ["7C","8D","7D","7S","TC","7H","TD"] expected = ['TC', '7C', '7D', '7S', '7H'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 8) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11 } playing = True print('Welcome to blackjack!') deck = Deck(suits, ranks) deck.shuffle() player_chips = Chips() Play = True while Play == True: player = Hand() dealer = Hand() if player_chips.total == 0: print('Sorry, you have lost all your chips. Please come back later.') break bet = take_bet(player_chips.total) playing = True if player_chips.total < bet: print( 'Insufficient chips, please make a lower bet. Your chip balance is {}' .format(player_chips.total)) bet = take_bet() player.add_card(deck.deal(), values) player.add_card(deck.deal(), values) dealer.add_card(deck.deal(), values) dealer.add_card(deck.deal(), values)
def test_two_pairs(self): myHand = Hand("Vu") myCards = ["7C","8D","AD","7S","TC","KH","TD"] expected = ['AD', '7S', '7C', 'TD', 'TC'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 3) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def __init__(self): #hand to be stored by the AI self.hand = Hand()
def test_three_of_a_kind(self): myHand = Hand("Vu") myCards = ["7C","8D","7D","AS","TC","7H","JD"] expected = ['JD', 'AS', '7H', '7D', '7C'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 4) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def test_aceGetValue(self): hand = Hand() hand.addToHand(Card('A', 'spades')) hand.addToHand(Card('A', 'diamonds')) self.assertEquals(12, hand.getValue())
def test_flush(self): myHand = Hand("Vu") myCards = ["2C","4S","5C","3C","TC","AC","8C"] expected = ['3C', '5C', '8C', 'TC', 'AC'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 6) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def setUp(self): self.hand = Hand() self.hand.addToHand(Card(2, 'hearts')) self.hand.addToHand(Card(9, 'hearts'))
def test_compute_points_one_heart(hearts): board = Hand(inputString=("6C 7C 4H QC")) assert hearts.computeTrickPoints(board) == 1
def test_trick_winner_all_same_suit_4th_position(hearts, playOrder): board = Hand(inputString=("8H 9H 3H QH")) assert hearts.determineTrickWinner(board, playOrder).getName() == 'Doug'
class Blackjack(object): def __init__(self): self.players = [] self.setNumOfPlayers(1) self.setNumOfDecks(1) self.dealer = Hand() def setNumOfDecks(self, numOfDecks): self.numOfDecks = numOfDecks self.deck = MultiDeck(self.numOfDecks) def setNumOfPlayers(self, numOfPlayers): self.numOfPlayers = numOfPlayers self.players = [] for i in range(1, self.getNumOfPlayers()+1): self.players.append(Player("Player"+str(i))) def removePlayer(self, playerName): for player in self.players: if player.getName() == playerName: self.players.remove(player) self.numOfPlayers -= 1 return True return False def setUp(self): correctInput = False numOfPlayers = 0 while not correctInput: input = raw_input("please enter number of players: ") try: correctInput = True numOfPlayers = int(input) except ValueError: print("That's not a number!") correctInput = False continue else: if numOfPlayers > 0: self.setNumOfPlayers(numOfPlayers) else: correctInput = False correctInput = False numOfDecks = 0 while not correctInput: input = raw_input("please enter number of decks: ") try: correctInput = True numOfDecks = int(input) except ValueError: print("That's not a number!") correctInput = False continue else: if numOfDecks > 0: self.setNumOfDecks(numOfDecks) else: correctInput = False def startNewGame(self): if self.deck.getNumOfCards() < self.getNumOfDecks() * 52 / 2: self.deck.shuffle() self.dealer.resetHand() for player in self.players: player.resetHand() self.playersBet() self.dealCards() self.dealCards() for player in self.players: print(player.getName() + "'s hand: ") player.printHand() print("Dealer's hand:") self.dealer.printHand() print("\n\n") self.gameplay() def gameplay(self): for player in self.players: print(player.getName() + "'s hand: ") player.printHand() hold = False while player.getValue() < 21 and not hold: input = raw_input("Would you like to hit? (y/n): ") if input == 'y': nextCard = self.deck.getNextCard() player.addToHand(nextCard) player.printHand() if input == 'n': hold = True print('\n') while self.dealer.getValue() <= 17: nextCard = self.deck.getNextCard() self.dealer.addToHand(nextCard) print("Dealer's final hand:") self.dealer.printHand() self.payout() input = '' while input != 'y' and input != 'n': input = raw_input("Would you like to play again? (y/n): ") if input == 'y': self.startNewGame() def playersBet(self): self.bets = {} if self.numOfPlayers <= 0: print('Not enough players...') return for player in self.players: if player.showCredits() > 0: correctAmount = False amount = 0 while not correctAmount: input = raw_input(player.getName() + " please enter betting amount: ") try: correctAmount = True amount = int(input) except ValueError: print("That's not a number!") correctAmount = False continue else: correctAmount = player.bet(amount) self.bets[player.getName()] = amount else: self.removePlayer(player.getName()) def payout(self): for player in self.players: if (player.getValue() <= 21 and player.getValue() > self.dealer.getValue()) or\ (player.getValue() <= 21 and self.dealer.getValue() > 21): player.addCredits(self.bets[player.getName()]*2) elif player.getValue() == self.dealer.getValue(): player.addCredits(self.bets[player.getName()]) for player in self.players: print(player.getName() + " has " + str(player.showCredits()) + " credits.") def dealCards(self): for player in self.players: nextCard = self.deck.getNextCard() player.addToHand(nextCard) nextCard = self.deck.getNextCard() self.dealer.addToHand(nextCard) def getNumOfPlayers(self): return self.numOfPlayers def getNumOfDecks(self): return self.numOfDecks
def __init__(self): self.hand = Hand() self.trumpSuit = JOKER self.tNumber = 0 self.cardinal = 0
def test_trick_winner_winner_lower_than_3sluffs(hearts, playOrder): board = Hand(inputString=("4H 7C 8H QS")) assert hearts.determineTrickWinner(board, playOrder).getName() == 'Carol'
def __init__(self, name, no): self.name = name self.hand = Hand() self.playerNum=no self.score = 0 self.tricksWon = []
def test_compute_points_four_hearts(hearts): board = Hand(inputString=("6H 7H 4H QH")) assert hearts.computeTrickPoints(board) == 4
def test_one_pair(self): myHand = Hand("Vu") myCards = ["7C","TD","5D","AS","TC","3H","JD"] expected = ['7C', 'JD', 'AS', 'TC', 'TD'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 2) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def test_hand_initialise_two_cards(self): mock_card_one, mock_card_two = Mock(), Mock() mock_card_one.value = 2 mock_card_two.value = 4 self.assertEqual(Hand(mock_card_one, mock_card_two).total, 6)
def test_high_card(self): myHand = Hand("Vu") myCards = ["7C","8D","3C","KS","TC","JC","4D"] expected = ['7C', '8D', 'TC', 'JC', 'KS'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 1) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def test_ace_in_hand(self): mock_card = Mock() mock_card.value = 1 self.assertEqual(Hand(mock_card).total, 11)
def test_straight(self): myHand = Hand("Vu") myCards = ["7C","8D","3C","9S","TC","JC","TD"] expected = ["7C","8D","9S","TC","JC"] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 5) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def test_hand_initialise_one_card(self): mock_card = Mock() mock_card.value = 2 self.assertEqual(Hand(mock_card).total, 2)
def test_full_house_2(self): myHand = Hand("Vu") myCards = ["7C","8D","7D","TS","TC","7H","TD"] expected = ['7C', '7D', 'TS', 'TC', 'TD'] myHand.setCards(myCards) myHand.evaluateHand() self.assertEqual(myHand._category, 7) self.assertEqual(myHand._five_cards, expected) myHand.show_player_cards() myHand.show_player_evaluated_hand_name() myHand.show_player_evaluated_five_cards()
def nextHand(self): if not self.won: randomInt = random.randint(0, 2) self.prevHand = Hand.get_hand(randomInt) return self.prevHand
class Player(object): ''' Represents a player in the UNO game. Can be human, or can be controlled by an AI. ''' def __init__(self, name, initcards): ''' Constructs a new Player ''' self._name = name self._hand = Hand() for card in initcards: self._hand.addCard(card) def getCurrentHand(self): ''' Returns the current set of cards in the Players hand. ''' return self._hand.getCards() def testMove(self, current, card): ''' Test if playing card with the current card current is a valid move ''' if card.isWild(): #may always be played, however WD4 requires player to not have current color if card.getData() == "wild draw four" and self.hasCardsOfColor(current.getColor()): return False return True if card.getColor() == current.getColor() or card.getData() == current.getData(): return True else: return False def hasCardsOfColor(self, color): for card in self._hand.getCards(): if card.getColor() == color: return True def getPlayableCards(self, current): ''' Return a list of cards that are valid moves''' res = [] for card in self._hand.getCards(): if self.testMove(current, card): res.append(card) return res def getName(self): ''' Returns name of player ''' return self._name def giveCard(self, cards): ''' Add card(s) to the player's hand ''' if isinstance(cards, Card): self._hand.addCard(cards) else: for card in cards: self._hand.addCard(card) def removeFromHand(self, card): ''' Remove given card from player's hand ''' self._hand.removeCard(card)
def __init__(self, seed): self.prevHand = Hand(0) random.seed(seed)
def __init__(self): self.players = [] self.setNumOfPlayers(1) self.setNumOfDecks(1) self.dealer = Hand()
class Human(pygame.sprite.Sprite): def __init__(self): super().__init__() # загрузка фрэймов walk_image = Helper.load_image('walk.png') run_image = Helper.load_image('run.png') self.walk_frames_right = Helper.get_frames(walk_image, 7) self.run_frames_right = Helper.get_frames(run_image, 7) left_image = pygame.transform.flip(walk_image, True, False) self.walk_frames_left = Helper.get_frames(left_image, 7) self.walk_frames_left.reverse() left_image = pygame.transform.flip(run_image, True, False) self.run_frames_left = Helper.get_frames(left_image, 7) self.run_frames_left.reverse() self.cur_frame = 0 self.image = self.walk_frames_right[0] self.mask = pygame.mask.from_surface(self.image) self.last_time = 0 self.right = True self.rect = self.image.get_rect() # создам группу спрайтов и добавляем в нее этот спрайт self.group = pygame.sprite.Group() self.group.add(self) self.hand = Hand() self.group.add(self.hand) # ускорение падения self.acceleration = 2 self.mouse_x = 0 self.mouse_y = 0 # переместить человека в координаты x,y def set_pos(self, x, y): self.rect.x = x self.rect.y = y self.hand.set_pos(x, y, self.mouse_x, self.mouse_y) # сместить человека на dx,dy def move(self, dx, dy): self.set_pos(self.rect.x + dx, self.rect.y + dy) def set_mouse(self, x, y): self.mouse_x = x self.mouse_y = y # перемещение вправо def go_right(self): self.right = True self.move(2, 0) # меняем кадр через 45 мс if pygame.time.get_ticks() > self.last_time + 45: self.cur_frame += 1 if self.cur_frame == len(self.walk_frames_right): self.cur_frame = 0 self.image = self.walk_frames_right[self.cur_frame] self.last_time = pygame.time.get_ticks() # перемещение влево def go_left(self): self.right = False self.move(-2, 0) if pygame.time.get_ticks() > self.last_time + 45: self.cur_frame += 1 if self.cur_frame == len(self.walk_frames_left): self.cur_frame = 0 self.image = self.walk_frames_left[self.cur_frame] self.last_time = pygame.time.get_ticks() # бег вправо def run_right(self): self.right = True self.move(4, 0) if pygame.time.get_ticks() > self.last_time + 45: self.cur_frame += 1 if self.cur_frame == len(self.run_frames_right): self.cur_frame = 0 self.image = self.run_frames_right[self.cur_frame] self.last_time = pygame.time.get_ticks() # бег влево def run_left(self): self.right = False self.move(-4, 0) if pygame.time.get_ticks() > self.last_time + 45: self.cur_frame += 1 if self.cur_frame == len(self.run_frames_left): self.cur_frame = 0 self.image = self.run_frames_left[self.cur_frame] self.last_time = pygame.time.get_ticks() # остановка def stop(self): self.cur_frame = 0 if self.right: self.image = self.walk_frames_right[self.cur_frame] else: self.image = self.walk_frames_left[self.cur_frame] # полет, меняем кадр на 4-й def fly(self): self.cur_frame = 4 if self.right: self.image = self.walk_frames_right[self.cur_frame] else: self.image = self.walk_frames_left[self.cur_frame] # рисование человека def draw(self, screen): self.group.draw(screen)