def SetUpPlayer(self): self.nPlayer = int(input("幾位玩家?(1 or 2) ")) i = 0 while i < self.nPlayer: print("輸入玩家暱稱: ", end='') playerName = input() self.playerList.append(Player(name=playerName)) i += 1 self.dealer = Dealer(name="莊家") self.Play()
def test_01(self): # Set up presetCards = [Card(3, 1), Card(2, 11), Card(1, 10)] deck = Deck(presetCards=presetCards) player = Player() dealer = Dealer() # run player.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) player.SaveACard(deck.DealACard()) # check self.assertTrue(player.blackJack) self.assertTrue(dealer.safe)
def test_04(self): # Set up presetCards = [Card(3, 8), Card(2, 5), Card(2, 8), Card(3, 9), Card(0, 6)] deck = Deck(presetCards=presetCards) player = Player() dealer = Dealer() # run player.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) player.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) player.SaveACard(deck.DealACard()) # check self.assertTrue(player.burst) self.assertTrue(dealer.safe)
def test_05(self): # Set up presetCards = [Card(3, 8), Card(2, 5), Card(2, 8), Card(3, 9), Card(0, 6)] deck = Deck(presetCards=presetCards) player = Player() dealer = Dealer() # run player.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) player.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) dealer.SaveACard(deck.DealACard()) # check self.assertEqual(player.totalPoints, 16) self.assertEqual(dealer.totalPoints, 20)
def __init__(self): self.deck = Deck() self.bots = [] self.total_players = [] self.not_stand_players = [] self.starting_player_money = 200 self.min_bet, self.max_bet = 1, 20 self.max_bots_allowable = 6 self.player, self.dealer = RealPlayer(self.starting_player_money), Dealer()
def playgame(): dealer = Dealer() table = Table(1,400,dealer) deck = (table.get_dealer().loaddeck()) choose_number_of_players(table) input("START GAME (enter)") count = 0 for player in table.get_currently_playing(): for i in range(0,2): clear() table.print_properties() if count >= 1: print("Player {} cards:".format(count)) table.get_player_nr(count-1).printhand() print("Player {} cards:".format(count+1)) dealer.deal_card(table.get_player_nr(count), deck, table, i) player.printhand() time.sleep(1) count+=1
def initGame(playCount,botCount,deckN,scrn,showCount,startCash): ''' Initializes game and deck according the the game optons Args: playCount - number of players botCount - number of bots deckN - number of decks scrn - screen to be drawn onto showCount - whether or not card count is to be displayed startCash - starting player money ''' #reinitialize variables if we already played if len(playList) != 0: pCards.pop() #need extra pop because it is 1 longer for i in range(len(playList)): playList.pop() pCards.pop() deckNum = deckN #init dealer object dealer = Dealer() #append him to the his position of 0 pCards.append(cardPile(0)) #reinitialize screen options if len(screenOp) >= 2: screenOp[1] = showCount else: screenOp.append(scrn) screenOp.append(showCount) #init the deck deck = Deck() #init deck deck = initDeck(deck,deckN) #init players for i in range(playCount): player = Player(i) cPile = cardPile(i+1) player.money = startCash playList.append(player) pCards.append(cPile) updateStats(player,deck) # init bots for i in range(botCount): bot = Player(i+playCount,True) cPile = cardPile(i+playCount+1) bot.money = startCash playList.append(bot) pCards.append(cPile) updateStats(bot,deck) return (deck,dealer)
class Game: def __init__(self): self.playerList = [] # playerList可顯示最後result的清單,可保持原本玩家順序,以及拿來reset self.removeList = [] # 沒有籌碼的人將被剔除 # 透過seed可以控制Deck的隨機種子 def Run(self, seed=None, presetCards=None): nDeck = int(input("使用幾副牌? ")) # For test_black_jack if presetCards is not None: self.deck = Deck(nDeck=nDeck, presetCards=presetCards) elif seed is not None: self.deck = Deck(nDeck=nDeck, seed=123) else: self.deck = Deck(nDeck=nDeck) self.SetUpPlayer() def SetUpPlayer(self): self.nPlayer = int(input("幾位玩家?(1 or 2) ")) i = 0 while i < self.nPlayer: print("輸入玩家暱稱: ", end='') playerName = input() self.playerList.append(Player(name=playerName)) i += 1 self.dealer = Dealer(name="莊家") self.Play() def Play(self): # ----------------------------------------------------------- # 檢查是否有足夠玩家 self.DeletePlayer() if len(self.playerList) == 0: print("---------------------------------------------") print("Game over") # 下注籌碼 self.DealMoney() # ----------------------------------------------------------- # Round 1 self.DealCard() # Round 2 self.DealCard() self.InsuranceCheck() # Player hit card or stand self.HitCard() # ----------------------------------------------------------- # Compute result self.CompareWithDealer() self.ShowResult() self.AskPlayAgain() def DealMoney(self): for player in self.playerList: print("{0}, 請輸入下注金額: ".format(player.name), end='') ans = int(input()) while ans > player.totalCash or ans <= 0: print("下注金額應大於零,但不可大於現有籌碼,請重新輸入") print("{0}, 請輸入下注金額: ".format(player.name), end='') ans = int(input()) # Set Cash player.gambleCash = ans player.totalCash -= player.gambleCash def DealCard(self): for player in self.playerList: player.SaveACard(self.deck.DealACard()) player.Dump() self.ShowPlayerStatus(player) self.dealer.SaveACard(self.deck.DealACard()) self.dealer.Dump() sleep(5) print("---------------------------------------------") def HitCard(self): print("加牌階段") AllBurst = True for player in self.playerList: while player.safe and player.WantOneMoreCard( ) and self.deck.HasMoreCard(): player.SaveACard(self.deck.DealACard()) player.Dump() sleep(5) if player.safe: AllBurst = False print("---------------------------------------------") self.ShowPlayerStatus(player) # Deal hit condition: status pass, poinnts < 17, deck has more card, still have alive player while not AllBurst and self.dealer.safe and self.dealer.WantOneMoreCard( ) and self.deck.HasMoreCard(): self.dealer.SaveACard(self.deck.DealACard()) self.dealer.Dump() sleep(5) print("---------------------------------------------") def CompareWithDealer(self): # 先篩選莊家爆牌 if self.dealer.burst: for player in self.playerList: if player.burst: continue player.win = True # 先跟莊家比大小確定勝負或平手 else: for player in self.playerList: if player.burst: continue if self.dealer.totalPoints > player.totalPoints: player.win = False continue elif self.dealer.totalPoints == player.totalPoints: player.push = True player.win = False continue else: player.win = True # 算錢 for player in self.playerList: if player.blackJack and player.win: player.totalCash += player.gambleCash * 2.5 # 拿回賭金+獎金 (1+1.5) player.result = "籌碼增加" + str(player.gambleCash * 2.5) continue elif player.win: player.totalCash += player.gambleCash * 2 player.result = "籌碼增加" + str(player.gambleCash * 2) continue elif player.push: player.totalCash += player.gambleCash player.result = "和局" continue elif not player.win or player.burst: player.result = "籌碼損失 " + str(player.gambleCash) def ShowResult(self): self.dealer.Dump(show=True) if self.dealer.burst: print("{0} 爆牌, 所有剩餘玩家獲勝".format(self.dealer.name)) print("---------------------------------------------") for player in self.playerList: print("{0} 本局結果: {1}".format(player.name, player.result)) print("{0} 剩餘籌碼: {1}".format(player.name, player.totalCash)) def ShowPlayerStatus(self, player): if player.blackJack: print("{0} 二十一點!!!".format(player.name)) elif player.burst: print("{0} 爆牌!!!".format(player.name)) def DeletePlayer(self): # 刪除沒有籌碼的人 for player in self.playerList: if player.totalCash == 0: self.removeList.append(player) for removePlayer in self.removeList: if removePlayer in self.playerList: self.playerList.remove(removePlayer) def AskPlayAgain(self): print("---------------------------------------------") print("要再玩一局嗎?(y/n)") ans = input() if ans.lower() == "y": # Reset Game for player in self.playerList: player.Reset() self.dealer.Reset() # Play again self.Play() else: print("---------------------------------------------") print("Game over") def InsuranceCheck(self): if self.HasInsuranceSituation(): for player in self.playerList: print("{0}, 是否要保險? (y/n)".format(player.name)) ans = input() if ans.lower() == "y": if not self.dealer.blackJack: player.gambleCash /= 2 return def HasInsuranceSituation(self): pt = self.dealer.hand[1].rank if self.dealer.hand[1].rank > 10: pt = 10 return pt == 1 or pt == 10
assign_cards() show_cards(list(players.values())) for player in players.values(): if not player.black_jack and not player.bust: print(game_interface()) print( f"{player.name}, Your turn. Your cards are shown below. Remember your cards" ) print( merge_graphics([card_grapics(x, "\t\t") for x in player.cards])) player_turn(player) if player_left(): dealer_turn() else: print("No player left... resetting game") rst_players() sleep(3) refresh() print_money() deck = load_cards() play_game() if __name__ == "__main__": players = {} sam = Dealer("sam") deck = load_cards() load_players() print("All of you get $100 each") play_game()
def Game(Shuffle_Req=52): Game_Play=True while Game_Play: print "Do you want to start a game" print "1. Yes" print "2. No" Game_Play_Choice=raw_input("Enter number corresponding to your choice") GPC=int(Game_Play_Choice) if GPC!=1: Game_Play=False break if GPC==1: Deck=GameDeck(4) Deck.shuffle_game_deck() players=[] number_of_players=raw_input("Number of Players") NUM_Players=int(number_of_players) Game_Number=1 d=0 v=0 while d < NUM_Players*5: if d%5==0: v=v+1 h=d+1 players.append(Player()) players[d].key=v extra=1 print "Player %d" %players[d].key d=d+1 ##this was coded to allow keeping track of total gains and losses for a given player. Tack can still be kept without the below statments and each player is assumed to stat with zero ## Cash_Available=raw_input("Amount of Cash") ## Bet=raw_input("Place bet") ## players[d-1].cash=int(Cash_Available) continue ## the next couple lines are used to set up set up places for split hands. Up to four split hands are allowed. else: e=d%5 players.append(Player()) players[d].key=v players[d].playing_status=False players[d].turn_status=False players[d].Hand_number=e d=d+1 continue GameDealer=Dealer() while len(Deck.Available_Cards)>Shuffle_Req: #asks players for they bets z=0 while z<NUM_Players*5: if z%5==0: print "Player %d" %players[z].key Bet=raw_input("Place bet") players[z].bet=int(Bet) z=z+1 else: z=z+1 #establishes game dealers hand GameDealer.Get_Cards(Deck) players.append(GameDealer) #deals each player 2 cards for i in range(len(players)-1): if players[i].playing_status==True: players[i].Get_Cards(Deck) else: continue #Here is where players take their turns. Players ability to split and double down are limited to situations when their active hand is of size 2 # splitting and doubline down are allowed after hands are split only on the turn were the split hand is of size 2 #Also the system returns your array of hand values. #one a play has been made, surrendering is not allowed for that player during a given round #Ability to make decisions (split, hit, double down, stand, surrender) are determined the attributtes Split_stats, Hit_status, Double_Down_status, Stand_status, and Surrender print "Game starts now" for i in range(len(players)-1): while players[i].turn_status==True and players[i].playing_status==True and players[i].Bust_status==False: print "Player %d turn" %players[i].key print "Hand %d" %(players[i].Hand_number) players[i].Print_Hand() print players[i].hand_value if len(players[i].hand)==2: players[i].Double_Down_status=True players[i].Split_status=True else: players[i].Double_Down_status=False players[i].Split_status=False if players[i].Hit_status==True: print "1. Hit" if players[i].Double_Down_status==True: print "2. Double Down" if players[i].Surrender_status==True: print "3. Surrender" if players[i].Stand_status==True: print "4. Stand" if players[i].Split_status==True: print "5. Split" choice_number=raw_input("Enter choice") choice=int(choice_number) if choice==1 and players[i].Hit_status==True: print players[i].Print_Hand() players[i].Hit(Deck,1) elif choice==2 and players[i].Double_Down_status==True: players[i].Double_Down(Deck,1) elif choice==3 and players[i].Surrender_status==True: players[i].Surrender() elif choice==4 and players[i].Stand_status==True: players[i].Stand() elif choice==5 and players[i].Split_status==True and len(players[i].hand)==2 and players[i].hand[0].card_value==players[i].hand[1].card_value: x=1 while(x<5): if players[i+x].playing_status==False and players[i+x].key==players[i].key: players[i+x].playing_status=True players[i+x].turn_status=True players[i+x].hand.append(players[i].hand.pop()) players[i+x].bet=players[i].bet players[i].Surrender_status=False players[i+x].Surrender_status=False if players[i].hand[0].card_value[0]==players[i].hand[0].card_value[1]: players[i].hand_value=[] players[i+x].hand_value=[] players[i].hand_value.append(players[i].hand[0].card_value[0]) players[i+x].hand_value.append(players[i].hand[0].card_value[0]) else: players[i].hand_value=players[i].hand[0].card_value players[i+x].hand_value=players[i].hand[0].card_value break else: x=x+1 continue else: continue continue #Here we establish that the dealer will stand on hard 17, 18, hard 18, and higher and hit on everything else Dealer_Hit=True while(Dealer_Hit==True): print "Dealer Hand" players[len(players)-1].Print_Hand() if all(soft_17<17 for soft_17 in players[len(players)-1].hand_value) and players[len(players)-1].Best_Value()<=17: players[len(players)-1].Hit(Deck) else: Dealer_Hit=False break if all(card_values>21 for card_values in players[i].hand_value): players[i].Bust_status=True #Here we establish the rules of winning and loosing. Ties are pushed. Wins with blackjack are returned with 1.5 the bet value. Losses result in losses of the bet value. for i in range(len(players)-2): if i%5==0: split_hands=0 while split_hands<5: if players[i+split_hands].playing_status==True: if players[i+split_hands].Bust_status==True: players[i].cash-=players[i+split_hands].bet players[len(players)-1].cash+=players[i+split_hands].bet players[i+split_hands].bet=0 print "Player %d lost on hand %d" %(players[i+split_hands].key, players[i+split_hands].Hand_number) elif players[i+split_hands].Bust_status==False and players[len(players)-1].Bust_status==True: if players[i+split_hands].Best_Value()==21 and len(players[i+split_hands].hand)==2: players[i+split_hands].bet=players[i+split_hands].bet*1.5 players[i].cash+=players[i+split_hands].bet players[len(players)-1].cash+=players[i+split_hands].bet players[i+split_hands].bet=0 print "Player %d won on hand %d" %(players[i+split_hands].key, players[i+split_hands].Hand_number) elif players[i+split_hands].Bust_status==False and players[len(players)-1].Bust_status==False: players[i+split_hands].hand_value.sort() players[len(players)-1].hand_value.sort() if players[i+split_hands].Best_Value()<players[len(players)-1].Best_Value(): players[i].cash-=players[i+split_hands].bet players[len(players)-1].cash-=players[i+split_hands].bet players[i+split_hands].bet=0 print "Player %d lost on hand %d" %(players[i+split_hands].key, players[i+split_hands].Hand_number) elif players[i+split_hands].Best_Value()>players[len(players)-1].Best_Value(): if players[i+split_hands].Best_Value()==21 and len(players[i+split_hands].hand)==2: players[i+split_hands].bet=players[i+split_hands].bet*1.5 players[i].cash+=players[i+split_hands].bet players[len(players)-1].cash+=players[i+split_hands].bet players[i+split_hands].bet=0 print "Player %d won on hand %d" %(players[i+split_hands].key, players[i+split_hands].Hand_number) elif players[i+split_hands].Best_Value()==players[len(players)-1].Best_Value(): players[i+split_hands].bet=0 print"Player %d pushed on hand %d" %(players[i+split_hands].key, players[i+split_hands].Hand_number) split_hands=split_hands+1 continue #shows the players what there total gains/losses are at the end of each round for i in range(len(players)-1): if i%5==0: print "Players %d Cash" %players[i].key print players[i].cash #gets the players ready for the next round by setting statuses back to default. for i in range(len(players)-1): players[i].bet=0 players[i].hand=[] players[i].hand_value=[0] players[i].turn_status=True players[i].playing_status=True players[i].Bust_status=False players[i].Hit_status=True players[i].Double_Down_status=True players[i].Surrender_status=True players[i].Stand_status=True if i%5!=0: players[i].playing_status=False players[i].turn_status=False players.pop() GameDealer.hand=[] GameDealer.hand_value=[0] Game_Number=Game_Number+1 continue
def __init__(self, player_name, decks_used=4): self.players = [Player(player_name)] self.dealer = Dealer() self.number_of_decks = decks_used self.card_pool = CardPool(number_of_decks=decks_used) self.used_card_pool = []
class Table: def __init__(self, player_name, decks_used=4): self.players = [Player(player_name)] self.dealer = Dealer() self.number_of_decks = decks_used self.card_pool = CardPool(number_of_decks=decks_used) self.used_card_pool = [] def deal_top(self, player): """Takes the top card in the cardpool and gives it to the player received Input: Player Output: None """ player.add_card_to_hand(self.card_pool.remove_top_deck()) def play_round(self): """Plays all the actions since the start of the betting phase for all players in the game Input: None Output: None""" playing_players = self.enter_bets() self.give_cards() for player in self.players: if player.name in playing_players: self.play_hand(player) def play_hand(self, player): """Let's a player choose its actions to play a hand of blackjack once the bets have been made and the cards have been given to each player Input: Player Output: None""" if not player.has_blackjack(): while player.get_hand_value() <= 21: self.print_current_state(player, sd=False) action = player.get_action() if action == 'Hit': self.deal_top(player) if action == 'Stand': break if action == 'Split': pass if action == 'Double': player.stack -= player.amount_bet player.amount_bet *= 2 self.deal_top(player) break # If player did not bust dealer plays if (player.get_hand_value() <= 21): self.dealer_plays() self.print_current_state(player, sd=True) self.declare_winner(player) self.reset_table() print(self.players[0]) def reset_table(self): """Clears all players and dealer hands storing their contents on Self.UsedCards and adds those cards back to the cardpool and reshuffles if the 65% of the deck has been gone through""" # Clear dealers hand storing used cards on a list while self.dealer.hand: self.used_card_pool.append(self.dealer.hand.pop(0)) # Clear all players hands storing used cards on a list for player in self.players: while player.hand: self.used_card_pool.append(player.hand.pop(0)) # If we're reaching certain depth on our cardpool we add the used cards back to it and then reshuffle the deck if len(self.card_pool.cards) < self.number_of_decks * 52 * 0.65: self.card_pool.add_cards(self.used_card_pool) self.card_pool.shuffle_cards() def dealer_plays(self): """ While the dealer has exceeded 17 the dealer keeps dealing cards to him """ while self.dealer.get_hand_value(showdown=True) < 17: self.deal_top(self.dealer) def declare_winner(self, player): """ Checks if the player or the dealer won, giving the player a reward acording to it bet, except on a natural 21 where the reword follows a 2:1 ratio :param player: Indicate the player that we have to check against the dealer """ if player.has_blackjack(): print(f"BLACKJACK! Player wins!{player.amount_bet * 2}\n") player.stack += player.amount_bet * 3 elif player.get_hand_value() > 21: print('BUSTED, HOUSE WINS!\n') elif self.dealer.get_hand_value(showdown=True) > 21: print('DEALER BUSTED, PLAYER WINS!\n') player.stack += 2 * player.amount_bet elif player.get_hand_value() > self.dealer.get_hand_value( showdown=True): print('PLAYER IS CLOSER TO 21, PLAYER WINS!') player.stack += 2 * player.amount_bet elif self.dealer.has_blackjack(): print('DEALER HAS BLACKJACK, HOUSE WINS!') elif self.dealer.get_hand_value( showdown=True) == player.get_hand_value(): print('PUSH! PLAYER GETS BACK ITS BET') player.stack += player.amount_bet else: print('DEALER IS CLOSER TO 21, HOUSE WINS!') def print_current_state(self, player, sd=False): """Print both Dealers and player recieved as a parameter hands Input: Player Output: None""" self.dealer.show_hand(showdown=sd) player.show_hand(bet=True) def give_cards(self): """Gives every player 2 initial hole cards and 2 cards for the dealer""" # Cards for players for player in self.players: self.deal_top(player) self.deal_top(player) # Cards for the Dealer self.deal_top(self.dealer) self.deal_top(self.dealer) def enter_bets(self): """We ask for every player player if they want to play the hand and how much would they like to bet""" all_bets = {} for player in self.players: bet = player.input_bet_amount() all_bets[player.name] = bet player.amount_bet = bet return all_bets