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()
    def __init__(self, path_rede_branca, path_rede_preta):
        self.rede_branca = pickle.load(open(path_rede_branca, "rb"))
        self.rede_preta = pickle.load(open(path_rede_preta, "rb"))
        self.train_time = self.rede_branca['time']
        self.game = Game()
        self.game.consecutive_noncapture_move_limit = 300
        # self.game.consecutive_noncapture_move_limit = 40
        self.players = {1: -1, 2: 1}
        self.playersPrint = {1: 'B', 2: 'P'}

        index = np.arange(1, 33)
        self.positions_map = {}
        for i, j in zip(np.arange(1, 5), np.arange(1, 8, 2)):
            self.positions_map[i] = [0, j]
            self.positions_map[i + 8] = [2, j]
            self.positions_map[i + 16] = [4, j]
            self.positions_map[i + 24] = [6, j]

        for i, j in zip(np.arange(5, 9), np.arange(0, 8, 2)):
            self.positions_map[i] = [1, j]
            self.positions_map[i + 8] = [3, j]
            self.positions_map[i + 16] = [5, j]
            self.positions_map[i + 24] = [7, j]

        self.sr_branca = 0
        self.draw = 0
        self.sr_preta = 0
Beispiel #3
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()
Beispiel #4
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()
 def __init__(self, tournament_id):
     self.tournament_id = tournament_id
     self.moves = []
     self.start_time = None
     self.end_time = None
     self.game = Game()
     self.start()
Beispiel #6
0
def main():
    run = True
    clock = pg.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())

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

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

                game.select(row, col)


        game.update()

    pg.quit()
Beispiel #7
0
    def _min_max(self, game: Game,
                 maximize_score: bool,
                 move_list: List[Tuple[int, int]] = None,
                 alpha=MinMaxWeight.LOSE, beta=MinMaxWeight.WIN,
                 depth=0) \
            -> Tuple[float, Optional[int]]:
        """
        Calculate the min max
        :param depth: The current depth of the branch
        :return: The score and the move
        """

        # Check if the game is over
        if game.is_over():
            winner = game.get_winner()
            if winner == self.player:
                return MinMaxWeight.WIN, None
            return MinMaxWeight.LOSE, None

        # Check if the max depth is reached
        if depth >= self.branch_depth:
            return self.evaluate_path(game), None

        if not move_list:
            move_list = game.get_possible_moves()
            random.shuffle(move_list)

        # Get the smallest/largest number to initialize the var
        best_score: float = MinMaxWeight.LOSE if maximize_score else MinMaxWeight.WIN
        best_move = move_list[0]

        # Iterate through the moves and recursively find the best
        for move in move_list:
            updated_game = copy.deepcopy(game)
            updated_game.move(move)
            returned_best_score, _ = MinMax._min_max(self,
                                                     updated_game,
                                                     not maximize_score,
                                                     alpha=alpha,
                                                     beta=beta,
                                                     depth=depth + 1)

            if maximize_score and best_score < returned_best_score:
                best_score = returned_best_score
                best_move = move
                alpha = max(alpha, best_score)

                if beta <= alpha:
                    break

            elif not maximize_score and returned_best_score < best_score:
                best_score = returned_best_score
                best_move = move
                beta = min(beta, best_score)

                if beta <= alpha:
                    break

        return best_score, best_move
Beispiel #8
0
    def __init__(self, player: int, *_):
        """
        Generate a new Random game
        :param player: The player of the RandomGame (1 or 2)
        """

        self.player = player
        self._game = Game()
    def startGame(self):
        self.game = Game()
        while 1:
            try:
                player = int(
                    input(
                        "Deseja jogar com as peças brancas (1) ou pretas (2): "
                    ))
                if player == 1 or player == 2:
                    self.player = player
                    break
                else:
                    print("Escolha inválida")
            except:
                print("Escolha inválida")
        if self.player == 2:
            k1 = self.rede_branca['k']
            weights = self.rede_branca['weights']
            num_hidden_layers = self.rede_branca['num_hidden_layers']
            hidden_size = self.rede_branca['hidden_size']
        else:
            k1 = self.rede_preta['k']
            weights = self.rede_preta['weights']
            num_hidden_layers = self.rede_preta['num_hidden_layers']
            hidden_size = self.rede_preta['hidden_size']
        k2 = -1 * k1

        limit = 33 * hidden_size
        weights = [
            self.reconstructWeightsMatrix(weights[:limit], 0, hidden_size),
            self.reconstructWeightsMatrix(weights[limit:-1], 1, hidden_size)
        ]  #temporario pra contornar o sigma
        rede = [num_hidden_layers, hidden_size, weights]

        print("\nAs posições são as seguintes: \n")
        self.printBoard(board_encoded=None, demo=True)

        print("\nJogador 1 começa\n")

        while not self.game.is_over():
            board_encoded = self.createBoard(self.game, k1, k2, print=True)
            self.printBoard(board_encoded)

            if self.game.whose_turn() != self.player:
                self.play(k1, k2, rede, rede)
            else:
                selected = self.selectMove()
                if not isinstance(selected, list) and selected < 0:
                    break
                self.game.move(selected)

            print("Vez do jogador ", self.game.whose_turn())

        if not isinstance(selected, list) and selected < 0:
            print("Player ", self.player, " desistiu. Jogador ",
                  3 - self.player, " venceu.")
        else:
            print("Player ", self.game.get_winner(), " venceu")
