def test_1(self): data = open("test.txt", "r").read().split("\n\n") game = Cards() game.deal(data) game.play() self.assertEqual([3, 2, 10, 6, 8, 5, 9, 4, 7, 1], game.winner) self.assertEqual(306, game.score())
def BlackjackGame(): # make the 2 players playerscore = 0 dealerscore = 0 deckPlayer = BlackjackHand() # make empty deck deckDealer = BlackjackHand() deck = Cards() def makeDeck(): deckType = input( "Deck type - Enter 1 for regular deck or 2 for 6-deck shoe:") while deckType not in "2" and deckType not in "1": deckType = input("Please enter either 1 or 2." ) #Makes the deck based on user's choice of deck deckType = int(deckType) if deckType == 1: for suit in ['h', 'd', 's', 'c']: for rank in [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K' ]: c = BlackjackCard(rank, suit) deck.add(c) deck.shuffle() if deckType == 2: for i in range(6): for suit in ['h', 'd', 's', 'c']: for rank in [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K' ]: c = BlackjackCard(rank, suit) deck.add(c) deck.shuffle() makeDeck() print("Welcome to Blackjack!!") #Initial welcoming and name def name(): time.sleep(0.5) name = input("What is your name?") print("Hi", name + "!") time.sleep(0.5) return name name = name() def bet(): # find out how much money the player would like to bet. bet = input("How much money do you want to bet every round?") while not bet.isnumeric(): bet = input( "How much money would you like to bet? Please enter a valid integer." ) bet = int(bet) return bet bet = bet() amount = 0 - bet #takes away bet from money player = BlackjackPlayer(str(name), amount) dealer = BlackjackDealer("Dealer", amount) def rounds(): #asks how many rounds to play rounds = input("How many rounds would you like to play?") while not rounds.isnumeric(): rounds = input( "How many rounds would you like to play? Please enter a valid integer." ) return rounds rounds = rounds() for round in range(1, (int(rounds) + 1)): print("* SHUFFLING NEW DECK *") deck.shuffle() dealer.tossHand() # reset the hands from old round if applicable player.tossHand() deckPlayer = BlackjackHand() # make empty hand deckDealer = BlackjackHand() naturalwin = False win = False tie = False def dealCards( ): # deal cards at the beginning of every round to the player and dealer. print("Round [", round, "] Score: Dealer", dealerscore, "vs.", name, playerscore) for i in range(2): v = deck.deal() deckPlayer.add(v) player.addCard(deckPlayer) v = deck.deal() deckDealer.add(v) dealer.addCard(deckDealer) return v v = dealCards() print("Your hand:", deckPlayer) # Inform the player of their hand print("Dealer's hand:", dealer.initialDisplay()) # reveal one card of the dealer if (deckPlayer.getTotalWithAce() ) == 21: # decide if dealer of player has a natural 21 print(name + ":", deckPlayer, "=> Natural 21!") win = True naturalwin = True elif (deckDealer.getTotalWithAce()) == 21: win = False print(name + ":", deckPlayer, "=> ", deckPlayer.getTotalWithAce()) else: totalDealer = deckDealer.getTotalWithAce() print(name + ":", deckPlayer, "=> ", deckPlayer.getTotalWithAce()) while not deckPlayer.bust() and not deckDealer.bust( ) and deckDealer.getTotalWithAce( ) <= 21 and deckPlayer.getTotalWithAce() <= 21 and not naturalwin: t = player.askHit(v) # Asks if the player would like to hit if t == True: v = deck.deal() deckPlayer.add(v) player.addCard(deckPlayer) newPTotal = deckPlayer.getTotalWithAce( ) # New Player total after hitting print(name + ":", deckPlayer, ":", newPTotal) if newPTotal > 21: win = False elif t == False: startDealer = deckDealer.getTotalWithAce() print("Dealer:", deckDealer, "=>", startDealer) #Dealer side nDealer = deckDealer.getTotalWithAce() while nDealer < 17: v = deck.deal() deckDealer.add(v) dealer.addCard(deckDealer) nDealer = deckDealer.getTotalWithAce() print("Dealer: ", deckDealer, "=>", nDealer) break def decideWinner(win, tie): # figures out who won FinalPlayer = deckPlayer.getTotalWithAce() FinalDealer = deckDealer.getTotalWithAce() if FinalPlayer > FinalDealer and FinalPlayer <= 21: print("Yay!! You won this round.", FinalPlayer, "vs.", FinalDealer) win = True elif FinalDealer > 21: print("The Dealer busts with " + str(FinalDealer) + ". You win!") win = True elif int(FinalPlayer) == int(FinalDealer) and not naturalwin: print("Push: You tied with the Dealer.", FinalPlayer, "vs.", FinalDealer) tie = True elif FinalDealer == 21: print("Dealer has 21: You Lose", FinalPlayer, "vs.", FinalDealer) win = False elif FinalPlayer < 21 and FinalDealer < 21 and FinalDealer > FinalPlayer: print("Ooops! you lost this round. Better luck next time.") win = False elif FinalPlayer > 21: print("Oops, you busted,", FinalPlayer, " the dealer wins.") return (win, tie) (win, tie) = decideWinner(win, tie) if tie: if playerscore == 1: player.addMoney( bet) #players bet is given back, nothing lost or gained elif win: playerscore += 1 # figure out the player score if naturalwin: player.addMoney(bet + bet * 1.5) # Adds or takes away money print("You won extra from your natural 21 ${}".format(bet * 1.5)) else: if playerscore == 1: player.addMoney(bet * 2) else: player.addMoney(bet) print("You won ${}".format(bet)) else: dealerscore += 1 player.addMoney(-bet) print("You lost ${}".format(bet)) print("") time.sleep(1) def finalPrint( name, playerscore ): # print out final standings for the player (money, score) print("------------------------------------- ") print("| Final Score: Dealer", dealerscore, "vs.", name, playerscore, "|") if player.money < 0: print("| You ended with: -${} |".format( abs(player.money))) else: print("| You ended with: ${} |".format(player.money)) print("------------------------------------- ") finalPrint(name, playerscore)
class Game(): """ GAME - class class implements UI for videopoker in pygame. """ def __init__(self): """ INIT """ # pygame - setup pygame.init() self.FPS = 30 self.clock = pygame.time.Clock() self.size = (600, 500) self.center = (300, 250) self.screen = pygame.display.set_mode(self.size) self.card_imgs= [] self.balance = 100 self.bet_amount = 5 self.cm = Cards() self.reset() self.key_pressed = "stop" self.key_pressed_hold = "" self.player_rect_clip = pygame.Rect(0, 0, 75, 100) self.stage = 0 self.step = 0 self.last_mouse = (0, 0) # set up fonts self.basicFont = pygame.font.SysFont(None, 48) self.subFont = pygame.font.SysFont(None, 24) self.subsubFont = pygame.font.SysFont(None, 12) self.card_layout_play() def card_layout_play(self): self.card_rects = [] self.card_rects.append(pygame.Rect(20, 10, 75, 100)) self.card_rects.append(pygame.Rect(20, 105, 75, 100)) self.card_rects.append(pygame.Rect(20, 200, 75, 100)) self.card_rects.append(pygame.Rect(20, 295, 75, 100)) self.card_rects.append(pygame.Rect(20, 390, 75, 100)) self.deal_rect = pygame.Rect(200, 200, 75, 100) self.deal_card = pygame.transform.scale(pygame.image.load("cards/deal.png"),(72, 90)) self.bet_rect = pygame.Rect(200, 105, 75, 100) self.bet_card = pygame.transform.scale(pygame.image.load("cards/5coin.png"),(72, 90)) self.help_rect = pygame.Rect(200, 10, 75, 100) self.help_card = pygame.transform.scale(pygame.image.load("cards/help.png"),(72, 90)) def reset(self): """ RESET """ self.deck = self.cm.shuffledeck(self.cm.opendeck()) # for testing, call for particular hands: # self.deck = self.cm.test_hand("four of a kind") self.card_imgs=[] for i in range (0,5): self.card_imgs.append(pygame.transform.scale(pygame.image.load("cards/back.png"),(72, 90))) self.hand =[None,None,None,None,None,] self.card_locks = [False, False, False, False, False] self.message = 'Set bet and click deal.' def handle_events(self): """ HANDLE EVENTS - keys and mouse clicks """ for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: self.key_pressed = "esc" elif event.key == pygame.K_F1: self.key_pressed = "help" elif event.key == pygame.K_SPACE: self.key_pressed = "space" else: pass if event.type == pygame.MOUSEBUTTONUP: self.last_mouse = event.pos self.key_pressed_hold = self.key_pressed self.key_pressed = "mouse" def cardN_button(self,n): """ CARD pressed - flip card """ if self.step == 2 or self.step == 0: pass else: if self.hand[n].is_dealt: self.card_imgs[n] = pygame.transform.scale(pygame.image.load("cards/"+self.hand[n].display+".png"),(72, 90)) self.card_locks[n] = True self.hand[n].is_dealt = False else: self.card_imgs[n] = pygame.transform.scale(pygame.image.load("cards/back.png"),(72, 90)) self.card_locks[n] = False self.hand[n].is_dealt = True def score_hand(self): """ SCORE HAND """ vodds = vp_odds() x,s = vodds.calculate_payout(self.hand, self.bet_amount) self.message = s + ' pays: $'+ str(x) return x def deal_tapped(self): """ DEAL button tapped. """ if self.step == 2: self.reset() self.step = 0 self.message = 'Set bet, press deal.' else: self.step += 1 self.message = 'Pick, and deal.' hand = self.cm.deal(5,self.deck) for i in range(0,5): if not self.card_locks[i]: self.hand[i] = hand[i] self.card_imgs[i] = pygame.transform.scale(pygame.image.load("cards/"+hand[i].display+".png"),(72, 90)) self.card_locks = [True, True, True, True, True] if self.step == 2: self.balance += self.score_hand() if self.balance <= 0: self.stage = 3 def bet_next(self): """ BET changed """ if self.step !=0: return if self.bet_amount == 5 : self.bet_amount = 10 self.bet_card = pygame.transform.scale(pygame.image.load("cards/10coin.png"),(72, 90)) elif self.bet_amount == 10: self.bet_amount = 20 self.bet_card = pygame.transform.scale(pygame.image.load("cards/20coin.png"),(72, 90)) elif self.bet_amount == 20: self.bet_amount = 5 self.bet_card = pygame.transform.scale(pygame.image.load("cards/5coin.png"),(72, 90)) else: pass def draw_stage1(self): """ DRAW STAGE 1 - Play Screen """ self.screen.fill(BLUE) for i in range(0, len(self.card_imgs)): self.screen.blit(self.card_imgs[i], self.card_rects[i], self.player_rect_clip) self.screen.blit(self.deal_card, self.deal_rect, self.player_rect_clip) self.screen.blit(self.bet_card, self.bet_rect, self.player_rect_clip) self.screen.blit(self.help_card, self.help_rect, self.player_rect_clip) for i in range(0, len(self.card_imgs)): if self.card_rects[i].collidepoint(self.last_mouse): self.cardN_button(i) self.last_mouse = (-1, -1) break if self.deal_rect.collidepoint(self.last_mouse): self.last_mouse = (-1, -1) self.deal_tapped() if self.bet_rect.collidepoint(self.last_mouse): self.last_mouse = (-1, -1) self.bet_next() if self.help_rect.collidepoint(self.last_mouse): self.last_mouse = (-1, -1) self.key_pressed ="help" self.stage1_text = self.basicFont.render(self.message, True, WHITE, BLUE) textRect = self.stage1_text.get_rect() textRect.x = 220 textRect.y = 320 self.screen.blit(self.stage1_text, textRect) balance = "Current balance is: " + str(self.balance) balance_text = self.subFont.render(balance, True, WHITE, BLUE) textRect = self.stage1_text.get_rect() textRect.x = 220 textRect.y = 400 self.screen.blit(balance_text, textRect) def draw_stage0(self): """ DRAW STAGE 0 - Title/Splash """ # set up the text self.stage0_text = self.basicFont.render('Welcome to Video Poker', True, WHITE, BLACK) self.stage0_subtext1 = self.subFont.render('Press SPACE to Continue', True, WHITE, BLACK) self.stage0_subtext2 = self.subFont.render('F1 for help Or ESC to exit', True, WHITE, BLACK) self.screen.fill(BLACK) if self.key_pressed == "space": self.stage = 1 textRect = self.stage0_text.get_rect() textRect.center = self.center textRect.centery -= 150 self.screen.blit(self.stage0_text, textRect) textRect.centery += 50 self.screen.blit(self.stage0_subtext1, textRect) textRect.centery += 20 self.screen.blit(self.stage0_subtext2, textRect) def draw_stage2(self): """ DRAW STAGE 2 - Help """ # set up the text self.stage2_text = self.basicFont.render('Video Poker - Help', True, WHITE, GREEN) self.stage2_subtext1 = self.subFont.render('Press SPACE to Continue', True, WHITE, BLACK) self.screen.fill(GREEN) if self.key_pressed == "space": self.stage = 1 textRect = self.stage2_text.get_rect() textRect.center = self.center textRect.centery -= 200 self.screen.blit(self.stage2_text, textRect) sub_text = "Press SPACE to Play" xtext_rect = self.subFont.render(sub_text, True, WHITE, GREEN) sub_text_rect = xtext_rect.get_rect() sub_text_rect.center = self.center sub_text_rect.centery -= 175 self.screen.blit(xtext_rect, sub_text_rect) # get the list of odds from the odds machine v = vp_odds() odds = v.list_odds() for i in range(0, len(odds)): text = odds[i] xtext = self.subFont.render(text, True, WHITE, GREEN) textRect = xtext.get_rect() textRect.x = 120 textRect.y = 120 + i*30 self.screen.blit(xtext, textRect) def draw_stage3(self): """ DRAW STAGE 3 - Broke """ self.screen.fill(BLUE) if self.key_pressed == "space": self.stage = 1 notes = [] notes.append("You have run out of money!") notes.append("I will credit you 100 dollars.") notes.append("Press space to continue") notes.append("or ESC to return to the title screen") for i in range(0, len(notes)): text = notes[i] xtext = self.subFont.render(text, True, WHITE, BLUE) textRect = xtext.get_rect() textRect.x = 120 textRect.y = 120 + i*30 self.screen.blit(xtext, textRect) self.balance = 100 @staticmethod def main(): x = Game() x.run() def run(self): """ RUN - main loop. """ while True: self.handle_events() if self.key_pressed == "esc" and self.stage == 0: pygame.quit() sys.exit() if self.key_pressed == "esc" and self.stage != 0: self.key_pressed = "none" self.stage = 0 if self.key_pressed == "help" and self.stage !=2: self.direcion = "none" self.stage = 2 if self.stage == 0: self.draw_stage0() elif self.stage == 1: self.draw_stage1() elif self.stage == 2: self.draw_stage2() elif self.stage == 3: self.draw_stage3() else: pass self.clock.tick(self.FPS) pygame.display.update()
def BlackjackGame(): #>>make the 2 players name = input("Welcome to Blackjack! What is your name? ") player = BlackjackPlayer(name, 1) dealer = BlackjackDealer("Dealer", 1) player.money = 1000 #>>get number of rounds roundsin = input("How many rounds would you like to play, {}? ".format( player.name)) #while (ans != 'y' and ans != 'n'): #ans = input("Please answer with either a 'y' for yes or an 'n' for no: ") print() rounds = int(roundsin) #>>checking if player wants to use autoplayer. autoplaying = False betting = False print( "There are two different modes you can use to play this game: Autoplayer or Manual with betting." ) print("Keep in mind that autoplayer mode does not involve money.") autoplayermode = input( "Do you want the computer to automatically play for you? (Autoplayer mode) " ) while (autoplayermode != 'y' and autoplayermode != 'n'): autoplayermode = input( "Please answer with either a 'y' for yes or an 'n' for no: ") print() if autoplayermode == 'y': autoplaying = True elif autoplayermode == 'n': autoplaying = False betting = True #>>game executes itself for specified number if rounds print() if autoplaying: player = BlackjackDealer(name, 1) else: print("You have $1000 to begin with.") print() #>>make a deck of card deck = Cards() # make empty deck #>>number of cards -> to know when to shuffle cardCount = 0 #>>single deck if rounds <= 6: for s in Card.SUIT: for r in Card.RANK: x = BlackjackCard(r, s) deck.add(x) cardCount = 52 #>>6 deck shoe else: for i in range(6): for s in Card.SUIT: for r in Card.RANK: x = BlackjackCard(r, s) deck.add(x) cardCount = 312 deck.shuffle() #print (deck) #>>special deck for testing #deck = Cards() #cardCount = 12345 #deck.add(BlackjackCard('2', 'd')) #deck.add(BlackjackCard('3', 'd')) #deck.add(BlackjackCard('2', 's')) #deck.add(BlackjackCard('3', 's')) #deck.add(BlackjackCard('5', 's')) #deck.add(BlackjackCard('5', 's')) #deck.add(BlackjackCard('A', 's')) #>>number of rounds won by each player playerWin = 0 dealerWin = 0 #>>whether the player has money hasMoney = False #>>starts the game for i in range(rounds): print("***************!ROUND {} of {}!***************".format( i + 1, rounds)) #>>shuffling cards if necessary if cardCount < 15: print("Please wait one moment while the deck is being shuffled...") while (cardCount > 0): cardCount -= 1 deck.deal() for s in Card.SUIT: for r in Card.RANK: x = BlackjackCard(r, s) deck.add(x) deck.shuffle() cardCount = 52 #>>asking betting money valid = False if betting: print("You have ${} now.".format(player.money)) if int(player.money > 0): betting_money = int( input("How much money would you like to bet? ")) if betting_money <= player.money and betting_money > 0: valid = True while (valid == False): betting_money = int( input( '''Please answer with a betting amount less than or equal to ${}. Remember betting value has to be greater than $0. '''.format(player.money))) if betting_money <= player.money and betting_money > 0: valid = True #>>adding first 2 cards to hand player.addCard(deck.deal()) dealer.addCard(deck.deal()) player.addCard(deck.deal()) dealer.addCard(deck.deal()) cardCount -= 4 #print(player) #print(dealer) #>>initial print statements with hand, score print("{}'s Current Score: {}".format(player.name, playerWin)) print("Dealer's Current Score: {}".format(dealerWin)) print(player) #print(player.hand.getTotalWithAce()) visibleDealerCard = str(dealer.hand) print("Dealer: [{} ??]".format(visibleDealerCard[1:3])) #print(dealer) #>>game (checks for blackjack, then does hitting routine) if (player.hand.getTotalWithAce() == 21 and dealer.hand.getTotalWithAce() == 21): print("Push 21 vs. 21") elif (player.hand.getTotalWithAce() == 21): print("Blackjack! {} wins!".format(player.name)) playerWin += 1 if betting: player.money += betting_money elif (dealer.hand.getTotalWithAce() == 21): print("Blackjack! Dealer wins!") dealerWin += 1 if betting: player.money -= betting_money else: #>>to see how far into the game we go continueToDealer = True continueToScore = True #>>player hitting and busting hit = True while (hit): if (player.askHit() == False): hit = False else: cardCount -= 1 player.addCard(deck.deal()) print(player, "=> {}".format(player.hand.getTotalWithAce())) if (player.hand.bust()): print("Dealer wins! {} busts with {}.".format( player.name, player.hand.getTotalWithAce())) dealerWin += 1 if betting: player.money -= betting_money hit = False continueToDealer = False continueToScore = False #>>dealer hitting and busting if (continueToDealer): hit = True while (hit): if (dealer.askHit() == False): hit = False else: cardCount -= 1 dealer.addCard(deck.deal()) print(dealer, "=> {}".format(dealer.hand.getTotalWithAce())) if (dealer.hand.bust()): print("{} wins! Dealer busts with {}.".format( player.name, dealer.hand.getTotalWithAce())) playerWin += 1 if betting: player.money += betting_money hit = False continueToScore = False #>>compare final scores and see who wins! playerTotal = player.hand.getTotalWithAce() dealerTotal = dealer.hand.getTotalWithAce() if (continueToScore): print(player) print(dealer) if playerTotal > dealerTotal: print("{} wins with a total of {} vs {}!".format( player.name, playerTotal, dealerTotal)) playerWin += 1 if betting: player.money += betting_money elif playerTotal < dealerTotal: print("Dealer wins with a total of {} vs {}!".format( dealerTotal, playerTotal)) dealerWin += 1 if betting: player.money -= betting_money else: print("Push! {} vs {}.".format(playerTotal, dealerTotal)) #>>ending: where hands are cleared & all variables are set to be ready for next round player.tossHand() dealer.tossHand() print() #>>checks if player still has money left if betting: if player.money <= 0: hasMoney = False break #>>for manual mode #>>checking betting/money value of player if betting: #>>if the player still has money if player.money > 0: if player.money > 1000: print( "Congratulations! You have earned money! You now have a total of ${}!!!" .format(player.money)) else: print( "Congratulations! You have not lost all of your money! You now have a total of ${}!!" .format(player.money)) #>>printing final scores after all rounds are over! winGame = "" if (playerWin > dealerWin): caps = player.name.upper() winGame = "FINAL SCORE: Dealer {} vs {} {}. {} WINS!!!".format( dealerWin, player.name, playerWin, caps) print() elif (playerWin < dealerWin): winGame = "FINAL SCORE: Dealer {} vs {} {}. DEALER WINS!!".format( dealerWin, player.name, playerWin) print() else: winGame = "FINAL SCORE: Dealer {} vs {} {}. TIE!".format( dealerWin, player.name, playerWin) print() print(">>> {} <<<".format(winGame)) #>>if the player lost all of their money else: print(">>> GAME OVER! You have lost all of your money! <<<") else: #>>for autoplayer mode #>>printing final scores after all rounds are over! winGame = "" if (playerWin > dealerWin): caps = player.name.upper() winGame = "FINAL SCORE: Dealer {} vs {} {}. {} WINS!!!".format( dealerWin, player.name, playerWin, caps) print() elif (playerWin < dealerWin): winGame = "FINAL SCORE: Dealer {} vs {} {}. DEALER WINS!!".format( dealerWin, player.name, playerWin) print() else: winGame = "FINAL SCORE: Dealer {} vs {} {}. TIE!".format( dealerWin, player.name, playerWin) print() print(">>>{}<<<".format(winGame))
if count(player) == 21 or count(dealer) > 21: print("Você venceu!") elif count(dealer) == 21 or count(player) > 21: print("Lamento, você perdeu!") elif count(player) > count(dealer): print("Você venceu!") else: print("Lamento, você perdeu!") while True: if user_input == '0': cards = Cards(2, 2) cards.shuffle() dic_cards = cards.deal() dealer = dic_cards['hands'][0] player_1 = dic_cards['hands'][1] hill = dic_cards['hill'] if count(dealer) <= 10: new_card = hill.pop() dealer.append(new_card) print(dealer[0]) print(player_1) print("Escolha sua jogada:") print("0: abandonar rodada") print("1: mostrar mão") print("2: pedir carta") print("4: sair")
class HoldEmRef: """the successor to the PokerRef class.""" def __init__(self): """initialize all variables""" self.dealer = -1 self.deck = Cards() self.players = [] #this array contains only players, not viewers self.n_play = len(self.players) #number of current players self.cur_player = None #the player on whom the action rests self.min_bet = 0 #the current minimum a player must bet self.pot = 0 #the current value of the pot self.no_raise = 1 #true if the hand has not yet been raised self.calls = 0 #number of current calls ### #public functions ### def set_players(self, players): """players should be an array of types derived from PokerPlayer These should be people sitting at the table, not viewers of the game""" self.players = players self.n_play = len(self.players) def rem_player(self, p): """remove a player from the game""" def get_blinds(self, ante, blind): """get the blinds and ante from the players""" self._init_hand() if ante: for p in self.players: p.payAnte(ante) self.transmit_bet(p, ante) sb = int(round(blind/2.0)) small = self.next_active(self.dealer) self.big_blind = self.next_active(small) if not small.payBlind(sb): raise "blind error" if not self.big_blind.payBlind(blind): raise "blind error" self.transmit_bet(small, sb) self.transmit_bet(self.big_blind, blind) self.min_bet = blind self.cur_player = self.next_active(self.big_blind) def get_next_bet(self): """get the next player's bet""" self.cur_player.transmitBet(self.min_bet - self.cur_player.active_bet) def deal(self): """deal the cards to the players""" for p in self.players: p.re_init() cards = self.deck.deal(self.n_play*2) if self.dealer == -1: #pick a random player self.dealer = self.players[self.deck.randint(0, self.n_play-1)] else: self.dealer = self.next_active(self.dealer) cur_player = self.next_active(self.dealer) for card in cards: cur_player.addCard(card) cur_player = self.next_active(cur_player) ### #private functions ### def _init_hand(self): """reinitialize the values needed for the hand""" self.n_play = len(self.players) self.cur_player = None self.min_bet = 0 self.pot = 0 self.no_raise = 1 self.calls = 0 for p in self.players: p.active = 1 self.active_players = self.n_play def count_active(self): count = 0 for p in self.players: if p.active: count += 1 return count def next_active(self, p): """return the next to play after p""" if not type(3) == type(p): p = p.position p = self.players[(p+1) % self.n_play] while not p.active: p = self.players[(p+1) % self.n_play] return p def transmit_bet(self, player, bet): for p in self.players: p.receiveBet(bet, p.position) def receive_bet(self, bet, player): p = self.players[player] p.active_bet += bet if p.active_bet < self.min_bet and bet != -1: p.active_bet -= bet raise BetTooSmallError if p.active_bet > p.money: p.active_bet -= bet raise BetTooBigError if bet == -1: self._fold(p) elif p.active_bet == self.min_bet: self._call(p, bet) else: self._raise(p, bet) self.transmit_bet(p, bet) self.cur_player = self.next_active(self.cur_player) def _fold(self, player): player.active_bet = 0 player.active = 0 self.active_players -= 1 if not self.active_players: self.endHand() def _call(self, player, bet): """handle a player's call""" self.pot += player.active_bet player.money -= bet self.calls += 1 if self.calls >= self.active_players and not self._big_blind_exempt(): if len(self.comm_cards) == 0: self.deal_comm_cards(3) elif len(self.comm_cards) == 3: self.deal_comm_cards(1) elif len(self.comm_cards) == 4: self.deal_comm_cards(1) else: self.endHand() else: self.get_next_bet() def deal_comm_cards(self, n): pass def _big_blind_exempt(self): """return true if this is the special case where the big blind gets to raise his bet. We already know calls > active_players""" if len(self.comm_cards) == 0\ and self.cur_player.position == self.big_blind.position\ and self.no_raise: return 1 return 0 def _raise(self, player, bet): """handle a player's raise""" self.min_bet = player.active_bet self.pot += bet player.money -= bet self.calls = 0 self.no_raise = 0
class Game: def __init__(self): self.cards = Cards() self.playerCounter = 0 self.player = [None, None, None, None] self.started = 0 self.now_player = 0 self.pass_cnt = 0 self.pre_cards = [] self.game_args = [0, 0, 0] def set_args(self, args): with lock: # 顶大暂不实现 self.game_args = args if dbg: print("设置参数", "方块三" if not args[0] else "随机", "不顶大" if not args[1] else "顶大", "困难" if not args[2] else "简单") def game_over(self, ind): print("winner", ind) for p in self.player: if type(p) == Player: p.game_over(ind) self.started = 0 def next_player(self, now_cards: list): with lock: ok = self.cards.check(self.pre_cards, now_cards) if(dbg): print("player/AI", self.now_player, "display", now_cards, ("ok" if ok else "not ok")) if not ok: t = Thread(target = self.player[self.now_player].play, args = ((len(self.pre_cards) != 0) | 2,)) t.start() else: if dbg: for i in range(0,4): c = [TYPE.suit[j//13] + str(TYPE.point[j%13]) for j in self.player[i].card] print("player", i, c) print("---------------------------------------------") print() print("---------------------------------------------") over_flg = -1 for i,p in enumerate(self.player): if p.display(self.now_player, now_cards): over_flg = i if over_flg != -1: self.game_over(over_flg) return if len(now_cards) == 0: self.pass_cnt += 1 # 三人pass,则大者继续出牌 if self.pass_cnt == 3: self.pass_cnt, self.pre_cards = 0, [] else: self.pass_cnt = 0 self.pre_cards = now_cards self.now_player = (self.now_player + 1) % 4 t = Thread(target = self.player[self.now_player].play, args = (len(self.pre_cards) != 0,)) t.start() def start(self): with lock: if not self.started and self.playerCounter == 4: self.started = 1 else: return if dbg: print("game start") self.cards.shuffle() deal = self.cards.deal() for i in range(0,4): self.player[i].getCards(deal[i]) if dbg: print("player", i, deal[i]) self.pass_cnt = 0 self.pre_cards = [] ind = -1 if self.game_args[0] == 0: for i, p in enumerate(self.player): for c in p.card: if c == 0: ind = i else: ind = randint(0,3) self.now_player = ind self.player[ind].play(0) def addPlayer(self, Player, socket = None): with lock: ind = -1 for i, p in enumerate(self.player): if p == None: ind = i break if ind == -1: return -1, None for p in self.player: if p != None: p.addPlayer(ind) self.playerCounter += 1 self.player[ind] = Player(socket, ind, self) if dbg: print("addPlayer", ind) print("now player", self.player) return ind, self.player def delPlayer(self, ind: int): with lock: if g.started and type(self.player[ind]) == AI: return self.player[ind] = None for p in self.player: if p != None: p.delPlayer(ind) self.playerCounter -= 1 # 无玩家清场功能 clr_flg = 1 for p in self.player: if type(p) == Player: clr_flg = 0 if clr_flg: if dbg: print("cleared AI for no online player") self.player = [None, None, None, None] self.playerCounter = 0 if self.started: for p in self.player: if type(p) == Player: p.game_over(127) self.started = 0 if dbg: print("delPlayer", ind) print("now player", self.player)
class HoldEmRef: """the successor to the PokerRef class.""" def __init__(self): """initialize all variables""" self.dealer = -1 self.deck = Cards() self.players = [] #this array contains only players, not viewers self.n_play = len(self.players) #number of current players self.cur_player = None #the player on whom the action rests self.min_bet = 0 #the current minimum a player must bet self.pot = 0 #the current value of the pot self.no_raise = 1 #true if the hand has not yet been raised self.calls = 0 #number of current calls ### #public functions ### def set_players(self, players): """players should be an array of types derived from PokerPlayer These should be people sitting at the table, not viewers of the game""" self.players = players self.n_play = len(self.players) def rem_player(self, p): """remove a player from the game""" def get_blinds(self, ante, blind): """get the blinds and ante from the players""" self._init_hand() if ante: for p in self.players: p.payAnte(ante) self.transmit_bet(p, ante) sb = int(round(blind / 2.0)) small = self.next_active(self.dealer) self.big_blind = self.next_active(small) if not small.payBlind(sb): raise "blind error" if not self.big_blind.payBlind(blind): raise "blind error" self.transmit_bet(small, sb) self.transmit_bet(self.big_blind, blind) self.min_bet = blind self.cur_player = self.next_active(self.big_blind) def get_next_bet(self): """get the next player's bet""" self.cur_player.transmitBet(self.min_bet - self.cur_player.active_bet) def deal(self): """deal the cards to the players""" for p in self.players: p.re_init() cards = self.deck.deal(self.n_play * 2) if self.dealer == -1: #pick a random player self.dealer = self.players[self.deck.randint(0, self.n_play - 1)] else: self.dealer = self.next_active(self.dealer) cur_player = self.next_active(self.dealer) for card in cards: cur_player.addCard(card) cur_player = self.next_active(cur_player) ### #private functions ### def _init_hand(self): """reinitialize the values needed for the hand""" self.n_play = len(self.players) self.cur_player = None self.min_bet = 0 self.pot = 0 self.no_raise = 1 self.calls = 0 for p in self.players: p.active = 1 self.active_players = self.n_play def count_active(self): count = 0 for p in self.players: if p.active: count += 1 return count def next_active(self, p): """return the next to play after p""" if not type(3) == type(p): p = p.position p = self.players[(p + 1) % self.n_play] while not p.active: p = self.players[(p + 1) % self.n_play] return p def transmit_bet(self, player, bet): for p in self.players: p.receiveBet(bet, p.position) def receive_bet(self, bet, player): p = self.players[player] p.active_bet += bet if p.active_bet < self.min_bet and bet != -1: p.active_bet -= bet raise BetTooSmallError if p.active_bet > p.money: p.active_bet -= bet raise BetTooBigError if bet == -1: self._fold(p) elif p.active_bet == self.min_bet: self._call(p, bet) else: self._raise(p, bet) self.transmit_bet(p, bet) self.cur_player = self.next_active(self.cur_player) def _fold(self, player): player.active_bet = 0 player.active = 0 self.active_players -= 1 if not self.active_players: self.endHand() def _call(self, player, bet): """handle a player's call""" self.pot += player.active_bet player.money -= bet self.calls += 1 if self.calls >= self.active_players and not self._big_blind_exempt(): if len(self.comm_cards) == 0: self.deal_comm_cards(3) elif len(self.comm_cards) == 3: self.deal_comm_cards(1) elif len(self.comm_cards) == 4: self.deal_comm_cards(1) else: self.endHand() else: self.get_next_bet() def deal_comm_cards(self, n): pass def _big_blind_exempt(self): """return true if this is the special case where the big blind gets to raise his bet. We already know calls > active_players""" if len(self.comm_cards) == 0\ and self.cur_player.position == self.big_blind.position\ and self.no_raise: return 1 return 0 def _raise(self, player, bet): """handle a player's raise""" self.min_bet = player.active_bet self.pot += bet player.money -= bet self.calls = 0 self.no_raise = 0
class MyView(ui.View): def cardN_button(self,n): if self.step == 2 or self.step == 0: pass else: if self.hand[n].is_dealt: self.card_imgs[n] = self.make_button(self.card_button[n], 'cards/'+self.hand[n].display+'.png') self.card_locks[n] = True self.hand[n].is_dealt = False else: self.card_imgs[n] = self.make_button(self.card_button[n], 'cards/back.png') self.card_locks[n] = False self.hand[n].is_dealt = True self.set_needs_display() def card1_button(self, sender): self.cardN_button(0) def card2_button(self, sender): self.cardN_button(1) def card3_button(self, sender): self.cardN_button(2) def card4_button(self, sender): self.cardN_button(3) def card5_button(self, sender): self.cardN_button(4) def set_bet_5(self, sender): if self.step ==0: self.bet_amount = 5 self.play_coin = self.make_button(self.set_bet_10, "cards/5coin.png") self.set_needs_display() def set_bet_10(self, sender): if self.step ==0: self.bet_amount = 10 self.play_coin = self.make_button(self.set_bet_20, "cards/10coin.png") self.set_needs_display() def set_bet_20(self, sender): if self.step ==0: self.bet_amount = 20 self.play_coin = self.make_button(self.set_bet_5, "cards/20coin.png") self.set_needs_display() def __init__(self): """ INIT """ self.bet_amount = 5 # default bet is 5 self.stage = "title" # play, title, help self.title_b = self.make_button(self.goto_play_screen, "cards/play.png") self.help_b = self.make_button(self.goto_play_screen, "cards/play.png") self.play_b = self.make_button(self.goto_help_screen, "cards/help.png") self.play_coin = self.make_button(self.set_bet_10, "cards/5coin.png") self.message = "Click deal." self.balance = 100 self.cm = Cards() self.content_mode=ui.CONTENT_SCALE_ASPECT_FIT self.card_imgs=[] self.buttons=[] self.step = 0 self.card_button = [self.card1_button, self.card2_button, self.card3_button, self.card4_button, self.card5_button,] self.reset() self.buttons.append(self.make_button(self.button_tapped, "cards/deal.png")) self.score_label = ui.Label() self.score_label.x = 150 self.score_label.y = 450 self.score_label.height = 30 self.score_label.width = 100 self.score_label.text = "Balance: " self.score_value_label = ui.Label() self.score_value_label.x = 250 self.score_value_label.y = 450 self.score_value_label.height = 30 self.score_value_label.width =75 self.score_value_label.text = "$" + str(self.balance) self.score_value_label.background_color = (55,55,55) self.winning_label = ui.Label() self.winning_label.x = 250 self.winning_label.y = 350 self.winning_label.height = 30 self.winning_label.width =175 self.winning_label.text = self.message #self.winning_label.background_color = (55,55,55) def score_hand(self): """ SCORE HAND """ vodds = vp_odds() x,s = vodds.calculate_payout(self.hand, self.bet_amount) self.message = s + ' pays: $'+ str(x) return x def button_tapped(self, sender): if self.step == 2: self.reset() self.step = 0 self.message = 'Deal for next hand.' else: self.step += 1 self.message = 'Pick, and deal.' hand = self.cm.deal(5,self.deck) for i in range(0,5): if not self.card_locks[i]: self.hand[i] = hand[i] self.remove_subview(self.card_imgs[i]) self.card_imgs[i] = self.make_button(self.card_button[i], 'cards/'+hand[i].display+'.png') self.card_locks = [True, True, True, True, True] if self.step == 2: self.balance += self.score_hand() if self.balance <= 0: self.stage = 'broke' self.score_value_label.text = "$" + str(self.balance) self.set_needs_display() def make_button(self, callback, image): button = ui.Button() button.width = 72 button.height = 90 button.background_image = ui.Image.named(image) button.flex = 'LRTB' button.action = callback return button def reset(self): """ RESET """ self.deck = self.cm.shuffledeck(self.cm.opendeck()) # for testing, call for particular hands: # self.deck = self.cm.test_hand("four of a kind") self.card_imgs=[] for i in range (0,5): self.card_imgs.append(self.make_button(self.card_button[i], "cards/back.png")) self.hand =[None,None,None,None,None,] self.card_locks = [False, False, False, False, False] self.message = 'Click deal.' def did_load(self): pass def will_close(self): pass def goto_play_screen(self, sender): self.stage = "play" self.set_needs_display() def goto_help_screen(self, sender): self.stage = "help" self.set_needs_display() def draw(self): """ DRAW """ # self.bounds =(0,0,320,504) # print self.width,',',self.height path = ui.Path.rect(0,0,self.width, self.height) ui.set_color('brown') path.fill() # ui.set_color('green') # path.line_width=30 # path.stroke() # Remove all the current sub views. for i in self.subviews: self.remove_subview(i) if self.stage == "play": for i in range(0,len(self.card_imgs)): self.card_imgs[i].center = (82, 50+100*i) self.add_subview(self.card_imgs[i]) x = self.width * 0.5 + 100 y = self.height * 0.5 for i in range(0,len(self.buttons)): self.buttons[i].center = (x, y + 100*i) self.add_subview(self.buttons[i]) self.add_subview(self.score_label) self.score_value_label.x = 225 self.add_subview(self.score_value_label) self.winning_label.x = 150 self.winning_label.text = self.message self.add_subview(self.winning_label) self.play_coin.center = (x,y-100) self.add_subview(self.play_coin) self.play_b.center = (x,y-200) self.add_subview(self.play_b) if self.stage == "help": # add in our views self.add_subview(self.help_b) tit = ui.Label() tit.x = 100 tit.y = 0 tit.height = 60 tit.width = 500 tit.text = "Video Poker - Help" self.add_subview(tit) v = vp_odds() list_odds = v.list_odds() for i in range(0, len(list_odds)): x = ui.Label() x.x = 10 x.y = 100 + i*30 x.height = 30 x.width = 350 x.text = list_odds[i] self.add_subview(x) if self.stage == "title": tit = ui.Label() tit.x = 100 tit.y = 0 tit.height = 60 tit.width = 500 tit.text = "- Video Poker - " self.add_subview(tit) self.add_subview(self.title_b) if self.stage == 'broke': tit = ui.Label() tit.x = 100 tit.y = 0 tit.height = 60 tit.width = 500 tit.text = "- Video Poker - " self.add_subview(tit) self.add_subview(self.title_b) self.balance = 100 self.score_value_label.text = "$" + str(self.balance) list_text = ['You are broke!','I will credit you 100 dollars,','Press play to continue.'] for i in range(0, len(list_text)): x = ui.Label() x.x = 10 x.y = 100 + i*30 x.height = 30 x.width = 350 x.text = list_text[i] self.add_subview(x) def layout(self): pass def touch_began(self, touch): pass def touch_moved(self, touch): pass def touch_ended(self, touch): pass def keyboard_frame_will_change(self,frame): pass def keyboard_frame_did_change(self, frame): pass
class PokerRef: def __init__(self, gui): self.dealer = -1 self.players = [] self.gui = gui self.deck = Cards() self.pot = 0 self.cur_player = None self.min_bet = 0 self.calls = 0 self.active_hands = 0 self.comm_cards = [] #community cards self.no_raise = 1 #set to false if somebody has raised the #big blind self.big_blind = 0 #denotes the big blind self.hand_over = 0 #true if the hand is over def mainLoop(self): while 1: self.deal() self.cur_player = (self.dealer + 1) % len(self.players) while not self.hand_over: self.getNextBet(self.nextActive(self.cur_player)) self.gui.Update() #assure that the bet has been received before proceeding self.hand_over = 0 def nextActive(self, cur): cur = (cur + 1) % len(self.players) while self.players[cur].active == 0: cur = (cur + 1) % len(self.players) return cur def countActive(self): count = 0 for p in self.players: if p.active: count += 1 return count def newGame(self, players, blind, ante): """start a new game players is an array with a string. 'h' means human player, for now. blind is the size of the small blind. The big will be assumed to be twice that. ante is the size of the ante. """ self.players = players self.blind = blind self.ante = ante for i in range(len(players)): if players[i] == 'h': players[i] = PokerHuman(10000, "player%s" % i, i) elif players[i] == 'b': players[i] = PokerBot(10000, "player%s" % i, i, self) elif players[i] == None: pass else: raise "illegal player" self.gui.setUpPlayers(players) self.dealer = -1 self.deal() def cardsToCmpName(self, cards): outCards = [] for card in cards: b = int(card[:-1]) + 2 if b > 9: if b == 10: b = 't' elif b == 11: b = 'j' elif b == 12: b = 'q' elif b == 13: b = 'k' elif b == 14: b = 'a' outCards.append(str(b) + card[-1:]) return outCards def getWinner(self): self.winner = [] cmd = './mycmpn ' self.eval_hands = [] positions = [] for p in self.players: if p.active: positions.append(p.position) for card in self.cardsToCmpName(p.getHand()): cmd += '%s ' % card cmd += '-- ' for card in self.cardsToCmpName(self.comm_cards): cmd += '%s ' % card output = commands.getoutput(cmd).split() print cmd, "\n", output if len(output) == 1: win_pos = positions[int(output[0])] self.players[win_pos].money += self.pot self.winner.append(win_pos) else: split = int(self.pot) / len(output) for i in output: win_pos = positions[int(i)] self.players[win_pos].money += split self.winner.append(win_pos) return self.winner def endHand(self): """code to run at the end of a hand""" print "ending hand" self.winner = [] if self.active_hands == 1: self.players[self.nextActive(0)].money += self.pot self.winner.append(self.nextActive(0)) else: self.winner = self.getWinner() self.gui.clearTable(self.winner, self.pot, self.players) self.deck.reset() for p in self.players: p.endHand(self.winner) self.pot = 0 self.cur_player = self.dealer self.min_bet = 0 self.calls = 0 self.active_hands = 0 self.no_raise = 1 self.comm_cards = [] self.gui.refreshMoney(self.players) self.hand_over = 0 self.deal() def deal(self): """deal 2 cards to each player""" cards = self.deck.deal(len(self.players)*2) if self.dealer == -1: self.dealer = 8 #self.dealer = self.deck.randint(0, len(self.players)-1) else: self.dealer = (self.dealer + 1) % len(self.players) count = 1 for card in cards: cur_player = (self.dealer + count) % len(self.players) self.players[cur_player].addCard(card) count += 1 self.getBlinds() self.gui.deal(self.players, self.dealer) self.active_hands = self.countActive() self.gui.refreshPot(self.pot) self.cur_player = (self.dealer + 2) % len(self.players) self.gui.fireBetEvent() def getBlinds(self): small_blind = (self.dealer + 1) % len(self.players) self.big_blind = (small_blind + 1) % len(self.players) for p in self.players: if p.position == small_blind: if p.payBlind(self.blind): p.receiveBet(self.big_blind, self.blind * 2) else: raise "what to do if they don't accept the blind?" elif p.position == self.big_blind: if p.payBlind(self.blind * 2): p.receiveBet(small_blind, self.blind) else: raise "what to do if they don't accept the blind?" else: p.receiveBet(small_blind, self.blind) p.receiveBet(self.big_blind, self.blind * 2) self.gui.refreshMoney(self.players) self.pot += self.blind * 3 self.min_bet = self.blind * 2 def dealCommCards(self, num): """Deal num community cards""" print "dealing %d community cards" % num self.min_bet = 0 self.calls = 0 cards = self.deck.deal(num) for card in cards: self.comm_cards.append(card) self.gui.dealCommCards(cards) for p in self.players: p.receiveCommCards(cards) p.active_bet = 0 def fold(self, p): """folds a hand. p should be an actual reference to the player""" print "player %d folds" % p.position p.active = 0 self.gui.clearHand(p.position) self.active_hands -= 1 self.transmitBet(-1, p.position) self.gui.refreshMoney(self.players) self.gui.refreshPot(self.pot) if self.active_hands == 0 or self.active_hands - 1 == self.calls: self.hand_over = 1 self.endHand() else: self.gui.fireBetEvent() def raiseBet(self, bet, p): """performs a raise. bet should be a bet amount p should be a reference to a player""" print "player %d raises to $%d" % (p.position, bet) self.pot += bet p.money -= bet self.calls = 0 self.no_raise = 0 self.min_bet = p.active_bet self.transmitBet(bet, p.position) self.gui.refreshMoney(self.players) self.gui.refreshPot(self.pot) self.gui.fireBetEvent() def callBet(self, bet, p): """performs a call. bet should be a bet amount p should be a reference to a player""" print "player %d calls for $%d. Active: %d. no_raise: %d" % \ (p.position, bet, p.active_bet, self.no_raise) self.pot += bet p.money -= bet self.calls += 1 self.transmitBet(bet, p.position) self.gui.refreshMoney(self.players) self.gui.refreshPot(self.pot) #the second condition allows the big blind to bet on the first round #if nobody raises to him print self.calls, self.active_hands, self.hand_over if self.calls >= self.active_hands and not\ self.isBigBlindBet(self.nextActive(self.cur_player)): self.cur_player = self.nextActive(self.dealer) if len(self.comm_cards) == 0: self.no_raise = 0 #big blind can only raise 1st round self.dealCommCards(3) elif len(self.comm_cards) == 3: self.dealCommCards(1) elif len(self.comm_cards) == 4: self.dealCommCards(1) elif len(self.comm_cards) == 5: self.hand_over = 1 self.endHand() if not self.hand_over: self.gui.fireBetEvent() def isBigBlindBet(self, p): """returns true if it's big blind's chance to bet on the first round p is the number of the next player""" if p == self.big_blind and self.no_raise and len(self.comm_cards) == 0: return 1 return 0 def getNextBet(self): player = self.nextActive(self.cur_player) print "getNextBet from %d" % player if self.players[player].type == "HUMAN": self.gui.getBet(player, self.min_bet - \ self.players[player].active_bet) else: self.players[player].transmitBet(self.min_bet - \ self.players[player].active_bet) def receiveBet(self, bet, player): self.cur_player = player p = self.players[player] if bet > 0: p.active_bet += bet if bet < 0: self.fold(p) #this call has side effects! elif p.active_bet < self.min_bet: p.active_bet -= bet raise BetTooSmallError elif p.active_bet > p.money: p.active_bet -= bet raise BetTooBigError elif p.active_bet == self.min_bet: self.callBet(bet, p) elif p.active and p.active_bet > self.min_bet: self.raiseBet(bet, p) else: raise "Something is fscked up!!1!" def transmitBet(self, bet, player): """transmits a bet to all current players bet should be the dollar amount of the bet (<0 for folds) player should be the player's position on the table""" for p in self.players: p.receiveBet(bet, player)