def __init__(self, mode, difficulty, screen, menu):
     self.mode = mode
     self.screen = screen
     self.current_player = None #x always goes first
     self.player = None    
     self.pc = None
     self.menu = menu
     self.gameBoard = GameBoard()
     self.AI = MoveGenerator(difficulty)
Beispiel #2
0
 def __init__(self, PLAYER_COUNT=1, NUMBER_OF_DECKS=1, MINIMUM_BET=1):
     self._dealer = Dealer()
     self._players = [Player(x) for x in xrange(PLAYER_COUNT)]
     self._shoe = Horseshoe(NUMBER_OF_DECKS)
     self._MINIMUM_BET = MINIMUM_BET
     self._move_generator = MoveGenerator(self._shoe)
Beispiel #3
0
class Board:
    
    def __init__(self, PLAYER_COUNT=1, NUMBER_OF_DECKS=1, MINIMUM_BET=1):
        self._dealer = Dealer()
        self._players = [Player(x) for x in xrange(PLAYER_COUNT)]
        self._shoe = Horseshoe(NUMBER_OF_DECKS)
        self._MINIMUM_BET = MINIMUM_BET
        self._move_generator = MoveGenerator(self._shoe)
    
    def play(self):
        players = self._players
        shoe = self._shoe
        #movegen = MoveGenerator(shoe)
                    
        while True:
            if players:
                eliminated_players = []
                for player in players:
                    if not player.can_bet(self._MINIMUM_BET):
                        eliminated_players.append(player)
                        players.remove(player)
                if eliminated_players:
                    print '<'*60
                    print 'Following players cannot bet any further and are removed from table:'
                    for player in eliminated_players:
                        print 'Player {0}'.format(player.id)
                    print '>'*60
                    pass
                else:
                    #Collect bets from each player
                    bets = self._collect_bets(players)
                    
                    #Initialize them a hand for the bet they made
                    hands = [ [player,Hand(bet)] for player, bet in zip(players, bets) ]
                    dealer_hand = Hand(0)
                    
                    
                    print '#'*60
                    print 'First Card will be served'
                    print '#'*60
                    #Serve them their first card
                    [hand.insert(shoe.draw()) for player,hand in hands]
                    #Serve the dealer the first card
                    #TODO When we have limits for dealer, break conditions here
                    dealer_hand.insert(shoe.draw())
                    #Print state for each player
                    for player,hand in hands:
                        print 'Player {0} : Your Cards are :'.format(player.id)
                        print hand
                        print '*'*50

                    print 'Dealers Hand :'
                    print dealer_hand
                    print '*'*50

                    
                    print '#'*60
                    print 'Next Card will be served'
                    print '#'*60
                    #Serve them their second card
                    [hand.insert(shoe.draw()) for player,hand in hands]
                    dealer_hand.insert(shoe.draw())
                    
                    for player,hand in hands:
                        print 'Player {0} : Your Cards are :'.format(player.id)
                        print hand

                    print '#'*60
                    
                    final_hands =[]
                    
                    for player,hand in hands:
                        for ret_hand in self._user_action(player,hand):
                            final_hands.append(ret_hand)
                    
                    #Show Dealer's Hand 
                    print '#'*60
                    print 'Dealer\s Hand'
                    print dealer_hand  

                    while True:
                        dealer_value = dealer_hand.evaluate()
                        if dealer_value in range(1,17):
                            self._move_generator._hit(self._dealer,dealer_hand)
                        else:
                            break

                    print '#'*60
                    print 'Dealer\'s Final Hand'
                    print dealer_hand     
                    #Print Dealer's state 
                    
                    for player,hand in final_hands:
                        payoff_code = self._compare(hand,dealer_hand)
                        value = self._payoff(player, hand, payoff_code)
                        
                        if payoff_code >  1:
                            print 'Player {0} had a blackjack. Gets Back {1}'.format(player.id, value)
                        if payoff_code == 1:
                            print 'Player {0} had a win.       Gets Back {1}'.format(player.id, value)
                        if payoff_code == 0:
                            print 'Player {0} had a push.      Gets Back {1}'.format(player.id, value)
                        if payoff_code <  0:
                            print 'Player {0} had a loss.      Loses     {1}'.format(player.id, value)

                        #collect used cards
                        for card in hand._cards:
                            self._shoe.collect(card)    
                    
                    
            else:
                print 'Table is now empty. Now closing the table.'
                break
    
    def _collect_bets(self,players):
        bets = []
        for player in players:
            while True:
                try:
                    suggested_bet = int(raw_input("Hi Player {0}. Enter your bet in range({1},{2}) : ".format(player.id, self._MINIMUM_BET,player.credit)))
                    print '*'*50
                    #suggested_bet = 10
                    if suggested_bet<0 or not player.can_bet(suggested_bet):
                        pass
                    else:
                        bets.append(player.bet(suggested_bet))
                        break
                except ValueError:
                    pass
        return bets
    
    def _user_action(self,player,hand):
        while True:
            print 'Player {0} : Your Hand is :'.format(player.id)
            print hand.describe()

            methods = [meth for meth in self._move_generator.generate_possible_methods(player,hand)]
            
            #print methods and take input from user to invoke appropriate method
            print 'Player {0} :  What do you want to do?'.format(player.id)
            i=0
            for method_name, method in methods:
                print '{0} : {1}'.format(i,method_name)
                i+=1    

            #Continue taking input till we have a valid input
            choice =0
            while True:
                try:
                    input = int(raw_input("Please select the action_number : "))
                    if input in range(len(methods)):
                        choice = input
                        break
                except ValueError:
                    pass
            try:
                #call the method
                #method call will raise StopIteration upon bust or stand move
                child_hands = methods[choice][1](player,hand)
                
                #Will be null unless split is called
                if child_hands:
                    processed_hands = []
                    for child_hand in child_hands:
                        #recursive call for each child_hand from split
                        to_process_tuples = self._user_action(player,child_hand)
                        
                        #child_hands added to list
                        for tup in to_process_tuples:
                            processed_hands.append(tup)

                    #final list 
                    return processed_hands
        
            except StopIteration:
                print '^'*50
                print 'Player {0} : Your Final Hand : '
                print hand
                print '^'*50
                
                return [[player,hand]]
                
    #Compares hands. Returns -1,0,1 or 2    
    def _compare(self,player_hand, dealer_hand):
        player_value = player_hand.evaluate()
        dealer_value = dealer_hand.evaluate()
        
        if dealer_hand.isBlackjack():
            if player_hand.isBlackjack():
                return 0
            else:
                return -1
        else:
            if player_hand.isBlackjack():
                return 2
            if player_value > dealer_value:
                return 1
            if player_value == dealer_value:
                return 0
            else:
                return -1

    #Calculates payoff for the bet placed on the hand based on the code
    #Updates the bet in hand and then if code is >=0, player collects the money back else dealer gets it
    def _payoff(self,player,hand,code):
        bet = hand.get_bet()
        dealer = self._dealer
        if code>=0:
            #3:2 payoff for blackjack
            if code == 2:
                bet_amount = dealer.bet(bet*1.5)
            
            #1:1 Regular win for the player
            if code == 1:
                bet_amount = dealer.bet(bet)
            
            #push - no payoffs
            if code == 0:
                bet_amount = 0
            hand.add_bet(bet_amount)
            bet = hand.get_bet()

            player.collect_bet(hand.collect_bet())
        else:
            #player loses
            dealer.collect_bet(hand.collect_bet())
        return bet
