class Game: """ゲームの情報を持つ.""" def __init__(self): self.deck = Deck() self.dealer = Player('Dealer', self.deck, []) self.player = Player('Player', self.deck, []) #TODO: 読み取りだけに専念するべき? def begin(self): random.shuffle(self.deck) for _ in range(2): self.player.hit() self.dealer.hit() @property def turn_is_over(self): return (self.dealer.point >= result.BLACKJACK or self.player.point >= result.BLACKJACK) @property def game_is_over(self): return (self.player.frozen() or self.turn_is_over) @property def game_result(self): if not self.game_is_over: return None return result.judge_from_point(self.dealer.point, self.player.point)
def test_contain_ace( self ): #Checks if the Player holds an ace or not. Returns true if he does, false if he doesn't player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) self.assertTrue(player.contains_ace(), "Fails if there's no ace in hand")
def test_dealInitialHands(self): """Each player should recive an card from the first to dealer in the initial deal This process should happend twice """ table = Table() newPlayer = Player(0, '1', Role.HUMAN) table.activePlayers.append(newPlayer) newPlayer = Player(20, '2', Role.HUMAN) newPlayer.bet = 20 table.activePlayers.append(newPlayer) newPlayer = Player(40, '3', Role.HUMAN) newPlayer.bet = 20 table.activePlayers.append(newPlayer) table.dealInitialHands() for player in table.activePlayers: assert(len(player.hand.cards) == 2) for i in range(len(table.activePlayers)): assert(table.activePlayers[i].hand.cards[0] == table.deck._Deck__deck[i]) assert(table.activePlayers[i].hand.cards[1] == table.deck._Deck__deck[i + 4]) assert(table.hand.cards[0] == table.deck._Deck__deck[3]) assert(table.hand.cards[1] == table.deck._Deck__deck[7])
def cost_blackjack(network): AI = Player('AI', network=network) stats = AI.getPlayerPerformance(10, False) win_rate = stats[0] ave_bank = stats[1] ave_reward = stats[2] cost = win_rate + ave_bank / 1000.0 + 1.1 * ave_reward return cost
def test_value( self ): #Tests my calc_val() method in my Player class. It calculates the value sum of the hand of the player player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Hearts", "King", 10)) self.assertEqual( player.calc_val(), 21, "Total should be 21" ) #In this scenario it tests if the appended cards give a sum of 21 which they should do
def test_a_player_can_win_or_lose_a_hand(): p = Player() p.bet(100) assert p.bank == 900 p.payout(200) assert p.bank == 1100 p.bet(500) assert p.bank == 600 p.payout(0) assert p.bank == 600
class TestPlayer(unittest.TestCase): @classmethod def setUp(self): self.player = Player('Player', ['7C', '8H']) self.dealer = Player('Dealer', ['KS', 'AD']) def test_display_hand(self): self.assertEqual(self.player.display_hand(), '7C 8H') self.assertEqual(self.dealer.display_hand(), 'KS AD') def test_draw_a_card(self): deck = ['5S', '2D', '3C'] self.assertEqual(self.player.draw_a_card(deck), '3C') self.assertEqual(len(self.dealer.hand), 2) self.assertEqual(len(self.player.hand), 3) self.assertEqual(len(deck), 2) def test_evaluate_card(self): self.assertEqual(self.player.evaluate_card('JC'), 10) self.assertEqual(self.player.evaluate_card('QH'), 10) self.assertEqual(self.player.evaluate_card('KS'), 10) self.assertEqual(self.player.evaluate_card('AD'), 11) def test_evaluate_hand(self): self.assertEqual(self.player.evaluate_hand(), 15) self.assertEqual(self.dealer.evaluate_hand(), 21) def test_check_blackjack(self): self.assertTrue(self.dealer.check_blackjack()) self.assertFalse(self.player.check_blackjack())
def test_check_draw(self): #Testing if the game ends when there's a draw deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", "Jack", 10)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", "Jack", 10)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the game drawed")
def test_check_dealer_win( self): #Testing if the game ends if the dealer wins deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", 2, 2)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", 7, 7)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertFalse(bj.game_running, "Game should be over since the dealer won")
def trainGeneration(models, epoch, mutation_rate, print_info): for i in range(epoch): max_network = getMaxNetwork(models) AI = Player('AI', network=max_network) stats = AI.getPlayerPerformance(10, False) win_rate = stats[0] ave_bank = stats[1] if print_info == True and i % 10 == 0: print("Epoch: " + str(i) + " - Win rate: " + str(round(win_rate * 100.0, 1)) + "% - Ave. bank (5 plays): $" + str(round(ave_bank, 2))) for i in range(len(models)): models[i] = mutateNetwork(max_network, mutation_rate * (0.60 - win_rate) / 0.60)
def test_MultiplePlayerDrawCard(): """ Test that multiple players can draw cards from a deck to their hand. Ensure the card is present in the player's hand but not present in the deck after being drawn or in the other player's hand. """ d = Deck() d.shuffle() p1 = Player("Matt") p2 = Player("Sarah") for i in range(2): p1.draw(d) p2.draw(d) assert len(p1.hand) > 0 assert len(p2.hand) > 0 for card in p1.hand: assert card not in d.cards assert card not in p2.hand for card in p2.hand: assert card not in d.cards assert card not in p1.hand return
def test_ace_values( self ): #Checks if the calc_val() method correctly recalculates the sum of the Players hand if there are multiple aces in the Players hand player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Diamonds", "Ace", 11)) self.assertEqual( player.calc_val(), 12, "If the player starts with 2 aces the value should be 12 and not 22" ) player.hand.append(Card("Spades", "Ace", 11)) self.assertEqual( player.calc_val(), 13, "Fails if the calc.val() doesn't correctly make the value 13")
class TestPlayer(unittest.TestCase): """Test case for player.""" def setUp(self): player_config = {'id': 1, 'name': 'Chris Money Maker', 'chips': 100} self.player = Player(player_config) def test_add_chips(self): """Test add chips to player.""" self.player.add_chips(10) self.assertEqual(self.player.chips, 110) def test_subtract_chips(self): """Test subtract chips from player.""" self.player.subtract_chips(10) self.assertEqual(self.player.chips, 90)
def test_Player(): """ Test that player objects are created correctly. """ p1 = Player("Matt") p2 = Player("Penny") assert isinstance(p1, Player) assert p1.name == "Matt" assert isinstance(p1, Player) assert p2.name == "Penny" return
def test_check_keeps_going( self ): #Testing if the game keeps running even if the dealer has more value than the player (dealer has to keep hitting till he hits atleast 17) deck = Deck() player = Player("Mikkel") player.hand.append(Card("Hearts", "Ace", 11)) player.hand.append(Card("Spades", 2, 2)) dealer = Player("dealer") dealer.hand.append(Card("Clubs", "Ace", 11)) dealer.hand.append(Card("Diamonds", 4, 4)) bj = Blackjack(player, dealer, deck) bj.check_who_won() self.assertTrue( bj.game_running, "Game should keep running since the dealer hasn't hit atleast 17 value yet" )
def test_concludeRound(self): """at the end of the round all players should be deleted properly and reset""" table = Table() newPlayer = Player(0, '1', Role.HUMAN) table.activePlayers.append(newPlayer) newPlayer = Player(20, '2', Role.HUMAN) newPlayer.bet = 20 table.activePlayers.append(newPlayer) newPlayer = Player(40, '3', Role.HUMAN) newPlayer.bet = 20 table.activePlayers.append(newPlayer) for player in table.activePlayers: player.hand.add(Card(CardValues.QUEEN, Suits.DIAMONDS)) player.hand.add(Card(CardValues.QUEEN, Suits.DIAMONDS)) player.hand.add(Card(CardValues.QUEEN, Suits.DIAMONDS)) newPlayer = Player(40, '4', Role.HUMAN) newPlayer.bet = 20 newPlayer.hand.add(Card(CardValues.QUEEN, Suits.DIAMONDS)) newPlayer.hand.add(Card(CardValues.ACE, Suits.DIAMONDS)) table.activePlayers.append(newPlayer) table.hand.add(Card(CardValues.QUEEN, Suits.DIAMONDS)) table.hand.add(Card(CardValues.KING, Suits.DIAMONDS)) table.concludeRound() assert(len(table.activePlayers) == 2) assert (table.activePlayers[0].name == '3') assert (table.activePlayers[1].name == '4') assert (len(table.activePlayers[0].hand.cards) == 0) assert (table.activePlayers[0].purse == 20) assert (table.activePlayers[1].purse == 60) assert (len(table.activePlayers[1].hand.cards) == 0)
def main(): # create a player P1 = Player('P1', 200) # start w 200 P1_bank = P1.bank deck = Deck() dealer = Player('dealer') value = Value() # show beginning bank # test count print(len(deck.show_deck())) print(c(deck.show_deck())) # win round P1.add_bet(20) P1_bank = P1.win() print(P1_bank) # check if a card in deck is discarded print('deck before drawing: %s' % (len(deck._deck))) print() print('you drew a %s' % (deck.deal_card())) print() print('deck after drawing: %s' % (len(deck._deck))) # checking hand P1.hand.append(deck.deal_card()) P1.hand.append(deck.deal_card()) print('current hand:') print(P1.show_hand()) P1_hand_value = value.hand_value(P1.hand) + value.ace_present(P1.hand) print(P1_hand_value) while P1_hand_value < 21 and value.hand_value(P1.hand) != 0: P1.hand.append(deck.deal_card()) print('you drew %s' % (P1.hand[-1])) print('hand value is now %s' % (P1_hand_value)) if value.hand_value(P1.hand) == 0: print('You busted')
def test_overall_play(): wager_amts = [1, 1, 1, 1, 1, 1, 4, 8, 16] ranges = [-3, -2, -1, 0, 0, 1, 2, 3] betting_policy = (wager_amts, ranges) player = Player( bankroll=100, hard_policy=hard_policy, soft_policy=soft_policy, split_policy=split_policy, betting_policy=betting_policy, ) deck = Deck() # first hand player wins and wins 1 count is now 4 cards_1 = [ Cards.TEN, Cards.THREE, Cards.TEN, Cards.FOUR, Cards.THREE, Cards.FOUR, Cards.TWO, Cards.FOUR, ] cards_2 = [ Cards.TEN, Cards.THREE, Cards.TEN, Cards.FOUR, Cards.JACK, Cards.ACE, Cards.TEN, Cards.TEN, ] # second hand player wagers 16 and wins 16*1.5 = 24 deck.set_cards(cards_2 + cards_1) resolve_environment(player, deck, 8, 1, 0.001) assert player.get_bankroll() == 101 assert deck.get_count() == 4 assert player.calculate_wager(deck.get_true_count()) == 16 resolve_environment(player, deck, 8, 1, 0.001) assert player.get_bankroll() == 125
def test_parallel(): player = Player( bankroll=10000, hard_policy=hard_policy, soft_policy=soft_policy, split_policy=split_policy, betting_policy=betting_policy, ) output = parallel_processing(player=player, iterations=100, n_samples=10) assert len(output) == 10
class TestBlackjack(unittest.TestCase): def setUp(self): self.blackjack = Blackjack() self.player = Player() def test_game_over_end_game(self): deck = ["8♥", "6♣", "2♦", "10♦"] for card in range(len(deck)): self.player.hit_card(deck) self.assertTrue(self.blackjack.game_over([self.player])) """Method return True to Game Over""" def test_game_over_continue_game(self): deck = ["8♥", "6♣", "2♦"] for card in range(len(deck)): self.player.hit_card(deck) self.assertFalse(self.blackjack.game_over([self.player])) """Method return False to Game Over, i.e., the game continues""" def tearDown(self): pass
def __init__(self): # game logic related self.pot = 0 self.player = Player() self.dealer = Dealer() # interface related - add interface elements here self.root = Tk() self.root.title('Casino') self.root.iconbitmap( 'C:/Users/SavSamuShaman/Desktop/blackjack/pkc2.ico') # labels self.header_label = Label( self.root, text="You walk to the table and the dealer ask for your name") self.message_label = Label( self.root, text='Best of luck a the blackjack table ;)') self.error_message_label = Label(self.root) self.player_money_label = Label( self.root, text=f'Your money : {self.player.chips}') self.dealer_money_label = Label( self.root, text=f'Dealer money : {self.dealer.chips}') self.pot_label = Label(self.root, text=f'Pot : 0') self.current_score_label = Label(self.root, text=f'Current score : 0') # buttons self.hit_me_button = Button(self.root, text='Hit me', command=self.hit_me) self.stay_button = Button(self.root, text='Stay', command=self.stay) self.bet_button = Button(self.root, text='Bet', command=self.bet) self.start_button = Button(self.root, text='Tell the dealer your name', command=self.set_up_environ) # input box self.entry = Entry(self.root, width=30) # element placement self.header_label.grid(row=0, column=1) self.entry.grid(row=1, column=1, columnspan=3) self.start_button.grid(row=2, column=1, padx=15, pady=20) self.root.mainloop()
def test_player(self): # Get money test money_amt = 750 test_player = Player(money_amt) self.assertEqual(test_player.get_money(), money_amt) # Loss test money_amt -= 25 test_player.lose_bet(25) self.assertEqual(test_player.get_money(), money_amt) # Win test money_amt += 50 test_player.win_bet(50) self.assertEqual(test_player.get_money(), money_amt)
def test_refresh(self): player = Player('You') for i in range(3): player.draw_card(i) assert len(player.hold_cards) == 3 assert player.get_point() != [ 0, ] player.refresh() assert len(player.hold_cards) == 0 assert player.get_point() == [ 0, ]
def test_SinglePlayerDrawCard(): """ Test that a single player can draw a card from a deck to their hand. Ensure the card is present in the player's hand but not present in the deck after being drawn. """ d = Deck() d.shuffle() p1 = Player("Matt") for i in range(2): p1.draw(d) assert p1.hand != None assert len(p1.hand) > 0 for card in p1.hand: assert card not in d.cards return
def setUp(self): self.table = Table(min_bet=10, max_bet=25) player_configs = [{ 'id': 1, 'name': 'Player 1', 'chips': 100 }, { 'id': 2, 'name': 'Player 2', 'chips': 100 }] self.players = [Player(pc) for pc in player_configs]
def test_change_chips(self): """A test which makes sure that the change_chips method of the Player class functions properly.""" # Check valid chip changes valid_chip_changes = [ 1, 100, -1, -100, ] for chip_change in valid_chip_changes: player = Player(200) self.assertEqual(player.chips, 200, msg="The starting chips of the player was not correctly set.") player.change_chips(chip_change) self.assertEqual(player.chips, 200 + chip_change, msg="A player chip change of " + str(chip_change) + " chips did not work correctly.") # Check for invalid chip changes invalid_chip_changes = [ 0, 1.1, "1", None, ] for chip_change in invalid_chip_changes: player = Player(200) success = False try: player.change_chips(chip_change) except InvalidChipsChange: success = True self.assertTrue(success, msg="An invalid player chips change of " + str(chip_change) + " was able to be made.")
def write_table(): keys = Parser.freq.keys() table = {} if len(keys) != 0: for key in keys: hand, dealer = key if hand not in table: table[hand] = {} # win % for hit, stay table[hand][dealer] = [0, 0] hit_num_win, hit_num_total = Parser.freq[key][Player.move("HIT")] stay_num_win, stay_num_total = Parser.freq[key][Player.move("STAY")] table[hand][dealer][0] = round(float(hit_num_win)/max(float(hit_num_total), 1), 2) table[hand][dealer][1] = round(float(stay_num_win)/max(float(stay_num_total), 1), 2) print table return table
def parse(): f = open("log.txt") line = f.readline() while line != "": hand, dealer, move, outcome = line.split(" ") key = hand, dealer move_key = int(float(move)) outcome_key = int(float(outcome)) if key not in Parser.freq: Parser.freq[key] = { Player.move("HIT"): [0,0], Player.move("STAY"): [0,0] } if outcome_key == Game.round_outcome("WIN"): Parser.freq[key][move_key][0] += 1 Parser.freq[key][move_key][1] += 1 line = f.readline() f.close()
def test_draw(self): player = Player('You') assert len(player.hold_cards) == 0 player.draw_card(0) assert player.hold_cards == [ 'Spade A', ] player.draw_card(4) assert player.hold_cards == ['Spade A', 'Spade 5']
class Deadoralive(object): print("DEADORALIVE") def __init__(self): self._deck = Deck() self._deck.shuffle() self._player = Player([self._deck.deal(), self._deck.deal()]) self._dealer = Dealer([self._deck.deal(), self._deck.deal()]) def getValue(self): """Returns the number of points in the hand.""" count = 0 for card in self._cards: if card.rank > 9: count += 10 elif card.rank == 1: count += 11 else: count += card.rank return count def compare(self,other): """compare the cards and returns message""" """we can compare by using the value function""" playerpoint = self._player.getValue() dealerpoint = other._dealer.getValue() if playerpoint > dealerpoint: print("\nPlayer Won") elif playerpoint < dealerpoint: print("\nDealer Won") def playdead(self): print("Player:\n", self._player) print("Dealer:\n", self._dealer) while True: if len(self._deck._cards) == 0: print("game has ended") break else: _deadoralive.compare(self._player,self._dealer)
def main(): # Initialize game_over = False deck = build_deck() used_cards = [] p1 = Player(deck, used_cards) dealer = Dealer(deck, used_cards) players = [p1, dealer] while not game_over: get_wager() deal_cards([p1, dealer]) p1_move() dealer_move() eval_hands() clear_table([p1, dealer])
def check_hands_test(self): p1 = Player() p1.add_card(Card("ace", "spades")) p1.add_card(Card("jack", "hearts")) self.assertEqual("ace of spades & jack of hearts", p1.print_hand()) p2 = Dealer() p2.add_card(Card("one", "spades")) p2.add_card(Card("ten", "diamonds")) self.assertEqual("XX & ten of diamonds", p2.print_hand())
class TestTakeTurn(unittest.TestCase): @classmethod def setUp(self): self.deck = ['5S', '2D', '3C'] self.player = Player('Player', ['7C', '8H']) self.dealer = Player('Dealer', ['KS', 'AD']) def test_take_turn(self): self.player.take_turn(self.deck, 17) self.dealer.take_turn(self.deck, 18) self.assertEqual(self.player.evaluate_hand(), 18) self.assertEqual(self.dealer.evaluate_hand(), 21)
def test_draw( self ): #This method tests if the player draws correctly. In the beginning the player should draw 2 cards and then 1 card each time onwards when the method is called. player = Player("Mikkel") deck = Deck() player.draw(deck) self.assertTrue( len(player.hand) == 2, "The player should get 2 cards in the beginning of the first round" ) player.draw(deck) self.assertTrue( len(player.hand) == 3, "If the player hits once after the first round he should have 3 cards in hand" )
class TestPlayer(unittest.TestCase): def setUp(self): self.player = Player() def test_hand_property(self): self.player.hand = "A♣" self.assertEqual(self.player.hand, ["A♣"]) def test_show_hand_one_card(self): """Test show_hand output with one card""" import sys from io import StringIO self.player.hand = "A♣" saved_stdout = sys.stdout try: fake_out = StringIO() sys.stdout = fake_out self.player.show_hand() output = fake_out.getvalue().strip() self.assertEqual(output, '1 card: A♣') finally: sys.stdout = saved_stdout def test_show_hand_more_than_two_card(self): """Test show_hand output with more than two cards""" import sys from io import StringIO self.player.hand = ["A♣", "2♣", "3♣"] saved_stdout = sys.stdout try: fake_out = StringIO() sys.stdout = fake_out self.player.show_hand() output = fake_out.getvalue().strip() self.assertEqual(output, '3 cards: A♣, 2♣, 3♣') finally: sys.stdout = saved_stdout def test_hit_card(self): deck = ["A♣", "2♣", "3♣"] self.player.hit(deck) self.assertEqual(self.player.hand, ["A♣"]) self.assertEqual(len(deck), 2)
def start_game(room): deck = Deck() deck.shuffle() print('starting game for room ' + room) starter = -1 club = Card(Card.CLUBS, 2) print(rooms[room]) for i in range(0, len(rooms[room]['players'])): rooms[room]['players'][i]['player'] = Player( rooms[room]['players'][i]['user']) player_ = rooms[room]['players'][i] player_['player'].draw_n(deck, 13) if player_['player'].has(club): starter = i emit('hand', player_['player'].serialize(), room=player_['sid']) print('starting player is ' + str(starter)) rooms[room]['starter'] = starter emit('declare', True, room=rooms[room]['players'][0]['sid']) rooms[room]['declaring'] = 0
play_game = True while play_game: print "---- Start of Round ----" print "dealing cards ...." dealer = Dealer() # Deal 2 cards for Dealer rank, suit = deal_card().split(',') dealer.add_card(Card(rank,suit)) rank, suit = deal_card().split(',') dealer.add_card(Card(rank,suit)) # Deal player cards player = Player() rank, suit = deal_card().split(',') player.add_card(Card(rank,suit)) rank, suit = deal_card().split(',') player.add_card(Card(rank,suit)) # Show hands print "Dealers Hand : %s", dealer.print_hand() print "Players Hand : %s", player.print_hand() # Get choice from Player player_choice = raw_input("Enter Choice : H(it) or S(tand) - ").lower() if player_choice == 'h': rank, suit = deal_card().split(',') player.add_card(Card(rank,suit))
def get_hand_score_test(self): p1 = Player() p1.add_card(Card("ace", "spades")) p1.add_card(Card("jack", "hearts")) self.assertEqual(21, p1.calculate_hand_score())
def setUp(self): self.player = Player()
def setUp(self): self.blackjack = Blackjack() self.player = Player()
class TestPlayer(unittest.TestCase): def setUp(self): self.player = Player() def test_player_hand_property(self): self.player.hand = "8♥" self.assertEqual(self.player.hand, ["8♥"]) self.assertRaises(ValueError, setattr, self.player, "hand", 1) def test_player_money_property(self): self.assertEqual(self.player.money, Decimal("2000.0")) def test_hit_card(self): deck = ["8♥", "6♣", "2♦"] self.player.hit_card(deck) self.assertEqual(self.player.hand, ["8♥"]) self.assertEqual(self.player.points, 8) self.assertEqual(len(deck), 2) def test_show_points(self): deck = ["8♥", "6♣", "2♦"] for card in range(3): self.player.hit_card(deck) import sys from io import StringIO saved_stdout = sys.stdout try: fake_out = StringIO() sys.stdout = fake_out self.player.show_points() output = fake_out.getvalue().strip() self.assertEqual(output, "Points in game: 16") finally: sys.stdout = saved_stdout def test_show_hand(self): self.player.hand = ["8♥", "6♣", "2♦"] import sys from io import StringIO saved_stdout = sys.stdout try: fake_out = StringIO() sys.stdout = fake_out self.player.show_hand() output = fake_out.getvalue().strip() self.assertEqual(output, "The player have 3 cards: 8♥, 6♣, 2♦") finally: sys.stdout = saved_stdout def test_show_money(self): import sys from io import StringIO saved_stdout = sys.stdout try: fake_out = StringIO() sys.stdout = fake_out self.player.show_money() output = fake_out.getvalue().strip() self.assertEqual(output, "Money in game: 2000.0") finally: sys.stdout = saved_stdout def test_deal_cards(self): deck = ["8♥", "6♣", "2♦", "10♦", "3♣"] self.player.deal_cards(deck) self.assertEqual(self.player.hand, ["8♥", "6♣", "2♦"]) self.assertEqual(deck, ["10♦", "3♣"]) self.assertEqual(len(deck), 2) def test_bet(self): self.assertEqual(self.player.bet(100), 100) self.assertRaises(Exception, lambda: self.player.bet(10)) def test_get_card_value(self): self.assertEqual(self.player.get_card_value("6♣"), 6) def tearDown(self): pass
def setUp(self): self.player = Player('Player', ['7C', '8H']) self.dealer = Player('Dealer', ['KS', 'AD'])
class PlayerTests(unittest.TestCase): def setUp(self): self.player = Player() def test_init_accepts_hand(self): cards = ace, king = u'A♠', u'K♠' player = Player(list(cards)) self.assertEquals(2, len(player.hand)) self.assertEquals(ace, player.hand[0]) self.assertEquals(king, player.hand[1]) def test_add_card(self): hand_size = len(self.player.hand) card = Card(u'A♠') self.player.add_card(card) self.assertEquals(hand_size + 1, len(self.player.hand)) self.assertEquals(card, self.player.hand[0]) def test_can_hit_with_hand_value_lt_21(self): '''A player can hit if their hand value is less than 21.''' self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'Q♠')) self.assertEquals(20, self.player.hand_value()) self.assertTrue(self.player.can_hit()) def test_can_hit_with_hand_value_gte_21(self): '''A player cannot hit if their hand value is 21 or higher.''' self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'6♠')) self.player.add_card(Card(u'5♠')) self.assertFalse(self.player.can_hit()) def test_get_hand_value_with_hard_ace(self): '''An ace is hard (1) if a soft ace (11) would cause the player to bust.''' self.player.add_card(Card(u'A♠')) self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'Q♠')) self.assertEquals(21, self.player.hand_value()) def test_get_hand_value_with_soft_ace(self): '''An ace is soft (11) if it won't cause the player to bust.''' self.player.add_card(Card(u'A♠')) self.player.add_card(Card(u'K♠')) self.assertEquals(21, self.player.hand_value()) def test_get_hand_value_with_many_aces(self): '''Only one ace in a hand can be soft (11). The rest must be hard (1).''' self.player.add_card(Card(u'A♠')) self.player.add_card(Card(u'A♥')) self.player.add_card(Card(u'A♣')) self.player.add_card(Card(u'A♦')) self.assertEquals(14, self.player.hand_value()) def test_get_hand_value_with_no_aces(self): self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'Q♠')) self.assertEquals(20, self.player.hand_value()) def test_has_blackjack_with_blackjack(self): self.player.add_card(Card(u'A♠')) self.player.add_card(Card(u'K♠')) self.assertTrue(self.player.has_blackjack()) def test_has_blackjack_with_hand_value_ne_21(self): self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'Q♠')) self.assertFalse(self.player.has_blackjack()) def test_has_blackjack_with_gt_2_cards(self): self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'6♠')) self.player.add_card(Card(u'5♠')) self.assertFalse(self.player.has_blackjack()) def test_has_busted_with_hand_value_lte_21(self): self.player.add_card(Card(u'A♠')) self.player.add_card(Card(u'K♠')) self.assertFalse(self.player.has_busted()) def test_has_busted_with_hand_value_gt_21(self): self.player.add_card(Card(u'K♠')) self.player.add_card(Card(u'Q♠')) self.player.add_card(Card(u'2♠')) self.assertTrue(self.player.has_busted())
from blackjack import Deck, Player, Blackjack #The classes are instantiated deck = Deck() deck.shuffle() player = Player("Mikkel") dealer = Player("dealer") bj = Blackjack(player, dealer, deck) while bj.game_running == True: #A loop that keeps the game running untill the player decides he wants to quit bj.run_game() #The game is started if bj.player.cash == 0: print("Your balance is 0 and you will have to rebuy to play again.") if input("Play again? Press any key to play or press q to quit! ") == "q": #If the player presses "q" the game stops - if not the game starts again quit() else: #The else block resets the game bj.game_running = True player.hand = [] dealer.hand = []
def run_sims(): button_start = st.sidebar.button("Start Sim") bet_size = st.sidebar.number_input("Bet Size: ", value=1, step=1) num_samples = st.sidebar.number_input("Number of Sessions: ", min_value=1, max_value=1000, value=100, step=1) iterations = st.sidebar.number_input( "Number of Hands per Session: ", min_value=1, max_value=10000, value=1000, step=1, ) num_decks = st.sidebar.number_input("Number of decks in a shoe: ", min_value=1, max_value=8, value=6, step=1) cut_card_threshhold = st.sidebar.number_input( "Dealer Cut Card Proportion", min_value=0.01, max_value=0.5, value=0.35, step=0.01, ) bet_multipler_neg = st.sidebar.slider( "Betting multiplier for count of 0 and negatives", 0, 100, 1) bet_multiplier_1 = st.sidebar.slider("Betting multiplier for count of 1", 1, 100, 8) bet_multiplier_2 = st.sidebar.slider("Betting multiplier for count of 2", 1, 100, 16) bet_multiplier_3 = st.sidebar.slider("Betting multiplier for count of 3", 1, 100, 32) bet_multiplier_4 = st.sidebar.slider("Betting multiplier for count of 4", 1, 100, 32) bet_multiplier_5 = st.sidebar.slider("Betting multiplier for count of 5+", 1, 100, 32) if button_start: wager_amts = [ bet_multipler_neg, bet_multipler_neg, bet_multipler_neg, bet_multiplier_1, bet_multiplier_2, bet_multiplier_3, bet_multiplier_4, bet_multiplier_5, ] ranges = [0, 0, 1, 2, 3, 4, 5] betting_policy = (wager_amts, ranges) try: warning = st.warning("Running simulations. Please hold...") progress_bar = st.progress(0) chunks = run_in_chunks(num_samples, 10) final_results = [] for idx, n_samples_small in enumerate(chunks): player = Player( bankroll=1000, hard_policy=hard_policy, soft_policy=soft_policy, split_policy=split_policy, betting_policy=betting_policy, ) results = parallel_processing( player, num_decks=num_decks, iterations=iterations, n_samples=n_samples_small, threshold=cut_card_threshhold, ) final_results = final_results + results progress_bar.progress(min(idx / len(chunks), 1.0)) final_results = [i * bet_size for i in final_results] layout_results(final_results) finally: if warning is not None: warning.empty() if progress_bar is not None: progress_bar.empty()
def create_player_test(self): p1 = Player() p1.add_card(Card("ace", "spades")) p1.add_card(Card("jack", "hearts")) self.assertEqual([("ace", "spades"), ("jack", "hearts")], p1.cards)
def setUp(self): self.deck = ['5S', '2D', '3C'] self.player = Player('Player', ['7C', '8H']) self.dealer = Player('Dealer', ['KS', 'AD'])
def check_hands_for_winning_hand_test(self): p1 = Player() p1.add_card(Card("ace", "spades")) p1.add_card(Card("jack", "hearts")) p2 = Player() p2.add_card(Card("ace", "spades")) p2.add_card(Card("nine", "hearts")) self.assertEqual(p1, get_winning_hand(p1, p2)) p3 = Player() p3.add_card(Card("ace", "diamonds")) p3.add_card(Card("jack", "clubs")) self.assertEqual("draw", get_winning_hand(p1, p3))