Beispiel #1
0
def main():
    run = True
    clock = pygame.time.Clock()

    game = Game(WIN)

    # piece = board.get_piece(0, 1)
    # board.move(piece, 4, 3)
    while run:
        clock.tick(FPS)

        if game.turn == BLACK:
            new_board = minimax(game.get_board(), 3, True, game)[1]
            game.ai_move(new_board)

        if game.winner() != None:
            print(game.winner())
            game.reset()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col, WIN)
        game.update()

    pygame.quit()
Beispiel #2
0
    def start_the_game_ai(self):
        run = True
        clock = pygame.time.Clock()
        game = Game(self.win)
        while run:
            clock.tick(self.fps)

            if game.turn == BLACK:
                value, new_board = minimax(game.get_board(),
                                           self.ai_difficulty, BLACK, game)
                game.ai_move(new_board)

            if game.winner() != None:
                self.print_winner(game.winner())

            if game.draw():
                print("draw")
                run = False

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    game.select(pos)

            game.update()
Beispiel #3
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)

    while run:
        clock.tick(60)

        if game.turn == WHITE:
            #value, new_board = minimax(game.get_board(), 4, WHITE, game)
            value, new_board = alpha_beta(game.get_board(), 2, WHITE, game,
                                          float('-inf'), float('inf'))
            game.ai_move(new_board)

        if game.winner() != None:

            run = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Beispiel #4
0
def main_Human_vs_AI():
    clock = pygame.time.Clock()
    game = Game(WIN)

    run = True
    while run:
        clock.tick(FPS)
        game.update()

        if game.turn == WHITE:
            value, new_board = alpha_beta_pruning(game.get_board(), 5, False,
                                                  float("-inf"), float("inf"),
                                                  game)
            if new_board is None:
                print("White loose")
                run = False
                time.sleep(5000)
            else:
                game.ai_move(new_board)

        if game.winner() != None:
            run = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                x = get_row_col_from_mouse(pygame.mouse.get_pos())
                if x is not None:
                    game.select(x[1], x[0])

    pygame.quit()
def main():
    pygame.mixer.init()
    mixer.music.load('background.wav')
    mixer.music.play(-1)
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)

    while True:
        clock.tick(FPS)

        winner = game.winner()
        if winner != None:
            messagebox.showinfo(
                "Winner",
                "{0}! You won smarty pants!".format("Red" if winner == (
                    255, 0, 0) else "Blue"))
            break

        if game.turn == BLUE:
            value, new_board = minimax(game.get_board(), 3, BLUE, game)
            game.ai_move(new_board)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                break

            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(mouse_pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Beispiel #6
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)

    while run:
        clock.tick(FPS)

        if game.turn == WHITE:
            value, new_board = minimax(game.get_board(), 3, WHITE, game)
            game.ai_move(new_board)

        if game.winner() != None:
            print(game.winner())
            run = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Beispiel #7
