def test_get_complex_hand_values(self): hand = [Card(0),Card(1),Card(2),Card(13)] dealer = Dealer(None,None) values = dealer.getHandValues(hand) self.assertIn(7,values) self.assertIn(17,values) self.assertIn(27,values)
def test_dealer_not_bust(self,mock_bust): mock_bust.return_value = Card(1) # return a 2 hand = [Card(0),Card(1)] dealer = Dealer(None,None) dealer.dealersHand = hand result = dealer.dealerDraw() self.assertEqual(result,17)
def test_dealer_bust(self,mock_bust): mock_bust.return_value = Card(12) # return a King hand = [Card(1),Card(2),Card(13)] dealer = Dealer(None,None) dealer.dealersHand = hand result = dealer.dealerDraw() self.assertEqual(result,0)
def test_dealer_is_busted(self): dealer = Dealer(None,None) hand = [Card(12),Card(12)] # 2 kings dealer.playersHand = hand hand = [Card(12),Card(12),Card(12)] # 3 kings dealer.dealersHand = hand self.assertEqual(dealer.getHandResult(),'win')
def test_player_loses(self): dealer = Dealer(None,None) hand = [Card(12),Card(3)] # 1 king, 4 dealer.playersHand = hand hand = [Card(12),Card(12)] # 2 kings dealer.dealersHand = hand self.assertEqual(dealer.getHandResult(),'lose')
def test_player_wins_with_blackjack(self): dealer = Dealer(None,None) hand = [Card(12),Card(0)] # 1 king, one ace dealer.playersHand = hand hand = [Card(12),Card(3)] # 1 king, 4 dealer.dealersHand = hand self.assertEqual(dealer.getHandResult(),'win')
class VideoPoker(object): def __init__(self, player=None, dealer=None, hand_evaluator=None, hand_list=None): self.player = Player() self.dealer = Dealer() self.hand_evaluator = HandEvaluator() def deal_player_hand(self): for k in range (5): self.player.add_card(self.dealer.deal_card()) def deal_player_card(self): # print "hand before deal_player_card" # self.hand.print_hand() self.player.add_card(self.dealer.deal_card()) def deal_player_indexed_card(self, index): self.player.add_card(self.dealer.deal_indexed_card(index)) def deal_player_indexed_card_from_strategy(self, index): self.player.add_card(self.dealer.deck.pop(index)) def player_submit_play(self): self.discard_pile = self.player.submit_play() def player_add_discard_pile(self): discard_pile_length = len(self.discard_pile) for k in range(discard_pile_length): self.player.add_card(self.discard_pile.pop(0)) def return_card_to_deck(self, index): # print k # self.hand.print_hand() self.player.hand.insert(index, Card(-1, -1)) self.dealer.deck.append(self.player.hand.pop(index+1)) def insert_card_to_deck(self, hand_index, deck_index): self.player.hand.insert(hand_index, Card(-1, -1)) self.dealer.deck.insert(deck_index, self.player.hand.pop(hand_index+1)) def return_hand_to_deck(self): for k in range(5): self.return_card_to_deck(k) def return_hand_to_deck_indexed(self, ls): ls.sort() for k in range(5): self.insert_card_to_deck(k, ls[k]) def populate(self, ls): for k in range(5): self.deal_player_indexed_card(ls[k]) self.hand_list = ls ls.sort(reverse=True) for k in range(5): self.dealer.deck.pop(ls[k])
def __init__(self, num_players=1, num_decks=6): self.num_decks = num_decks self.dealer = Dealer() self.bot = Bot('Bot') self.players = [] self.busted = [] self.stand = [] self.move = 0 self.dealer_done = False self.bot_moves = [] for i in xrange(0,num_players): self.players.append(Player('Player'+str(i+1))) self.players.append(self.bot) self.deck = Deck(num_decks) self.bot_deck = self.deck.deck * 1 for player in self.players: player.make_bet() if player.name == 'Bot': player.add(self.bot_deck.pop()) player.add(self.bot_deck.pop()) self.bot_deck.pop() self.bot_deck.pop() else: player.add(self.deck.draw()) player.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.rules = RulesEngine(self.dealer, self.players)
def setup_new_game(self): self.log("Setting up new game") self.dealer = Dealer(self, self.cd_kick) self.dealer.regEvt("won", self.pl_won) self.dealer.regEvt("kick", self.pl_kicked) self.status = 0 self.count_time = 0 self.playing_list = [] for c in self.clients: c.playerId = 0 self.check_countdown()
def game_update(self, gid=1): print ("\n--------------------------------GAME ID: %i-------------------------------" %(gid)) for player in self.players: while player.want_more_card(self.dealer.highest_player_card_value, self.safe_odd(player)) is True: new_card = self.dealer.draw_next_card() player.cards.append(new_card) print player.name + " draw new card " + Dealer.get_card_face(new_card) self.dealer.check_player(player) print "-------------------" self.dealer.check_self(self.players) # NOW: dealer move return self.accounting()
def main(): circ = QuantumCircuit(5, 5) q = QuantumRegister(5, 'q') c = ClassicalRegister(5, 'c') game = Dealer(circ) player = Player() while not player.broke(): if player.rounds > 0: circ = QuantumCircuit(5, 5) game.reset(circ) state_position = [] state_string = ["0", "0", "0", "0", "0"] state_position.append(random.randint(0, 4)) state_position.append(random.randint(0, 4)) state_string[state_position[0]] = "1" state_string[state_position[1]] = "1" circ.x(q[state_position[0]]) if state_position[0] != state_position[1]: circ.x(q[state_position[1]]) print("Your starting state is:") print("|" + ''.join(state_string[::-1]) + ">") while not game.finished(): state_string[game.current_qubit] = mark_qubit( state_string, game.current_qubit) print("--" * 30) print("Total Points: %d" % player.points) print("Round: %d/5" % (game.current_qubit + 1)) print("Cash: $%d" % player.wallet) print("Current status of qubits:") print("|" + ' '.join(state_string[::-1]) + ">") choice = input("'0': Hit($5) '1': Stand($10)?") while choice not in ["0", "1"]: choice = input("Please input '0'(Hit) or '1'(Stand)") if (player.wallet < 10 and choice == "1") or (player.wallet < 5): print( "insufficient funds... proceeding with draw (this is on the house!)" ) choice = "0" new_gate = game.action(int(choice), player) state_string[game.current_qubit - 1] = new_gate + state_string[game.current_qubit - 1][1] if new_gate == "C": state_string[game.current_qubit - 2] = "N" + state_string[game.current_qubit - 2] new_gate = "CNOT" print("You drew %s!" % new_gate) print("--" * 30) print("Your final state is:") time.sleep(1) print("|" + ' '.join(state_string[::-1]) + ">") print("Time for measurement!") time.sleep(1) final_string = game.evaluate() method, points = score(final_string) player.win(points) print("The result:") print("|" + ''.join(final_string[::+1]) + ">") print("You won %d points by means of %s" % (points, method)) if not player.broke(): print("Prepare for the next game!") time.sleep(1) print("\n" * 5) print("You finished %d rounds with %d points!" % (player.rounds, player.points)) print("Your points/$ was %3f" % (player.points / 100))
class Game(object): """ A sequence of Blackjack Rounds that keeps track of total money won or lost """ def __init__(self, strategy=None): self.shoe = Shoe(SHOE_SIZE) self.money = 0.0 self.bet = 1.0 self.stake = 1.0 self.player = Player(strategy=strategy) self.dealer = Dealer() def get_status(self, hand): if not hand.surrender: if hand.busted(): status = "LOST" else: if hand.blackjack(): if self.dealer.hand.blackjack(): status = "PUSH" else: status = "WON 3:2" elif self.dealer.hand.busted(): status = "WON" elif self.dealer.hand.value < hand.value: status = "WON" elif self.dealer.hand.value > hand.value: status = "LOST" elif self.dealer.hand.value == hand.value: if self.dealer.hand.blackjack(): status = "LOST" # player's 21 vs dealers blackjack else: status = "PUSH" else: status = "SURRENDER" return status def get_hand_winnings(self, hand): win = 0.0 bet = self.stake status = self.get_status(hand) if status == "LOST": win += -1 elif status == "WON": win += 1 elif status == "WON 3:2": win += 1.5 elif status == "SURRENDER": win += -0.5 if hand.doubled: win *= 2 bet *= 2 win *= self.stake return win, bet, status def play_round(self): self.stake = 1.0 player_hand = Hand([self.shoe.deal(), self.shoe.deal()]) dealer_hand = Hand([self.shoe.deal()]) self.player.set_hands(player_hand, dealer_hand) self.dealer.set_hand(dealer_hand) print "Dealer Hand: %s" % self.dealer.hand print "Player Hand: %s\n" % self.player.hands[0] self.player.play(self.shoe) self.dealer.play(self.shoe) for hand in self.player.hands: win, bet, flag = self.get_hand_winnings(hand) self.money += win self.bet += bet self.player.strategy.record_result(hand, self.player, win) # print "Player Hand: %s %s (Value: %d, Busted: %r, BlackJack: %r, Splithand: %r, Soft: %r, Surrender: %r, Doubled: %r)" % (hand, status, hand.value, hand.busted(), hand.blackjack(), hand.splithand, hand.soft(), hand.surrender, hand.doubled) # print "Dealer Hand: %s (%d)" % (self.dealer.hand, self.dealer.hand.value) print self.player.strategy.qlearner.print_q() def get_money(self): return self.money def get_bet(self): return self.bet
def test_sum_hand(self): player = Player([Cards("♥", "K"), Cards("♠", "10")], False, 100, 0, True) dealer = Dealer([Cards("♦", "7"), Cards("♣", "10")], False, False, False, False) self.assertEqual(player.checkSum(), 20, "Player hand should be = 20"), self.assertEqual(dealer.checkSum(), 17, "Dealer hand should be = 17"),
def __init__(self): self.shoe = Shoe(DECKS_IN_SHOE) self.players = [] self.dealer = Dealer()
show_all(dealer) return False # # # # START OF THE GAME # # # # # CREATES PLAYER AND DEALER player = Player() dealer = Dealer() playing = True print("WELCOME TO BLACK JACK 21") print(f'The inicial amount of chips is: {player.chips.total}') while True: # Print an opening statement print("NEW MATCH!\n\n") # Create & shuffle the deck, deal two cards to each player deck = Deck() deck.shuffle()
def test_hand_is_busted(self): hand = [Card(12),Card(12),Card(12)] # 3 kings dealer = Dealer(None,None) result = dealer.getMaxHandValue(hand) self.assertEqual(result,0)
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()
def main(): player = Player() dealer = Dealer() print "Hello! Welcome to Blackjack!" print "The table minimum is " + str(table_min) + " and table maximum is " + str(table_max) """Initialize variables""" hand_counter = 1 while True: try: player.set_current_bal(decimal.Decimal(raw_input("How much would you like to start with? \n"))) break except decimal.InvalidOperation: print "\nPlease type in a valid number.\n" while True: """Check if the player can play first.""" if not player.get_current_bal() >= table_min: print "Sorry! You do not have enough money. Thank you for playing. " print "Your current balance is $" + str(player.get_current_bal()) break """Get command (Check Balance, Leave Table, Next hand)""" print "\nCommands:" command = raw_input("Current balance is $" + str( player.get_current_bal()) + " x = Exit Enter in bet amount:\n(Or Enter to keep the previous bet.)\n") while command != 'x' or command != 'X': if command == '': if player.get_current_bet() < table_min: print "You have not put in an initial bet. " \ "Please bet above the table minimum: $" + str(table_min) + "\n" elif player.get_current_bet() > player.get_current_bal() or \ not table_min <= player.get_current_bet() <= table_max: player.set_current_bet(0) print "Please reenter your bet below your balance and within the table range: " \ "$" + str(table_min) + "-$" + str(table_max) + "\n" else: break elif command == 'x' or command == 'X': break else: try: if table_min <= decimal.Decimal(command) <= player.get_current_bal() and decimal.Decimal(command) <= table_max: player.set_current_bet(decimal.Decimal(command)) break else: print "Please bet below your balance and within the table range: " \ "$" + str(table_min) + "-$" + str(table_max) + "\n" except decimal.InvalidOperation: print "\nPlease type in a valid command or " +\ "number above the table minimum ($" + str(table_min) + ")\n" command = raw_input("Current balance is $" + str( player.get_current_bal()) + " x = Exit Enter in bet amount:\n" "(Or Enter to keep the previous bet.)\n") if command == 'x': # Exit the game break # I know there is a better way to do this but this works. """Deal Hands""" print "\nHand " + str(hand_counter) player.set_hand([Card(0, 10), Card(0, 10)]) dealer.set_hand(dealer.deal_hand()) dealer.show_hand(dealer.get_hand(), [player.get_hand()], False) dealer, player, continue_game = dealer.insurance(dealer, player) if continue_game: """play""" dealer, player, bust = player.play(dealer, player, True) if not bust: player.set_current_bal_difference(-player.get_current_bet()) print "Dealer wins." else: if len(player.get_hands()) == 1: if len(player.get_hand()) == 2 and Dealer.value_hand(player.get_hand()) == 21: player.set_current_bal_difference(decimal.Decimal(1.5) * player.get_current_bet()) print "Winner Winner Chicken Dinner! Blackjack! You win!" else: dealer, player = dealer.dealer_play(dealer, player) dealer_hand = Dealer.value_hand(dealer.get_hand()) player_hand = Dealer.value_hand(player.get_hand()) if player_hand > dealer_hand or dealer_hand > 21: player.set_current_bal_difference(player.get_current_bet()) print "You win!" elif player_hand == dealer_hand: print "Push! Tie" else: player.set_current_bal_difference(-player.get_current_bet()) print "Dealer wins." else: dealer, player = dealer.dealer_play(dealer, player) dealer_hand = Dealer.value_hand(dealer.get_hand()) split_hand = 1 for hand in player.get_hands(): player_hand = Dealer.value_hand(hand) if player_hand > 21: print "Hand " + str(split_hand) + " busts!" elif player_hand > dealer_hand or dealer_hand > 21: player.set_current_bal_difference(player.get_current_bet()) print "Hand " + str(split_hand) + " wins!" elif player_hand == dealer_hand: print "Hand " + str(split_hand) + " pushes! Tie" else: player.set_current_bal_difference(-player.get_current_bet()) print "Hand " + str(split_hand) + " Dealer wins" split_hand += 1 else: dealer.show_hand(dealer.get_hand(), player.get_hand(), True) if Dealer.value_hand(dealer.get_hand()) == 21 and Dealer.value_hand(player.get_hand()) == 21: print "Push! Tie" elif Dealer.value_hand(dealer.get_hand()) == 21: print "Dealer Wins. Dealer Hand Value: 21" else: print "Dealer Wins! ~ But not exactly sure why" hand_counter += 1
return player.show(), dealer.show() def show_all(player, dealer): print(f'Player has {player.adjust_for_ace()}') print(f'Dealer has {dealer.adjust_for_ace()}') return player.adjust_for_ace(), dealer.adjust_for_ace() if __name__ == '__main__': chip = '' while not chip.isdigit(): chip = input('How many chips do you have? ') chips = Chips(int(chip)) player = Player() dealer = Dealer() player.chips = 200 while True: print(f'Your total Chips is {chips.total}') deck = Deck() deck.shuffle() player.cards = [] dealer.cards = [] player.value = 0 dealer.value = 0 bet = 0 bet += take_bet(chips.total - bet) player.add_card(deck.deal()) dealer.add_card(deck.deal()) player.add_card(deck.deal()) dealer.add_card(deck.deal())
@counting.setter def counting(self, new_counting): self._counting = new_counting @property def play_status(self): return self._play_status @play_status.setter def play_status(self, new_play_status): self._play_status = new_play_status if __name__ == "__main__": p = BasicPlayer() d = Dealer() # p.deal() # print(p.hand) # print(d.deal()) # # while p.make_decision(d.hand[0]): # print(p.hand) # # print("p hand", p.hand) # d.open_second_card() # # while d.make_decision(): # print(d.hand) # # print("d hand", d.hand)
def __init__(self, player=None, dealer=None, hand_evaluator=None, hand_list=None): self.player = Player() self.dealer = Dealer() self.hand_evaluator = HandEvaluator()
def playGame(): # The deck array represents the cards used for the game. deck = [1, 13] * 4 print("\n---------------------") print("Blackjack!") print("---------------------\n") # Initialize Dealer and VisitingTourist Objects, then shuffle the deck. dealer = Dealer() visitingTourist = VisitingTourist() dealer.deckShuffle(deck) checkMethods = CheckMethods() # The Dealer and the VisitingTourist both get their cards, and then their total scores are calculated. The User is notified of their cards, score, # and the Dealer's face up card. dealer._getCards(dealer._playerHand, deck) visitingTourist._getCards(visitingTourist._playerHand, deck) dealer._calculateScore(dealer._playerHand) visitingTourist._calculateScore(visitingTourist._playerHand) print("Your Hand is " + str(visitingTourist._playerHand) + " for a total of " + str(visitingTourist._playerScore) + ".\n") print("The Dealer is showing a " + str(dealer._playerHand[1]) + ".\n") # The program checks if the VisitingTourist or Dealer has a Blackjack with their original cards. If not, the game continues. check = checkMethods.blackjackCheck(visitingTourist._playerScore, dealer._playerScore) while (check == 0): # The program asks the User what they would like to do with their first hand after splitting. This message is only activated after splitting. if (visitingTourist.splitCount == 1): userInput = input( "Would you like to [h]it, [sp]lit, or [s]tand with your " + str(visitingTourist.firstHand) + "?\n") # The program asks the User what they would like to do with their second hand after splitting. This message is only activated after splitting # and finishing the firstHand. elif (visitingTourist.splitCount == 2): userInput = input( "Would you like to [h]it, [sp]lit, or [s]tand with your " + str(visitingTourist.secondHand) + "?\n") # The program asks the User what they would like to do with their hand. else: userInput = input( "Would you like to [h]it, [sp]lit, or [s]tand?\n") # If the User chooses to hit their hand, call the hit method. if userInput == 'h': # Set the original hand to the current hand. currentHand = visitingTourist._playerHand # If the User chose to split, set firstHand as the current hand. if (visitingTourist.splitCount == 1): currentHand = visitingTourist.firstHand # If the User chose to split, set secondHand as the current hand. if (visitingTourist.splitCount == 2): currentHand = visitingTourist.secondHand # Call hit method on current User hand and calculate/display score. Send User a bust message if their score after hitting exceeds 21. visitingTourist._hit(currentHand, deck) userScore = visitingTourist._calculateScore(currentHand) if (checkMethods.bustCheck(visitingTourist, userScore) == 1): break # If the User chooses to stand with their hand, call the stand method. Call the splitStand method if the User chose to split their original hand. elif userInput == 's': # If standing with the User's firstHand, flag and move onto secondHand in while loop. if (visitingTourist.splitCount == 1): # Flag that firstHand is done, splitCount now equals 2. visitingTourist.splitCount += 1 continue # If standing with the User's secondHand, Dealer does their turn. After Dealer turn, display messages to player about final results. if (visitingTourist.splitCount == 2): # Allow Dealer to do their turn, then store their final score. dealerScore = dealer.dealerTurn(dealer._playerHand, deck) # Send scores of VisitingTourist's hands and Dealer hand into splitStand. Send User to playGame menu. visitingTourist.splitStand( visitingTourist._calculateScore(visitingTourist.firstHand), visitingTourist._calculateScore( visitingTourist.secondHand), dealerScore) break # If User did not split, allow Dealer to have turn and then send scores to stand method. Send User to playGame menu. if (visitingTourist.splitCount == 0): userScore = visitingTourist._calculateScore( visitingTourist._playerHand) dealerScore = dealer.dealerTurn(dealer._playerHand, deck) checkMethods.stand( visitingTourist._calculateScore( visitingTourist._playerHand), dealer._calculateScore(dealer._playerHand)) break # If User chooses to split with their hand, call the split method. elif userInput == 'sp': # If the cards in the User's hand do not match, they are not allowed to split. if (visitingTourist._playerHand[0] != visitingTourist._playerHand[1]): print("You cannot split with two cards that don't match!\n") # If the User has already chosen to split, they cannot split again. elif (visitingTourist.splitCount == 1): print("You cannot split more than once!\n") # Send current hand to split method. Flag that split has occured then display cards and scores of two new hands. else: firstHand, secondHand = visitingTourist.split( visitingTourist._playerHand, deck) visitingTourist.splitCount += 1 print("Your First Hand is " + str(firstHand) + " for a total of " + str(visitingTourist._calculateScore(firstHand)) + ".\n") print("Your Second Hand is " + str(secondHand) + " for a total of " + str(visitingTourist._calculateScore(secondHand)) + ".\n") # If User input is not recognized, send message to try again. else: print("Previous command not recognized, try again!") # Current game has ended, ask User if they would like to play again. userInput = input("Would you like to play again, [y]es or [n]o?\n") if userInput == 'y': playGame() else: exit()
class Game(object): def __init__(self): self.shoe = Shoe(DECKS_IN_SHOE) self.players = [] self.dealer = Dealer() def init_game(self): print(''' .------. |A_ _ | Welcome to Ben's Blackjack Game |( \/ ).-----. | \ /|J /\ | Please follow the prompts below | \/ | / \ | `-----| \ / | | \/ J| `------' ''') self.init_players() def init_players(self): player_count = get_non_negative_int_lt( "How many players will be playing: ", 6) for i in range(1, int(player_count) + 1): name = input("Player %d name: " % i) self.players.append(Player(name)) print('\n', end='') def play(self): while True: self.play_round() def play_round(self): self.take_bets() self.display_dealer() for player in self.players: print(f"\nIt is now {player.name}'s turn") self.play_hand(player) self.dealer.play(self.shoe) self.display_dealer() self.resolve_bets() self.display_money() self.kick_players() def take_bets(self): for player in self.players: bet_amount = get_non_negative_int_lt( f"How much would {player.name} like to bet? [Minimum: ${MINIMUM_BET}, Balance: {player.money}]: $", player.money, "You can not bet that amount!") if bet_amount < MINIMUM_BET: bet_amount = MINIMUM_BET player.money -= bet_amount player.set_hand( Hand([self.shoe.deal(), self.shoe.deal()], bet_amount)) self.dealer.set_hand(Hand([self.shoe.deal(), self.shoe.deal()])) print('\n', end='') def display_dealer(self): print("Dealer's Hand:", self.dealer.hand) def play_hand(self, player): for i, hand in enumerate(player.hands): while not hand.busted() and not hand.stayed: print(f"\t{player.name}'s hand {i+1}\n\t", hand) choice = self.handle_hand_options(player, hand) if choice == 'Hit': print(f"\t{player.name} chose to Hit!") player.hit(hand, self.shoe) elif choice == 'Stay': print(f"\t{player.name} chose to Stay!") player.stay(hand) elif choice == "Double Down": print(f"\t{player.name} chose to Double Down!") player.double_down(hand, self.shoe) elif choice == "Split": print(f"\t{player.name} chose to Split!") player.split(hand) if hand.busted(): print(f"\t{player.name}'s final hand {i+1} went bust\n\t", hand) else: print(f"\t{player.name}'s final hand {i+1}\n\t", hand) print('\n', end='') def handle_hand_options(self, player, hand): option_number = 1 valid_options = [] print('\tType the corresponding number:') print(f"\t\t[{option_number}] 'Stay'") valid_options.append('Stay') option_number += 1 if hand.value < 21: print(f"\t\t[{option_number}] 'Hit'") valid_options.append('Hit') option_number += 1 if hand.length( ) == 2 and hand.value != 21 and player.money > hand.bet and not hand.split_hand: print(f"\t\t[{option_number}] 'Double Down'") valid_options.append('Double Down') option_number += 1 if hand.splitable() and len([ h for h in player.hands if h.split_hand ]) <= SPLIT_LIMIT and player.money > hand.bet: print(f"\t\t[{option_number}] 'Split'") valid_options.append('Split') option_number += 1 choice = get_non_negative_int_lt('\tChoice: ', max_val=option_number - 1, err="That is an invalid choice") print('\n', end='') return valid_options[choice - 1] def display_money(self): for player in self.players: print(f"{player.name} has ${player.money}") print("\n", end='') def resolve_bets(self): print(f"\tBetting Results:") dealer_value = self.dealer.hand.value dealer_blackjack = self.dealer.hand.blackjack() for player in self.players: for hand in player.hands: if not hand.busted() and hand.value > dealer_value: player.money += hand.bet * WIN_MULTIPLIER print(f"\t{player.name} won ${hand.bet * WIN_MULTIPLIER}") elif not hand.busted( ) and hand.value == dealer_value and not dealer_blackjack: player.money += hand.bet print(f"\t{player.name} pushed") else: print(f"\t{player.name} lost his bet of ${hand.bet}") print('\n', end='') def kick_players(self): for player in self.players: if player.money == 0: self.players.remove(player) print(f"{player.name} has been eliminated") print("\n", end='')
def __init__(self): self.name = 'Blackjack' self.dealer = Dealer('Dealer', 0) self.players = None self.shoe = None
def test_get_next_card(self): dealer = Dealer(None,None) predictedCard = dealer.getNextCardCheat() nextCard = dealer.dealCard() self.assertEqual(predictedCard.getIndex(),nextCard.getIndex())
def __init__(self, number_of_decks, number_of_players, name_of_players): self.dealer = Dealer() self.players = [Player(name) for name in name_of_players] self.cards = Cards(number_of_decks)
""" from Deck import Deck from Player import Player from Dealer import Dealer ranks = [ 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King' ] suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds'] chips = [1, 5, 10, 20, 50, 100] #set up the game #create game deck, player and dealer dealer = Dealer("Dealer") player = Player("The Chosen One", 1900) #player starts with 1900 chips input( "Welcome to Blackjack. Dealer must draw on 16, stay on 17.\nPress 'Enter' to continue\n" ) GAME_ON = True while GAME_ON: #we'll create a new deck at the beginning of each game for an 'endless' game (Player running out of chips will end it) game_deck = Deck(ranks, suits) game_deck.shuffle_deck() #betting phase, prompt for a valid bet until the enter a valid bet, then continue VALID_BET = False while not VALID_BET: bet = input(
reward_episode.append(avg_reward) ''' # Done running save off avg rewards per episode avg_reward = np.array(reward_episode) np.save('/Users/befeltingu/DeepRL/Data/Graph/black_jack_reward.npy', avg_reward) if __name__ == '__main__': player = DeepPlayer(3, 2) dealer = Dealer(1) run_black_jack(player, dealer, batch_size=32, num_episodes=1000, game_sample_size=2000, avg_score_sample_size=10000) player.create_policy_df() player.save( '/Users/befeltingu/DeepRL/Data/models/blackjack_simple_model.h5')
def test_tie(self): dealer = Dealer(None,None) hand = [Card(12),Card(12)] # 2 kings dealer.playersHand = hand dealer.dealersHand = hand self.assertEqual(dealer.getHandResult(),'tie')
def initiate_dealer(self): self.dealer = Dealer() self.dealer.shuffle(self.deck)
class Game: def __init__(self, num_players=1, num_decks=6): self.num_decks = num_decks self.dealer = Dealer() self.bot = Bot('Bot') self.players = [] self.busted = [] self.stand = [] self.move = 0 self.dealer_done = False self.bot_moves = [] for i in xrange(0,num_players): self.players.append(Player('Player'+str(i+1))) self.players.append(self.bot) self.deck = Deck(num_decks) self.bot_deck = self.deck.deck * 1 for player in self.players: player.make_bet() if player.name == 'Bot': player.add(self.bot_deck.pop()) player.add(self.bot_deck.pop()) self.bot_deck.pop() self.bot_deck.pop() else: player.add(self.deck.draw()) player.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.rules = RulesEngine(self.dealer, self.players) def ongoing(self): return not len(self.players) == 0 or not self.dealer_done def winner(self): self.stand.sort(key=lambda x: x.val) self.stand.reverse() winner = self.dealer if self.dealer.val <= 21 else Player("Default") for player in self.stand: if player.val > winner.val: winner = player return winner def payout(self): self.rules.update(self.stand) def reset(self): self.players = self.rules.players self.stand = [] self.busted = [] self.dealer_done = False self.bot.update(self.players+[self.dealer]) if len(self.deck.deck) <= self.deck.num_decks*52*0.25: # re-shuffle if < 75% of deck left self.deck.deck = self.deck.generate(self.deck.num_decks) self.deck.shuffle() self.reset_count() self.dealer.clear_hand() for player in self.players: player.clear_hand() self.bot_deck = self.deck.deck * 1 for player in self.players: player.make_bet() if player.name == 'Bot': player.add(self.bot_deck.pop()) player.add(self.bot_deck.pop()) self.bot_deck.pop() self.bot_deck.pop() else: player.add(self.deck.draw()) player.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.dealer.add(self.deck.draw()) self.bot_moves = [] def move_player(self, player, hand): newplayers = [] if self.players[0].name == "Bot": move = player.play(self.dealer,hand) else: move = self.move if move == 1: player.add(self.deck.draw(),hand) if hand == len(player.hands)-1: newplayers.append(player) elif move == -1: if hand == len(player.hands)-1: self.busted.append(player) elif move == 2: player.add(self.deck.draw(),hand) player.doubled_down = True player.cash -= player.bet player.bet *= 2 if hand == len(player.hands)-1: newplayers.append(player) elif move == 3: player.aces.append(0) player.tmp.append(0) player.hands.append([]) card2 = player.hands[0].pop() player.val[0] = 0 player.add(player.hands[0].pop(),0) player.cash -= player.bet player.val.append(0) player.add(card2,1) player.add(self.deck.draw(),0) player.add(self.deck.draw(),1) newplayers.append(player) def run(self): newplayers = [] move = self.dealer.play() if move == 1: self.dealer.add(self.deck.draw()) self.bot_deck.pop() else: self.dealer_done = True for i in xrange(0,len(self.players)): for j in xrange(0,len(self.players[i].hands)): if self.players[i].name == "Bot": move = self.players[i].play(self.dealer,j) if move == 2 and len(self.bot.hands[j]) > 2: move = 1 if not (move == 0 and (j,move) in self.bot_moves): self.bot_moves.append((j,move)) else: move = self.move if move == 1: if self.players[i].name == 'Bot': self.players[i].add(self.bot_deck.pop(),j) else: self.players[i].add(self.deck.draw(),j) if j == len(self.players[i].hands)-1: newplayers.append(self.players[i]) elif move == -1: if j == len(self.players[i].hands)-1: self.busted.append(self.players[i]) elif move == 2: if self.players[i].name == 'Bot': self.players[i].add(self.bot_deck.pop(),j) else: self.players[i].add(self.deck.draw(),j) self.players[i].doubled_down = True self.players[i].cash -= self.players[i].bet self.players[i].bet *= 2 if j == len(self.players[i].hands)-1: newplayers.append(self.players[i]) # STAND? elif move == 3: self.players[i].aces.append(0) self.players[i].tmp.append(0) self.players[i].hands.append([]) card2 = self.players[i].hands[0].pop() self.players[i].val[0] = 0 self.players[i].add(self.players[i].hands[0].pop(),0) self.players[i].cash -= self.players[i].bet self.players[i].val.append(0) self.players[i].add(card2,1) if self.players[i].name == 'Bot': self.players[i].add(self.bot_deck.pop(),0) self.players[i].add(self.bot_deck.pop(),1) else: self.players[i].add(self.deck.draw(),0) self.players[i].add(self.deck.draw(),1) newplayers.append(self.players[i]) else: if j == len(self.players[i].hands)-1: self.stand.append(self.players[i]) self.players = newplayers def reset_count(self): self.bot.rcount = 0 self.bot.tcount = 0 self.bot.dead_cards = 0 def __repr__(self): repr = ['\n'] repr.append('Dealer: ' + str(self.dealer)) for player in self.players: repr.append('Active Player --> ' + str(player)) for player in self.stand: repr.append('Standing Player --> ' + str(player)) for player in self.busted: repr.append('Busted Player --> ' + str(player)) repr.append('\n') return '\n'.join(repr)
class Game(object): def __init__(self): return def generate_deck(self): self.deck = Deck() def initiate_players(self, intHumans=2, intAI=0): self.players = [Player(str(x)) for x in range(intHumans)] def initiate_dealer(self): self.dealer = Dealer() self.dealer.shuffle(self.deck) def initiate_table(self): self.table = Table2() def add_player(self, player): '''Accepts the player object''' self.players.append(player) def deal_cards(self, numberOfCards=0): for x in range(len(self.players)): self.dealer.deal(self.deck, self.players[x], numberOfCards) def debug(self): self.dealer.deal(self.deck, self.players[1], 12) self.dealer.deal(self.deck, self.players[0], 12) print(self.players[1].hand[1]) self.players[1].look_at_hand() print(' Create table object') t = Table2() for x in range(0, len(self.players[1].hand)): print(' ' + `x` + " of " + `len(self.players[1].hand)`) print(`self.players[1].hand[x].value` + " of " + self.players[1].hand[x].suit + " owned by " + `self.players[1].hand[x].owner`) print(' Groups printout') print(t.groups) print(' Group printout') print(t.groups[0]) print('\n\n\n Add New Group') t.new_group() print(' Groups printout') print(t.groups) print(' Group printout') print(t.groups[1]) print('\n\n\n Add card from hand to group[0]') t.add_card_to_group(self.players[1].give_card(1), 0) print(' Groups printout') print(t.groups) print(' Group printout') print(t.groups[1]) print('\n\n\n Add Three cards to group[1]') t.add_card_to_group(self.players[1].give_card(3), 1) t.add_card_to_group(self.players[1].give_card(2), 1) t.add_card_to_group(self.players[1].give_card(0), 1) print(' Groups printout') print(t.groups) print(' Group printout') print(t.groups[1])
def test_pop_size(self): deck = Deck.deck Dealer.dealCards(Deck, deck) self.assertEqual(len(deck), 51, "Deck size should = 51 (card drawn)")
from Player import Player from Dealer import Dealer import mainfunc player_name = input("What is your name: ") player = Player(player_name) print('=============================================') print(" BLACK-JACK-GAME ") print('=============================================') print("Type 'QUIT' anytime to quit the game") # each game loop while True: game_deck = Deck() game_dealer = Dealer() bet = mainfunc.initialise_game(player, game_deck, game_dealer) # each round loop while True: mainfunc.print_cards(player, game_dealer) # check conditions if (mainfunc.round_checker(player, game_dealer) > 0): mainfunc.game_over(mainfunc.round_checker(player, game_dealer), bet, player) break game_deck.shuffle() player_choice = input( "What would you like to do? Press (1) for STAY (2) for HIT: ")
from random import randint, random from math import floor from Card import Card from Deck import Deck from Shuffler import Shuffler from Dealer import Dealer from Player import Player import sys decks = [Deck(), Deck(), Deck()] players = [Player(100)] Cdeck = Shuffler(decks) dave = Dealer(players, Cdeck) dave.deal() #print(Cdeck)
class Game(object): def __init__(self): self.game_over = False self.player = Player() self.deck = Deck() self.dealer = Dealer(self.deck) self.start_game() def start_game(self): print 'Welcome to Blackjack Version 0.1.0' print 'Developed by Christian M. Brandalise' print '------------------------------------' player_name = raw_input('Please enter you name\n') try: self.player.set_name(player_name) except: print 'Error' else: self.game_loop() def set_bet(self): bet = raw_input('Please enter your bet from 1 to {cash}'.format(cash=self.player.cash)) try: bet = int(bet) except: print 'You did not enter a number.' if bet in range(1, self.player.cash + 1): self.player.cash -= bet self.dealer.current_bet += bet def display_balance(self): print 'Your balance \n' print self.player.cash print 'Dealers balance \n' print self.dealer.register def check_win(self, player_hand, dealer_hand): if self.check_hand_value(player_hand) > self.check_hand_value(dealer_hand): return True else: return False def hit(self): card = self.dealer.deal_card() self.player.add_card_to_hand(card) def check_hand_value(self, hand): total = 0 for card in hand: if card.rank in ['2', '3', '4', '5', '6', '7', '8', '9', '10']: total += int(card.rank) elif card.rank in ['Jack', 'Queen', 'King']: total += 10 else: c_ace = total c_ace += 11 if c_ace > 21: total += 1 else: total += 11 return total def check_bust(self, hand): if self.check_hand_value(hand) > 21: return True else: return False def award_bet(self, to_who): if to_who == 'dealer': self.dealer.register += self.dealer.current_bet self.dealer.current_bet = 0 else: winning = self.dealer.current_bet * 2 self.dealer.register -= winning self.player.cash += winning def game_loop(self): print 'Let\'s play some Blackjack!' self.set_bet() self.display_balance() print '********* Dealing your hand ***********\n' hand = self.dealer.deal_hand(2) self.player.set_hand(hand) self.player.display_hand() print '\n' print '********* Dealing dealers hand ***********\n' dhand = self.dealer.deal_hand(2) self.dealer.set_dealer_hand(dhand) self.dealer.display_hand(True) print '******************************************' while not self.game_over: self.player.display_hand() print '\n' self.dealer.display_hand(True) print 'What would you like to do?' print '1. HIT' print '2. STOP' choice = int(raw_input()) if choice in range(1,4): if choice == 1: self.hit() self.player.display_hand() if self.check_bust(self.player.hand): print 'You busted!' self.award_bet('dealer') self.display_balance() self.game_over = True elif choice == 2: print 'Let\'s see who won!' if self.check_win(self.player.hand, self.dealer.hand): self.award_bet('player') self.display_balance() print "Blackjack! Congratulations" else: self.award_bet('dealer') self.display_balance() print "The dealer has won" self.dealer.display_hand(False) self.game_over = True else: print 'The game has ended my dear' self.game_loop()
def __init__(self): self.dealer = Dealer() self.player = Player() self.deck = Deck()
def __init__(self): self.game_over = False self.player = Player() self.deck = Deck() self.dealer = Dealer(self.deck) self.start_game()
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"
def __init__(self): self.dealer = Dealer() self.player = Player(500) self.deck = Deck() self.table = Table()
class Game: def __init__(self): # self.players_cards = [] # self.dealers_cards = [] self.player = Player() self.dealer = Dealer() self.deck = Deck() self.deck.build_deck() self.deck.shuffle() #This runs the game def game_running(self): in_play = True while in_play: deck = Deck() # If either hand has 0 cards, deal a random card from the card list while len(self.player.hand) < 1 and len(self.player.hand) < 1: player_first_card = deck.deal() self.player.add_card(player_first_card) dealer_first_card = deck.deal() self.dealer.add_card(dealer_first_card) # Show the hand and ask player to hit or stay print(f" Your hand is: {self.player.show_hand()}") # print(f"Dealer's hand is: {self.dealer.display()}") choice = input("Please choose [Hit / Stay] ").lower() while choice not in ["h", "s", "hit", "stay"]: choice = input( "Please enter 'hit' or 'stay' (or H/S) ").lower() # If they hit, add card to their hand and update the score if choice == "hit" or choice == "h": #Deal a card to both player and dealer self.player.add_card(deck.deal()) self.dealer.add_card(deck.deal()) #This checks if dealer or player has blackjack player_blackjack, dealer_blackjack = self.check_blackjack() #If blackjack is True, this ends the game if player_blackjack or dealer_blackjack: return player_blackjack, dealer_blackjack elif choice == "stay" or choice == "s": #If player has higher score, player wins if self.player.get_hand() > self.dealer.get_hand(): print("Your hand was higher, you win!") print("Final Results") print("Dealer's hand:", self.dealer.reveal()) else: #If dealer has higher score, dealer wins, and reveals their cards print("You busted. The dealer wins") print("Final Results") print("Dealer's hand:", self.dealer.reveal()) # Checks if player or dealer has reached 21 or if the player has higher hand def check_blackjack(self): player_blackjack = False dealer_blackjack = False players_hand = self.player.calculate_hand() dealers_hand = self.dealer.calculate_hand() if players_hand == 21 or dealers_hand > 21: player_blackjack = True if dealers_hand == 21 or players_hand > 21: dealer_blackjack = True return player_blackjack, dealer_blackjack # When game is over ask to play # This method returns true or false if the player wants to play again def is_game_over(self, player_has_blackjack, dealer_has_blackjack): game_over = False # If this returns True then the game is over if player_has_blackjack and dealer_has_blackjack: game_over = True print("Draw!") if player_has_blackjack: game_over = True print("dealer busted. you win!") print(self.dealer.reveal()) print(self.player.show_hand()) if dealer_has_blackjack: game_over = True print(self.dealer.reveal()) print(self.player.show_hand()) print("You busted. The dealer wins") if game_over == True: play_again = input("Would you like to play again? Y/N ").lower() if play_again == "n": print("Thanks for playing BlackJack!") return True else: return False
class Game: # Constants for min bet, max bet, payout as a string, payout as a float, and when to shuffle MINBET = 20 MAXBET = 500 BLACKJACKPAYOUTSTR = '3:2' BLACKJACKPAYOUT = int(BLACKJACKPAYOUTSTR.split(':')[0]) / int(BLACKJACKPAYOUTSTR.split(':')[1]) DEALER = Dealer() CARDS = Cards() SCORING = Scoring() WHENTOSHUFFLE = (CARDS.getNumDecks() * 52) // 3 # WHENTOSHUFFLE is a const int that indicates how many cards need to be left before reshuffling the deck def __init__(self): self.players = [] self.roundOver = True self.winnings = [] def _determineWager(self, player: Player) -> int: """ Private helper function that keeps prompting the player for a wager until they provide a valid input The wager input must be: an int, within the min/max bet range, no more than the amount of money they have left """ player_money = player.getMoney() wager_is_int = False # Accounting for user error of inputting anything other than an int for the wager. while not wager_is_int: try: # Covering the edge case of a player have less money left than the minimum bet. if player_money < self.MINBET: print() print(f'Since you currently have less money than the minimum bet (${self.MINBET}), you\'ll have to bet all your money!') breakpoint = input('') wager = player_money # Makes sure player bets within the range of the preset min and max bet. # Also, the player must have enough money left to make the bet. else: wager = int(input(f'Please make a wager from ${self.MINBET} to ${self.MAXBET}: ')) while (wager < self.MINBET) or (wager > self.MAXBET) or (wager > player_money): if wager < self.MINBET: print(f'Sorry, you must bet at least ${self.MINBET}.') elif wager > self.MAXBET: print(f'Sorry, you can\'t bet more than ${self.MAXBET}.') elif wager > player_money: print('You don\'t have enough money to make that bet!') print() wager = int(input(f'Please make a wager from ${self.MINBET} to ${self.MAXBET}: ')) wager_is_int = True except ValueError: print('Must give an int for your wager.') print() return wager def _determineInsuranceWager(self, player: Player) -> int: """ Private helper function that keeps prompting the player for an insurance wager until they provide a valid input The insurance wager input must be: an int, at least $1 and no more than half their original wager, and it cannot be more than the amount of money the player has left (after their wage is deducted) """ insurance_wager_is_int = False print(f'Total money left (after your wager of ${player.getWager()}): ${player.getMoney()-player.getWager()}') breakpoint = input('') # Accounting for user error of inputting anything other than an int for the wager. while not insurance_wager_is_int: try: insurance_wager = int(input(f'Please make an insurance wager from $1 to ${player.getWager() // 2} ')) while (insurance_wager < 1) or (insurance_wager > player.getWager() // 2) or (player.getMoney() - player.getWager() - insurance_wager < 0): if insurance_wager < 1: print('Sorry, you can\'t wager anything less than $1.') elif insurance_wager > player.getWager() // 2: print(f'Sorry, you can\'t wager anything more than ${player.getWager() // 2}.') else: print('You don\'t have enough money to make that bet!') print() insurance_wager = int(input(f'Please make an insurance wager from $1 to ${player.getWager() // 2} ')) insurance_wager_is_int = True except ValueError: print('Insurance wager must be an int.') print() return insurance_wager def addPlayer(self, player: Player) -> None: """ Add a player to the game, but only after the round is over """ if self.roundOver: self.players.append(player) # Removes a player from the game. Player is allowed to leave before # round is over, but they'll lose their wager. def removePlayer(self, player: Player) -> None: if player in self.players: self.players.remove(player) # Returns the current number of players def getNumPlayers(self) -> int: return len(self.players) # Returns a bool indicating whether the round is over or not def isRoundOver(self) -> bool: return self.roundOver # Uses the Scoring class to compare the player's hand to the dealer's # hand. Based on the winner and whether each person has a BlackJack, # the winnings (or losings) are determined for the player based on their # hand and their wager def determineWinnings(self) -> None: dealer_hand = self.DEALER.getHand() dealer_score = self.DEALER.getTotalScore() print('~~~~~~~~~~~~~~~Final Standings~~~~~~~~~~~~~~~') print(f'Dealer\'s final hand: {dealer_hand} === {dealer_score} points') breakpoint = input('') for player in self.players: for hand_num in range(1, player.getNumHands()+1): wager = player.getWager(hand_num) insurance_wager = player.getInsuranceWager() # Might cause an error because of duplicate counting player_hand = player.getHand(hand_num) player_score = player.getTotalScore(hand_num) # If dealer gets a BlackJack, the player loses their wager unless they also have a BlackJack. # Also, they win twice their insurance wager if they chose to make one at the beginning of the round. if dealer_score == 21 and self.DEALER.handSize() == 2: if player_score == 21 and player.handSize(hand_num) == 2: winning = 0 + (insurance_wager * 2) else: winning = (wager * -1) + (insurance_wager * 2) # Payout for a BlackJack is based on the preset amount elif player_score == 21 and player.handSize(hand_num) == 2: winning = int(wager * self.BLACKJACKPAYOUT) + (insurance_wager * -1) # If player busts, they lose their wager regardless of what hand the dealer has (even if dealer busts) elif player_score > 21: winning = (wager * -1) + (insurance_wager * -1) # If the dealer busts or the player has a higher score than the dealer, they win their wager back elif dealer_score > 21 or player_score > dealer_score: winning = wager + (insurance_wager * -1) # If neither the player nor dealer busts, but the player has a lower score than the dealer, # the player loses their wager. elif player_score < dealer_score: winning = (wager * -1) + (insurance_wager * -1) # The last case is where the player has the same score as the dealer. else: winning = 0 + (insurance_wager * -1) print(f'<{player.getName()}> Hand #{hand_num}: {player_hand} === {player_score} points | Winnings: {winning}') self.winnings.append((player, winning)) breakpoint = input('') self.distributeWinnings() # Distributes all the winnings (or losings) back to the players and # changes their total money accordingly def distributeWinnings(self) -> None: for player, money in self.winnings: player.addMoney(money) # Kick a player out of the round if they're out of money for player in self.players[:]: if player.getMoney() <= 0: print(f'Sorry, {player.getName()}! You\'re out of money :( Thanks for playing!') self.removePlayer(player) breakpoint = input('') self.endRound() # Starts a new round and asks each player to make a wager before the cards are dealt. # New players are not allowed to join until the round is over. # Also, a round can't be started if there's no players in the game yet. def newRound(self) -> None: self.roundOver = False print() print('~~~~~~~~~~Welcome Challengers!~~~~~~~~~~') print(f'For this round we\'re using {self.CARDS.getNumDecks()} full decks and we have {len(self.players)} challengers playing.') print(f'The current number of cards left in the deck is {self.CARDS.deckSize()}') print(f'The deck will be reshuffled after {self.CARDS.deckSize() - self.WHENTOSHUFFLE} more cards are drawn') # For each player, print their name and total money, and then ask them to make a wager for player in self.players: print() print(f'Player: {player.getName()}') print(f'Total Money: ${player.getMoney()}') player.setWager(self._determineWager(player)) print() print('~~~~~~~~~~Let the round begin. Good luck!~~~~~~~~~~') print() self.dealInitialCards() # Ends the round, clearing all of the hands and previous winnings def endRound(self) -> None: self.roundOver = True self.winnings = [] # Shuffles the cards if necessary if self.CARDS.deckSize() <= self.WHENTOSHUFFLE: self.CARDS.shuffle() print('Shuffling cards...') breakpoint = input('') # Accounts for edge case that all the players lose their money and get kicked out of the game if self.getNumPlayers() > 0: print('~~~~~~~~~~~~~~~Everyone\'s Total Money~~~~~~~~~~~~~~~') for player in self.players: player.resetPlayer() print(f'{player.getName()}: ${player.getMoney()}') else: print('There\'s no more players left! Everyone ran out of money :(') self.DEALER.resetDealer() print() print('The round is over! Good game everyone!') breakpoint = input('') # Deals two cards to each player and then the dealer. Note that one # card is dealt to everyone before the second card is dealt. # I added 'breakpoint' variables for now to simulate dealing one card at a time. def dealInitialCards(self) -> None: self._dealPlayerInitialCards() self._dealDealerInitialCards() # All players have the option of making an insurance bet only if the dealer's first card is an Ace. if self.DEALER.getHand()[0][0] == 'A': self._insuranceBetting() self._dealPlayerInitialCards() self._dealDealerInitialCards() self.dealPlayerCards() # Helper function that deals one of the two initial cards to the player at the start of the round. def _dealPlayerInitialCards(self) -> None: for player in self.players: still_dealing = True while still_dealing: num_hands = player.getNumHands() for hand_num in range(1, num_hands+1): # This is so we can skip the hands that already have two cards and only look at the rest that split. if player.handSize(hand_num) != 2: player.addCard(self.CARDS.getCard(), hand_num) player_hand = player.getHand(hand_num) player_score = self.SCORING.totalScore(player_hand) print(f'<{player.getName()}> Hand #{hand_num}: {player_hand} === {player_score} points') # Check to see if player wants to double down or split, but only if they have enough money to do so. # Note, player cannot double down on a BlackJack. if (player.handSize(hand_num) == 2) and (player.getWager(hand_num) + player.totalWager() <= player.getMoney()) and (player_score != 21): print() is_doubling_down = input('Want to double down? (Y/N) ') while (is_doubling_down.upper() != 'Y') and (is_doubling_down.upper() != 'N'): is_doubling_down = input('Want to double down? (Y/N) ') print() if is_doubling_down.upper() == 'Y': player.doubleDown(hand_num) print('Doubling down...') breakpoint = input('') # If player's two cards are identical, give them the choice to split. # Note that the player cannot split to make more than 4 hands. elif player_hand[0][0] == player_hand[1][0] and player.getNumHands() < 4: is_splitting = input('Want to split? (Y/N) ') while (is_splitting.upper() != 'Y') and (is_splitting.upper() != 'N'): is_splitting = input('Want to split? (Y/N) ') print() if is_splitting.upper() == 'Y': player.split(hand_num) print('Splitting hand...') breakpoint = input('') if hand_num == player.getNumHands(): still_dealing = False # Only stop dealing if we've successfully dealt two cards to all the hands. elif hand_num == player.getNumHands(): still_dealing = False breakpoint = input('') # This is solely for printing purposes in the edge case that the user cannot split or double # down due to lack of funds, and still has cards left to be dealt to their other hands. elif player.handSize(hand_num) == 2: breakpoint = input('') player.setTotalScore(player_score, hand_num) # Helper function that deals one of the two initial cards to the dealer at the start of the round. def _dealDealerInitialCards(self) -> None: self.DEALER.addCard(self.CARDS.getCard()) # Want to show only dealer's first card face up. if self.DEALER.handSize() == 1: dealer_hand = self.DEALER.getHand() dealer_score = self.SCORING.totalScore(dealer_hand) print(f'Dealer\'s hand: {dealer_hand} === {dealer_score} points') else: dealer_hand = [self.DEALER.getHand()[0], '?'] dealer_score = self.SCORING.totalScore(self.DEALER.getHand()) print(f'Dealer\'s hand: {dealer_hand} <= {self.SCORING.totalScore( [dealer_hand[0]] )} points') self.DEALER.setTotalScore(dealer_score) breakpoint = input('') # Helper function that asks players if they want to make an insurance bet. def _insuranceBetting(self) -> None: for player in self.players: # Accounts for edge case that player bet all their money and don't have any left for the insurance bet if player.getMoney() - player.getWager() == 0: print(f'Sorry, {player.getName()}! You don\'t have anymore money left to make an insurance bet :(') breakpoint = input('') else: insurance = input(f'{player.getName()}, care to make an insurance bet? (Y/N) ') while (insurance.upper() != 'Y') and (insurance.upper() != 'N'): insurance = input(f'{player.getName()}, care to make an insurance bet? (Y/N) ') print() if insurance.upper() == 'Y': player.setInsuranceWager(self._determineInsuranceWager(player)) # Deals the rest of the cards to the players (depending on whether they choose # to hit or stand) and then to the dealer def dealPlayerCards(self) -> None: for player in self.players: print(f'~~~~~~~~~~~~~~~~{player.getName()}\'s Turn~~~~~~~~~~~~~~~~') print() for hand_num in range(1, player.getNumHands()+1): player_hand = player.getHand(hand_num) hand_score = player.getTotalScore(hand_num) # Check to see if the player has a BlackJack. Otherwise, proceed with their turn. if hand_score == 21: print(f'Hand #{hand_num}: {player_hand} === {hand_score} points') print() print(f'Congrats, {player.getName()}! You got a BlackJack!') breakpoint = input('') # If player doubled down on this hand, they only get one more card. elif player.hasDoubledDown(hand_num): player.addCard(self.CARDS.getCard(), hand_num) player_hand = player.getHand(hand_num) hand_score = self.SCORING.totalScore(player_hand) print('Since you doubled down on this hand, you only get one more card.') breakpoint = input('') print(f'Hand #{hand_num}: {player_hand} === {hand_score} points') breakpoint = input('') if hand_score > 21: print(f'Sorry, {player.getName()}, this hand a bust!') breakpoint = input('') else: player.setTurn(True) while player.isTurn(): player_hand = player.getHand(hand_num) hand_score = self.SCORING.totalScore(player_hand) print(f'Hand #{hand_num}: {player_hand} === {hand_score} points') print() # If player busts, their turn is over. if hand_score > 21: print(f'Sorry, {player.getName()}, this hand is a bust!') player.setTurn(False) breakpoint = input('') # Player cannot hit anymore when their hand gets to a score of 21. elif hand_score == 21: print(f'This hand is equal to 21, so you can\'t hit anymore') player.setTurn(False) breakpoint = input('') else: hit_or_stand = input('Would you like to hit or stand? ') while (hit_or_stand.lower() != 'hit') and (hit_or_stand.lower() != 'stand'): print('Must choose hit or stand.') print() hit_or_stand = input('Would you like to hit or stand? ') if hit_or_stand.lower() == 'hit': player.addCard(self.CARDS.getCard(), hand_num) else: player.setTurn(False) print() player.setTotalScore(hand_score, hand_num) self.dealDealerCards() # Dealer has their own set of rules for hitting and standing. Their decisions # are essentially made automatically: If the dealer's hand is 16 or less points, they # must hit. If their hand is 17 or more points, they must stand. def dealDealerCards(self) -> None: print('~~~~~~~~~~~~~~~~Dealer\'s Turn~~~~~~~~~~~~~~~~') print() dealer_hand = self.DEALER.getHand() dealer_score = self.DEALER.getTotalScore() if dealer_score == 21: print(f'Dealer\'s hand: {dealer_hand} === {dealer_score}') print() print(f'The dealer got a BlackJack!') breakpoint = input('') else: self.DEALER.setTurn(True) while self.DEALER.isTurn(): dealer_hand = self.DEALER.getHand() dealer_score = self.SCORING.totalScore(dealer_hand) print(f'Dealer\'s hand: {dealer_hand} === {dealer_score}') breakpoint = input('') if dealer_score > 21: print('The dealer\'s hand is a bust!') self.DEALER.setTurn(False) elif dealer_score <= 16: print('The dealer chose to hit.') self.DEALER.addCard(self.CARDS.getCard()) else: print('The dealer chose to stand.') self.DEALER.setTurn(False) breakpoint = input('') self.DEALER.setTotalScore(dealer_score) self.determineWinnings() # Returns the list of players who had winning hands def getWinners(self) -> [Player]: return [player for player, winning in self.winnings if winning > 0] # Returns the preset minimum bet def getMinBet(self) -> int: return self.MINBET # Returns the preset maximum bet def getMaxBet(self) -> int: return self.MAXBET # Returns the preset payout for getting a BlackJack def getPayout(self) -> float: return self.BLACKJACKPAYOUT # Returns the present payout for getting a BlackJack as a str def getPayoutStr(self) -> str: return self.BLACKJACKPAYOUTSTR
def test_get_multiple_hand_values(self): hand = [Card(0),Card(1)] dealer = Dealer(None,None) values = dealer.getHandValues(hand) self.assertIn(3,values) self.assertIn(13,values)
from Player import Player from Deck import Deck from Dealer import Dealer player = Player([], False, 100, 0, True) dealer = Dealer([], False, False, False, False) gameEnd = False # When the game starts, player turn is automatically set to true. while player.playerTurn: player.gameType(dealer) # Game running while not gameEnd: deck = Deck([]) deck.createDeck() player = Player([], player.isUser, player.balance, 0, True) dealer = Dealer([], dealer.isUser, False, False, False) # Player bets if player.isUser: print(f"Your current balance is: {player.balance}") player.desiredBet() print(f"Bet: {player.bet}") # Player bet is fixed, if dealer gametype is chosen if not player.isUser: player.bet = 20 # Creating the starting hands, and printing to terminal player.hand.append(dealer.dealCards(deck.deck))
def test_get_max_hand_value(self): hand = [Card(0),Card(1),Card(2),Card(13)] dealer = Dealer(None,None) maxValue = dealer.getMaxHandValue(hand) self.assertEqual(maxValue, 17)
def test_if_name_is_correct(self): d = Dealer() self.assertEqual(True, d.name == "Nick")
print('{} won'.format(player1.get_name())) return if player1.get_score() == player2.get_score(): print('draw game') elif player1.get_score() > player2.get_score(): print('{} won'.format(player1.get_name())) elif player1.get_score() < player2.get_score(): print('{} won'.format(player2.get_name())) if __name__ == '__main__': # program start here! # make characters! dealer = Dealer() player = Player() # introduce dealer.greet(player) # make tools deck = Deck() # deck is shuffled deck.shuffle() dealer.first_draw(deck) player.first_draw(deck) # game dealer.show_hand(True)
class Game(BaseClass): """ The Game """ def __init__(self, com, minPl, maxPl, cd_join, cd_kick, d): BaseClass.__init__(self) self.com = com self.minPl = minPl self.maxPl = maxPl self.maxQueue = 20 self.cd_join = cd_join self.cd_kick = cd_kick self.com.regEvt("chat", self.chat) self.com.regEvt("join", self.join) self.com.regEvt("play", self.pl_play) self.com.regEvt("client_error", self.cl_er) self.clients = [] self.debug = d def setup_new_game(self): self.log("Setting up new game") self.dealer = Dealer(self, self.cd_kick) self.dealer.regEvt("won", self.pl_won) self.dealer.regEvt("kick", self.pl_kicked) self.status = 0 self.count_time = 0 self.playing_list = [] for c in self.clients: c.playerId = 0 self.check_countdown() def start_game(self): """ this is the actual start game method counting down is another one """ self.log("starting game") n = len(self.clients) if n > self.maxPl: n = self.maxPl self.total_player = n for i in xrange(0, n): self.clients[i].playerId = i + 1 self.playing_list.append(self.clients[i]) self.dealer.start_game(n) self.status = 2 # playing #time comes #this is called every time in the outer loop #it will check 2 things: counting down in the game #and counting down in player move def check_time(self): now = time.time() if self.status == 1: #waiting if now - self.count_time >= self.cd_join: #time up self.start_game() elif self.status == 2: #playing self.dealer.check_time() #event def chat(self, sockId, msg): playerName = self.by_sockId(sockId).playerName self.com.bc_chat(playerName, msg) def join(self, sockId, msg): if len(self.clients) > self.maxQueue: self.com.kick_bysockId(sockId) return for c in self.clients: if c.sockId == sockId: self.com.s_invalid(sockId, "You already joined") return if c.playerName == msg: self.com.s_invalid(sockId, "The name is already taken") return try: p = PlayerInfo(msg, 0, sockId) except: self.com.s_invalid(sockId, msg) return self.clients.append(p) self.com.s_accept(sockId, msg) if self.status == 0 or self.status == 1: # waiting or counting self.check_countdown() else: self.com.s_wait(sockId, msg) self.com.bc_newplayer(self.all_player()) def pl_play(self, sockId, msg): if self.status == 2: player = self.by_sockId(sockId) try: self.dealer.play(player.playerId, msg) except UnoException as e: self.com.s_invalid(sockId, e.__str__()) def pl_won(self, playerId): playerName = self.by_playerId(playerId).playerName self.com.bc_gg(playerName) self.setup_new_game() def pl_kicked(self, playerId): p = self.by_playerId(playerId) self.playing_list.remove(p) self.kick(p) def cl_er(self, sockId): try: player = self.by_sockId(sockId) except Exception as e: return if player in self.playing_list: self.dealer.kick_player(player.playerId) else: self.kick(player) if self.status == 1: #counting self.check_countdown() def kick(self, p): sockId = p.sockId self.clients.remove(p) self.com.kick_bysockId(sockId) self.com.bc_newplayer(self.all_player()) #check if we should start counting down def check_countdown(self): if len(self.clients) >= self.minPl and len(self.clients) <= self.maxPl: self.count_time = time.time() self.status = 1 else: self.status = 0 #helper def all_player(self): n = len(self.clients) all_player = ",".join([p.playerName for p in self.clients if p.playerId <= n]) return all_player def by_sockId(self, sockId): return [c for c in self.clients if c.sockId == sockId][0] def by_playerId(self, playerId): return [c for c in self.playing_list if c.playerId == playerId][0] def by_name(self, name): return [c for c in self.client if c.playerName == name][0] def log(self, s): if self.debug: print s #send method from player class def com_s_deal(self, playerId, msg): self.log("Sending deal to: %d with %s" % (playerId, msg)) sockId = self.by_playerId(playerId).sockId self.com.s_deal(sockId, msg) def com_s_go(self, playerId, msg): sockId = self.by_playerId(playerId).sockId self.com.s_go(sockId, msg) def com_bc_gg(self, playerId): playerName = self.by_playerId(playerId).playerName self.com.bc_gg(playerName) def com_bc_uno(self, playerId): playerName = self.by_playerId(playerId).playerName self.com.bc_uno(playerName) def com_bc_play(self, playerId, msg): playerName = self.by_playerId(playerId).playerName self.com.bc_play(playerName, "%s,%s" % (playerName, msg)) def com_bc_startgame(self): msg = ",".join([p.playerName for p in self.playing_list]) self.com.bc_start(msg)
class CasinoBJTable(object): DEBUG = False ROLLOUTS = False def __init__(self, numDecks, numPlayers): self.numDecks = numDecks self.deck = Shoe(numDecks) self.dealer = Dealer(Dealer.bankStart, numDecks) self.playersList = [] self.numPlayers = numPlayers for i in range(0, numPlayers): if CasinoBJTable.ROLLOUTS: playerPerson = Player(i, Player.startingBank, numDecks) self.playersList.append(playerPerson) else: self.playersList.append( ROPlayer(i, Player.startingBank, numDecks, "MEGA_DICT.bin")) self.playersList.append( BSPlayer(i, Player.startingBank, numDecks)) self.playersList.append( CCPlayer(i, Player.startingBank, numDecks)) # self.playersList.append(Dealer(Dealer.bankStart, numDecks)) shuffle(self.playersList) def givePlayerCard(self, player): aCard = self.deck.getTopCard() print "Giving the player: " + aCard player.getCard(aCard, 0) def updatePlayers(self, aCard): for i in range(0, self.numPlayers): self.playersList[i].countCard(aCard) def saveGameState(self): exit("Save Not implemented") def playRound(self): for pl in self.playersList: counter = 0 moreHands = True if CasinoBJTable.DEBUG: StaticBJLogger.writeDealerMove( DealerMove("TEST" + str(pl.getHands()[0].getHandValue()), pl.getHands()[counter])) # Move.NOTCOMPLETE)) while moreHands: old = len(pl.getHands()) while counter < len(pl.getHands()): if CasinoBJTable.DEBUG: print "counter:", counter keepGoing = True while keepGoing == True: if CasinoBJTable.DEBUG: keepGoing = pl.play(counter) else: keepGoing = pl.play( counter, self.dealer.getVisibleHand(0).getHandValue()) if keepGoing == True: newCard = self.deck.getTopCard() pl.getHands()[counter].addCard(newCard) self.updatePlayers(newCard) if CasinoBJTable.ROLLOUTS: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getVisibleHand( 0).getHandValue(), Move.NOTCOMPLETE)) counter += 1 if CasinoBJTable.DEBUG: print "OUT" moreHands = (old != len(pl.getHands())) keepGoing = True while keepGoing == True: keepGoing = self.dealer.play(None, None) if keepGoing == True: newCard = self.deck.getTopCard() self.dealer.getHands()[0].addCard(newCard) self.updatePlayers(newCard) if (CasinoBJTable.ROLLOUTS): if (len(pl.getHands()) == 2): if (self.dealer.getHands()[0].isBust() and pl.getHands()[0].isBust() and pl.getHands()[1].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.NOTCOMPLETE)) elif (self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust() and not pl.getHands()[1].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.WON_BOTH)) elif (self.dealer.getHands()[0].isBust() and pl.getHands()[0].isBust() and not pl.getHands()[1].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_2)) elif (self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust() and pl.getHands()[1].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_1)) elif ( not self.dealer.getHands()[0].isBust() and (pl.getHands()[0].isBust() and pl.getHands()[1].isBust())): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.LOST)) elif (not self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust() and pl.getHands()[1].isBust()): if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[0].getHandValue()): StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.LOST)) else: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_1)) elif (not self.dealer.getHands()[0].isBust() and pl.getHands()[0].isBust() and not pl.getHands()[1].isBust()): if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[1].getHandValue()): StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.LOST)) else: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_2)) elif (not self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust() and not pl.getHands()[1].isBust()): if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[0].getHandValue()): if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[1].getHandValue()): StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.LOST)) else: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_2)) else: if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[1].getHandValue()): StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_1)) else: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_BOTH)) else: # House rules: tie on a bust for dealer and player if (self.dealer.getHands()[0].isBust() and pl.getHands()[0].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.NOTCOMPLETE)) elif (self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_1)) elif (not self.dealer.getHands()[0].isBust() and pl.getHands()[0].isBust()): StaticBJLogger.writeDealerMove( DealerMove(self.dealer.getHands()[0].getHandValue(), Move.LOST)) elif (not self.dealer.getHands()[0].isBust() and not pl.getHands()[0].isBust()): if (self.dealer.getHands()[0].getHandValue() >= pl.getHands()[0].getHandValue()): StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.LOST)) else: StaticBJLogger.writeDealerMove( DealerMove( self.dealer.getHands()[0].getHandValue(), Move.WON_HAND_1)) else: for pl in self.playersList: gm = GameMove() for val in pl.getHandsVals(): if val > 21: gm.incBust() elif val > self.dealer.getHands()[0].getHandValue(): gm.incWon() else: gm.incLoss() if isinstance(pl, BSPlayer): if CasinoBJTable.DEBUG: print "BS" StaticBJGameLogger.writeBSMove(gm) elif isinstance(pl, ROPlayer): if CasinoBJTable.DEBUG: print "RO" StaticBJGameLogger.writeROMove(gm) elif isinstance(pl, CCPlayer): if CasinoBJTable.DEBUG: print "CC" StaticBJGameLogger.writeCCMove(gm) elif isinstance(pl, Dealer): if CasinoBJTable.DEBUG: print "Dealer" StaticBJGameLogger.writeDealerMove(gm) else: if CasinoBJTable.DEBUG: "wah wah" def initPlayers(self): for i in range(0, 2): for pl in self.playersList: newCard = self.deck.getTopCard() pl.getHands()[0].addCard(newCard) self.updatePlayers(newCard) if (i == 1): # Hide the dealers other card topCard = self.deck.getTopCard() topCard.setIsVisible(False) self.dealer.getHands()[0].addCard(topCard) else: newCard = self.deck.getTopCard() self.dealer.getHands()[0].addCard(newCard) self.updatePlayers(newCard) def resetPlayers(self): for pl in self.playersList: pl.setHand([Hand([])]) pl.hasDouble = False pl.hasSplit = False self.dealer.setHand([Hand([])]) def __repr__(self): strPlayers = "" for i in range(0, self.numPlayers): strPlayers += str(self.playersList[i]) strPlayers += "\n" return (strPlayers) # plays blackjack till a specific time # day, hour, minute is the ending time for the function def play(self, day, hour, minute): endTime = DateTimeCustom(day, hour, minute) self.resetPlayers() while not endTime.greaterEqualTo(): if self.deck.yellowCardPassed(): del self.deck self.deck = Shoe(self.numDecks) self.initPlayers() self.playRound() self.resetPlayers()
# winners takes home money def playGame(): playerPoints = player.hand() board.checkCards(playerPoints, player.getCards(), player) if player.playerBust(): print("You lost ${}".format(player.roundBet())) return False if player.totalScore() == 21: print("{} won ${}!".format(player.getName(), board.getTableBet())) return False answer = board.hitOrStay(player) if not player.playerBust() and "Hit" in answer or "hit" in answer: player.addCard(dealer.deal()) else: dealerPlay() return False return True player = Player("Luis", 500) dealer = Dealer() board = Board() while player.hasMoney() and board.gameIsActive(): board.newRound(player, dealer) print("New Round:\n") if firstPlay(): while playGame() and board.roundIsActive(): pass
def test_get_simple_hand_value(self): hand = [Card(2),Card(3)] dealer = Dealer(None,None) self.assertIn(7,dealer.getHandValues(hand))
from Deck import Deck from Dealer import Dealer from Player import Player while True: print("Welcome to Blackjack!") # create the deck deck = Deck() deck.shuffle() # create the dealer, the player and deal cards dealer = Dealer(deck) player = Player(100) dealer.ask_for_bet(player) dealer.deal_cards(player) dealer.show_cards(player) # player's turn, choose if he hits or stands while dealer.hit_or_stand(player): player.hand.show_cards() if player.hand.value == 21: dealer.player_wins(player) if player.hand.value > 21: dealer.player_busts(player) break if not player.busted: print("Dealer's turn") while dealer.hand.value < 17: card = deck.get_card() dealer.hand.add_card(card)
def test_if_score_is_zero_on_initialization(self): d = Dealer() self.assertEqual(0, d.score)
print('Welcome to blackjack') player1 = input("Enter name player 1: ") player2 = input("Enter name player 2: ") while True: try: bank1 = int(input(player1 + " ,please place your bet:")) bank2 = int(input(player2 + " ,please place your bet:")) except ValueError: print("Please enter integer value bets") continue else: pl1 = Player(player1, bank1) pl2 = Player(player2, bank2) break deal = Dealer(bankroll=0) deck = Deck() deck.shuffle() i = 0 while i <= 1: deal.draw() pl1.draw() pl2.draw() i += 1 deal.show() pl1.show() pl2.show() print("The dealer's upward facing card is:") deal.turn() print("Player moves list:\n")
def test_value_for_ace_card_on_initialization(self): d = Dealer() self.assertEqual(11, d.value_for_ace_card)
class Game(object): ''' classdocs ''' def __init__(self, me, NumberOfPlayers=Number, current_river_card=[]): ''' Constructor ''' self.NumberOfPlayers = NumberOfPlayers self.me = me self.players = list() me.showCards() self.players.append(me) self.dealer = Dealer() self.dealer.dropTargetCard(me.cards_inhand[0]) self.dealer.dropTargetCard(me.cards_inhand[1]) self.riverCards = [] self.current_river_cards = current_river_card for card in current_river_card: self.dealer.dropTargetCard(card) for id in range(1, self.NumberOfPlayers): p = Player(id) p.receiveCards(self.dealer.sendRandomCard(), self.dealer.sendRandomCard()) p.showCards() self.players.append(p) self.getRiverCards() def showRiverCards(self): str = 'River Cards include ' if len(self.riverCards) == 0: PRINT('There is no cards on the table.', 1) return else: for card in self.riverCards: str += '{%2d%s} ' % (card.rank, card.suit) str += '\n' PRINT(str, 1) # print str def getRiverCards(self): number_of_current_river_cards = len(self.current_river_cards) for i in range(5 - number_of_current_river_cards): self.riverCards.append(self.dealer.sendRandomCard()) # self.showRiverCards() self.riverCards += self.current_river_cards return self.riverCards def wehterIAmGoingtoWin(self): myscore = self.me.getScore(self.riverCards) for player in self.players: # print player.playerID # print player.cards_inhand PRINT("Player %d" % player.playerID) if player.getScore(self.riverCards) > myscore: PRINT('I lost.') return False PRINT('I Win.') return True