def assess_game_outcome(hand, d_hand, Player, Dealer): # assess player winner = None loser = None if sum(hand) == 0: # player automatically loses on a bust before dealer draws winner = d_hand loser = hand elif sum(d_hand) < sum(hand): winner = hand loser = d_hand else: winner = d_hand loser = hand # record wins and losses, and settle bets if winner == hand: # print("Player wins") Player.set_wins(1) Player.set_win_streak(1) Player.set_pot(Player.get_bet()) Dealer.set_pot(-Player.get_bet()) elif loser == hand: # print("Player loses") Player.set_losses(1) Player.set_win_streak(-1) Player.set_pot(-Player.get_bet()) Dealer.set_pot(Player.get_bet()) else: # will count as loss but pot is not deducted Player.set_losses(1) Player.set_win_streak(-1) # reset hands to zero del hand[2:] del d_hand[2:]
def play_game(game_deck): # initialize the dealer, which also initializes the agent/player dealer = Dealer(game_deck, game_mode) AgentWins = 0 for x in range(0, NUM_GAMES): dealer.deal() AgentWins += dealer.play() if SLOW_MODE: time.sleep(SLEEP_TIME) print("Agent Won %d Times" % AgentWins)
def test_show_score(self): test_dealer = Dealer() test_player = Player() test_dealer.score = 0 test_player.score = 2 self.assertEqual( "Current Score\n" + "-------------\n" + "Player:" + str(test_player.score) + "\n" + "Dealer:" + str(test_dealer.score) + "\n", "Current Score\n" + "-------------\n" + "Player:" + str(2) + "\n" + "Dealer:" + str(0) + "\n")
def runProgram(numPlayers): players = [] if numPlayers * Constants.CARDS_PER_PLAYER + Constants.NUM_STACKS > Constants.MAX_FACE_VALUE: print "Too many players, not enough cards" quit() if numPlayers < 2: print "Too few players" quit() for i in range(numPlayers): players.append(Player(i)) dealer = Dealer(players) return dealer.playGame()
def __init__(self): self.leaderBoard = [] self.roundStatus = 0 # roundStatus: 0 = round over; 1 = round underway self.playerCount = int(input("Enter the number of Players: ")) self.deckCount = int(input("Enter the number of Decks: ")) self.cardpool = CardPool(self.deckCount) #self.cardpool.showDeck() self.dealer = Dealer() self.players = {} for i in range(0,self.playerCount,1): temp = Player() self.players[temp.name] = temp
def __init__(self, playernum, myposition=1, deckqty=1): self.dealer = D.Shuffle(deckqty) self.myposition = myposition stop = playernum + 1 self.visiblecards = [] r = np.arange(1, stop) self.players = [["dealer", []]] for x in r: addp = ("player%s" % (x)) self.players.append([str(addp), []]) for p, hand in self.players: carddealt = self.dealer.DealCards(1) for val in carddealt: carddealt = val hand.append(carddealt) self.visiblecards.append(carddealt) #draw1 for p, hand in self.players: carddealt = self.dealer.DealCards(1) for val in carddealt: carddealt = val hand.append(carddealt) if (p is self.players[self.myposition][0]): self.visiblecards.append(carddealt) else: pass #self.visiblecards.append(carddealt) #myhand = self.players[self.myposition][1] #print(myhand) #print(self.visiblecards) return (None)
def solve_mdp(self): # 'G' is action stating its absorbing goal state # Stand Goal states for player_hv in xrange(2, 22): for dfc in xrange(1, 11): self.val_act_dict[(11, player_hv, dfc, False)] = (Dealer.rewardPlayer( player_hv, dfc, self.fcp, False), 'G') # Black Jacks for dfc in xrange(1, 11): self.val_act_dict[(11, 21, dfc, True)] = (Dealer.rewardPlayer( 21, dfc, self.fcp, True), 'G') # Bust self.val_act_dict[(21, 0, 0, False)] = (-1.0, 'G') # first hard values for hard_value in xrange(2, 22): for dfc in xrange(1, 11): # self.val_act_dict[(0, hard_value, dfc, True)] = self.solve_state(0, hard_value, dfc, True) # first soft values for soft_value in xrange(2, 10): for dfc in xrange(1, 11): # self.val_act_dict[(1, soft_value, dfc, True)] = self.solve_state(1, soft_value, dfc, True) # duplicates for dup in xrange(1, 11): for dfc in xrange(1, 11): if dup == 1: # self.val_act_dict[(dup, dup, dfc, True)] = (0.0, 'N') prev_val = 0.0 curr_val = 1.0 epsilon = 0.1 max_divergence = 15 # self.val_act_dict[(dup, dup, dfc, True)] = while not (-epsilon < (curr_val - prev_val) < epsilon): prev_val = curr_val curr_val = self.solve_state(dup, dup, dfc, True) if (curr_val - prev_val > max_divergence): break else: curr_val = self.solve_state(dup, dup, dfc, True)
def start(self): number_rounds = int(NUMBER_CARDS / self.players.num_players()) dealer = Dealer.Dealer() for round_number in range(1, number_rounds + 1): dealer.reset_card_deck() dealer.deal_cards(players=self.players, amount=round_number) trump_color = dealer.determine_trump() Console_Output.print_new_round_info(round_number, trump_color) self.players.play_round(round_number, trump_color) self.determine_winners()
def spider(file_date=None, log_type=Configuration.logType): ''' TODO: 用Configuration.logType 作参数不合适 ''' if not DBMS.connect(Configuration.db_path): return False # 将文件名拆成名字和后缀 file_list = [] if isinstance(log_type, str): print(log_type, Configuration.logType) if log_type not in Configuration.logType: return False log_type = [log_type] for t in log_type: if file_date: if os.path.isfile(Configuration.log_path + t + '/' + t + '.' + file_date): Dealer.classification(Configuration.log_path + t + '/' + t + '.' + file_date) file_list.append((t, '.' + file_date)) else: print "ERROR: file " + Configuration.log_path + t + '/' + t + '.' + file_date + " don't exist." # 关键字提取 result = None for name in file_list: if name[0] in Configuration.doc[ 'input'] and 'type' in Configuration.doc['input'][name[0]]: if name[0] == 'mis_clt': result = unpacking_general.classifying_mis("".join( tuple(name))) else: result = unpacking_general.classifying("".join(tuple(name))) # 可以返回json或则入库 DBMS.delete_table(name[0]) DBMS.insert_dict_into_sql(name[0], result) DBMS.disconnect() return True
def initialGame(self): self.dealer = Dealer.dealer() self.initial_game_list.append(self.initial_game_list.pop(0)) self.in_game_list = [] self.in_game_list.extend(self.initial_game_list) self.move_list = [] self.move_list.extend(self.in_game_list) self.POT = 0 self.raiseAmount = 0 self.israised = False return
def __init__(self, num_of_decks=1, q_values=util.Counter(), epsilon=0.05, gamma=0.8, alpha=0.2, train_episodes=1000): self.dealer = Dealer.Dealer(num_of_decks) self.q_values = q_values self.epsilon = epsilon self.discount = gamma self.alpha = alpha self.train_episodes = train_episodes
def testFindWinner(self): dealer = Dealer([Player(0), Player(1), Player(2), Player(3)]) self.assertEquals(dealer.findWinner(), -1) dealer.players[1].addBullPoints(66) self.assertEquals(dealer.findWinner(), 1) dealer.players[1].addBullPoints(-1) self.assertEquals(dealer.findWinner(), -1) dealer.players[3].addBullPoints(71) self.assertEquals(dealer.findWinner(), 3)
def test_GetWinner_Confirm_Winner_And_Losers(self): svc = self.Dealer # TODO - # - Create players svc.CreatePlayers(1) # - Get Intial Cards Player = svc.Players[0] Player.GetPlayingCard("K - Hearts") Player.SetCurrentHandValue(10) Player.GetPlayingCard("9 - Hearts") Player.SetCurrentHandValue(9) # - Get players inital bets Player.SetBet(30.00) # - Have players make their bets Player.SetBet(100.00) Dealer = None Dealer = User.User() # - Plays gets one additional hand Dealer.GetPlayingCard("8 - Hearts") Dealer.SetCurrentHandValue(8) Dealer.GetPlayingCard("10 - Clubs") Dealer.SetCurrentHandValue(10) #print(PlayerCardHandValue) PlayerIsWinner = False if Player.CurrentCardValues > Dealer.CurrentCardValues: PlayerIsWinner = True else: PlayerIsWinner = False self.assertTrue(PlayerIsWinner)
def test_start_round(self): test_dealer = Dealer() test_player = Player() test_deck = Deck() for i in range(0, 2): test_player.hand.append(test_deck.get_random_card()) test_dealer.hand.append(test_deck.get_random_card()) self.assertEqual(len(test_player.hand), 2) self.assertEqual(len(test_dealer.hand), 2) for x in range(0, 2): self.assertEqual(type(test_player.hand[x]), tuple) self.assertEqual(type(test_dealer.hand[x]), tuple)
def __init__(self, num_of_decks=1, q_values=util.Counter(), epsilon=0.05, gamma=0.8, alpha=0.2, train_episodes=1000, extractor='SimpleExtractor'): self.dealer = Dealer.Dealer(num_of_decks) self.q_values = q_values self.epsilon = epsilon self.discount = gamma self.alpha = alpha self.train_episodes = train_episodes self.weights = util.Counter() self.featExtractor = util.lookup(extractor, globals())()
from flask import Flask, url_for import Buyer, Dealer, Brand, Product app = Flask(__name__) app.config['SECRET_KEY'] = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' @app.route("/") def home(): try: return app.send_static_file("index.html") except Exception as e: return str(e) Buyer.add_routes(app) Dealer.add_routes(app) Brand.add_routes(app) Product.add_routes(app) if __name__ == "__main__": app.run()
score_list.append("Player " + str(_ + 1) + ": Win") else: score_list.append("Player " + str(_ + 1) + ": Loss") else: # Add if dealer score is lower than player scores. if playerDictionary[i].score == 0: score_list.append("Dealer Loss") elif playerDictionary[i].score >= 22: score_list.append("Dealer Loss") else: score_list.append("Dealer Win") print(score_list) # GAME CODE. # Create a dealer, give him 1 card (update score with 1 card.) dealer = Dealer.Dealer(0) # Creates a dealer object playerDictionary[ len(playerDictionary )] = dealer # Puts the dealer last int he player dictionary # print(playerDictionary) # Give all players 2 cards (update points/score using 2 cards.) for x in range(numOfPlayers): generate_card() generate_card() print("Current score of Player " + str(x + 1) + " is: " + str(playerDictionary[x].score)) print("------------------------------------------------") current_player += 1 print("All players have been dealt cards! Switching to Hit/Hold phase... \n") # Set current player back to 0 so we can go to Hit / Hold phase.
def setUp(self): self.Dealer = Dealer.Dealer()
class BlackJack: """ Defines the black jack game """ players = [] cardBank = None dealer = Dealer.Dealer() roundsPlayed = 0 def deal(self): """ Deal a card """ pass def play(self): """ single round of the game """ helpers.disabledPrint() while self.cardBank.cardsAvailable(): self.roundsPlayed += 1 print("Round " + str(round)) self.__InitialDeal() print("") helpers.disabledPrint() helpers.enablePrint() self.__payoutSideBet() helpers.disabledPrint() self.__IntermediateCheck() print("") self.__ContinuePlay() print("") self.__cleanUp() print("") print("") def __init__(self, players, deckCount): """ constructor :param playerCount: number of players in the game :param deckCount: number of decks to use """ self.players = players self.cardBank = CardBank.CardBank(deckCount) def __InitialDeal(self): """ Deal the first round of cards to all players and the Dealer :return: """ for player in self.players: if player.balance > 0: card = self.cardBank.nextCard() player.hands[0].append(card) print("Player " + str(player.id) + " got " + str(card)) dealer_card = self.cardBank.nextCard() self.dealer.hand.append(dealer_card) for player in self.players: if player.balance > 0: card = self.cardBank.nextCard() player.hands[0].append(card) print("Player " + str(player.id) + " got " + str(card)) dealer_card = self.cardBank.nextCard() self.dealer.hand.append(dealer_card) print("Dealer top card " + str(dealer_card)) def __IntermediateCheck(self): """ Check for payouts, blackjacks etc before continuing the play :return: """ #TODO: payout the side bet of lucky lucky #self.__payoutSideBet() # payout black jacks for player in self.players: if player.balance > 0: hand = player.hands[0] if helpers.isBlackJack(hand): player.balance += player.bet * 1.5 print("Player " + str(player.id) + " got a black jack.") print("Balance: " + str(player.balance)) def __ContinuePlay(self): """ continute the play for all players until the end of round :return: """ for player in self.players: if player.balance > 0: for hand in player.hands: doubled = False print("Dealer top card: " + str(self.dealer.getVisibleCard())) while True and not helpers.isBlackJack(hand): decision = player.decide(self.dealer.hand[1], hand) # 1 is the top card of dealer print("Player " + str(player.id) + " hand total: " + str(helpers.handSum(hand))) print("Player " + str(player.id) + " decided to " + str(decision)) if not self.validDecision(player, decision): print("Not a valid choice.") continue if decision == decision.Stand: break elif decision == decision.Hit: card = self.cardBank.nextCard() print("Player " + str(player.id) + " got " + str(card)) hand.append(card) if helpers.handSum(hand) > 21: print("Player " + str(player.id) + " busyed with hand total: " + str(helpers.handSum(hand))) player.balance -= player.bet print(player.balance) player.resetHand() continue elif decision == decision.Double: card = self.cardBank.nextCard() print("Player " + str(player.id) + " got " + str(decision)) hand.append(card) break # only one card given for double else: helpers.printHand(hand) print("Dealer card: " + str(self.dealer.hand[1])) print("Player decided to: " + str(decision)) print("") player.splitHands() hand = player.hands[0] #handle dealer hits while helpers.handSum(self.dealer.hand) < 17: card = self.cardBank.nextCard() print("Dealer got " + str(card)) self.dealer.hand.append(card) for player in self.players: if player.balance > 0: for hand in player.hands: if len(hand) == 0: print(hand) continue print("Player hand: ") print(helpers.printHand(hand)) print("Dealer hand: ") print(helpers.printHand(self.dealer.hand)) if helpers.handSum(self.dealer.hand) > 21: player.winCount += 1 print("Player 1 won") print(player.balance) player.balance += player.bet print(player.balance) print("") break if len(hand) != 0: if helpers.handSum(hand) > helpers.handSum(self.dealer.hand): player.winCount += 1 print(helpers.handSum(hand)) print(helpers.handSum(self.dealer.hand)) print("Player 1 won") print(player.balance) player.balance += player.bet print(player.balance) print("") break else: print("Player 1 lost") print(player.balance) player.balance -= player.bet print(player.balance) print("") break def __cleanUp(self): """ Clean up the board after each play :return: """ for player in self.players: if player.balance > 0: player.resetHand() self.dealer.hand = [] def __payoutSideBet(self): """ Pay out side bet of lucky lucky Using the players 2 cards and dealers top card Payouts: 18 or less loss 19, 20: 2 to 1 21: 3 to 1 21 (Suited): 15 to 1 6,7,8: 30 to 1 7,7,7: 50 to 1 6,7,8 (Suited): 100 to 1 7,7,7 (Suited): 200 to 1 :return: """ dealer_card = self.dealer.getVisibleCard() for player in self.players: if player.balance > 0: player_first_card = player.hands[0][0] player_second_card = player.hands[0][1] suited = False if player_first_card.suit == player_second_card.suit == dealer_card.suit: suited = True if player_first_card.value == player_second_card.value == dealer_card.value == 7: if suited: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got a suited 777") player.balance += player.sideBet * 200 else: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got an unsuited 777") player.balance += player.sideBet * 50 elif player_first_card in [6, 7, 8] and player_second_card in [6, 7, 8] and dealer_card in [6, 7, 8] \ and (player_first_card.value + player_second_card.value + dealer_card.value) == 21: if suited: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got a suited 678") player.balance += player.sideBet * 100 else: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got an unsuited 678") player.balance += player.sideBet * 30 elif (player_first_card.value + player_second_card.value + dealer_card.value) == 21: if suited: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got a suited 21") player.balance += player.sideBet * 15 else: player.sideBetWinCount += 1 print("Player " + str(player.id) + " got an unsuited 21") player.balance += player.sideBet * 3 elif (player_first_card.value + player_second_card.value + dealer_card.value) in [19, 20]: player.sideBetWinCount += 1 print("Player got crap") player.balance += player.sideBet * 2 def validDecision(self, player, decision): """ Make sure the player can make they decision :param player: :param decision: :return: """ return True
else: current_game.outcome = "Dealer wins" dealer.score += 1 if __name__ == '__main__': print(chr(27) + "[2J") print("========================\n" "| Blackjack Assessment |\n" "| By: Joshua Irwin |\n" "========================\n") sleep(1) current_game = Game current_player = Player() dealer = Dealer() deck = Deck() keep_playing = True while keep_playing is True: # Clear the lists in deck to allow past cards to come back into play, essentially reshuffling # the entire deck back into the game. deck.used_card = [] deck.used_suit = [] # Clear each player's hand current_player.hand = [] dealer.hand = [] player_has_bust = False player_dealt_blackjack = False start_round()
def testDealTenToEach(self): dealer = Dealer([Player(0), Player(1), Player(2), Player(3)])
(at your option) any later version. BlackJack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with BlackJack. If not, see <http://www.gnu.org/licenses/>. """ import Player import Dealer ore = Player.Player() omae = Dealer.Dealer() add_draw_p = True add_draw_d = True while True: if add_draw_p: text = input('hit or stay?\n') if text == 'hit': card = ore.deck.draw() ore.hand.add(card.suit, card.rank) print(ore.hand.count()) else: add_draw_p = False if add_draw_d: add_draw_d = omae.play() if (not add_draw_p) and (not add_draw_d): break
# BlackJacGame.py - This file represents the execution of the game BlackJack # Author: Brandon M. Hunter # Created Date: 11.05.2017 import CardDeckService import Dealer import User import time import locale CDS = CardDeckService.CardDeckService() # Build the card deck and shuffle the cards. CDS.BuildCardDeck() CDS.ShuffleCardDeck() DealerUser = Dealer.Dealer() # Intro print("----------------------------------------------------------") print(" Welcome to BlackJack - written in Python - Version 1.0.0") print(" Developed By: Brandon M. Hunter ") print("----------------------------------------------------------") print("") ValidNumberOfPlayersInput = False NumberOfPlayers = 0 ContinuePlay = True while ValidNumberOfPlayersInput == False: try: NumberOfPlayers = int( input( "Hi, my name is Dealer. How many people do we have playing today? " )) except:
from Deck import * from Dealer import * running = True while running: players = [] win_score = 0 winners = [] d = Deck() d.shuffle() dealer = Dealer() print('Welcome to BlackJack.\n') prompt = '' while prompt == '': try: prompt = int(input("How many players? ")) except ValueError: print('Please enter a valid number. \n') num_play = prompt for i in range(num_play): players.append(Player()) print('Dealing hand...') for p in players: p.add_card(d.deal_card())
from flask import Flask, url_for import Buyer, Dealer, Brand, Product app = Flask(__name__) app.config['SECRET_KEY'] = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' @app.route("/") def home(): try: return app.send_static_file("index.html") except Exception as e: return str(e) Buyer.add_routes(app) Dealer.add_routes(app) Brand.add_routes(app) Product.add_routes(app) if __name__ == "__main__": app.run()
class Board(): def __init__(self): self.leaderBoard = [] self.roundStatus = 0 # roundStatus: 0 = round over; 1 = round underway self.playerCount = int(input("Enter the number of Players: ")) self.deckCount = int(input("Enter the number of Decks: ")) self.cardpool = CardPool(self.deckCount) #self.cardpool.showDeck() self.dealer = Dealer() self.players = {} for i in range(0,self.playerCount,1): temp = Player() self.players[temp.name] = temp def GetPlayerSummary(self): for player in self.players: print(self.players[player].GetDetails()) def GetCardPool(self): self.cardpool.ShowDeck() def CheckWin(self): winner = [] for player in self.players: if not self.dealer.CheckBusted(): dealerScore = self.dealer.GetHandDetails()['Points'] if not self.players[player].CheckBusted(): if self.players[player].GetHandDetails()['Points'] >= dealerScore: winner.append(player) # Player is a winner if Neither Player nor Dealer busts and player score >= dealer score else: winner.append(player) # Everyone is a winner if Dealer Busts return winner def DistributeCards(self, noOfCards,player): for i in range(0,noOfCards,1): (marker, cardsPoint) = self.cardpool.AssignCard(player) if player != "Dealer": self.players[player].Play(marker,cardsPoint) else: self.dealer.Play(marker,cardsPoint) def BeginRound(self): self.roundStatus = 1 # Players Dealt and Bet for player in self.players: #deal out cards print("\nNow Dealing:",player) self.DistributeCards(2,player) #print info about cards delt here print(self.players[player].GetHandDetails()) #bet print("\nNow Betting:",player) self.players[player].PlaceBet() # Dealer Dealt print("\nDealer Cards:") self.DistributeCards(2,"Dealer") self.dealer.DealerShow() return 0 def PlayRound(self): # Players Call for player in self.players: print("Playing:",player) while(self.players[player].playState): print(self.players[player].GetHandDetails()) move = int(input("Stand (0) | Hit (1) :")) if move == 1: (marker, cardsPoint) = self.cardpool.AssignCard(player) self.players[player].Play(marker, cardsPoint) else: self.players[player].Play() print("Final Status for "+player+":",self.players[player].GetHandDetails()) return 0 def EndRound(self): self.roundStatus = 0 while(self.dealer.playState): if self.dealer.GetHandDetails()['Points'] >= self.dealer.threshold: self.dealer.playState = False break (marker, cardsPoint) = self.cardpool.AssignCard("Dealer") self.dealer.Play(marker, cardsPoint) print("Final Status for Dealer:",self.dealer.GetHandDetails()) winner = self.CheckWin() print("Winners are:",winner) for player in self.players: self.players[player].RoundEnds(player in winner) self.dealer.RefreshHand() return 0 def UpdateLeaderBoard(self): temp = [] for player in self.players: if self.players[player].GetDetails()['Broke']: temp.append(player) for player in temp: del self.players[player] self.leaderBoard.append(player) def ShowLeaderBoard(self): self.leaderBoard.reverse() for i in range(0,len(self.leaderBoard),1): print("#",i+1,"->",self.leaderBoard[i]) def CheckGameState(self): if len(self.leaderBoard)< self.playerCount: return True else: return False def RefreshCardPool(self): cardPoolStatus = self.cardpool.GetDeck() if len(cardPoolStatus['Unplayed']) < 4*self.playerCount: print("---- Refreshing Card Pool ----") self.cardpool.RefreshPool() return 0
d_hand = ([0, 0]) # initial hands are two-cards p1_hand = ([0, 0]) p2_hand = ([0, 0]) p3_hand = ([0, 0]) p4_hand = ([0, 0]) win_streak = 0 # default last win flag, necessary for one of the strategies # create players Player1 = Player.Player(p1_pot, min_bet, p1_wins, p1_losses, win_streak, profit) Player2 = Player.Player(p2_pot, min_bet, p2_wins, p2_losses, win_streak, profit) Player3 = Player.Player(p3_pot, min_bet, p3_wins, p3_losses, win_streak, profit) Player4 = Player.Player(p4_pot, min_bet, p4_wins, p4_losses, win_streak, profit) Dealer = Dealer.Dealer(d_pot, d_wins, d_losses) # create data structures for output martingale_pot = np.zeros(r) manhattan_pot = np.zeros(r) oscars_pot = np.zeros(r) safe_pot = np.zeros(r) dealers_pot = np.zeros(r) martingale_winloss = np.zeros(r) manhattan_winloss = np.zeros(r) oscars_winloss = np.zeros(r) safe_winloss = np.zeros(r) martingale_streak = np.zeros(r) manhattan_streak = np.zeros(r) oscars_streak = np.zeros(r) safe_streak = np.zeros(r)
def __init__(self, playerName): self.deck = Deck.Deck() self.player = Player.Player(playerName, self.deck.drawCard(), self.deck.drawCard()) self.dealer = Dealer.Dealer(self.deck.drawCard(), self.deck.drawCard())
class Blackjack(object): """ This class controls how the game's logic should flow""" window = Tk() WINDOW_WIDTH = 700 WINDOW_HEIGHT = 700 bWaitingForRound = True bWaitingForNextRound = False bDealerPlaying = False bLooping = True money = 5000 MINIMUM_BET = 20 MAXIMUM_BET = 400 USER_BET = 0 PlayerOne = Player.Player() DealerPlayer = Dealer.Dealer() def on_closing(self): if messagebox.askokcancel("Quit", "Do you really want to quit?" ): self.window.destroy() def CreateWindow(self): self.window.protocol("WM_DELETE_WINDOW", self.on_closing) self.window.resizable(width = False, height = False) self.window.minsize(width = self.WINDOW_WIDTH, height = self.WINDOW_HEIGHT) self.window.title("BlackJack") return True def WaitForNextRound(self): DealButton.place(x = 150, y = 650) DealButton.place(x = 150, y = 650) BetFive.place(x = 450, y = 670) BetTen.place(x = 470, y = 670) BetFifty.place(x = 495, y = 670) BetHundred.place(x = 520, y = 670) ResetBet.place(x = 550, y = 670) StayButton.place_forget() def UpdateCardList(self): PlayerOneRenderList.clear() for cards in self.PlayerOne.hand: PlayerOneRenderList.append(cards.GrabCard(CARD_SHEET)) DealerRenderList.clear() for cards in self.DealerPlayer.hand: if(cards.Visible): DealerRenderList.append(cards.GrabCard(CARD_SHEET)) else: DealerRenderList.append(CARD_BACK) def EndRound(self): if self.DealerPlayer.HasBlackJack(): self.DealerWin() elif self.PlayerOne.HasBlackJack(): self.PlayerWin() elif self.DealerPlayer.Busted() and not self.PlayerOne.Busted(): self.PlayerWin() elif self.PlayerOne.Busted(): self.DealerWin() elif self.DealerPlayer.hand_value == self.PlayerOne.hand_value: self.DealerWin() elif self.DealerPlayer.hand_value < self.PlayerOne.hand_value: self.PlayerWin() else: self.DealerWin() self.bDealerPlaying = False def PlayerWin(self): self.money += self.USER_BET messagebox.showinfo("WIN", "Player Win!\nPlayer: %d\nDealer: %d" % (self.PlayerOne.hand_value, self.DealerPlayer.hand_value)) def DealerWin(self): self.money = self.money - self.USER_BET messagebox.showerror("LOSS", "Dealer Win!\nPlayer: %d\nDealer: %d" % (self.PlayerOne.hand_value, self.DealerPlayer.hand_value)) def Update(self): if self.money <= 0: self.money == 0 messagebox.showerror("Loss", "Game Over") if self.bDealerPlaying: self.DealerPlayer.hand[0].Visible = True if self.DealerPlayer.hand_value < 17: self.DealerPlayer.DealSelf() else: self.EndRound() if self.bWaitingForRound: DealButton.place(x = 150, y = 650) BetFive.place(x = 450, y = 670) BetTen.place(x = 470, y = 670) BetFifty.place(x = 495, y = 670) BetHundred.place(x = 520, y = 670) ResetBet.place(x = 550, y = 670) HitButton.place_forget() StayButton.place_forget() return if self.bWaitingForNextRound: self.WaitForNextRound() return DealButton.place_forget() HitButton.place(x = 150, y = 650) StayButton.place(x = 200, y = 650) def Render(self): self.Clear() canvas.create_image(self.WINDOW_WIDTH / 2, self.WINDOW_HEIGHT / 2, image = BACKGROUND) canvas.create_image(636, 352, image = CARD_BACK) for i in range(0, len(PlayerOneRenderList)): canvas.create_image(350 + (72/ 2 * i), 621, image = PlayerOneRenderList[i]) for i in range(0, len(DealerRenderList)): canvas.create_image(350 + (72 / 2 * i), 66, image = DealerRenderList[i]) self.window.title("Blackjack Bet $%d Balance $%d" % (self.USER_BET , self.money)) self.window.update() def HitPressed(self): if self.PlayerOne.Busted(): return self.DealerPlayer.DealNextCard(player = self.PlayerOne) def Clear(self): canvas.delete("all") def StayPressed(self): self.bDealerPlaying = True self.bWaitingForNextRound = True def DealPressed(self): self.PlayerOne.hand.clear() self.DealerPlayer.hand.clear() if(self.USER_BET < self.MINIMUM_BET): self.USER_BET = self.MINIMUM_BET BetFive.place_forget() BetTen.place_forget() BetFifty.place_forget() BetHundred.place_forget() ResetBet.place_forget() self.DealerPlayer.DealPlayerInitialHand(player = self.PlayerOne) self.DealerPlayer.DealSelf() self.DealerPlayer.hand[0].Visible = False self.DealerPlayer.DealSelf() self.bWaitingForRound = False self.bWaitingForNextRound = False def Bet(self, amount = 20): if(self.USER_BET < self.MAXIMUM_BET): self.USER_BET += amount def ResetBet(self): self.USER_BET = 0 def Initialize(self): global CARD_BACK global CARD_SHEET global BACKGROUND global canvas global PlayerOne global PlayerTwo global DealButton global HitButton global StayButton global ResetButton global BetFive global BetTen global BetFifty global BetHundred global ResetBet global PlayerOneRenderList global DealerRenderList PlayerOneRenderList = [] DealerRenderList = [] canvas = Canvas(self.window, width = self.WINDOW_WIDTH, height = self.WINDOW_HEIGHT) CARD_BACK = PhotoImage(file="back.png") CARD_SHEET = PhotoImage(file="cards.png") BACKGROUND = PhotoImage(file="background.png") HitButton = Button(self.window, text = "Hit", command = self.HitPressed) StayButton = Button(self.window, text = "Stay", command = self.StayPressed) DealButton = Button(self.window, text = "Deal", command = self.DealPressed) BetFive = Button(self.window, text = "5", command = partial(self.Bet, 5)) BetTen = Button(self.window, text = "10", command = partial(self.Bet, 10)) BetFifty = Button(self.window, text = "50", command = partial(self.Bet, 50)) BetHundred = Button(self.window, text = "100", command = partial(self.Bet, 100)) ResetBet = Button(self.window, text = "Reset Bet", command = self.ResetBet) if(not(self.CreateWindow())): return False canvas.create_image(self.WINDOW_WIDTH / 2, self.WINDOW_HEIGHT / 2, image = BACKGROUND) canvas.pack() return True
) print("\t\t\tThe dealer will draw a new card if its score is under 16;") print("\t\t\tThe dealer will stop drawing cards if its score is above 17;") print("\t-5: \tThe players that are bust automatically lose.") print( "\t\tOf the players that are not bust, if the dealer is bust, everyone wins;" ) print("\t\tOf the players that are not bust, if the dealer is not bust:") print("\t\tthe ones with scores higher or equal to the dealer's score win.") print() #initialization #get number of players nb_players = inputNbPlayers() deck = Deck.Deck(nb_players) dealer = Dealer.Dealer() players = [Player.Player() for i in range(nb_players)] human_idx = random.randrange(0, nb_players) print("You are in position ", human_idx, " (starting from 0)!") #getting the bets print("Everyone places a bet:") for i in range(human_idx): bet_amount = random.randrange(1, 99) players[i].hands[0].setBet(bet_amount) print("Player #", str(i), "'s bet is: \t", str(bet_amount)) #getting your bet bet_amount = inputBet() players[human_idx].hands[0].setBet(bet_amount)
#self.visiblecards.append(carddealt) #myhand = self.players[self.myposition][1] #print(myhand) #print(self.visiblecards) return (None) def checkhand(self): myhand = self.players[self.myposition][1] return (myhand) def splitnums(self, playerpos): handnums = [] for val in self.players[playerpos][1]: num, suit = val.split('-') handnums.append(num) return (handnums) def hit(self, playerpos): self.players[playerpos][1].append(self.dealer.DealCards(1)) #return(card) #test2 pass if __name__ == '__main__': deckqty = '5' dealer = D.Shuffle(deckqty) #for h in hand: # num,lost = h.split('-') # number = np.append(number,num)