0
def main():

      run = True
      clock = pygame.time.Clock()
      game = Game(WIND)
      menu = Menu(WIND)
      Mode = None

      while run:

            # setting refresh rate..
            clock.tick(FPS) 

            if Mode and game.winner() != None:
                  print(game.winner()+" WON!!")
                  font = pygame.font.Font('freesansbold.ttf', 32) 
                  text = font.render(game.winner()+" WON!!", True, BLACK, WHITE)
                  textRect = text.get_rect() 
                  textRect.center = (WIDTH // 2, WIDTH // 2)
                  WIND.fill(WHITE)
                  WIND.blit(text, textRect)
                  pygame.display.update()
                  pygame.time.delay(5000)
                  run=False
            
            if (Mode == 2 or Mode ==3) and game.turn == WHITE:
                  value,new_board = minimax(game.get_board(),5, True,game,float('-inf'),float('+inf'))
                  pygame.time.delay(1000)
                  game.ai_move(new_board)
            
            if Mode ==3 and game.turn == BLACK:
                  value,new_board = minimax(game.get_board(),5, False,game,float('-inf'),float('+inf'))
                  pygame.time.delay(1000)
                  game.ai_move(new_board)


            #setting event loop
            for event in pygame.event.get():

                  if event.type == pygame.QUIT:
                        run = False
                  
                  if event.type == pygame.MOUSEBUTTONDOWN:
                        pos = pygame.mouse.get_pos()
                        if Mode == None:
                              Mode = menu.selected_mode(pos)
                              print("Selected Mode: "+str(Mode))

                        if Mode == 1 or Mode == 2:

                              row,col = get_square_pos_from_mouse(pos)
                              game.select(row,col)
            
            if Mode:
                  game.update()
      
      # close the window.
      pygame.quit()
Beispiel #8
0
def main():
    """
    run this function to run the game.
    event loop. 
    will run every x time per second and check if the player pressed on something and update the display
    """
    run = True  #boolean variable - remains true as long as there's no winner.
    clock = pygame.time.Clock()
    game = Game(WIN)  #is for game window
    board = Board()
    difficultyLevel = get_level()

    while run:
        clock.tick(FPS)

        if game.turn == WHITE:  #there are two palyers: White and Red
            value, new_board = minimax(game.get_board(), difficultyLevel + 1,
                                       WHITE, game)
            game.ai_move(new_board)

        if game.winner() != None:
            run = False

        for event in pygame.event.get():
            #check if events have happened at the current time
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:  #player press on mouse
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

            pos = pygame.mouse.get_pos()
            row, col = get_row_col_from_mouse(pos)
        if (difficultyLevel < 3):
            game.update_board(row, col)
        else:
            game.update3(row, col)

    if game.winner() == WHITE:
        messagebox.showinfo("Game Over", "White is Winner")
    elif game.winner() == RED:
        messagebox.showinfo("Game Over", "RED is Winner")
    elif game.winner() == BLACK:
        messagebox.showinfo("Game Over",
                            "Too many moves with no change\n Result: Draw")
    elif game.winner() == PITCH:
        messagebox.showinfo("Game Over",
                            "Red has no more valid moves\nWhite is Winner\n")
    elif game.winner() == GRAY:
        messagebox.showinfo("Game Over",
                            "White has no more valid moves\nRed is Winner\n")
    pygame.quit()  #close board window
Beispiel #9
0
def main():
    clock = pygame.time.Clock()
    game = Game(WINDOW)
    play_with_ai = True
    ai_vs_ai = False
    ai_color = WHITE
    player_color = RED

    while True:
        clock.tick(FPS)
        game.update()

        if play_with_ai and game.turn == ai_color:
            new_board = minimax(game.get_board(), DEPTH, True, ai_color,
                                player_color)[1]
            if new_board is None:
                is_player_winner = True
                break
            game.ai_move(new_board)
            if ai_vs_ai:
                time.sleep(1)

        if ai_vs_ai and game.turn != ai_color:
            new_board = minimax(game.get_board(), DEPTH, True, player_color,
                                ai_color)[1]
            if new_board is None:
                is_player_winner = False
                break
            game.ai_move(new_board)
            time.sleep(1)

        if game.winner() is not None:
            is_player_winner = game.winner() != ai_color
            break

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)
            if event.type == pygame.QUIT:
                pygame.quit()

    print_end_message(is_player_winner)
    pygame.quit()
Beispiel #10
0
def main():
    clock = pygame.time.Clock()

    game = Game(WIN)

    run = True
    while run:
        clock.tick(FPS)
        game.update()

        if game.winner() != None:
            run = False

        if game.turn == WHITE:
            value, new_board = alpha_beta_pruning(game.get_board(), 3, False,
                                                  float("-inf"), float("inf"),
                                                  game)
            if new_board is None:
                print("WUT")
                time.sleep(5000)
            game.ai_move(new_board)
        # else:
        #     value, new_board = alpha_beta_pruning(game.get_board(), 3, True, float("-inf"), float("inf"), game)
        #     if new_board is None:
        #         print("WUT")
        #         print("WUT")
        #         time.sleep(5000)
        #     game.ai_move(new_board)

        #pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                x = get_row_col_from_mouse(pygame.mouse.get_pos())
                if x is not None:
                    game.select(x[1], x[0])
                    print(f"1: {game.board.evaluation_1()}")
                    print(f"2: {game.board.evaluation_2()}")
                    print(f"3: {game.board.evaluation_3()}")

    pygame.quit()
