class Player: #Two types of players: Player and Dealer #Deck input should be the same deck for every player def __init__(self, name, deck, playertype='Player'): self._name = name self._deck = deck self._type = playertype self._hand = Hand() def hitMe(self): card = self._deck.draw() self._hand.addToHand(card) self._hand.updateSum() def getName(self): return self._name def displayHand(self): print(self._name + ' has the following cards:') self._hand.display() def getSum(self): return self._hand.getSum() def displaySum(self): print(self._name + '\'s sum is ' + str(self.getSum())) def isBust(self): return self._hand.isBust()
def test_hand_display(self): hand = Hand() hand.add_card(Card(14, 'Hearts')) hand.add_card(Card(7, 'Clubs')) hand.add_card(Card(14, 'Diamonds')) hand.add_card(Card(11, 'Hearts')) hand.add_card(Card(6, 'Diamonds')) hand.add_card(Card(5, 'Spades')) hand.display()
class GameController: '''A controller for a simple Blackjack game''' def __init__(self): self.BLACKJACK = 21 self.dealer = Dealer() self.player_hand = Hand() def start_play(self): '''Start the game''' print("The dealer's score is", self.dealer.score) self.deal_two() self.display_hand() def deal_two(self): '''Deal two cards''' self.player_hand.receive_cards(self.dealer.deal_one()) self.player_hand.receive_cards(self.dealer.deal_one()) def display_hand(self): '''Display the hand''' self.player_hand.display() self.stay_or_hit(input('Would you like to stay or hit?\n')) def stay_or_hit(self, s_or_h): if s_or_h == 'hit': self.player_hand.receive_cards(self.dealer.deal_one()) self.display_hand() if self.player_is_bust(): self.do_bust() else: self.stay_or_hit(input('Would you like to stay or hit?\n')) elif s_or_h == 'stay': self.do_stay() else: self.stay_or_hit(input('Would you like to stay or hit?\n')) def player_is_bust(self): '''Determine if player is bust''' return self.player_hand.score(self.BLACKJACK) > self.BLACKJACK def do_stay(self): if self.player_hand.score(self.BLACKJACK) > self.dealer.score: print('You win!') elif self.player_hand.score(self.BLACKJACK) < self.dealer.score: print('You lose!') else: print('You tied!') def do_bust(self): print('**************') print(' BUST ') print('**************')
class GameController: """A controller for a simple blackjack game""" def __init__(self): self.deck = Deck() self.dealer_score = r.randint(17, 21) # dealer 的分数在17-21 self.player_hand = Hand() def start_play(self): print("The dealer's score is", self.dealer_score) self.deal_two() self.display_hand() self.stay_or_hit(input("Would you like to stay or hit?\n")) def deal_two(self): # After two times shuffling, get two last cards. 两次洗牌,每次得到洗牌后最后一张牌 self.player_hand.receive_card(self.deck.deal_one()) self.player_hand.receive_card(self.deck.deal_one()) def display_hand(self): self.player_hand.display() # 展示现在手上的牌 def stay_or_hit(self, s_or_h): if s_or_h == "hit": # 要不要继续拿牌? self.player_hand.receive_card(self.deck.deal_one()) # 再拿一次洗牌后的最后一张 self.display_hand() if self.player_is_bust(): # 如果击败dealer最大分数 21 self.do_bust() else: self.stay_or_hit( input("Would you like to stay or hit?\n")) # 没有击败继续问 elif s_or_h == "stay": # 如果不想继续拿牌 self.do_stay() #直接现在的牌和dealer的分数比较 else: self.stay_or_hit(input("Would you like to stay or hit?\n")) def player_is_bust(self): return self.player_hand.score() > 21 # 现在手上的牌的总值,是不是比21大 def do_stay(self): if self.player_hand.score() > self.dealer_score: print("You Win!!!") elif self.player_hand.score() < self.dealer_score: print("You lose.") else: print("You tied.") sys.exit() def do_bust(self): print("*********************************") print("*** BUST! ***") print("*********************************\n") sys.exit()
class Game: def __init__(self): self.deck = Deck() self.dealer_hand = Hand() self.player_hand = Hand() self.deck.shuffle() def reset(self): self.deck.reset() self.dealer_hand.clear() self.player_hand.clear() self.deck.shuffle() def ask_user(self, prompt, valid_inputs): """ Prompt the user with a question, and repeat until they give a valid answer For example, `self.ask_user('Choose:', ['hit', 'stay'])` will display: Choose: (hit/stay) and loop until the user types either hit or stay :param prompt: The question to display :param valid_inputs: the valid answers :return: one of the valid answers given """ joined_inputs = '/'.join(valid_inputs) prompt_string = f'{prompt} ({joined_inputs}) ' result = input(prompt_string) while result not in valid_inputs: print('Invalid input, please try again') result = input(prompt_string) return result def play_hand(self): # First, make sure everything is cleared out to play the hand self.reset() # Setup and deal two cards to each player self.player_hand.add_card(self.deck.draw()) self.dealer_hand.add_card(self.deck.draw()) self.player_hand.add_card(self.deck.draw()) self.dealer_hand.add_card(self.deck.draw()) # Print the game state out to the user self.display_game() # Checks for natural 21 if self.player_hand.score() == 21: print('You Win!') return # Start by asking the user if they want to hit or stay user_input = self.ask_user('Choose:', ['hit', 'stay']) # Loop so long as the user is not busted and they have not entered "stay" while user_input != 'stay' and not self.player_hand.is_bust(): # Deal the player another card self.player_hand.add_card(self.deck.draw()) # Print out the game state again self.display_game() # Check if the user is busted and if so, return because the hand is done if self.player_hand.is_bust(): print('Bust! You Lose!') return # Ask the user again if they'd like to hit, which determines if the loop will run again user_input = self.ask_user('Choose:', ['hit', 'stay']) # If the player hasn't busted, dealer plays # From here on out we don't mask the dealer's cards beyond the first self.display_game(dealer_hidden=False) # Dealers hit on 16 and stay on 17, so that's the condition for our loop while self.dealer_hand.score() < 17: print('Dealer hits') # Dealer draws a card self.dealer_hand.add_card(self.deck.draw()) # Print out the game state again self.display_game(dealer_hidden=False) # Check if the dealer has busted and if so, return out of this function if self.dealer_hand.is_bust(): print('Dealer busted! You Win!') return # Neither player has busted, who wins? if self.player_hand.score() > self.dealer_hand.score(): print('You Win!') else: # Dealer wins in case of a tie print('You Lose!') def display_game(self, dealer_hidden=True): """ Print out the game state to the console :param dealer_hidden: If cards in the dealers hand beyond the first should be "face down" :return: None """ print('Your hand:') print(self.player_hand.display()) print(f'Score: {self.player_hand.score()}') print('Dealer\'s hand:') print(self.dealer_hand.display(dealer_hidden)) print() def run(self): """ Main entry point to the game. Plays hands in a loop until the user chooses to exit :return: None """ play_again = None while play_again != 'n': self.play_hand() play_again = self.ask_user('Play again?', ['y', 'n'])
class Game: def __init__(self): pass def play(self): playing = True while playing: self.deck = Deck() self.deck.shuffle() self.player_hand = Hand() self.dealer_hand = Hand(dealer=True) for i in range(2): self.player_hand.add_card(self.deck.deal()) self.dealer_hand.add_card(self.deck.deal()) print("Your hand is: ") self.player_hand.display() print() print("Dealer's hand is: ") self.dealer_hand.display() game_over = False while not game_over: player_has_blackjack, dealer_has_blackjack = self.check_for_blackjack( ) if player_has_blackjack or dealer_has_blackjack: game_over = True self.show_blackjack_results(player_has_blackjack, dealer_has_blackjack) continue choice = input("Please choose to [HIT/STAY]").lower() while choice not in ["h", "s", "hit", "stay"]: choice = input( "Please enter one of the options [HIT/STAY]") if choice in ["hit", "h"]: self.player_hand.add_card(self.deck.deal()) self.player_hand.display() if self.player_is_over(): print("You went over 21, your cards add to: ", self.player_hand.get_value(), ", you lost") game_over = True else: player_hand_value = self.player_hand.get_value() dealer_hand_value = self.dealer_hand.get_value() print("Final results:") print("Your hand's value is: ", player_hand_value) print("Dealer's hand's value is: ", dealer_hand_value) if player_hand_value > dealer_hand_value: print("You won!") elif dealer_hand_value > player_hand_value: print("You lost!") else: print("You tied the dealer and win your money back!") game_over = True again = input("Would you like to play again? [YES/NO]").lower() while again not in ["y", "yes", "n", "no"]: again = input( "Please enter if you would like to play again [YES/NO]") if again in ["no", "n"]: print("Thanks for playing!") playing = False else: game_over = False def check_for_blackjack(self): player = False dealer = False if self.player_hand.get_value() == 21: player = True if self.dealer_hand.get_value() == 21: dealer = True return player, dealer def show_blackjack_results(self, player_has_blackjack, dealer_has_blackjack): if player_has_blackjack and dealer_has_blackjack: print("Both players have blackjack... TIED!") elif player_has_blackjack: print("You got blackjack... YOU WON!") elif dealer_has_blackjack: print("Dealer got blackjack... sorry, you lost :(") def player_is_over(self): return self.player_hand.get_value() > 21
class Game: def __init__(self): # Initialisation des joueurs self.user = User([]) # Appel de la méthode pour créer les joueurs self.user.generate_player() # Appel du nom des joueurs self.players = self.user.players # Initialisation des paris self.bet = Bet(1000) # Initialisation du paquet self.deck = Deck() # Appel de la méthode pour mélanger le paquet self.deck.shuffle() def play(self): # Initialisation de l'état de la partie playing = True # Initialisation du nombre de tour self.tour = 1 # Partie while playing: # Affichage du nombre de tour print( r"""+===================================================================+ """ ) print( "| TOUR", self.tour, ": |", ) print( r"""+===================================================================+ """ ) # Compteur de tour self.tour += 1 # Appel de la méthode pour parier self.bet.drop_bet() # Appel des jetons du joueur après pari self.player_token = self.bet.player_token # Initialisation des mains des joueurs self.player_hand = Hand() # Initialisation de la main du dealer self.dealer_hand = Hand(dealer=True) # 1e carte self.nb_card = 1 # Le croupier distribue une 1e carte aux joueurs self.player_hand.add_card(self.deck.deal()) # Le croupier se distribue une 1e carte self.dealer_hand.add_card(self.deck.deal()) # 2e carte self.nb_card = 2 # Le croupier distribue une 1e carte aux joueurs self.player_hand.add_card(self.deck.deal()) # Affichage de la main du joueur print( r"""+-------------------------------------------------------------------+""" ) print() print("Votre main:\n") self.player_hand.display(self.nb_card) print() print( r"""+-------------------------------------------------------------------+""" ) # Le croupier se distribue une 1e carte self.dealer_hand.add_card(self.deck.deal()) # Affichage de la main du croupier print( r"""+-------------------------------------------------------------------+""" ) print() print("Main de la Banque:\n") self.dealer_hand.display(self.nb_card) print() print( r"""+-------------------------------------------------------------------+""" ) # n carte suivante self.nb_card = 3 game_over = False while not game_over: player_has_blackjack, dealer_has_blackjack = self.check_for_blackjack() if player_has_blackjack: dealer_has_blackjack = False game_over = True self.show_blackjack_results( player_has_blackjack, dealer_has_blackjack ) continue print( r"""+===================================================================+ """ ) choice = input( "\n Que voulez vous faire ? [Piocher / Sauver] " ).lower() print() while choice not in ["p", "s", "piocher", "sauver"]: choice = input( " Entrer 'piocher' ou 'sauver' (ou P/S) " ).lower() if choice in ["piocher", "p"]: print("Votre main:\n") self.player_hand.add_card(self.deck.deal()) self.player_hand.display(self.nb_card) if self.player_is_over(): print( r"""+===================================================================+ """ ) print("\n C'est perdu !") print( "\n Vous perdez", self.bet.table_bet, "jetons...", ) print() print( r"""+===================================================================+ """ ) game_over = True Bet(self.player_token) else: if dealer_has_blackjack: player_has_blackjack = False game_over = True self.show_blackjack_results( player_has_blackjack, dealer_has_blackjack ) continue else: player_hand_value = self.player_hand.get_value() print() print( r"""+-------------------------------------------------------------------+""" ) print("\nMain de la Banque:\n") self.dealer_hand.display(self.nb_card) dealer_hand_value = self.dealer_hand.get_value() print() if dealer_hand_value < 17: while dealer_hand_value < 17: self.dealer_hand.add_card(self.deck.deal()) dealer_hand_value = self.dealer_hand.get_value() print() print( r"""+-------------------------------------------------------------------+""" ) print("\nLe croupier doit retirer une carte\n") print("Main de la Banque:") self.dealer_hand.display(self.nb_card) print() print( r"""+-------------------------------------------------------------------+""" ) print("\n Score final\n") print("Votre main:", player_hand_value) print() print("Main de la banque:", dealer_hand_value) print() if player_hand_value > dealer_hand_value: print("C'est gagné!\n") self.bet.win_gain() elif player_hand_value == dealer_hand_value: print("Égalité... La Banque gagne!\n") print("Vous perdez", self.bet.table_bet, "jetons...") Bet(self.player_token) elif dealer_hand_value > 21: print("C'est gagné!\n") self.bet.win_gain() else: print("La Banque gagne!\n") print("Vous perdez", self.bet.table_bet, "jetons...") Bet(self.player_token) game_over = True again = input("\nContinuer? [O/N] \n") while again.lower() not in ["o", "n"]: again = input("Entrer O ou N ") if again.lower() == "n": print("\nMerci d'avoir joué!\n") playing = False else: game_over = False menu = Menu() menu.main_title() def player_is_over(self): return self.player_hand.get_value() > 21 def check_for_blackjack(self): player = False dealer = False if self.player_hand.get_value() == 21: player = True if self.dealer_hand.get_value() == 21: dealer = True return player, dealer def show_blackjack_results(self, player_has_blackjack, dealer_has_blackjack): if player_has_blackjack: print( r"""+===================================================================+ """ ) print( "| Blackjack !!!!!! Bravo", self.players[0], "!!!!!! |", ) print( r"""+===================================================================+ """ ) self.bet.black_jack_gain() elif dealer_has_blackjack: print( r"""+===================================================================+ """ ) print( "| Blackjack pour la Banque! |" ) print( r"""+===================================================================+ """ )