def initialize_game(moves):
    game = Game()
    boards = [game.board]

    for move in moves:
        game.move(move)
        boards.append(game.board)

    return game, boards
Beispiel #11
0
 def __init__(self, board: str = None) -> None:
     self.game = Game()
     if board:
         lines = board.split('\n')
         self.theme = int(lines.pop(0))
         for mov in lines.pop(0).split():
             self.game.move(list(map(int, mov.split(','))))
     else:
         self.theme = 0
    def test_possible_moves(self):
        self.game = Game()

        self.expect([[9, 13], [9, 14], [10, 14], [10, 15], [11, 15], [11, 16],
                     [12, 16]]).move([10, 14])
        self.expect([[21, 17], [22, 17], [22, 18], [23, 18], [23, 19],
                     [24, 19], [24, 20]]).move([23, 18])
        self.expect([[14, 23]]).move([14, 23])
        self.expect([[26, 19], [27, 18]]).move([27, 18])
        self.expect([[6, 10], [7, 10], [9, 13], [9, 14], [11, 15], [11, 16],
                     [12, 16]]).move([9, 13])
        self.expect([[18, 14], [18, 15], [21, 17], [22, 17], [24, 19],
                     [24, 20], [26, 23], [31, 27], [32, 27]]).move([21, 17])
        self.expect([[5, 9], [6, 9], [6, 10], [7, 10], [11, 15], [11, 16],
                     [12, 16]]).move([6, 10])
        self.expect([[17, 14], [18, 14], [18, 15], [24, 19], [24, 20],
                     [25, 21], [26, 23], [31, 27], [32, 27]]).move([18, 14])
        self.expect([[1, 6], [2, 6], [5, 9], [10, 15], [11, 15], [11, 16],
                     [12, 16]]).move([2, 6])
        self.expect([[14, 9], [22, 18], [24, 19], [24, 20], [25, 21], [26, 23],
                     [31, 27], [32, 27]]).move([31, 27])
        self.expect([[5, 9], [6, 9], [10, 15], [11, 15], [11, 16],
                     [12, 16]]).move([11, 16])
        self.expect([[14, 9], [22, 18], [24, 19], [24, 20], [25, 21], [26, 23],
                     [27, 23]]).move([22, 18])
        self.expect([[13, 22]]).move([13, 22])
        self.expect([[22, 31]]).move(
            [22, 31]
        )  #double jump where 10-17 is also in a jumpable position if not for piece restriction
        self.expect([[14, 9], [18, 15], [24, 19], [24, 20], [25, 21], [25, 22],
                     [27, 23], [30, 26]]).move([24, 19])
        self.expect([[10, 17], [16, 23], [31, 24]]).move([31, 24])
        self.expect([[24, 15]]).move([24, 15])
        self.expect([[15, 22]]).move([15, 22])
        self.expect([[25, 18]]).move([25, 18])
        self.expect([[10, 17]]).move([10, 17])
        self.expect([[18, 14], [18, 15], [28, 24], [29, 25], [30, 25],
                     [30, 26], [32, 27]]).move([29, 25])
        self.expect([[5, 9], [6, 9], [6, 10], [7, 10], [7, 11], [8, 11],
                     [16, 19], [16, 20], [17, 21], [17, 22]]).move([17, 21])
        self.expect([[18, 14], [18, 15], [25, 22], [28, 24], [30, 26],
                     [32, 27]]).move([30, 26])
        self.expect([[21, 30]]).move([21, 30])
        self.expect([[18, 14], [18, 15], [26, 22], [26, 23], [28, 24],
                     [32, 27]]).move([18, 15])
        self.expect([[30, 23]]).move([30, 23])
        self.expect([[15, 10], [15, 11], [28, 24], [32, 27]]).move([15, 11])
        self.expect([[8, 15]]).move([8, 15])
        self.expect([[28, 24], [32, 27]]).move([28, 24])
        self.expect([[3, 8], [4, 8], [5, 9], [6, 9], [6, 10], [7, 10], [7, 11],
                     [15, 18], [15, 19], [16, 19], [16, 20], [23, 26],
                     [23, 27], [23, 18], [23, 19]]).move([4, 8])
        self.expect([[24, 19], [24, 20], [32, 27], [32, 28]]).move([24, 19])
        self.expect([[15, 24]]).move([15, 24])
        self.expect([[32, 27], [32, 28]]).move([32, 27])
        self.expect([[23, 32], [24, 31]]).move([23, 32])
        self.expect([])