Beispiel #11
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)
    AIbot = AI()
    no_moves = False
    while run:
        clock.tick(FPS)

        if game.turn == WHITE:
            value, new_board = AIbot.minimax(game.get_board(), 4,
                                             float('-inf'), float('inf'),
                                             False, WHITE, game)
            if (new_board is not None):
                game.ai_move(new_board)
            else:
                no_moves = True

        if game.winner() != None:
            print(game.winner())
            run = False
        if no_moves == True:
            if game.turn == RED:
                print("WHITE Wins!")
            else:
                print("RED Wins!")
            run = False

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                print("Explored node: ", AIbot.explored_node())
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                print("Explored node: ", AIbot.explored_node())
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Beispiel #12
0
def main_AI_vs_AI():
    clock = pygame.time.Clock()
    game = Game(WIN)

    run = True
    while run:
        clock.tick(FPS)
        game.update()

        if game.turn == WHITE:
            value, new_board = alpha_beta_pruning(game.get_board(), 4, False,
                                                  float("-inf"), float("inf"),
                                                  game)
            if new_board is None:
                print("White loose")
                run = False
                time.sleep(5000)
            else:
                game.ai_move(new_board)

        else:
            value, new_board = alpha_beta_pruning(game.get_board(), 3, True,
                                                  float("-inf"), float("inf"),
                                                  game)
            if new_board is None:
                print("White loose")
                run = False
                time.sleep(5000)
            else:
                game.ai_move(new_board)

        if game.winner() != None:
            run = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

    pygame.quit()
Beispiel #13
0
def main():
    run = True

    # Make sure game doesn't run too fast or too slow
    clock = pygame.time.Clock()

    # Create a Game object which will control the board for us
    game = Game(WIN)

    # Create an event loop while the game is running
    while run:
        clock.tick(FPS)

        if game.turn == WHITE:
            value, new_board = minimax(game.get_board(), 3, WHITE, game)
            game.ai_move(new_board)  # Get the new board after the ai has moved

        if game.winner() != None:
            print(game.winner())
            run = False

        # Check for any events happening at current time
        for event in pygame.event.get():

            # End the game and get rid of window by clicking the cross
            if event.type == pygame.QUIT:
                run = False

            # If we press any button on mouse, we first get the row, column we are in
            # Then we will select the piece on that location and move that to wherever we want to move
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Beispiel #14
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)
    white_mcts = None
    black_mcts = None
    if white_player:
        white_mcts = algorithm.MCTS(True, white_player_time)
    if black_player:
        black_mcts = algorithm.MCTS(False, black_player_time)
    game.update()
    move = []
    is_simulation_running = False
    # main loop
    while run:
        clock.tick(FPS)
        if game.winner() is not None:
            print(game.winner())
            game.display_result(WIN)
            pygame.display.update()
            wait_for_reset = True
            while wait_for_reset:
                clock.tick(FPS)
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        game.reset()
                        game.update()
                        pygame.display.update()
                        wait_for_reset = False
                    if event.type == pygame.QUIT:
                        wait_for_reset = False
                        run = False

        if not is_simulation_running:
            if game.turn == c.WHITE:
                if white_mcts:
                    t = threading.Thread(target=white_mcts.move,
                                         args=(deepcopy(game.board), move))
                    t.daemon = True
                    t.start()
                    is_simulation_running = True
                else:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            run = False

                        if event.type == pygame.MOUSEBUTTONDOWN:
                            pos = pygame.mouse.get_pos()
                            row, col = get_row_col_from_mouse(pos)
                            game.select(row, col)
            else:
                if black_mcts:
                    t = threading.Thread(target=black_mcts.move,
                                         args=(deepcopy(game.board), move))
                    t.daemon = True
                    t.start()
                    is_simulation_running = True
                else:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            run = False

                        if event.type == pygame.MOUSEBUTTONDOWN:
                            pos = pygame.mouse.get_pos()
                            row, col = get_row_col_from_mouse(pos)
                            game.select(row, col)
        elif move:
            game.ai_move(move.pop())
            is_simulation_running = False
        pygame.event.pump()
        game.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

    pygame.quit()