class LocalGame:
    
    #Constructor params: 
    #@mode: 1 or 2, repping either 1 or 2 players
    #@difficulty = "Easy", "Normal" or "Hard"; only used if in 1P mode
    #@board_coordinates = starting (x,y) coordinate of the board
    #@screen = screen to blit to
    def __init__(self, mode, difficulty, screen, menu):
        self.mode = mode
        self.screen = screen
        self.current_player = None #x always goes first
        self.player = None    
        self.pc = None
        self.menu = menu
        self.gameBoard = GameBoard()
        self.AI = MoveGenerator(difficulty)
    
    def run_game(self):
        clock = pygame.time.Clock()
        #Determine whether AI or player goes first
        self.determine_turns()
        '''Game Loop'''
        while (not (self.check_game_over() or self.check_tie()) and (self.menu.current_state != 0)):
            #Event Processing
            mouse_click = (0,0)
            mouse_position = pygame.mouse.get_pos()
            for event in pygame.event.get(): 
                if event.type == pygame.QUIT: 
                    self.menu.current_state = -1
                    return
                if event.type == pygame.MOUSEBUTTONUP:
                    mouse_click = mouse_position
            #Logic
            if (self.mode == 1):
                if (self.current_player == self.player):
                    self.player_click(mouse_click[0], mouse_click[1])
                else:
                    self.pc_move()
            elif (self.mode == 2):
                try:
                    mouse_x = mouse_click[0]
                    mouse_y = mouse_click[1]
                    self.player_click(mouse_x, mouse_y)
                except:
                    pass
                    
            #Drawing
            self.draw_background()
            self.draw_buttons()
            self.draw_buttons_hover(mouse_position[0], mouse_position[1])
            self.draw_marker_hover(mouse_position[0], mouse_position[1])
            self.gameBoard.draw_markers(self.screen, constants.BOARD_COORDINATES)
            if (self.check_game_over()):
                self.switch_turns() #Turn is switched after move, so switch back to draw winner correctly
                if (self.current_player == "x"): 
                    l = self.gameBoard.x_list
                else:
                    l = self.gameBoard.o_list
                self.draw_win(l)
                
            pygame.display.flip()
            
            #If the game is over, pause for a moment to let player see that game is over
            if (self.check_game_over() or self.check_tie()):
                time.sleep(1)
            clock.tick(60)
    
    #For 1p, determine whether pc or player goes first. "x" always goes first
    def determine_turns(self):
        num = randint(1,10)
        if (num%2 == 0):
            self.player = "x"
            self.pc = "o"
            self.current_player = self.player
        else:
            self.player = "o"
            self.pc = "x"
            self.current_player = self.pc
            
    def check_game_over(self):
        if ((self.gameBoard.check_win(self.gameBoard.x_list, constants.WIN_POSITION_LIST)) or (self.gameBoard.check_win(self.gameBoard.o_list, constants.WIN_POSITION_LIST))):
            return True
        else:
            return False
    def check_tie(self):
        if (len(self.gameBoard.taken_positions_list) == 9) and (not (self.check_game_over())):
            return True
        else:
            return False
    
    def player_click(self, mouse_x, mouse_y):
        b_x = constants.BOARD_COORDINATES[0]
        b_y = constants.BOARD_COORDINATES[1]
        if b_x < mouse_x < (b_x + constants.TILE_DIMENSION):
            if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and ((((mouse_y - b_y) // 100)*3) not in self.gameBoard.taken_positions_list):
                position = ((mouse_y - b_y) // 100)*3
                self.gameBoard.update_player_list(self.current_player, position)
                self.switch_turns()
        elif b_x + constants.TILE_DIMENSION < mouse_x < (b_x + 2*constants.TILE_DIMENSION):
            if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and (((((mouse_y - b_y) // 100)*3+1) not in self.gameBoard.taken_positions_list)):
                position = ((mouse_y - b_y) // 100)*3+1
                self.gameBoard.update_player_list(self.current_player, position)
                self.switch_turns()       
        elif b_x + 2*constants.TILE_DIMENSION < mouse_x < (b_x + 3*constants.TILE_DIMENSION):
            if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and (((((mouse_y - b_y) // 100)*3+2) not in self.gameBoard.taken_positions_list)):
                position = ((mouse_y - b_y) // 100)*3+2
                self.gameBoard.update_player_list(self.current_player, position)
                self.switch_turns()
        elif (constants.GAME_BACK_ARROW_COOR[0] < mouse_x < constants.GAME_BACK_ARROW_COOR[0] + constants.BACK_ARROW.get_size()[0]):
            if (constants.GAME_BACK_ARROW_COOR[1] < mouse_y < constants.GAME_BACK_ARROW_COOR[1] + constants.BACK_ARROW.get_size()[1]):
                self.menu.current_state = 0
        if (constants.GAME_RESET_COOR[0] < mouse_x < constants.GAME_RESET_COOR[0] + constants.RESET.get_size()[0]):
            if (constants.GAME_RESET_COOR[1] < mouse_y < constants.GAME_RESET_COOR[1] + constants.RESET.get_size()[1]):
                self.reset_game()
            
    def pc_move(self):
        if self.current_player == "x":
            AI_list = self.gameBoard.x_list
            player_list = self.gameBoard.o_list
        else:
            AI_list = self.gameBoard.o_list
            player_list = self.gameBoard.x_list
            
        time.sleep(0.2)
        pc_move = self.AI.generate_move(AI_list, player_list, self.gameBoard.taken_positions_list)
        self.gameBoard.update_player_list(self.current_player, pc_move)
        self.switch_turns()
        
    def draw_background(self):
        self.screen.blit(constants.BACKGROUND, (0,0))
        self.screen.blit(constants.HEADING, constants.HEADING_COORDINATES)
        self.screen.blit(constants.TITLE, constants.TITLE_COORDINATES)
        self.screen.blit(constants.BOARD_SURFACE, constants.BOARD_COORDINATES)
        
    def draw_marker_hover(self, mouse_x, mouse_y):
        if (self.mode == 1):
            if (self.current_player == self.player):
                    self.draw_marker_hover_helper(mouse_x, mouse_y)
        else:
            self.draw_marker_hover_helper(mouse_x, mouse_y)
        
    def draw_marker_hover_helper(self, mouse_x, mouse_y):
        if (self.current_player == "x"):
            hover_marker = constants.HOVER_EX
        else:
            hover_marker = constants.HOVER_OH
        self.gameBoard.draw_hover(mouse_x, mouse_y, hover_marker, self.screen, constants.BOARD_COORDINATES)
                
    def draw_markers(self):
        self.gameBoard.draw_markers(self.screen, constants.BOARD_COORDINATES)
        
    def draw_buttons(self):
        self.screen.blit(constants.BACK_ARROW, constants.GAME_BACK_ARROW_COOR)
        self.screen.blit(constants.RESET, constants.GAME_RESET_COOR)
        
    def draw_buttons_hover(self, mouse_x, mouse_y):
        if (constants.GAME_BACK_ARROW_COOR[0] < mouse_x < constants.GAME_BACK_ARROW_COOR[0] + constants.BACK_ARROW.get_size()[0]):
            if (constants.GAME_BACK_ARROW_COOR[1] < mouse_y < constants.GAME_BACK_ARROW_COOR[1] + constants.BACK_ARROW.get_size()[1]):
                self.screen.blit(constants.BACK_ARROW_HOVER, constants.GAME_BACK_ARROW_COOR)
        if (constants.GAME_RESET_COOR[0] < mouse_x < constants.GAME_RESET_COOR[0] + constants.RESET.get_size()[0]):
            if (constants.GAME_RESET_COOR[1] < mouse_y < constants.GAME_RESET_COOR[1] + constants.RESET.get_size()[1]):
                self.screen.blit(constants.RESET_HOVER, constants.GAME_RESET_COOR)
    
    def draw_win (self, given_list):
        gset = set(given_list)
        for item in constants.WIN_POSITION_LIST:
            wset = set(item)
            intersection = wset.intersection(gset)
            if (len(intersection) == 3):
                if (self.current_player == "x"):
                    surface = constants.WINNING_EX
                else:
                    surface = constants.WINNING_OH
                for i in intersection:
                    
                    self.gameBoard.draw_marker(self.current_player, i, self.screen, constants.BOARD_COORDINATES, surface)
            
    def reset_game(self):
        self.gameBoard.x_list = []
        self.gameBoard.o_list = []
        self.gameBoard.taken_positions_list = []
        
    def switch_turns(self):
        if (self.current_player == self.player):
            self.current_player = self.pc
        else:
            self.current_player = self.player
            
    def change_difficulty(self, diff):
        self.AI.change_difficulty(diff)
Beispiel #5
0
class Board:
    
    def __init__(self, PLAYER_COUNT=1, NUMBER_OF_DECKS=1, MINIMUM_BET=1):
        self._dealer = Dealer()
        self._players = [Player(x) for x in xrange(PLAYER_COUNT)]
        self._shoe = Horseshoe(NUMBER_OF_DECKS)
        self._MINIMUM_BET = MINIMUM_BET
        self._move_generator = MoveGenerator(self._shoe)
    
    def play(self):
        players = self._players
        shoe = self._shoe
        #movegen = MoveGenerator(shoe)
                    
        while True:
            if players:
                eliminated_players = []
                for player in players:
                    if not player.can_bet(self._MINIMUM_BET):
                        eliminated_players.append(player)
                        players.remove(player)
                if eliminated_players:
                    print '<'*60
                    print 'Following players cannot bet any further and are removed from table:'
                    for player in eliminated_players:
                        print 'Player {0}'.format(player.id)
                    print '>'*60
                    pass
                else:
                    #Collect bets from each player
                    bets = self._collect_bets(players)
                    
                    #Initialize them a hand for the bet they made
                    hands = [ [player,Hand(bet)] for player, bet in zip(players, bets) ]
                    dealer_hand = Hand(0)
                    
                    
                    #print '#'*60
                    print 'First Card will be served'
                    #print '#'*60
                    #Serve them their first card
                    [hand.insert(shoe.draw()) for player,hand in hands]
                    #Serve the dealer the first card
                    #TODO When we have limits for dealer, break conditions here
                    dealer_hand.insert(shoe.draw())
                    #Print state for each player
                    for player,hand in hands:
                        print 'Player {0} : Your Cards are :'.format(player.id)
                        print hand
                        print '*'*50

                    print 'Dealers Hand :'
                    print dealer_hand
                    print '*'*50

                    
                    #print '#'*60
                    print 'Next Card will be served'
                    #print '#'*60
                    #Serve them their second card
                    [hand.insert(shoe.draw()) for player,hand in hands]
                    dealer_hand.insert(shoe.draw())
                    
                    for player,hand in hands:
                        print 'Player {0} : Your Cards are :'.format(player.id)
                        print hand

                    #print '#'*60
                    
                    final_hands =[]
                    
                    for player,hand in hands:
                        for ret_hand in self._user_action(player,hand):
                            final_hands.append(ret_hand)
                    
                    #Show Dealer's Hand 
                    #print '#'*60
                    print 'Dealer\s Hand'
                    print dealer_hand  

                    while True:
                        dealer_value = dealer_hand.evaluate()
                        if dealer_value in range(1,17):
                            try:
                                self._move_generator._hit(self._dealer,dealer_hand)
                            except StopIteration, e:
                                print ">> Dealer went bust! <<"
                        else:
                            break

                    #print '#'*60
                    print 'Dealer\'s Final Hand'
                    print dealer_hand     
                    #Print Dealer's state 
                    
                    for player,hand in final_hands:
                        payoff_code = self._compare(hand,dealer_hand)
                        value = self._payoff(player, hand, payoff_code)
                        
                        if payoff_code >  1:
                            print 'Player {0} had a blackjack. Gets Back {1}'.format(player.id, value)
                        if payoff_code == 1:
                            print 'Player {0} had a win.       Gets Back {1}'.format(player.id, value)
                        if payoff_code == 0:
                            print 'Player {0} had a push.      Gets Back {1}'.format(player.id, value)
                        if payoff_code <  0:
                            print 'Player {0} had a loss.      Loses     {1}'.format(player.id, value)

                        #collect used cards
                        for card in hand._cards:
                            self._shoe.collect(card)    
                    
                    
            else:
                print 'Table is now empty. Now closing the table.'
                break