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_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_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 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_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_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 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_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']
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
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
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_get_point(self): player = Player('You') player.draw_card(0) assert player.get_point() == [1, 11] player.draw_card(13) assert player.get_point() == [ 2, ] player.draw_card(10) player.draw_card(11) assert player.get_point() == [ 22, ]
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 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_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")
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" )
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 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_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 __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_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 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
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()
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 main(): # name variables deck, value = Deck(), Value() shuffled_deck = deck.shuffle_deck() spacer = '--------------------------' print (spacer) print ("BLACKJACK!!!") print (spacer) bank = eval(input('how much do you want to play with: ')) print (spacer) P1 = Player('P1', bank) dealer = Player('dealer') print ('You now have %s to bet' %(P1.bank)) print (spacer) answer = ['Y', 'y', 'n', 'N'] # input bank keep_playing = True a = 'Y' # does user want to play again while keep_playing == True: if a not in answer: # did not select Y/N print ('that answer is not an option...') a = input('do you want to keep playing? (Y/N) ') # ask once more continue else: if a == 'N' or a == 'n': keep_playing = False break # cut to game # start game if P1.bank == 0: P1.bank = int(input('you ran out of money, enter more money: ')) bet = int(input('enter your bet: ')) print (P1.add_bet(bet)) print () # pass cards to dealer & player(s) P1.hand.append(deck.deal_card()) dealer.hand.append(deck.deal_card()) P1.hand.append(deck.deal_card()) dealer.hand.append(deck.deal_card()) # show your hand & dealer's last hand print ('your current hand:') print (spacer) print (P1.show_hand()) print ('value of the hand is: %s' % (value.actual_value(P1.hand))) print (spacer) print ('dealer\'s hand: %s'% (dealer.hand[-1])) print (spacer) print ('card count: %s' % (c(deck.history))) bj = False if value.actual_value(P1.hand) != 21: choose = input('Do you want to hit or stand? (H/S): ') else: bj = True # plauer's turn while ((choose == 'H') and not bj) or ((choose == 'h') and not bj): P1.hand.append(deck.deal_card()) print (spacer) print ('you drew a %s. Hand value: %s' % (P1.hand[-1], value.actual_value(P1.hand))) print (spacer) print ('Current Hand:') print (P1.show_hand()) if value.actual_value(P1.hand) == 0: print ('You busted') break print ('card count: %s' % (c(deck.history))) choose = input('Do you want to hit or stand? (H/S): ') # Dealer's turn print ('Dealer\'s turn') print (spacer) print ('dealer\'s hand: ') print (dealer.show_hand()) print ('dealer\'s current value is: %s' % (value.actual_value(dealer.hand) )) while value.actual_value(dealer.hand) < 17 and value.actual_value(P1.hand) != 0: # soft 17 dealer.hand.append(deck.deal_card()) print ('dealer drew a %s' % (dealer.hand[-1])) print (spacer) # did dealer break? if value.hand_value(dealer.hand) != 0: print ('dealer value: %s' % (value.actual_value(dealer.hand))) if value.hand_value(dealer.hand) == 0: print ('dealer busted') break # reveal winner and give earnings print ('Your hand value: %s || Dealer\'s hand value: %s' % (value.actual_value(P1.hand), value.actual_value(dealer.hand))) if value.actual_value(P1.hand) > value.actual_value(dealer.hand): P1.win() # add winnings to bank if value.hand_value(dealer.hand) == 0: print ('Dealer busted') print ('You win!') print ('you now have %s dollars total' %(P1.bank)) elif value.hand_value(P1.hand) == value.hand_value(dealer.hand): print ('Tie.') else: P1.lose() # subtract bet from P1 bank print ('Dealer wins') print ('you now have %s dollars total' %(P1.bank)) print ('end of the round') print () # clear old hands dealer.new_hand() P1.new_hand() a = input('do you want to keep playing? (Y/N) ') bj = False if len(deck.history) < 26: deck._deck = deck.shuffle_deck()
def test_a_player_can_bet_amounts(): p = Player() assert p.bet(50) == 50 assert p.bank == 950
def test_a_game_auto_plays_until_someone_has_zero_dollars(): game = Game(Player(), Player(), Player()) turns = game.auto_play() assert turns > 0 assert any(p.bank == 0 for p in game.players)
def test_a_player_starts_with_amount(): p = Player() assert p.bank == 1000