Beispiel #15
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)
    AIbot = AI()
    AIbot2 = AI2()
    start_side = [WHITE, RED]
    no_moves = False

    p1_wins = 0
    p2_wins = 0
    rounds = 20
    curr_round = 0

    while run:
        clock.tick(FPS)
        if game.turn == start_side[0]:
            value, new_board = AIbot.minimax(game.get_board(), 3,
                                             float('-inf'), float('inf'), True,
                                             start_side[0], game)
            if (new_board is not None):
                game.ai_move(new_board)
            else:
                no_moves = True

        elif game.turn == start_side[1]:
            value, new_board = AIbot2.minimax(game.get_board(), 3,
                                              float('-inf'), float('inf'),
                                              True, start_side[1], game)
            if (new_board is not None):
                game.ai_move(new_board)
            else:
                no_moves = True

        if game.winner() != None:
            if (game.winner() == RED):
                if (start_side[0] == RED):
                    p1_wins += 1
                    print("RED Wins! (Agent 1)")
                else:
                    p2_wins += 1
                    print("RED Wins! (Agent 2)")

            else:
                if (start_side[0] == WHITE):
                    p1_wins += 1
                    print("WHITE Wins! (Agent 1)")
                else:
                    p2_wins += 1
                    print("WHITE Wins! (Agent 1)")
            curr_round += 1
            if (curr_round >= rounds):
                run = False
            else:
                swapSide(start_side)
                game.reset()

        if no_moves == True:
            if game.turn == RED:
                if (start_side[0] == RED):
                    p2_wins += 1
                    print("WHITE Wins! (Agent 2)")
                else:
                    p1_wins += 1
                    print("WHITE Wins! (Agent 1)")
            else:
                if (start_side[0] == WHITE):
                    p2_wins += 1
                    print("RED Wins! (Agent 2)")
                else:
                    p1_wins += 1
                    print("RED Wins! (Agent 1)")
            curr_round += 1
            if (curr_round >= rounds):
                run = False
            else:
                game.reset()
                swapSide(start_side)
                no_moves = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Explored node: ", AIbot.explored_node())
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                print("Explored node: ", AIbot.explored_node())
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    print("Player 1 Win count: " + str(p1_wins))
    print("Player 2 Win count: " + str(p2_wins))
    pygame.quit()
Beispiel #16
0
def main(games = 10):

    winners = []
    allTurns = []

    for i in range(games):
        clock = pygame.time.Clock()
        game = Game(WIN)
        turns = 0
        while True:
            clock.tick(FPS)

            ############## comment when playing human vs ai #################
            if game.turn == RED:
                value, new_board = minimax(game.get_board(), 4, RED, game)
                # value, new_board = randomAI(game.get_board(), RED, game)
                
                # This means we won as moves left are impossible
                if new_board is None:
                    print("Game", i + 1, "Winner:", WHITE_NAME)
                    winners.append(WHITE_NAME)
                    allTurns.append(turns)
                    break

                game.ai_move(new_board)

            #################################################################

            if game.turn == WHITE:
                value, new_board = minimax(game.get_board(), 4, WHITE, game)

                # This means we lost
                if new_board is None:
                    print("Game", i + 1, "Winner:", RED_NAME)
                    winners.append(RED_NAME)
                    allTurns.append(turns)
                    break

                game.ai_move(new_board)



            if game.winner() is not None:
                print("Game", i + 1, "Winner:", game.winner())
                winners.append(game.winner())
                allTurns.append(turns)
                break       

            turns += 1
            game.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                
                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    row, col = get_row_col_from_mouse(pos)
                    game.select(row, col)
        
    pygame.quit()

    with open('winners.csv', mode='w') as csv_file:
        fieldnames = ['game', 'winner', 'turns']
        writer = csv.DictWriter(csv_file, fieldnames = fieldnames)

        writer.writeheader()

        for i in range(len(winners)):
            writer.writerow({'game': i + 1, 'winner': winners[i], 'turns': allTurns[i]})