Beispiel #13
0
def test_game():
    james = RandomPlayer('James')
    peter = RandomPlayer('Peter')
    a_game = Game(james, peter)
    assert a_game.winner == 'Nobody'

    a_game.play()
    print('The winner is {}'.format(a_game.winner))
    for i, j, val in a_game.moves:
        print('{i}, {j} : {val}'.format(i=i, j=j, val=val))
Beispiel #14
0
    def test_get_possible_next_states(self):
        game1 = Game()
        game2 = game1.move([11, 16])

        next_states = game1.get_possible_next_states(actual_next_state=game2)
        self.assertEqual(len(next_states), 7)
        self.assertEqual(type(next_states[0]), Game)

        actual_next_state = next(s for s in next_states
                                 if s.last_move() == [11, 16])
        self.assertEqual(actual_next_state, game2)
def main():
    game = Game()
    game.consecutive_noncapture_move_limit = 100
    while (not game.is_over()):
        if game.whose_turn() == 1:
            human_move(
                game
            )  # if you want the bot to play for the human replace this line with bot_move(game,desired_depth)
            # bot_move(game, 1)
        else:
            bot_move(game, 5)
        print_game_to_console(game)
Beispiel #16
0
    def startGame(self, num_matches, num_executions=1):
        self.game = Game()
        self.sr_branca = 0
        self.draw_branca = 0
        self.sr_preta = 0
        self.draw_preta = 0
        
        k1 = self.rede_branca['k']
        k2 = self.rede_preta['k']


        weights = self.rede_branca['weights']
        num_hidden_layers = self.rede_branca['num_hidden_layers']
        hidden_size = self.rede_branca['hidden_size']
        limit = 33*hidden_size
        weights = [self.reconstructWeightsMatrix(weights[:limit], 0, hidden_size),
            self.reconstructWeightsMatrix(weights[limit:], 1, hidden_size)]
        rede_branca = [num_hidden_layers, hidden_size, weights]

        weights = self.rede_preta['weights']
        num_hidden_layers = self.rede_preta['num_hidden_layers']
        hidden_size = self.rede_preta['hidden_size']
        limit = 33*hidden_size
        weights = [self.reconstructWeightsMatrix(weights[:limit], 0, hidden_size),
            self.reconstructWeightsMatrix(weights[limit:], 1, hidden_size)]
        rede_preta = [num_hidden_layers, hidden_size, weights]


        self.sr_branca = np.zeros(num_executions)
        self.sr_preta = np.zeros(num_executions)
        self.draw = np.zeros(num_executions)
        for e in tqdm(range(num_executions)):
            for i in tqdm(range(num_matches), leave=False):
                while not self.game.is_over():
                    if self.game.whose_turn() == 1:
                        self.play(k1, k1, rede_branca, rede_preta)
                    else:
                        self.play(k2, k2, rede_branca, rede_preta)

                if self.game.get_winner() is not None:
                    if self.game.get_winner() == 1:
                        self.sr_branca[e] += 1/num_matches
                        # self.sr_branca += 1/num_matches
                    else:
                        self.sr_preta[e] += 1/num_matches
                        # self.sr_preta += 1/num_matches
                else:
                    self.draw[e] += 1/num_matches
                    # self.draw += 1/num_matches
                
                self.game = Game()
Beispiel #17
0
def main():
    run = True
    # define a clock if we want our game to run in a constant frame rate
    clock = pygame.time.Clock()
    game = Game(WIN)

    while run:
        clock.tick(
            FPS
        )  # to make sure the main event loop does not run too fast or too slow

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

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

            if event.type == pygame.MOUSEBUTTONDOWN:  # pressing buttons
                # when we click, pygame will take the position of our 'click'
                pos = pygame.mouse.get_pos()
                # take the row and column corresponding to this position
                row, col = get_row_col_from_mouse(pos)
                # the board will recognize the piece in these row and column
                game.select(row, col)

        game.update()

    pygame.quit()
