def play(wallet): deck = Deck() dealer = Dealer() human = Human(wallet) # Deal cards to dealer dealer.hit(deck.getCard()) dealer.hit(deck.getCard()) # Deal cards to human human.hit(deck.getCard()) human.hit(deck.getCard()) # Show cards print('Dealer Hand: ', '[]', dealer.hand[1]) human.showHand() # Check if human has won naturally if human.has21(): return GameResult(True, '21 already, you\'ve won') # Ask Human hit/stick while(input('Hit or stick?')[0].lower() == 'h'): human.hit(deck.getCard()) human.showHand() # Game ends if human has won with 21 if human.has21(): return GameResult(True, '21 already, you\'ve won') # Game ends if human is bust elif human.isBust(): return GameResult(False, 'Tough luck, you are bust') # Reveal dealer hand dealer.showHand() # Game ends if dealer has a higher total than the human if human.getTotal() < dealer.getTotal(): return GameResult(False, 'Sorry dealer has a better hand') # If the dealer has less than 17 he gets more cars while(dealer.getTotal() < 17): dealer.hit(deck.getCard()) dealer.showHand() # Game ends if human is bust if dealer.isBust(): return GameResult(True, 'Dealer went bust, you win') # Game ends if dealer has a higher total than the human elif human.getTotal() < dealer.getTotal(): return GameResult(False, 'Sorry dealer has a better hand') # Game ends and human wins when his total is more than the dealers return GameResult(True, f'Dealer sticks at {dealer.getTotal()}')
class Game(): """docstring for Game"f __init__(self, arg): super(Game,.__init__() self.arg = arg """ def __init__(self): self.player = Player("Player",100) self.dealer = Dealer("CPU-Dealer") self.deck_of_cards = Deck() def playOfTheDealer(): while self.dealer.score() < 17: pass def startTheGame(self): #player needs to bet print("___New Hand___") self.dealer.hit(self.deck_of_cards.playCard()) self.player.hit(self.deck_of_cards.playCard()) self.dealer.hit(self.deck_of_cards.playCard()) self.player.hit(self.deck_of_cards.playCard()) def displayGame(self,dealerReveal=False): print("") print(self.dealer.name + "'s hand: ") if dealerReveal == False: self.dealer.showCard(0) #print("???") Card.displayBlankCard() else: self.dealer.showHand() print(self.dealer.name + " score = " + str(self.dealer.score())) print("-------") print(self.player.name + "'s hand: ") self.player.showHand() print(self.player.name + " score = " + str(self.player.score())) print(self.player.name + " bank = " + str(self.player.bank)) print("") def checkForBlackJack(self): if self.dealer.score() == 21: print(self.dealer.name + " wins") return True if self.player.score() == 21: print(self.player.name + " wins") self.player.bank = self.betAmount*3 return True return False def inputFromThePlayer(self): result = input("j to hit:\nf to hold:\nq to Quit:\n") return result def main(self): playing = True while playing == True: self.dealer.clearHand() self.player.clearHand() try: self.betAmount = float(input("What do you want to bet?: ")) except: print("quitting the game") playing = False break if self.player.bet(self.betAmount) == False: print("GET OUT OF THE CASINO!!") playing = False break self.startTheGame() self.displayGame() playingHand = True while playingHand == True: if self.checkForBlackJack() == True: playingHand = False break result = self.inputFromThePlayer() if result == "q": playing = False playingHand = False if result == "j": self.player.hit(self.deck_of_cards.playCard()) self.displayGame() if self.player.bust() == True: print(self.player.name + " loses!") playingHand = False break if result == "f": #print("dealer's score = " + str(self.dealer.score()) self.displayGame(True) while self.dealer.score() < 17 and self.dealer.bust() == False: self.dealer.hit(self.deck_of_cards.playCard()) self.displayGame(True) if self.dealer.bust() == True: print(self.dealer.name + " loses!") self.player.bank = self.betAmount*2 playingHand = False break if self.dealer.score() > self.player.score(): print(self.player.name + " loses!") playingHand = False break if self.dealer.score() == self.player.score(): print("There is a draw") playingHand = False break if self.dealer.score() < self.player.score(): print(self.player.name + " wins!") self.player.bank = self.betAmount*2 break if self.dealer.score() > self.player.score(): print(self.player.name + " loses!") break
class Table: def __init__(self): self.dealer = Dealer() self.player_list = [] def add_player(self): name = input("Name: ") buy_in = input("Buy-in: ") self.player_list.append(Player(name, int(buy_in))) def remove_player(self, name): for player in self.player_list: if player.name == name: self.player_list.remove(player) def start_hand(self): self.dealer.reset_table() for player in self.dealer.players: player.bet(int(input("{}'s bet: ".format(player.name)))) self.dealer.deal_hand() def hit_loop(self): for player in self.dealer.players: print("{}'s turn.".format(player.name)) player.display_cards() while input("Hit or stand(s): ") != "s": self.dealer.hit(player) if player.card_value > 21: print("{} bust with:".format(player.name)) player.display_cards() break elif player.card_value == 21: print("{} has 21 with: ".format(player.name)) player.display_cards() break player.display_cards() def dealers_turn(self): self.dealer.play_own_hand() if self.dealer.card_value > 21: print("Dealer busts with {}.".format(self.dealer.display_cards())) for player in self.dealer.players: if player.card_value <= 21: self.dealer.winners.append(player) elif self.dealer.card_value <= 21: for player in self.dealer.players: if player.card_value == self.dealer.card_value: print("{} tied with dealer. ${} returned.".format( player.name, player.money_bet)) player.money += player.money_bet elif 21 >= player.card_value > self.dealer.card_value: print("{} beats the dealer. Won ${}.".format( player.name, player.money_bet * 2)) self.dealer.winners.append(player) elif player.card_value < self.dealer.card_value <= 21: print("{} lost ${}.".format(player.name, player.money_bet)) print("Dealers cards are:") self.dealer.display_cards() self.dealer.pay_winners()
class Game(object): def __init__(self): self.name = 'Blackjack' self.dealer = Dealer('Dealer', 0) self.players = None self.shoe = None def start_game(self, players, deck_size=1): self.players = [Player(player) for player in players] self.shoe = Shoe(deck_size) def quit_game(self): pass def place_bet(self, player, bet): """ only accepts 0 < valid bets <= player.score will make player inactive if bet of 0 is placed :param player: current player :param bet: integer :return: """ # bet only called on first hand of player player.bet = int(bet) if player.bet == 0: player.is_active = False return True elif player.bet == -1: return False else: return True def deal_cards(self, dealer_face=True): """ will deal out 1 card to every player and dealer (default face up) """ if len(self.players): # dont deal cards if no players left to play for player in self.players: # can only be one hand to start per player player.hit(player.hands[0], self.shoe.draw()) # deal card to dealer self.dealer.hit(self.dealer.hands[0], self.shoe.draw(dealer_face)) else: print "GAME: no players left to deal to should exit out of game here" def remove_players(self): # remove players from game since is_active is set to false: bet of 0, 0 points left new_players = [] for p in self.players: if p.is_active: new_players.append(p) else: print "GAME: removed {0}".format(p.name) self.players = new_players @staticmethod def insurance(player, taken=False): """ insurance is only offered to players if the dealer has an Ace showing on the initial deal :param player: individual player :param taken: True only if the player decided to take insurance """ pass def hit(self, player, hand=0): """ hitting happens on a per hand basis :param player: player object :param hand: hand index :return: returns False if the hit caused the player to bust """ # cur_player = self.players[player] # change from index to object cur_player = player cur_hand = cur_player.hands[hand] # TODO maybe make dealer deal instead of draw from shoe directly? bust = cur_player.hit(cur_hand, self.shoe.draw(True)) # print "{0} now added to {1}'s hand ".format(cur_player.hand[hand].list[-1], cur_player.name ) return bust, cur_hand ''' this should only be a view method @staticmethod def stand(player, hand): msg = player.name + " stands with a score of " + str(hand.score) return msg ''' @staticmethod def show_card(player, hand=0): """ first card in deck is usualy not shown, this will show it :param player: player to flip card :param hand: hand to flip card :return: last card """ for card in player.hands[hand].cards: card.visibility = True ''' use again when insurance feature added def check_dealer_card_ace(self): # return True if 2nd card is an ace # needed to check for insurance if self.dealer.hands[0].cards[1].rank == 'A': return True else: return False ''' def check_winner(self): # if dealer busts if self.dealer.hands[0].is_bust: # check players for bust for p in self.players: for h in p.hands: if not h.is_bust: h.status = "win" else: for p in self.players: self.compare(p, self.dealer) @staticmethod def collect_winnings(player): for h in player.hands: if h.status == "win": player.points = player.bet * 2 elif h.status == "tie": player.points = player.bet else: if not player.points: player.is_active = False def clear_hands(self): # reset all hands of players for start of new game for p in self.players: p.clear_hands() self.dealer.clear_hands() @staticmethod def compare(player, dealer): dealer_score = dealer.hands[0].score # compare score to player #print "dealer: {0}, {1}: {2}".format(dealer_score, player.name, player.hand[0].score) for h in player.hands: if not h.is_bust: if h.score > dealer_score: h.status = "wins" player.points += (player.bet * 2) dealer.hands[0].status = "loses" elif h.score == dealer_score and not dealer.hands[0].is_bust: h.status = "ties" player.points += player.bet dealer.hands[0].status = "ties" else: h.status = "loses" dealer.hands[0].status = "wins"
class Game: # Game class has attributes: def __init__(self, num_players, num_decks, blackjack): self.blackjack = blackjack #Pay outs for getting blackjack vary by the casino, default is 2 some do 1.2 self.num_players = num_players self.deck = Deck(num_decks) self.players = [] self.dealer = Dealer() self.shoeSize = len(self.deck.cardList) #a shoe is what casinos call the card dispenser self.num_decks = num_decks def setup(self): for i in range(self.num_players): self.players.append(Player(input("Enter player name:"), 1000.00)) #Bet phase def betPhase(self): print("\n=======Bet Phase=======") for p in self.players: print(p.name, 'Balance:', p.balance) print("-----------------------") for p in self.players: p.bet = float(input(p.name + ' bet:')) print("=======================") #Draw phase def drawPhase(self): print("\n\n=======Draw Phase======") self.dealer.hit(self.deck) print("-----------------------") print("Dealer's Hand:") print("-----------------------") self.dealer.printHand() input() for p in self.players: p.hit(self.deck) p.hit(self.deck) print("\n-----------------------") print(p.name, "'s Hand:") print("-----------------------") p.printHand() input() print("=======================") #Play phase def playerPlayPhase(self): print("\n\n======Play Phase=======") for p in self.players: split = False if p.hand[0].value == p.hand[1].value: split = True if p.getHandValue( ) != 'Blackjack': #players don't play if they get blackjack, they just win, unless dealer gets blackjack too in_play = True #can player still make moves first = True #is this the players first move while in_play: print("\n-----------------------") print(p.name, "'s hand:") print("-----------------------") p.printHand() print("+++++++++++++++++++++++") print(p.name, "'s Move:\n'hit'\n'stand'") if split and not ( p.split): #can the players cards be split print("'split'") if first: print("'double'\n'surrender'") play = input("Enter a move:") if (play == 'stand' ): #players turns are over when they stand in_play = False elif ( play == 'hit' ): #player choosed to add cards, check if they busted (>21) or reached 21, can no longer play if they did first = False p.hit(self.deck) v = p.getHandValue() if v == 'Bust' or v == 21: p.printHand() in_play = False input() elif ( play == 'double' and first ): #player can double their bet on their first move and get delt one card, then their turn is over, no more hitting, you get one 1 card only p.bet = p.bet * 2 p.hit(self.deck) print("\n-----------------------") print(p.name, "'s hand:") print("-----------------------") p.printHand() in_play = False input() elif ( play == 'surrender' and first ): #player can get half their bet back if they don't like their odds, their turns are over after this, like cutting your loses. p.balance -= p.bet / 2 p.bet = 0 in_play = False print( "\nHalf your bet is returned, your bet is now zero." ) elif ( play == 'split' and split and not (p.split) ): #if split is true (determined on ln 38 of Game.py) both cards have same value, can turn them into two hands. p.split = True #player attribute set to true to indicate player is playing two hands. p.splitHand.append(p.hand.pop()) # pop a card from first hand to the second p.splitBet = p.bet # second hand has an additional and equal bet to the first bet # else: print(p.name, 'hand:') p.printHand() for p in self.players: #if any player is has a split hand we play it out here with the same rules as before but with no further splitting if p.split: in_play = True first = True while in_play: print("\n-----------------------") print(p.name, "'s second hand:") print("-----------------------") p.printSplitHand() print("+++++++++++++++++++++++") print(p.name, "'s Move:\n'hit'\n'stand'") if first: print("'double'\n'surrender'") play = input("Enter a move:") if (play == 'stand'): in_play = False elif (play == 'hit'): first = False p.hitSplit(self.deck) v = p.getSplitHandValue() if v == 'Bust' or v == 21: print("\n-----------------------") print(p.name, "'s second hand:") print("-----------------------") p.printSplitHand() print("+++++++++++++++++++++++") in_play = False elif (play == 'double' and first): p.splitBet = p.splitBet * 2 p.hitSplit(self.deck) p.printSplitHand() in_play = False elif (play == 'surrender' and first): p.balance -= p.splitBet / 2 p.splitBet = 0 in_play = False print("=======================") #Dealer play phase def dealerPlayPhase(self): print("\n\n===Dealer Play Phase===") in_play = self.dealer.playoutTick(self.deck) #dealer always takes 1 turn, function returns true if the rules say they need to take more while ( in_play ): #keep playing untill the rules say the dealer stops, dealer has higher than 16 and it's not soft 17 or they busted out. in_play = self.dealer.playoutTick(self.deck) print("-----------------------") print('Dealer Hand:') print("-----------------------") self.dealer.printHand() print("=======================") input() #Payout phase def payoutPhase(self): print("\n\n======Payout Phase=======") dValue, soft = self.dealer.getHandValue() self.dealer.discardHand() #gets value of dealers hand for p in self.players: print("\n-----------------------") print(p.name, "'s hand:") print("-----------------------") p.printHand() if p.split: print("\n-----------------------") print(p.name, "'s second hand:") print("-----------------------") p.printSplitHand() for p in self.players: print("\n-----------------------") pValue = p.getHandValue() #for each player get the value of their hand p.discardHand() if pValue == 'Bust': #if player busts player loses, subtract bet from player balance p.balance -= p.bet print(p.name, 'Loses.') elif pValue == 'Blackjack' and dValue != 'Blackjack': #player got blackjack dealer did not, add bet * blackjack bonus value to player balance p.balance += p.bet * self.blackjack print(p.name, 'Wins by BlackJack.') elif dValue == 'Bust': #if dealer bust and player did not, player wins, add bet to player balance p.balance += p.bet print(p.name, 'Wins.') elif dValue == 'Blackjack' and pValue != 'Blackjack': #dealer got blackjack player didn't, normal player lose, subtract bet from balance p.balance -= p.bet print(p.name, 'Loses.') elif pValue == dValue: #player and dealer tie, player loses nothing print(p.name, 'Pushs.') elif pValue > dValue: #player wins by having higher value than dealer, add bet to balance p.balance += p.bet print(p.name, 'Wins.') else: #process of elimination, the dealer has the higher value, player lost, subtract bet from balance p.balance -= p.bet print(p.name, 'Loses.') print("-----------------------") for p in self.players: #same thing again for split hands if p.split: p.split = False pValue = p.getSplitHandValue() p.discardSplitHand() if pValue == 'Bust': p.balance -= p.splitBet print(p.name, 'Second Loses.') elif dValue == 'Bust': #dealer bust p.balance += p.splitBet print(p.name, 'Second Wins.') elif pValue == 'Blackjack' and dValue != 'Blackjack': #player bj dealer no bj p.balance += p.splitBet * self.blackjack print(p.name, 'Second BlackJacks.') elif dValue == 'Blackjack' and pValue != 'Blackjack': p.balance -= p.splitBet print(p.name, 'Second Loses.') elif pValue == dValue: print(p.name, 'Second Pushs.') elif pValue > dValue: p.balance += p.splitBet print(p.name, 'Second Wins.') else: p.balance -= p.splitBet print(p.name, 'Second Loses.') print("-----------------------") def replay( self ): #replay all phases of game. skip setup. if 2/3rds of deck has been played, refresh deck if len( self.deck.cardList ) < self.shoeSize / 3: #actually don't know if this is a rule but deck is never suposed to run out of cards del self.deck self.deck = Deck(self.num_decks) print('Refreshing Deck') self.betPhase() self.drawPhase() self.playerPlayPhase() self.dealerPlayPhase() self.payoutPhase()
stand = False busted = False # Action round while not stand: print "\nYour hand:" user.print_hand() if user.bust(): print "Busted!" busted = True break action = raw_input("Hit (H) or Stand (S): ").lower() if action == "h": dealer.hit(user) elif action == "s": stand = True if busted: continue # Dealer cards print "-----" print "Dealer's cards:" dealer.print_hand() while dealer.hand.value < 17: time.sleep(2) print "\nDealer hits:" dealer.hit(dealer)