Beispiel #17
0
class Control:
    def __init__(self):
        self.screen = WIN
        self.AI = True
        self.screen_rect = self.screen.get_rect()
        self.clock = pygame.time.Clock()
        self.done = False
        self.fps = 60
        self.game = Game(WIN)
        self.color = WHITE
        self.button = Button((0, 0, 200, 50),
                             RED,
                             self.change_opponent,
                             text='vs Player',
                             **BUTTON_STYLE)
        self.button2 = Button((0, 0, 200, 50),
                              RED,
                              self.main_loop,
                              text='vs AI',
                              **BUTTON_STYLE)
        self.button.rect.center = (self.screen_rect.centerx, 200)
        self.button2.rect.center = (self.screen_rect.centerx, 400)

    def ai(self):
        if self.game.turn == WHITE:
            value, new_board = minimax.algorithm(
                position=self.game.get_board(),
                depth=4,
                max_player=WHITE,
                game=self.game)
            self.game.ai_move(new_board)

    def change_opponent(self):
        self.AI = False
        self.main_loop()

    @staticmethod
    def get_row_col_from_mouse(pos):
        x, y = pos
        row = y // SQUARE_SIZE
        col = x // SQUARE_SIZE
        return row, col

    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            self.button.check_event(event)
            self.button2.check_event(event)
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = Control.get_row_col_from_mouse(pos)
                self.game.select(row, col)

    def menu(self):
        while not self.done:
            self.event_loop()
            self.screen.fill(self.color)
            self.button.update(self.screen)
            self.button2.update(self.screen)
            pygame.display.update()

    def main_loop(self):
        while not self.done:
            self.clock.tick(self.fps)

            if self.AI:
                self.ai()

            if self.game.winner():
                print(self.game.winner())
                self.done = True

            self.event_loop()
            self.game.update()
Beispiel #18
0
def main(opt):
    if opt.game_mode == 'person2person':
        run = True
        clock = pygame.time.Clock()
        game = Game(WIN)

        while run:
            clock.tick(FPS)

            if game.winner() is not None:
                print(game.winner())
                run = False

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    row, col = get_row_col_from_mouse(pos)
                    game.select(row, col)
            game.update()

    elif opt.game_mode == 'person2ai':
        run = True
        clock = pygame.time.Clock()
        game = Game(WIN)

        while run:
            clock.tick(FPS)
            if game.turn == WHITE:
                value, new_board = minimax(game.get_board(), opt.minimax_depth,
                                           WHITE, game)
                game.ai_move(new_board)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    row, col = get_row_col_from_mouse(pos)
                    game.select(row, col)
            game.update()

    elif opt.game_mode == 'ai2ai':
        run = True
        clock = pygame.time.Clock()
        game = Game(WIN)

        while run:
            clock.tick(FPS)

            if game.winner() is not None:
                print("The winner is: ", game.winner())
                run = False

            if game.turn == WHITE:
                value, new_board = minimax(game.get_board(), opt.minimax_depth,
                                           WHITE, game)
                game.ai_move(new_board)
            elif game.turn == RED:
                value, new_board = minimax(game.get_board(), opt.minimax_depth,
                                           False, game)
                game.ai_move(new_board)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            # pygame.time.delay(1000)
            game.update()

    elif opt.game_mode == 'person2ai_ml':
        pass
    elif opt.game_mode == 'ai2ai_ml':
        weights = None

        for epoch in range(opt.epochs):
            print("Epoch : {}".format(epoch))
            run = True
            clock = pygame.time.Clock()
            game = Game(WIN)
            red = white = False
            if weights is not None:
                game.board.apply_weights(weights.copy())

            print(game.board.return_weights())

            iter = 0
            while iter < 100 and run:
                clock.tick(FPS)

                if game.turn == WHITE:
                    white_value, new_board = minimax(game.get_board(),
                                                     opt.minimax_depth, True,
                                                     game)
                    situation = game.ai_move(new_board)
                    if situation:  # if we can't move any further
                        print('Can\'t move any further')
                        break
                    white = True
                elif game.turn == RED:
                    red_value, new_board = minimax(game.get_board(),
                                                   opt.minimax_depth, False,
                                                   game)
                    situation = game.ai_move(new_board)
                    if situation:
                        print('Can\'t move any further')
                        break
                    red = True

                if red and white:
                    loss = criterion(white_value, red_value)
                    game.board.optimize_weights(loss, 0.01)
                    red = white = False
                    try:
                        weights = game.board.return_weights()
                    except AttributeError:
                        pass
                    # print(loss)
                    if game.winner() is not None:
                        if game.winner() == WHITE:
                            loss = criterion(24, white_value)
                            game.board.optimize_weights(loss, 0.01)
                            print('White is the winner and the loss is : ',
                                  loss)
                            # weights = game.board.return_weights()
                            break

                        elif game.winner() == RED:
                            loss = criterion(-24, red_value)
                            game.board.optimize_weights(loss, 0.01)
                            print('Red is the winner and the loss is : ', loss)
                            # weights = game.board.return_weights()
                            break
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        run = False

                game.update()
                iter += 1
            try:
                weights = game.board.return_weights()
            except AttributeError:
                pass
            print(loss)
        # print(game.board.weights)

    pygame.quit()