def play_game(prediction_request, simulation_depth):
    startTime = datetime.now()
    global game, player1, player2

    game = Game()
    player1 = Player(1, game, MultiprocessModel(prediction_request))
    player2 = Player(2, game, MultiprocessModel(prediction_request))

    while not game.is_over():
        play_turn(simulation_depth)

    finalize_lessons()

    print('game over', datetime.now() - startTime, len(game.moves), 'moves')
Beispiel #19
0
def main():
	run = True
	clock = pygame.time.Clock()
	game = Game(WIN)
	

	while run:
		clock.tick(FPS)

		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()
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.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 #21
0
def main():
    """Game running example."""

    # Pick both players, User or RandomBot require a Player parameter...
    black_bot = User(Player.black)
    # ...and CheckerBot does too. An optional parameter is an integer
    # that represents the depth for the Bot. By default is 6.
    white_bot = CheckersBot(Player.white, 6)

    # Start Game class selecting how many games will be played.
    game = Game(1)

    # Start the program indicating the white player, the black one,
    # a boolean that requests printing on the console (True prints
    # the board), and who will have the first turn.
    game.simulate(white_bot, black_bot, True, Player.white)
Beispiel #22
0
 def test_position_layout_2d(self):
     board = Game().board
     np.testing.assert_array_equal(
         board.position_layout_2d,
         np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
                   [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24],
                   [25, 26, 27, 28], [29, 30, 31, 32]]))
Beispiel #23
0
def main():
    # What we run to run game

    run = True  # If you want the game to run
    clock = pygame.time.Clock()  # The fps speed of the game
    game = Game(WIN)

    while run:
        clock.tick(FPS)
        if game.winner() != None:
            print(f"{game.winner()} has won!!!")
        # The pygame event handler

        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # If hit red cross on pygame window
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:  # If any button on mouse pressed down
                pos = pygame.mouse.get_pos()
                row, col = row_col_from_mouse(pos)

                game.select(row, col)

        game.update()

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

    # mouse_pos is a tuple
    def get_row_col_from_mouse(mouse_pos):
        x, y = mouse_pos
        mouse_row = y // SQUARE_SIZE
        mouse_col = x // SQUARE_SIZE
        return mouse_row, mouse_col

    while run:
        # clock.tick(FPS)
        if game.winner() is not None:
            print(f"The winner is {game.winner()}!")
            break
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                # send the position of the selected square
                game.select(row, col)
        game.update()
    pygame.quit()
Beispiel #25
0
class Animation:
    def __init__(self):
        self.win = pygame.display.set_mode((WIDTH, HEIGHT + SQUARE_SIZE))
        pygame.display.set_caption("Checkers")
        self.game = Game(self.win)
        self.game_over = False
        self.end_screen = EndScreen(self.win, None)

    def update(self):
        result = self.game.get_winner()
        if self.game_over:
            self.game.board.draw(self.win)
            self.end_screen.draw()
        if result:
            self.end_screen.set_winner(result)
            self.game_over = True
        else:
            self.game.update()
        pygame.display.flip()

    def mouse_down(self, position):
        if not self.game_over:
            self.game.select(position)
        else:
            if self.end_screen.clicked(position):
                self.game.reset()
                self.game_over = False
class TournamentGame():
    def __init__(self, tournament_id):
        self.tournament_id = tournament_id
        self.moves = []
        self.start_time = None
        self.end_time = None
        self.game = Game()
        self.start()

    def start(self):
        self.start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    def end(self):
        self.end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    def move(self, move):
        self.game.move(move)
        self.moves.append(move)
Beispiel #27
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 #28
0
 def test_flip(self):
     board = Game().board
     self.assertEqual(board.flip_position(32), 1)
     self.assertEqual(board.flip_position(1), 32)
     self.assertEqual(board.flip_position(29), 4)
     self.assertEqual(board.flip_position(4), 29)
     self.assertEqual(board.flip_position(19), 14)
     self.assertEqual(board.flip_position(14), 19)
Beispiel #29
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)

    while run:
        clock.tick(FPS)

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                position = pygame.mouse.get_pos()
                row, col = get_coordinates_from_mouse_click(position)

        game.update()

    pygame.quit()
Beispiel #30
0
def join(sid, data):
    global games
    global playerColors

    playerColors[sid] = data["playerColor"]

    # print(playerColors[sid])
    games[sid] = Game()

    return {"board": games[sid].get_board_state()}