def __init__(self): self.my_card = Player() self.comp_card = Dealer() self.qt_rounds_played = 0 self.numbers_left = list(range(1, 91)) self.numbers_played = [] self.is_game_over = False
def __init__(self, num_player=1, player_tokens=1000, min_bet=10, max_bet=500, ndecks=6, shuffle_lim=10, sleep_time=0.7): # self.players = [Player.Player(ntokens=player_tokens) for _ in range(num_player)] self.player = Player(ntokens=player_tokens) self.dealer = Dealer() self.draw_count = 0 # keeps track of number of draws - first two counts as one self.min_bet = min_bet self.max_bet = max_bet self.current_bet = 0 self.sleep_time = sleep_time self.deck = Deck(ndecks, shuffle_lim)
def test_get_face_up_card_AND_get_face_down_card(self): d = Dealer() empty_cc = CardCollection() dest_cc = CardCollection() d.add_card_to_hand(3) self.assertEqual(d.get_face_up_card(), 3) d.add_card_to_hand(4) self.assertEqual(d.get_face_down_card(), 4)
def simulate(numHands): card_cut_ptr = [random.randint(CUT_MIN, CUT_MAX)] draw_pile = Deck(NUM_DECKS) discard_pile = CardCollection() dealer = Dealer() player1 = Player() players = [player1] log = [] for _ in range(numHands): # deal cards for _ in range(2): for p in players + [dealer]: p.add_card_to_hand(draw_pile.pop_a_card()) for p in players + [dealer]: play_round(p, card_cut_ptr, draw_pile, discard_pile) for p in players: evaluate_round(p, dealer) log.append(p.wallet) clear_table(players + [dealer], discard_pile) return log
def __init__(self): # Create the deck self.deck = Deck(6) # Create the player self.player = Player(self.deck) # Create the dealer self.dealer = Dealer(self.deck, [self.player])
def test_add_card_to_hand_AND_move_all_card(self): d = Dealer() empty_cc = CardCollection() dest_cc = CardCollection() d.add_card_to_hand(3) d.add_card_to_hand(4) d.add_card_to_hand(10) self.assertEqual(empty_cc, dest_cc) d.move_all_cards(dest_cc) self.assertEqual(empty_cc, d.hand) expected_dest = CardCollection() expected_dest[3] = 1 expected_dest[4] = 1 expected_dest[10] = 1 self.assertEqual(dest_cc, expected_dest)
def game(player): """ Данная функция управляет логикой игры, благодаря ней можно будет запускать несколько игр в разных потоках """ in_out.rules(player) card_deck = CardDeck() dealer = Dealer(player.resource) while True: try: # Вначале игры все карты возвращаются в колоду, даже # в начале игры, когда карты не розданы это не повредит # это сделано чтобы излишне не усложнять код card_deck.take_cards(player.return_cards()) card_deck.take_cards(dealer.return_cards()) card_deck.shuffle() # Переменные указывающие на наличие комбинации Блекджек у игрока # и диллера player_blackjack = False dealer_blackjack = False # Определить, есть ли деньги у игрока, если нет, то игра завершена # Также уточняется хочет ли пользователь играть if player.money < 1 or not in_out.start_game(player): in_out.finish(player) # Предложить сделать ставку, указав, что минимальная ставка # 1 доллар player.make_bet() # Сдается две карты игроку for _ in range(2): player.take_card(card_deck.give_card()) # Сдается одна карта дилеру dealer.take_card(card_deck.give_card()) # Показываются карты дилера in_out.player_info(dealer, 'Диллера') # Показываются карты игрока in_out.player_info(player, 'Ваши') # Если у игрока блекджек (на руках две карты, количество очков - # 21), то задается соответствующая переменная, иначе берется карта if player.points != 21: player.make_move(card_deck) else: player_blackjack = True # Проверка наличия блекджека у диллера dealer.take_card(card_deck.give_card()) if dealer.points != 21: dealer.make_move(card_deck) else: dealer_blackjack = True # Если у пользователя на руках блекджек и у диллера блекджека нет, # то пользователь выигрывает 3 к 1 if player_blackjack and not dealer_blackjack: player.money += player.bet * 2.5 in_out.print_message( player, 'Вы выиграли {:} $\ \n'.format( round(player.bet * 1.5, 2))) continue if player.points > 21: in_out.print_message(player, 'Вы проиграли, сожалеем.\n') continue in_out.player_info(dealer, 'Диллера') if player.points < dealer.points and dealer.points <= 21: in_out.print_message(player, 'Вы проиграли, сожалеем.\n') elif player.points > dealer.points or dealer.points > 21: player.money += player.bet * 2.0 in_out.print_message( player, 'Вы выиграли {:} $\ \n'.format(round(player.bet, 2))) else: player.money += player.bet in_out.print_message(player, 'Вы сыграли в ничью\n') except KeyboardInterrupt: in_out.finish(player)
class BlackJack: """Main class of pyBlackJack. Define a BlackJack game with a 6-deck shoe, one player and one dealer.""" def __init__(self): # Create the deck self.deck = Deck(6) # Create the player self.player = Player(self.deck) # Create the dealer self.dealer = Dealer(self.deck, [self.player]) def start(self): """Starts the game. A game ends when the player has no more chips.""" # Print game's title asciiArts.print_title() utils.print_separator() # While the player has enough money to play while self.player.get_bankroll() > 0: # Display player's bankroll print("Your current bankroll is: " + str(self.player.get_bankroll())) + " chips." # Play a game self.play() # End self.end() print("Thank you for playing pyBlackJack!") def play(self): """Play a round. The player first bets and then play his hand(s).""" # Clear player's and dealer's hand self.player.clear() self.dealer.clear() ################# # Ask for a bet # ################# bet = self.bet_step() # Register player's bet self.player.bet(bet) ############## # Deal cards # ############## # If the dealer has dealt 75% of the cards, then shuffle a new deck if self.deck.get_number_of_cards_left() < 78: self.deck = Deck(6) print("Dealing...") self.dealer.deal() utils.print_separator() self.print_dealer_hand(False) ######### # Split # ######### self.split_step() ############## # Play Hands # ############## for i in range(len(self.player.hands)): self.player.hand = self.player.hands[i] self.play_hand(i) def end(self): """End of player's turn. The dealer plays and unveils his cards. The results are then displayed.""" self.dealer.unveil_cards() self.dealer.hit_long() self.print_dealer_hand(True) self.display_results() def bet_step(self): """The player choses how many chips he wants to bet.""" while True: # Ask for the bet bet = utils.read_integer("Enter your bet (1 chip minimum): ") bankroll = self.player.get_bankroll() # If the bet is less than player's bankroll and higher than 1 chip, play the round if bet <= bankroll and bet >= 1: return bet # The bet is higher than player's bankroll elif bet >= bankroll: print("You cannot bet more than your current bankroll!") continue # The bet is lower than 1 chip elif bet < 1: print("The minimum bet is 1 chip!") continue # Other cases else: print("Wrong bet. Please enter a positive number greater than 1.") continue def split_step(self): """If player's hand is a pair, he has to choose whether he wants to split it or not.""" for i in range(len(self.player.hands)): self.player.hand = self.player.hands[i] # Check if player's hand is splittable (Player can play a maximum of 4 hands at the same time) if self.player.hand.is_splittable() and len(self.player.hands) < 4: # Print player's hand utils.print_separator() print("Player's hand #" + str(i) + ":\n") self.print_player_hand() # Ask player whether he wants to split the hand or not do_split = utils.read_boolean("Do you want to split? (Y/N)") if do_split: # Check if player has enough chips to split if self.player.can_split(): # Split the hand self.player.split() # Recursive call of split_bet to check if the new hands can also be split self.split_step() break else: print("Sorry, you don't have enough chips to split!") def play_hand(self, i): """Play a hand.""" # Print player's hand utils.print_separator() print("Player's hand #" + str(i) + ":\n") self.print_player_hand() # Check if the hand is a BlackJack if self.player.hand.is_blackJack(): self.player.hand.status = "blackjack" print("Congratulations! You got a Blackjack!\n") else: while self.player.hand.status == "active": # Ask for player's next move action = utils.multiple_choice_question("[H]it or [S]tand? (H/S): ", ["h", "s"]) utils.print_separator() # If he stands if action == "s": # Finish the current hand self.player.hand.status = "finished" # If he hits elif action == "h": # Hit self.player.hit() self.print_player_hand() # Check if player is busted if self.player.is_busted(): self.player.hand.status = "busted" print("You bust!\n") def display_results(self): """Compute player's gain and display results at the end of the round.""" gain = 0 # Check if dealer is busted if self.dealer.is_busted(): print("Dealer is busted!\n") # Compute player's gain. Loop through player's hands for hand in self.player.hands: if hand.is_blackJack(): gain += 2.5 * self.player.get_bet() elif hand.status == "finished": gain += 2 * self.player.get_bet() # Dealer got a BlackJack elif self.dealer.hand.is_blackJack(): print("Dealer got a BlackJack!\n") # Compute player's gain. Loop through player's hands for hand in self.player.hands: if hand.is_blackJack(): gain += self.player.get_bet() # Dealer has neither busted nor got a BlackJack else: # Compute player's gain. Loop through player's hands for hand in self.player.hands: if hand.is_blackJack(): gain += 2.5 * self.player.get_bet() elif hand.status == "finished": if hand.get_value() > self.dealer.hand.get_value(): gain += 2 * self.player.get_bet() elif hand.get_value() == self.dealer.hand.get_value(): gain += self.player.get_bet() # Add gain to player's account self.player.bankroll += gain # Player wins chips if gain > 0: print( "You won " + str(gain) + " chip(s)! Your new bankroll is: " + str(self.player.get_bankroll()) ) + " chips." # Player loses chips else: loss = len(self.player.hands) * self.player.get_bet() print( "You lost " + str(loss) + " chip(s)... Your new bankroll is: " + str(self.player.get_bankroll()) ) + " chips." utils.print_separator() utils.print_separator() def print_dealer_hand(self, with_value): """Print dealer's hand.""" print("Dealer's hand:\n") if with_value: print("value: " + str(self.dealer.hand.get_value()) + "\n" + str(self.dealer.hand)) else: print(str(self.dealer.hand)) def print_player_hand(self): """Print player's current hand.""" hand = self.player.hand print("value: " + str(hand.get_value()) + "\n" + str(hand))
def __init__(self): self.deck_of_cards = DeckOfCards() self.dealer = Dealer(self) self.player = HumanPlayer(self, 10000) #The human player starts with 10000 coins
def __init__(self): self.deck_of_cards = DeckOfCards() self.dealer = Dealer(self) self.player = Player(self, 10) #The human player starts with 10 coins self.start_game()
class Raffle(object): """This class represents a game from begging to the end. It inits instance of Dealer and Player classes, list of unique numbers from 1 to 90, counts of rounds played, list of selected numbers and flag is_game_over. Methods of this class includes: - random selection of a number for a round, - steps that need to be done to play one round of a game, - evaluation is game is over, - printout to console information about selected number, which includes number of a round played, selected number and a "funny" name of this number, - printout a game-over message. """ def __init__(self): self.my_card = Player() self.comp_card = Dealer() self.qt_rounds_played = 0 self.numbers_left = list(range(1, 91)) self.numbers_played = [] self.is_game_over = False def number_selection(self): """This method selects a random number from the list of available for this game. Every time it "shakes" or shuffle the list to make the choice more random. To maintain the uniqueness selected number is removed from list of available. It also keep tracking the qt of rounds played and updates list of numbers_played. :return: number: int """ random.shuffle(self.numbers_left) try: self.number = self.numbers_left.pop() self.numbers_played.append(self.number) self.qt_rounds_played += 1 except IndexError: print("Боченков не осталось!") self.number = None return self.number def print_selected_number(self): """Prints to console selected number and info about qt numbers left in pretty way. """ print() print(f"РАУНД {self.qt_rounds_played}") try: print( f"Выпало число: {self.number}! {str(number_names[self.number])}" ) except KeyError: print(f"Выпало число: {self.number}!") print(f"Осталось {len(self.numbers_left)} боченков \n") def play_a_round(self): """This method defines sequence of needed methods in every round of the game. This sequence is repeated untill the game is over. """ number = self.number_selection() self.print_selected_number() self.comp_card.print_a_card() self.my_card.print_a_card() self.comp_card.find_the_num_in_card(number) self.my_card.underline_number(number, self) self.findout_is_gameover() def findout_is_gameover(self): """This method checks if all numbers in players's cards are guessed. """ if not self.is_game_over: self.is_game_over = True if ( self.my_card.number_guessed == 15 or self.comp_card.number_guessed == 15) else False return self.is_game_over def print_endgame_message(self): """This method evaluates the message that should be printed according to who has won the game in a pretty way. It also prints statistic information about the game: - how many rounds were played, - what numbers were selected, - how many numbers have left, - what are these left numbers. """ message = "Вы выиграли!" if self.my_card.number_guessed == 15 else "Компьютер выиграл!" print(message) end_message = f"Игра закончена!\n" \ f"В игре прошло {self.qt_rounds_played} раундов \n" \ f"Выпали числа: {self.numbers_played} \n" \ f"Осталось {len(self.numbers_left)} чисел \n" \ f"{self.numbers_left}" print(end_message)
def test_get_hand_len(self): d = Dealer() d.add_card_to_hand(3) self.assertEqual(d.get_hand_len(), 1) d.add_card_to_hand(4) self.assertEqual(d.get_hand_len(), 2) d.add_card_to_hand(4) self.assertEqual(d.get_hand_len(), 3)
def test_get_hand_value(self): d = Dealer() d.add_card_to_hand(3) self.assertEqual(d.get_hand_value(), 3) d.add_card_to_hand(4) self.assertEqual(d.get_hand_value(), 7) d.add_card_to_hand(2) self.assertEqual(d.get_hand_value(), 9)
class Game: """ Holds the shoe, the players, and the logic for going through the game. Parameters ---------- dealer: Dealer The Dealer of the game. shoe: Shoe Shoe containing cards for use in the game. players: tuple of Player Sequence of Players playing the game. """ def __init__(self, *players): self.dealer = Dealer() self.shoe = Shoe() if not players: raise ValueError("No players entered.") self.players = [Player(player) for player in players] def start_screen(self): """Start screen for the game.""" print("\n" + "#" * 79 + "\n" + "BLACKJACK".center(79) + "\n" + "#" * 79) print("RULES".center(79) + "\n" + ("-" * 5).center(79)) print("*Standard Blackjack Rules apply." "\n*Six decks of cards are used in the shoe initially." "\n*Side-rules (doubling-down, splitting, etc.) are absent " "from this game." "\n*When dealer hits a 'Soft 17', he has to stand." "\n*All players start out with 100 credits each." "\n*Wins are paid out at 1:1, except for winning blackjacks " "which are paid at 3:2.") print("\n" + "#" * 79) time.sleep(1.75) def play(self): """Logic for playing the full game.""" self.shoe.shuffle() while True: # Print start screen and player details. self.start_screen() print("PLAYERS".center(79) + "\n" + ("-" * 7).center(79)) for i in range(len(self.players)): print(f"Player {i+1}" + "\n" + "=" * len(f"Player {i+1}") + f"\n\tName: {self.players[i].name}" + f"\n\tCredits: {self.players[i].credit}") print("\n" + "#" * 79) # Update shoe when more than 75% of cards are used up. if self.shoe.cards_left() < 78: self.shoe = Shoe() self.shoe.shuffle() # Betting process. print("PLAYERS, PLACE YOUR BETS".center(79) + "\n" + ("-" * 24).center(79) + "\n") for player in self.players: print(f"{player.name} has {player.credit} credits left.") player.bet = float( input(f"How many credits do you want" + f" to bet, {player.name}? ")) print("\n" + "#" * 79) # Beginning of Blackjack round. print("START OF ROUND".center(79) + "\n" + ("-" * 14).center(79)) # Initial dealing of cards - 2 cards to each player. # (dealing starts from the players and ends with the dealers). for i in range(2): for player in self.players: player.hand.draw_from(self.shoe) self.dealer.hand.draw_from(self.shoe) # Print details (hand, bet, credit) print("CURRENT BLACKJACK TABLE".center(79) + "\n" + ("=" * 23).center(79)) for player in self.players: print(f"{player.name},") player.show_hand() print("-" * 79) time.sleep(2.5) print("=" * 79 + "\n") self.dealer.show_hand(initial=True) time.sleep(2.5) print("\n" + "#" * 79) # Play starts from the players and ends with the dealers. print("PLAYERS, MAKE YOUR MOVES".center(79) + "\n" + ("-" * 24).center(79)) is_bust = [] # Checks how many players bust. for player in self.players: print(f"{player.name}'s move\n" + "=" * (len(player.name) + 7)) # Checks if player has a Blackjack. if player.hand.value == 21: player.show_hand() print("YOU HAVE GOT A BLACKJACK!\n") player.hand.value = "21B" # 'B' stands for Blackjack. is_bust.append(False) time.sleep(1.25) print("-" * 79) continue # All the players start playing. while player.play(): player.hand.draw_from(self.shoe) #Hit. if player.hand.value == "BUST": is_bust.append(True) else: is_bust.append(False) print("-" * 79) time.sleep(1.5) # Proceeds only if at least one player did not bust. if False in is_bust: print("=" * 79) print("\nDealer's move\n" + "=" * (13) + "\n") if self.dealer.hand.value == 21: self.dealer.show_hand() print("Dealer has got a Blackjack!\n") self.dealer.hand.value = "21B" time.sleep(2) else: while self.dealer.play(): self.dealer.hand.draw_from(self.shoe) # Hit. print("\n") time.sleep(2) print("#" * 79) time.sleep(2) #Results of the round. print("RESULTS OF THE ROUND".center(79) + "\n" + ("-" * 20).center(79), end='') for player in self.players: time.sleep(1.5) print("\n") if player.hand.value == "BUST": # Bet lost by player. print(player.name, "LOST THE ROUND!", f"\n{player.name}, YOU LOSE", player.bet, "CREDIT(S).") player.credit -= player.bet continue elif self.dealer.hand.value == "BUST": # Bet won by player. print(player.name, "WON THE ROUND!", f"\n{player.name}, YOU WIN", player.bet, "CREDIT(S).") player.credit += player.bet continue elif str(player.hand.value) > str(self.dealer.hand.value): # Bet won by player. if player.hand.value == "21B": # Blackjack returns 1.5 times the original bet. print(player.name, "WON THE ROUND!", f"\n{player.name}, YOU WIN", player.bet * 1.5, "CREDIT(S)", "BECAUSE OF YOUR BLACKJACK!") player.credit += (player.bet * 1.5) continue print(player.name, "WON THE ROUND!", f"\n{player.name}, YOU WIN", player.bet, "CREDIT(S).") player.credit += player.bet continue elif str(player.hand.value) < str(self.dealer.hand.value): # Bet lost by player. print(player.name, "LOST THE ROUND!", f"\n{player.name}, YOU LOSE", player.bet, "CREDIT(S).") player.credit -= player.bet continue elif player.hand.value == self.dealer.hand.value: # Draw. print(f"IT'S A DRAW, {player.name}!" + "\nThere is no change in your credits.") continue print("\n" + "#" * 79) # Ask players if they want to replay. print("END OF ROUND".center(79) + "\n" + ("-" * 12).center(79) + "\n") for player in self.players.copy(): time.sleep(1) if player.credit == 0: print(f"Sorry {player.name}, you can't play anymore, " "as you have no credits left.") self.players.remove(player) else: choice = input("Do you want to play another hand, " f"{player.name}? (Y/N) ") del player.bet player.hand.empty_cards() player.hand.value = 0 if choice.upper() == "N": self.players.remove(player) self.dealer.hand.empty_cards() self.dealer.hand.value = 0 # If every player quits, end game. if not self.players: print("\n" + "GAME OVER!".center(79)) print("#" * 79 + "\n") time.sleep(1) break
def setup(self, player, deck): self.player = [Player(), Dealer()] self.deck = deck
def __init__(self, *players): self.dealer = Dealer() self.shoe = Shoe() if not players: raise ValueError("No players entered.") self.players = [Player(player) for player in players]
def __init__(self, num_shuffles=1): self.num_shuffles = num_shuffles self.dealer = Dealer(name='Dealer') self.player = Player(name='1') self.game_over = False
class BlackjackGame: deck_of_cards = None dealer = None player = None active = None #This indicates if the game is active or not def __init__(self): self.deck_of_cards = DeckOfCards() self.dealer = Dealer(self) self.player = Player(self, 10) #The human player starts with 10 coins self.start_game() def start_game(self): self.active = True # As the game begins, we set this flag the True value while (self.not_ended()): self.begin_hand() self.player.ask_if_continues() #The player if asked if he wants to keep playing def not_ended(self): return self.active def clean_hands(self): self.player.clean_hand() self.dealer.clean_hand() def get_deck(self): return self.deck_of_cards def begin_hand(self): bet = self.player.bet() self.clean_hands() #Makes sure both the dealer and the player have empty hands self.dealer.get_card(self.deck_of_cards.give_a_card()) self.player.get_card(self.deck_of_cards.give_a_card()) self.player.get_card(self.deck_of_cards.give_a_card()) if (self.player.calculate_value() == 21): print 'BlackJack! You win' self.player.get_prize(bet + 1.5*bet) else: if (self.player.has_two_equal_valued_cards): if (self.player.wants_to_split()): self.split_hand() #Code the spit hand dealer_original_value = self.dealer.calculate_value() self.player.make_move(dealer_original_value) player_value = self.player.calculate_value() self.dealer.make_move(player_value) #TODO: Calculate results. If player's hand value is higher #TODO: than dealer's hand value, then the player wins. #TODO: If both have the same hand value, the bid is returned. #TODO: If anyone's hand value is over 21, he loses def split_hand(self): #TODO: Implement #If the player chooses to split, then two 'sub-hands' are played #instead of one. Each hand with one of the cards, and each hand #with the same bet. Obviously, if the player chooses to split, he #must bet again the same quantity. pass
if not hand.burn_flag and not self.dealer.hand.burn_flag: # hand isn't burned, dealer isn't burned if hand.black_jack and not self.dealer.hand.black_jack: # winning scenarios hand.win_black(player) continue if hand.value > self.dealer.hand.value: hand.win(player) continue if self.dealer.hand.value == hand.value: # draw with dealer hand.tie(player) hand.win(player) continue print("End of Game!") deck = Deck() active_players = [] g1 = Gambler("Ben", deck) g2 = Gambler("Gil", deck) dealer = Dealer() win = GraphicGame(deck, dealer, [g1, g2]) win.geometry("1200x700") win.title('Black Jack') main = MainGame(win, [g1, g2]) thread = threading.Thread(target=main.start_game) # make loop terminate when the user exits the window thread.daemon = True thread.start() win.mainloop()
class BlackjackGame: deck_of_cards = None dealer = None player = None active = None #This indicates if the game is active or not current_player_bet = None def __init__(self): self.deck_of_cards = DeckOfCards() self.dealer = Dealer(self) self.player = HumanPlayer(self, 10000) #The human player starts with 10000 coins def start_game(self, training_repetitions, real_games_repetitions): self.player.victories = 0 self.dealer.victories = 0 self.player.coins = 10000 self.active = True # As the game begins, we set this flag the True value training_flag = True #It's time to train! training_repetitions = training_repetitions #this number can be changed for x in range(0, training_repetitions): print 'Training hand #' + str(x) + '\n' self.begin_hand(training_flag) self.deck_of_cards.restart_deck_of_cards() training_flag = False #I'm tired of training, I want to play seriously!! print 'END OF TRAINING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' self.player.print_victories() self.dealer.print_victories() #On the while condition we could ask if the player wants to keep playing, #But here we prefer the automated player to play a fixed set of hands, let's say, 250 real_hands_to_play = real_games_repetitions i = 0 while (self.not_ended() and i < real_hands_to_play): i+=1 print '--------------------------------------------------' print '\n\nReal hand #' + str(i) + '\n' self.begin_hand(training_flag) self.deck_of_cards.restart_deck_of_cards() self.player.print_victories() self.dealer.print_victories() print 'Initial coins: ' + '10000' #it starts with 10000 coins print 'Coins (after the game): ' + str(self.player.coins) def not_ended(self): return self.active def clean_hands(self): self.player.clean_hand() self.dealer.clean_hand() def get_deck(self): return self.deck_of_cards def begin_hand(self, training_flag): self.current_player_bet = self.player.bet(training_flag) self.clean_hands() #Makes sure both the dealer and the player have empty hands print '\nNEW ROUND:' print '\n Dealer Hand:' self.dealer.get_card(self.deck_of_cards.give_a_card()) self.dealer.print_hand() print '\n Human Hand:' self.player.get_card(self.deck_of_cards.give_a_card()) self.player.get_card(self.deck_of_cards.give_a_card()) self.player.print_hand() dealer_original_value = self.dealer.calculate_value() move = self.player.make_move(dealer_original_value, training_flag) if (move == 'split'): self.split_hand(training_flag) else: player_value = self.player.calculate_value() self.dealer.make_move(player_value) self.compute_and_print_hand_results(self.current_player_bet, player_value, training_flag) #This should be refactored def compute_and_print_hand_results(self, bet, player_value, training_flag): if player_value == 21: print 'BlackJack! You win' print '-------------------------------------------------' if training_flag and (len(self.player.temp_state_action) > 0): self.player.update_fg_values('win') elif not training_flag: self.player.compute_victory() self.player.get_prize(1.5 * 2 * self.current_player_bet) result = 'win' elif (self.player.calculate_value() == self.dealer.calculate_value()): if not training_flag: self.player.get_prize(self.current_player_bet) print "It's a tie! Your bet is refunded" return 'tie' elif player_value > 21: print ' \nThe Dealer WINS! (Human got over 21)' print '-------------------------------------------------' if training_flag: self.player.update_fg_values('lose') else: self.dealer.compute_victory() self.player.get_prize(self.current_player_bet) result = 'lose' self.player.restart_temp_state_action() elif self.dealer.calculate_value() > 21: print '\nHuman Player WINS! (Dealer got over 21)' print '-------------------------------------------------' if training_flag: self.player.update_fg_values('win') else: self.player.compute_victory() self.player.get_prize(2 * bet) result = 'win' self.player.restart_temp_state_action() elif (21 - player_value) < (21 - self.dealer.calculate_value()): print "\nHuman Player WINS! (Has a better score)" print '-------------------------------------------------' if training_flag: self.player.update_fg_values('win') else: self.player.compute_victory() self.player.get_prize(2 * bet) result = 'win' self.player.restart_temp_state_action() elif (21 - player_value) > (21 - self.dealer.calculate_value()): print "\nThe Dealer WINS! (Has a better score)" print '-------------------------------------------------' if training_flag: self.player.update_fg_values('lose') else: self.dealer.compute_victory() result = 'lose' self.player.restart_temp_state_action() def split_hand(self, training_flag): #If the player chooses to split, then two 'sub-hands' are played #instead of one. Each hand with one of the cards, and each hand #with the same bet. Obviously, if the player chooses to split, he #must bet again the same quantity. player_initial_hand = copy.deepcopy(self.player.hand) dealer_hand = self.dealer.hand card = self.player.hand.cards.pop() print 'SPLIT!\n' print '----Split hand 1\n' self.begin_one_split_hand(training_flag, self.player.hand, dealer_hand) player_value_a = self.player.calculate_value() aux_temp_state_action_a = copy.deepcopy(self.player.temp_state_action) print aux_temp_state_action_a print '----Split hand 2\n' self.player.restart_temp_state_action() self.player.temp_state_action.append(((player_initial_hand.calculate_status(),dealer_hand.calculate_value()), 'split')) self.player.hand.clean() self.player.hand.add_card(card) self.begin_one_split_hand(training_flag, self.player.hand, dealer_hand) self.dealer.make_move(0) #0 because it play with 2 hands at the same time player_value_b = self.player.calculate_value() #hand b print "Hand 2:" self.compute_and_print_hand_results(self.current_player_bet, player_value_a, training_flag) #hand a print "Hand 1" self.player.temp_state_action = aux_temp_state_action_a self.compute_and_print_hand_results(self.current_player_bet, player_value_b,training_flag) def begin_one_split_hand(self, training_flag, player_hand, dealer_hand): dealer_original_value = dealer_hand.calculate_value() self.player.hand = player_hand self.player.make_move(dealer_original_value, training_flag)
class Game(object): def __init__(self, num_player=1, player_tokens=1000, min_bet=10, max_bet=500, ndecks=6, shuffle_lim=10, sleep_time=0.7): # self.players = [Player.Player(ntokens=player_tokens) for _ in range(num_player)] self.player = Player(ntokens=player_tokens) self.dealer = Dealer() self.draw_count = 0 # keeps track of number of draws - first two counts as one self.min_bet = min_bet self.max_bet = max_bet self.current_bet = 0 self.sleep_time = sleep_time self.deck = Deck(ndecks, shuffle_lim) def initialize_round(self): # for p in self.players: # p.initialize() self.player.initialize() # clear dealer hand self.dealer.initialize() self.draw_count = 0 def players_bet(self): self.current_bet = self.player.place_bet(min_bet=self.min_bet, max_bet=self.max_bet) def draw_cards(self, side, face_down=True): new_card = self.deck.draw() if not face_down: new_card.reveal() if side == 'p': self.player.hands[0].append(new_card) elif side == 'd': self.dealer.hand.append(new_card) def players_actions(self): """ Get player action from player :return: """ # compile list of valid actions for player # hit and stand are always valid valid_actions = [Action.Hit, Action.Stand] # split and double only occurs in draw one if self.draw_count == 1: valid_actions.append(Action.Double) if len(self.player.hands[0]) == 2 and self.player.hands[0][0].value == self.player.hands[0][1].value: valid_actions.append(Action.Split) action = self.player.choose_action(valid_actions) return action def result(self, code): # player blackjack, pays 3 to 2 if code == Condition.BLACKJACK: print("Congratulations, you got a blackjack!") update_tokens = int(self.current_bet * (1 + 1.5)) # player wins elif code == Condition.WIN: print("You won!") update_tokens = self.current_bet * 2 # player loses elif code == Condition.LOSE: print("You lost!") # player token already deducted, do nothing update_tokens = 0 # push elif code == Condition.PUSH: print("Push!") update_tokens = self.current_bet # compare hand values else: raise NotImplementedError self.player.tokens += update_tokens def condition(self): """ Check the current condition and returns a condition code :return: condition code """ # check blackjack if get_hand_best_value(self.player.hands[0]) == 21: # player blackjack, pays 3 to 2 if self.draw_count == 1: # check if dealer also blackjack return Condition.PUSH if get_hand_best_value(self.dealer.hand) == 21 else Condition.BLACKJACK # check dealer blackjack elif get_hand_best_value(self.dealer.hand) == 21 and self.draw_count == 1: print("Dealer got a blackjack!") return Condition.LOSE # check player bust elif get_hand_best_value(self.player.hands[0]) > 21: print("You busted!") return Condition.LOSE # check dealer bust elif get_hand_best_value(self.dealer.hand) > 21: print("Dealer busted!") return Condition.WIN # continue else: return Condition.CONTINUE def compare_hands(self): """ Compares the hands between dealer and player to decide result :return: a result code """ # take max <= 21 player_best = get_hand_best_value(self.player.hands[0]) dealer_best = get_hand_best_value(self.dealer.hand) # check blackjack if player_best == 21 and dealer_best != 21 and self.draw_count == 1: return Condition.BLACKJACK # check dealer bust if dealer_best > 21: return Condition.WIN if player_best > dealer_best: return Condition.WIN elif player_best < dealer_best: return Condition.LOSE elif player_best == dealer_best: return Condition.PUSH else: raise NotImplementedError def display_hands(self): # only print values <= 21, print minimum if no values <= 21 dealer_values = get_hand_value(self.dealer.hand) dealer_print = sorted([val for val in dealer_values if val <= 21]) if len(dealer_print) == 0: dealer_print = [min(dealer_values)] player_values = get_hand_value(self.player.hands[0]) player_print = sorted([val for val in player_values if val <= 21]) if len(player_print) == 0: player_print = [min(player_values)] print("Dealer hand:") print("%s, %s" % (self.dealer.hand, dealer_print)) print() print("Player hand:") print("%s, %s" % (self.player.hands[0], player_print)) print() sleep(self.sleep_time) def split(self): pass def round(self): self.initialize_round() self.players_bet() # draw two initial cards print("Drawing first two cards...") self.draw_cards('d', face_down=False) self.draw_cards('p', face_down=False) self.draw_cards('d', face_down=True) self.draw_cards('p', face_down=False) self.draw_count += 1 self.display_hands() code = Condition.CONTINUE # player draws until 21 or stand or double or busted while True: # drew to 21 if get_hand_best_value(self.player.hands[0]) == 21: code = Condition.BLACKJACK break # busted, reveal dealer card and end round if get_hand_best_value(self.player.hands[0]) > 21: code = Condition.LOSE # reveal dealer's cards for card in self.dealer.hand: card.reveal() self.display_hands() self.result(code) return player_action = self.players_actions() # player stand, end player drawing phase if player_action == Action.Stand: break if player_action == Action.Split: # TODO: split logic pass self.draw_cards('p', face_down=False) self.draw_count += 1 self.display_hands() # if player doubled if player_action == Action.Double: # checked if player had enough tokens # deducted from player balance # add to current bet self.current_bet *= 2 # end player draw (only one draw on doubles) break # reveal dealer's cards for card in self.dealer.hand: card.reveal() self.display_hands() # if player blackjack, skip dealer drawing if code != Condition.BLACKJACK: # dealer draws until >= 17 while True: dealer_action = self.dealer.choose_action() if dealer_action == Action.Stand: break self.draw_cards('d', face_down=False) self.display_hands() # dealer done drawing but still no result, so compare hands code = self.compare_hands() # game ended self.result(code)