Beispiel #19
0
class Checker:
    def __init__(self):
        """Initialize the main game object."""
        # Init pygame.
        self._init_pygame_object('Checker', (WIDTH, HEIGHT), 60)
        self._init_icon(ICON_DIR)

        # Init game status attributes.
        self.active = True
        self.new_game = True
        self.clock = pygame.time.Clock()

        # Create game object.
        self.game = Game(self.win)

        # Create PLAY button.
        self.play_button = PlayButton(self.win)

        # Load background image.
        self.bg_img = pygame.transform.scale(pygame.image.load(BG_DIR),
                                             (WIDTH, HEIGHT))

    def _init_pygame_object(self, game_caption, window_size, fps):
        """Initialize pygame object with some basic attributes."""
        pygame.init()
        pygame.display.set_caption(game_caption)
        self.FPS = fps
        self.win = pygame.display.set_mode(window_size)

    def _init_icon(self, icon_path):
        """Initialize icon for the game."""
        self.icon = pygame.image.load(ICON_DIR)
        pygame.display.set_icon(self.icon)

    @classmethod
    def _get_row_col_from_mouse(cls, pos):
        x, y = pos
        # x ~ column
        # y ~ row
        return y // SQUARE_SIZE, x // SQUARE_SIZE

    def _check_events(self):
        """Handle key and mouse interactions."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.active = False
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if self.new_game:
                    self._check_button(mouse_pos)
                else:
                    # Get the row and column of the clicked position.
                    row, col = Checker._get_row_col_from_mouse(mouse_pos)
                    self.game.select(row, col)

    def _check_keydown_events(self, event):
        """Handle keypress events."""
        if event.key == pygame.K_q:
            self.active = False

    def _check_button(self, mouse_pos):
        """Start a new game when user click the Play button."""
        play_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if play_clicked:
            self.new_game = False

    def _start_new_game(self):
        """Start a new game."""
        self.win.fill((0, 0, 0))
        self.win.blit(self.bg_img, (0, 0))
        self.play_button.draw_button()
        pygame.display.flip()

    def _check_winner(self):
        """Check if there is a winner."""
        winner = self.game.get_winner()
        if winner is not None:
            print(winner)
            self.active = False

    def run(self):
        while self.active:
            self.clock.tick(self.FPS)

            if not self.new_game:
                if self.game.turn == WHITE:
                    value, new_board = minimax(self.game.get_board(), 3, True,
                                               self.game)
                    self.game.ai_move(new_board)

                self._check_winner()
                self.game.update()
            else:
                self._start_new_game()

            self._check_events()