def resetHands(self): """ Reset the hands to empty hands for a new deal returns: nothing """ self.playerHands = [Hand()] self.dealerHand = Hand()
def the_discard(self, p1_hand, p2_hand, crib): '''Each player looks at his six cards and discards two of them to the crib. Choose the two cards that result in the highest score for the remaining four cards. TODO: >>Adjust discard strategy according to which player is currently the dealer (has the crib). >>Weight and apply various discard strategies. ''' for hand in [p1_hand, p2_hand]: ev = Evaluator(hand) discard_results = [] # check each 2 card combination for combo in itertools.combinations(hand.cards, 2): test_hand = Hand() test_hand.cards = [card for card in hand.cards if card not in combo] result = [ev.score()[0], combo] discard_results.append(result) discard_results.sort(key = lambda x: x[0], reverse = True) for card in discard_results[0][1]: index = hand.cards.index(card) crib.add(hand.cards.pop(index)) return
def main(): players = ["Peter", "John", "David", "Ford", "Derrick", "Darcy", "Jim", "Joyce", "Joanne", "Ruth"] myGame = game.Holdem(players) myDeck = Deck(myGame) myHands = Hand.createHandsFromList(Hand, myDeck, myGame.players) communityHand = Hand(myDeck) print(myGame.players)
def initialize_game(self): initializer = DeckInitializer() self.deck1 = initializer.make_std_deck() self.deck2 = initializer.make_std_deck() p1_starts = self._player1_starts() self.active_player = 0 if p1_starts else 1 self.players = [ Player(id=1, deck=self.deck1, hand=Hand(self.deck1), starts=p1_starts), Player(id=2, deck=self.deck2, hand=Hand(self.deck2), starts=not p1_starts) ] self.sides = [[initializer.create_hero('jaina')], [initializer.create_hero('jaina')]]
def test_type_checks(self): try: h = Hand(["!not a card!"]) except Exception as ex: assert False, "expected no error" try: h.check_contents() except ValueError as ex: assert "!not a card!" in str(ex) else: assert False, "expected runtime error"
def test_count(self): hand1 = self.HAND1 assert hand1.count(hand1[1]) == 1 assert hand1.count(hand1[1].suit) == 1 assert hand1.count(hand1[1].value) == 2 assert hand1.count(hand1[2]) == 1 assert hand1.count(hand1[2].suit) == 2 assert hand1.count(hand1[2].value) == 1 with Hand.default_comparison(deck.HandComparison.Suits): assert hand1.count(hand1[2]) == 2 with Hand.default_comparison(deck.HandComparison.Values): assert hand1.count(hand1[2]) == 1
def test_contains(self): hand1 = self.HAND1 assert hand1.index(hand1[1]) == 1 assert hand1.index(hand1[1].suit) == 1 assert hand1.index(hand1[1].value) == 1 assert hand1.index(hand1[2]) == 2 assert hand1.index(hand1[2].suit) == 0 assert hand1.index(hand1[2].suit, start=1) == 2 assert hand1.index(hand1[2].value) == 2 with Hand.default_comparison(deck.HandComparison.Suits): assert hand1.index(hand1[2]) == 0 with Hand.default_comparison(deck.HandComparison.Values): assert hand1.index(hand1[2]) == 2
def __init__(self, verbose, agentType, nHands, startingMoney, nTraining): """ Initialize the game! Create dealer and player objects and an initial gameState input: verbose whether or not to print each step as agents play input: agentType string representing the type of agent to instantiate input: nHands number of hands to play at max if agent never busts input: startingMoney the amount of money the agent gets to start with input: nTraining the number of training hands to do for a qlearning player returns: nothing """ self.verbose = verbose self.agentType = agentType self.nHands = int(nHands) + int(nTraining) self.nStartingHands = int(nHands) + int(nTraining) print("{} test {} train {} total".format(nHands, nTraining, self.nHands)) self.startingMoney = startingMoney self.nTraining = int(nTraining) self.dealer = Dealer() self.player = self.createAgent(self.agentType, self.startingMoney, nTraining) self.agents = [self.player, self.dealer] # Clean slate dealerHand = Hand() playerHand = Hand() deck = Deck() # list because player can split playerHands = [playerHand] if self.player: initialBets = [self.player.getBetAmt()] # Create initial game state self.gameState = GameState(verbose, self.dealer, dealerHand, self.player, playerHands, deck, initialBets) self.q = self.agentType == 'qlearning'
def test_union_value(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 10), Card("♥", 11)]) expect_hand3 = [*hand1, hand3[0]] hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Values): # Self-union should be the complete list assert list(hand1.union(hand1)) == list(hand1) assert list(hand2.union(hand2)) == list(hand2) # All values exist between hand1 and hand2 and so we get all of them assert list(hand1.union(hand2)) == list(hand1) # Only Tens are added assert list(hand1.union(hand3)) == expect_hand3 # Nothing is added assert list(hand1.union(hand4)) == list(hand1) # Check bitwise operator assert list(hand1 | hand3) == expect_hand3 # Check in-place operator h1 = Hand(c for c in hand1 if c.value == 3) h1 |= hand1 assert set(h1) == set(hand1)
def test_union_suit(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 10), Card("♥", 11)]) expect_hand3 = [*hand1, *hand3] hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Suits): # Self-union should be the complete hand assert list(hand1.union(hand1)) == list(hand1) assert list(hand2.union(hand2)) == list(hand2) # All suits exist between hand1 and hand2 and so we get all of them assert list(hand1.union(hand2)) == list(hand1) # Nothing is added assert list(hand1.union(hand3)) == list(hand1) # Nothing is added assert list(hand1.union(hand4)) == list(hand1) # Check bitwise operator assert list(hand1 | hand3) == list(hand1) # Check in-place operator h1 = Hand(c for c in hand1 if c.suit != deck.Suit.Hearts) h1 |= hand1 assert set(h1) == set(hand1)
def splitPlayableHand(self): """ Split the hand corresponding to player hand idx Create two hands, each with one of the cards and one newly dealt one and add them to playerHands list returns: nothing """ # Get the hand to split and remove it from the list handBeingSplit = self.playerHands.pop(self.playerHandIdx) if not handBeingSplit.isDoubles(): raiseErrorAtLoc() # Create a new hand, give it the second card from original and remove from original newHand = Hand() newHand.receiveCard(handBeingSplit.hand.pop(1)) # Deal each one a new card handBeingSplit.receiveCard(self.dealCard()) newHand.receiveCard(self.dealCard()) # Insert new hands back into the list where original was self.playerHands.insert(self.playerHandIdx, handBeingSplit) self.playerHands.insert(self.playerHandIdx + 1, newHand) # Apply the bet to new hand self.bets.insert(self.playerHandIdx + 1, self.player.getBetAmt())
def test_intersect_suit(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 11)]) expect_hand3 = {Card("♥", 2), Card("♥", 3)} hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Suits): # Self-intersect should be the complete set assert set(hand1.intersect(hand1)) == set(hand1) assert set(hand2.intersect(hand2)) == set(hand2) # All suits exist between hand1 and hand2 and so we get all of them assert set(hand1.intersect(hand2)) == set(hand1) # Only Hearts are retained assert set(hand1.intersect(hand3)) == expect_hand3 # Only Jokers are retained assert set(hand1.intersect(hand4)) == set(hand4) # Check bitwise operator assert set(hand1 & hand3) == expect_hand3 # Check in-place operator h1 = Hand(hand1) h1 &= hand3 assert set(h1) == expect_hand3 assert len(hand1) != len(h1)
def main(): while True: str_money_limit = input( "Welcome to blackjack! Set your limit, play within it:\n") try: money_limit = int(str_money_limit) if money_limit > 0: break else: print("enter a bet amount greater than zero") except ValueError: print("Please enter an integer.") playerHand = Hand(money=int(money_limit)) deck = Deck() dealerHand = Hand(money=0) while True: early_outcome = setupCards(playerHand, dealerHand, deck) if early_outcome == "continue": continue elif early_outcome == -1: break gameplay(playerHand, dealerHand, deck)
class HandTests(unittest.TestCase): HAND1 = Hand([ Card("♥", 2), Card("♦", 11), Card("♥", 3), Card(joker=True), Card("♠", 11) ]) HAND2 = Hand([ Card("♦", 2), Card("♥", 11), Card("♠", 3), Card(joker=True), Card("♠", 11) ]) def test_type_checks(self): try: h = Hand(["!not a card!"]) except Exception as ex: assert False, "expected no error" try: h.check_contents() except ValueError as ex: assert "!not a card!" in str(ex) else: assert False, "expected runtime error" def test_deal(self): deck = Deck() hands = deck.deal_hands() assert len(hands) == 2 assert len(hands[0]) == 5 assert len(hands[1]) == 5 def test_default_sort(self): hand = Hand(self.HAND1) hand.sort(deck.HandSort.Default) assert [c.value.value for c in hand] == [2, 3, 11, 11, 15] hand.sort(deck.HandSort.Default, reverse=True) assert [c.value.value for c in hand] == [15, 11, 11, 3, 2] def test_sort_suit(self): hand = Hand([Card("♦", 2), Card("♠", 2), Card("♣", 2), Card("♥", 2)]) hand.sort(deck.HandSort.Default) assert "".join(c.suit.value for c in hand) == "♣♦♥♠" hand.sort(deck.HandSort.Default, reverse=True) assert "".join(c.suit.value for c in hand) == "♠♥♦♣" def test_poker_sort(self): hand = Hand(self.HAND1) hand.sort(deck.HandSort.Poker) assert [c.value.value for c in hand] == [2, 3, 15, 11, 11] hand.sort(deck.HandSort.Poker, reverse=True) assert [c.value.value for c in hand] == [11, 11, 15, 3, 2] def test_contains(self): hand1 = self.HAND1 assert hand1.index(hand1[1]) == 1 assert hand1.index(hand1[1].suit) == 1 assert hand1.index(hand1[1].value) == 1 assert hand1.index(hand1[2]) == 2 assert hand1.index(hand1[2].suit) == 0 assert hand1.index(hand1[2].suit, start=1) == 2 assert hand1.index(hand1[2].value) == 2 with Hand.default_comparison(deck.HandComparison.Suits): assert hand1.index(hand1[2]) == 0 with Hand.default_comparison(deck.HandComparison.Values): assert hand1.index(hand1[2]) == 2 def test_count(self): hand1 = self.HAND1 assert hand1.count(hand1[1]) == 1 assert hand1.count(hand1[1].suit) == 1 assert hand1.count(hand1[1].value) == 2 assert hand1.count(hand1[2]) == 1 assert hand1.count(hand1[2].suit) == 2 assert hand1.count(hand1[2].value) == 1 with Hand.default_comparison(deck.HandComparison.Suits): assert hand1.count(hand1[2]) == 2 with Hand.default_comparison(deck.HandComparison.Values): assert hand1.count(hand1[2]) == 1 def test_intersect_exact(self): hand1, hand2 = self.HAND1, self.HAND2 # Self-intersect should be the complete set assert set(hand1.intersect(hand1, deck.HandComparison.Exact)) == set(hand1) assert set(hand2.intersect(hand2, deck.HandComparison.Exact)) == set(hand2) # Only exact matches should remain after an intersect assert set(hand1.intersect(hand2, deck.HandComparison.Exact)) == { Card(joker=True), Card("♠", 11), } def test_intersect_value(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 11)]) expect_hand3 = {Card("♦", 11), Card("♠", 11)} hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Values): # Self-intersect should be the complete set assert set(hand1.intersect(hand1)) == set(hand1) assert set(hand2.intersect(hand2)) == set(hand2) # All values exist between hand1 and hand2 and so we get all of them assert set(hand1.intersect(hand2)) == set(hand1) # Only Jacks are retained assert set(hand1.intersect(hand3)) == expect_hand3 # Only Jokers are retained assert set(hand1.intersect(hand4)) == set(hand4) # Check bitwise operator assert set(hand1 & hand3) == expect_hand3 # Check in-place operator h1 = Hand(hand1) h1 &= hand3 assert set(h1) == expect_hand3 assert len(hand1) != len(h1) def test_intersect_suit(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 11)]) expect_hand3 = {Card("♥", 2), Card("♥", 3)} hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Suits): # Self-intersect should be the complete set assert set(hand1.intersect(hand1)) == set(hand1) assert set(hand2.intersect(hand2)) == set(hand2) # All suits exist between hand1 and hand2 and so we get all of them assert set(hand1.intersect(hand2)) == set(hand1) # Only Hearts are retained assert set(hand1.intersect(hand3)) == expect_hand3 # Only Jokers are retained assert set(hand1.intersect(hand4)) == set(hand4) # Check bitwise operator assert set(hand1 & hand3) == expect_hand3 # Check in-place operator h1 = Hand(hand1) h1 &= hand3 assert set(h1) == expect_hand3 assert len(hand1) != len(h1) def test_union_exact(self): hand1, hand2 = self.HAND1, self.HAND2 # Self-union should be the original hand assert list(hand1.union(hand1, deck.HandComparison.Exact)) == list(hand1) assert list(hand2.union(hand2, deck.HandComparison.Exact)) == list(hand2) # Exact matches should not duplicate after a union assert list(hand1.union(hand2, deck.HandComparison.Exact)) == [ *hand1, *hand2[:3], ] def test_union_value(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 10), Card("♥", 11)]) expect_hand3 = [*hand1, hand3[0]] hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Values): # Self-union should be the complete list assert list(hand1.union(hand1)) == list(hand1) assert list(hand2.union(hand2)) == list(hand2) # All values exist between hand1 and hand2 and so we get all of them assert list(hand1.union(hand2)) == list(hand1) # Only Tens are added assert list(hand1.union(hand3)) == expect_hand3 # Nothing is added assert list(hand1.union(hand4)) == list(hand1) # Check bitwise operator assert list(hand1 | hand3) == expect_hand3 # Check in-place operator h1 = Hand(c for c in hand1 if c.value == 3) h1 |= hand1 assert set(h1) == set(hand1) def test_union_suit(self): hand1, hand2 = self.HAND1, self.HAND2 hand3 = Hand([Card("♥", 10), Card("♥", 11)]) expect_hand3 = [*hand1, *hand3] hand4 = Hand([Card(joker=True)]) with Hand.default_comparison(deck.HandComparison.Suits): # Self-union should be the complete hand assert list(hand1.union(hand1)) == list(hand1) assert list(hand2.union(hand2)) == list(hand2) # All suits exist between hand1 and hand2 and so we get all of them assert list(hand1.union(hand2)) == list(hand1) # Nothing is added assert list(hand1.union(hand3)) == list(hand1) # Nothing is added assert list(hand1.union(hand4)) == list(hand1) # Check bitwise operator assert list(hand1 | hand3) == list(hand1) # Check in-place operator h1 = Hand(c for c in hand1 if c.suit != deck.Suit.Hearts) h1 |= hand1 assert set(h1) == set(hand1)
def playGame(myGame): print(f"The game is {myGame.gameName}") myDeck = Deck(myGame) myDeck.shuffleCards myHands = Hand.createHandsFromList(Hand, myDeck, myGame.players) communityHand = Hand(myDeck) # Deal each round for rnd in myGame.rounds: if isinstance(rnd[0], list): for subrnd in rnd: if subrnd[1] == 'c': Hand.dealCommunityCards(Hand, myHands, communityHand, subrnd[0]) elif subrnd[1] == 'u' or subrnd[1] == 'd': Hand.dealRound(Hand, myHands, subrnd[0]) else: pass # TODO - code for draw else: if rnd[1] == 'c': Hand.dealCommunityCards(Hand, myHands, communityHand, rnd[0]) elif rnd[1] == 'u' or rnd[1] == 'd': Hand.dealRound(Hand, myHands, rnd[0]) else: pass # TODO - code for draw Hand.calculateHandValues(Hand, myHands, communityHand, myGame) myHands.sort(key=lambda x: x.value, reverse=True) printCurrentStandings(myGame, myHands, communityHand) input("Press Enter to continue...")
def test_poker_sort(self): hand = Hand(self.HAND1) hand.sort(deck.HandSort.Poker) assert [c.value.value for c in hand] == [2, 3, 15, 11, 11] hand.sort(deck.HandSort.Poker, reverse=True) assert [c.value.value for c in hand] == [11, 11, 15, 3, 2]
def test_sort_suit(self): hand = Hand([Card("♦", 2), Card("♠", 2), Card("♣", 2), Card("♥", 2)]) hand.sort(deck.HandSort.Default) assert "".join(c.suit.value for c in hand) == "♣♦♥♠" hand.sort(deck.HandSort.Default, reverse=True) assert "".join(c.suit.value for c in hand) == "♠♥♦♣"
def test_default_sort(self): hand = Hand(self.HAND1) hand.sort(deck.HandSort.Default) assert [c.value.value for c in hand] == [2, 3, 11, 11, 15] hand.sort(deck.HandSort.Default, reverse=True) assert [c.value.value for c in hand] == [15, 11, 11, 3, 2]
def checkActions(): game = Game(False, 'optimal', 100, 100, 0) gamestate = game.gameState hand = Hand() status = [] # tests a playable hand (9,4) hand.receiveCard(Card(Face.NINE, Suit.CLUBS)) hand.receiveCard(Card(Face.FOUR, Suit.CLUBS)) gamestate.playerHands = [hand] actions = gamestate.player.getValidActions(gamestate) status.append(actions == ['HIT', 'STAND', 'DOUBLE DOWN']) # tests a doubles hand hand (9,9) hand.hand[1] = (Card(Face.NINE, Suit.HEARTS)) gamestate.playerHands = [hand] actions = gamestate.player.getValidActions(gamestate) status.append(actions == ['HIT', 'STAND', 'DOUBLE DOWN', 'SPLIT']) # tests blackjack (Ace, King) hand.hand[0] = (Card(Face.ACE, Suit.HEARTS)) hand.hand[1] = (Card(Face.KING, Suit.HEARTS)) gamestate.playerHands = [hand] actions = gamestate.player.getValidActions(gamestate) status.append(actions == ['STAND']) # tests a soft hand hand (Ace,King, 3) hand.receiveCard(Card(Face.THREE, Suit.CLUBS)) gamestate.playerHands = [hand] actions = gamestate.player.getValidActions(gamestate) status.append(actions == ['HIT','STAND']) # tests a bust hand (Ace, King, 3, 9) hand.receiveCard(Card(Face.NINE, Suit.CLUBS)) gamestate.playerHands = [hand] actions = gamestate.player.getValidActions(gamestate) status.append(actions == ['STAND']) return status
def round(self, round_num): '''Plays a single round of cribbage. Deals two hands, discards to the crib, scores hands (and crib), and update the score for each player. TODO: Pegging ''' round = { 'p1': { 'hand': [], 'score': 0, 'brkdwn': None, 'crib': False }, 'p2': { 'hand': [], 'score': 0, 'brkdwn': None, 'crib': False }, 'starter': None } if round_num % 2 == 0: round['p2']['crib'] = True else: round['p1']['crib'] = True # Shuffle deck of cards and deal two hands self.deck.shuffle() p1_hand, p2_hand, crib = Hand(), Hand(), Hand() self.deal(p1_hand, p2_hand) # Discard phase...send two cards to crib self.the_discard(p1_hand, p2_hand, crib) round['p1']['hand'] = p1_hand round['p2']['hand'] = p2_hand # Cut deck and reveal the starter self.deck.cut() starter = self.deck[0] round['starter'] = starter p1_hand.cards.append(starter) p2_hand.cards.append(starter) # The show self.the_play(p1_hand, p2_hand) # Save round to game history and update total score p1_score = self.score_hand(p1_hand) round['p1']['score'] += p1_score[0] round['p1']['brkdwn'] = p1_score[1] p2_score = self.score_hand(p2_hand) round['p2']['score'] += p2_score[0] round['p2']['brkdwn'] = p2_score[1] for p in ['p1', 'p2']: if round[p]['crib'] == True: round[p]['score'] += self.score_hand(crib)[0] # Return all cards to deck for hand in [p1_hand, p2_hand, crib]: self.deck.return_hand(hand) return round
assert len(test_deck2) == 45 assert Card.suit_names[test_deck2.cards[0].suit] == "Spades" assert Card.rank_names[test_deck2.cards[0].rank] == "4" assert Card.suit_names[test_deck2.cards[44].suit] == None assert Card.rank_names[test_deck2.cards[44].rank] == "Joker" # Test initialization of a Black Jack deck (6 standard decks in on shoe). test_deck3 = Blackjack() assert len(test_deck3) == 312 assert Card.suit_names[test_deck3.cards[0].suit] == "Spades" assert Card.rank_names[test_deck3.cards[0].rank] == "Ace" assert Card.suit_names[test_deck3.cards[311].suit] == "Hearts" assert Card.rank_names[test_deck3.cards[311].rank] == "King" # Test initialization of Hands test_hand1 = Hand() test_hand2 = Hand() test_deck = Standard() assert len(test_hand1) == 0 assert len(test_hand2) == 0 assert len(test_deck) == 52 # Test adding cards manually to a deck object(Hand) test_hand1.add_card(test_card1) assert len(test_hand1) == 1 test_hand1.add_card(test_card2) assert len(test_hand1) == 2 # Test removing card manually from a deck object(Hand) test_hand1.remove_card(test_card1) assert len(test_hand1) == 1
def __init__(self, name="Player 1", hand=Hand()): self.name = name self.hand = hand self.pairs = 0
def checkHand(): status = [] hand = Hand() # empyt starting hand status.append(hand.getNumCards() == 0) status.append(hand.getHandValue() == 0) # correctly appends card card1 = Card(Face.NINE, Suit.CLUBS) hand.receiveCard(card1) status.append(hand.getNumCards() == 1) status.append(hand.getHandValue() == 9) # checks for correct isDoubles call hand.receiveCard(card1) status.append(hand.isDoubles()) hand.hand[1] = Card(Face.ACE, Suit.DIAMONDS) status.append(not hand.isDoubles()) # Check for blackjack status.append(not hand.isBlackjack()) hand.hand[0] = Card(Face.KING, Suit.CLUBS) status.append(hand.isBlackjack()) # checks for soft and hard hands status.append(hand.isHard()) status.append(not hand.isSoft()) hand.receiveCard(Card(Face.QUEEN, Suit.HEARTS)) status.append(hand.isHard()) status.append(not hand.isSoft()) # checks for bust status.append(not hand.isBust()) hand.receiveCard(Card(Face.SEVEN, Suit.SPADES)) status.append(hand.isBust()) # checks for 4 aces corner case hand.hand[0] = Card(Face.ACE, Suit.DIAMONDS) hand.hand[2] = Card(Face.ACE, Suit.DIAMONDS) hand.hand[3] = Card(Face.ACE, Suit.DIAMONDS) status.append(hand.getHandValue() == 14) return status