Esempio n. 1
0
 def get_cur_turn_side(self):
     if self.game_state is GameStates.ONLINE_GAME:
         player_turn = self.current_move
     else:
         player_turn = self.player_turn
     if player_turn is None:
         return None
     return Side(player_turn)
Esempio n. 2
0
    def roque_right(self, chess_board, correct_cells):

        # self does not move
        if self.was_moved is True:
            return

        # self not on check
        attack_cells = chess_board.summary_attacked_cells(
            Side.get_oposite(self.side))

        if self.position in attack_cells:
            return

        if self.side == Side.WHITE:
            default_rook_right_pos = gb.GameBoard.default_white_rook_right_pos
        else:
            default_rook_right_pos = gb.GameBoard.default_black_rook_right_pos

        right_rook = chess_board.get(default_rook_right_pos)

        # rook does not move
        if not (right_rook is not None and isinstance(right_rook, Rook)
                and right_rook.was_moved is False):
            return

        # not on attack cell
        if self.position + Vector2d(1, 0) in attack_cells:
            return

        ray_to_rook = []
        _add_correct_cells_by_ray(self.position, ray_to_rook, chess_board,
                                  Side.get_oposite(self.side), 1, 0)
        if len(ray_to_rook) == 0:
            return
        if chess_board.get(ray_to_rook[len(ray_to_rook) -
                                       1]).position != default_rook_right_pos:
            return

        correct_cells.append(self.position + Vector2d(2, 0))
Esempio n. 3
0
 def is_that_mate(self, my_side):
     enemy_figures = self.get_figures_list(Side.get_oposite(my_side))
     for i in range(len(enemy_figures)):
         cur_figure = enemy_figures[i]
         available_moves = cur_figure.generate_moves(self)
         for j in range(len(available_moves)):
             new_chess_board = copy.deepcopy(self)
             if new_chess_board.get(cur_figure.position) is None:
                 print(cur_figure.position.x)
                 print(cur_figure.position.y)
             new_chess_board.make_move(Move(cur_figure.position, available_moves[j]))
             if new_chess_board.is_that_check(my_side) is False:
                 return False
     return True
Esempio n. 4
0
    def check_move(self, move, side):
        """
        Check current position state function
        :param side: player current side
        :param move: move figure sructure (Vector2d)
        :param chess_board: chess board class (see ChessBoard.Board)
        :return: MoveResult
        """
        result = MoveResult.INCORRECT

        figure_in_src = self.game_board.get(move.point_from)

        if figure_in_src is None:
            return result

        if figure_in_src.side != side:
            return result

        if figure_in_src is None:
            return result

        my_side = figure_in_src.side
        correct_moves = figure_in_src.generate_moves(self.game_board)
        if len(correct_moves) == 0:
            return result

        if move.point_to in correct_moves:
            result = MoveResult.DEFAULT

        if result == MoveResult.INCORRECT:
            return result

        new_game_board = copy.deepcopy(self.game_board)
        new_game_board.make_move(move)
        if new_game_board.is_that_check(Side.get_oposite(my_side)):
            result = MoveResult.INCORRECT

        if result == MoveResult.INCORRECT:
            return result

        if new_game_board.is_that_check(my_side):
            result = MoveResult.CHECK
            if new_game_board.is_that_mate(my_side):
                result = MoveResult.MATE
        else:
            if new_game_board.is_that_stalemate(my_side):
                result = MoveResult.STALEMATE

        return result
Esempio n. 5
0
 def __init__(self, side, game_controller):
     """
     Initialize bot class function
     """
     super().__init__(side)
     self.side = Side(side)
     self.move = None
     self.game_controller = game_controller
     self.is_move_calculating = False
     self.value = None
     self.depth = 2
     self.pawn_swaped_figure = None
     self.pawn_swaped_latters = None
     if self.side is Side.WHITE:
         self.pawn_swaped_latters = ["Q", "N", "R", "B"]
     else:
         self.pawn_swaped_latters = ["q", "n", "r", "b"]
Esempio n. 6
0
    def check_board_res(self, side):
        result = MoveResult.DEFAULT

        new_game_board = copy.deepcopy(self.game_board)
        if new_game_board.is_that_check(Side.get_oposite(side)):
            result = MoveResult.INCORRECT

        if result == MoveResult.INCORRECT:
            return result

        if new_game_board.is_that_check(side):
            result = MoveResult.CHECK
            if new_game_board.is_that_mate(side):
                result = MoveResult.MATE
        else:
            if new_game_board.is_that_stalemate(side):
                result = MoveResult.STALEMATE

        return result
Esempio n. 7
0
    def on_update_time(self, text_dict):
        if self.game_state != GameStates.ONLINE_GAME:
            return

        if int(text_dict['is_playing']) == 0:
            self.online_game_was_started = False
            self.render.is_game_played = False
            if text_dict['result'] is None:
                self.game_result = None
            else:
                self.game_result = Side(int(text_dict['result']))
                if self.game_result == self.local_player.side:
                    self.render.sound.play(SoundTypes.WIN)
            self.delta_rate = self.rate - int(text_dict['self_rate'])
            self.rate = int(text_dict['self_rate'])

        self.local_player.update_login(self.login)
        self.local_player.update_rate(self.rate)
        self.local_player.init_time_from_str(text_dict['self_time'])

        self.online_player.update_rate(text_dict['opponent_rate'])
        self.online_player.init_time_from_str(text_dict['opponent_time'])
Esempio n. 8
0
def on_update_board(data):
    print("Message recieved: " + str(data))
    paramsDict = supp.getParamsValMap(data)

    # get board from database
    if clients[request.sid] is not None:
        query = "select * from chess.get_current_game_board_state({0})".format(clients[request.sid])
    else:
        return
    try:
        rec = execute_one_res_async(query)
        print("Game state is " + str(rec))
        board = rec[0]
        side = int(rec[1])
    except:
        print("Game doesn't exists")
        return
    # print("server_board is " + str(rec))
    # convert to game_controller
    print("Board is " + str(board))
    print("Side is " + str(side))
    if board is not None:
        cur_game_controller = game_controller.GameController(None, str(board))
    else:
        cur_game_controller = game_controller.GameController(Board())

    move = vec.Move(vec.Vector2d(int(paramsDict['p1']), int(paramsDict['p2'])),
                    vec.Vector2d(int(paramsDict['p3']), int(paramsDict['p4'])))

    res = cur_game_controller.check_move(move, Side(side))

    if res == game_controller.MoveResult.INCORRECT:
        print("Wrong move send")
        return

    is_playing = 1
    game_result = None
    pawn_swaped_figure = paramsDict['swapped_figure']

    print('Swaped figure is ' + str(pawn_swaped_figure))

    cur_game_controller.update(move, Side(side))

    if pawn_swaped_figure is not None:
        cur_game_controller.swap_pawn(move.point_to, pawn_swaped_figure)
        res = cur_game_controller.check_board_res(Side(side))

    if res == game_controller.MoveResult.STALEMATE:
        is_playing = 0
    elif res == game_controller.MoveResult.MATE:
        is_playing = 0
        game_result = 0 if Side(side) is Side.WHITE else 1

    if game_result is None:
        execute_no_res_async("call chess.update_game_state({0}, '{1}', "
                             "{2}::bit, NULL)".format(clients[request.sid],
                                                      cur_game_controller.serialize_to_str(),
                                                      is_playing))
    else:
        execute_no_res_async("call chess.update_game_state({0}, '{1}', "
                             "{2}::bit, {3}::bit)".format(clients[request.sid],
                                                          cur_game_controller.serialize_to_str(),
                                                          is_playing,
                                                          game_result))
Esempio n. 9
0
    def calc_best_move(self,
                       depth,
                       game,
                       player_color,
                       alpha=-999999999,
                       beta=999999999,
                       is_maximizing_player=True):
        # Base case: evaluate board
        if depth == 0:
            value = game.game_board.evaluate(self.side)
            return value, None

        # Recursive case: search possible moves
        best_swaped_figure = None
        best_move = None  # best move not set yet
        possible_moves = game.game_board.summary_moves(player_color)

        # Set random order for possible moves
        shuffle(possible_moves)

        # Set a default best move value
        if is_maximizing_player:
            best_move_value = -99999999
        else:
            best_move_value = 99999999

        # Search through all possible moves
        for i in range(len(possible_moves)):
            move_res = game.check_move(possible_moves[i], player_color)
            if move_res is not MoveResult.INCORRECT:
                move = possible_moves[i]

                # Make the move, but undo before exiting loop
                new_game = copy.deepcopy(game)
                new_game.update(possible_moves[i], player_color)

                # pawn swaped check
                expected_pawn = new_game.game_board.get(move.point_to)
                if isinstance(expected_pawn, Figures.Pawn):
                    assert (self.pawn_swaped_latters is not None)
                    if expected_pawn.side is Side.WHITE:
                        if move.point_to.y == 0:
                            for figure_lat in self.pawn_swaped_latters:
                                new_game.swap_pawn(move.point_to, figure_lat)
                                value, move_side_effect = self.calc_best_move(
                                    depth - 1, new_game,
                                    Side.get_oposite(player_color), alpha,
                                    beta, not is_maximizing_player)
                                if is_maximizing_player:
                                    # Look for moves that maximize position
                                    if value > best_move_value:
                                        best_move_value = value
                                        best_move = move
                                        best_swaped_figure = figure_lat
                                    alpha = max(alpha, value)
                                else:
                                    # Look for moves that minimize position
                                    if value < best_move_value:
                                        best_move_value = value
                                        best_move = move
                                        best_swaped_figure = figure_lat
                                    beta = min(beta, value)

                                # Check for alpha beta pruning
                                if beta <= alpha:
                                    # print('Prune', alpha, beta)
                                    return best_move_value, best_move
                        else:
                            # Recursively get the value from this move
                            value, move_side_effect = self.calc_best_move(
                                depth - 1, new_game,
                                Side.get_oposite(player_color), alpha, beta,
                                not is_maximizing_player)
                            if is_maximizing_player:
                                # Look for moves that maximize position
                                if value > best_move_value:
                                    best_move_value = value
                                    best_move = move
                                alpha = max(alpha, value)
                            else:
                                # Look for moves that minimize position
                                if value < best_move_value:
                                    best_move_value = value
                                    best_move = move
                                beta = min(beta, value)

                            # Check for alpha beta pruning
                            if beta <= alpha:
                                # print('Prune', alpha, beta)
                                return best_move_value, best_move

                    if expected_pawn.side is Side.BLACK:
                        if move.point_to.y == 7:
                            for figure_lat in self.pawn_swaped_latters:
                                new_game.swap_pawn(move.point_to, figure_lat)
                                value, move_side_effect = self.calc_best_move(
                                    depth - 1, new_game,
                                    Side.get_oposite(player_color), alpha,
                                    beta, not is_maximizing_player)
                                if is_maximizing_player:
                                    # Look for moves that maximize position
                                    if value > best_move_value:
                                        best_move_value = value
                                        best_move = move
                                        best_swaped_figure = figure_lat
                                    alpha = max(alpha, value)
                                else:
                                    # Look for moves that minimize position
                                    if value < best_move_value:
                                        best_move_value = value
                                        best_move = move
                                        best_swaped_figure = figure_lat
                                    beta = min(beta, value)

                                # Check for alpha beta pruning
                                if beta <= alpha:
                                    # print('Prune', alpha, beta)
                                    return best_move_value, best_move
                        else:
                            # Recursively get the value from this move
                            value, move_side_effect = self.calc_best_move(
                                depth - 1, new_game,
                                Side.get_oposite(player_color), alpha, beta,
                                not is_maximizing_player)
                            if is_maximizing_player:
                                # Look for moves that maximize position
                                if value > best_move_value:
                                    best_move_value = value
                                    best_move = move
                                alpha = max(alpha, value)
                            else:
                                # Look for moves that minimize position
                                if value < best_move_value:
                                    best_move_value = value
                                    best_move = move
                                beta = min(beta, value)

                            # Check for alpha beta pruning
                            if beta <= alpha:
                                # print('Prune', alpha, beta)
                                return best_move_value, best_move
                else:
                    # Recursively get the value from this move
                    value, move_side_effect = self.calc_best_move(
                        depth - 1, new_game, Side.get_oposite(player_color),
                        alpha, beta, not is_maximizing_player)

                    if is_maximizing_player:
                        # Look for moves that maximize position
                        if value > best_move_value:
                            best_move_value = value
                            best_move = move
                        alpha = max(alpha, value)
                    else:
                        # Look for moves that minimize position
                        if value < best_move_value:
                            best_move_value = value
                            best_move = move
                        beta = min(beta, value)

                    # Check for alpha beta pruning
                    if beta <= alpha:
                        # print('Prune', alpha, beta)
                        return best_move_value, best_move

        if depth == self.depth:
            self.move = best_move
            self.value = best_move_value
            self.pawn_swaped_figure = best_swaped_figure

        return best_move_value, best_move
Esempio n. 10
0
 def update(self, move, side):
     figure = self.game_board.get(move.point_from)
     assert figure is not None
     self.game_board.make_move(move)
     self.game_board.delete_double_move(Side.get_oposite(side))
Esempio n. 11
0
 def is_that_check(self, my_side):
     attacked_cells = self.summary_attacked_cells(my_side)
     enemy_king_cell = self.get_king_cell(Side.get_oposite(my_side))
     return enemy_king_cell in attacked_cells
Esempio n. 12
0
    def on_update_game(self, text_dict):
        while self.server_calculation:
            sleep(5.0 / 1000.0)
        self.server_calculation = True
        self.game_state = GameStates.MENU
        self.game_result = -1
        self.delta_rate = 0

        self.current_move = int(text_dict['next_move'])

        if text_dict['board'] is None:
            self.chess_board = Board()
            self.game_controller = GameController(self.chess_board)
        else:
            print("board is " + str(text_dict['board']))
            # play music
            self.render.sound.play(SoundTypes.MOVE)
            self.game_controller = GameController(None,
                                                  str(text_dict['board']))

        if text_dict['side'] == '0':
            self.local_player = LocalPlayer(Side.WHITE)
            self.online_player = Player(Side.BLACK)
            self.render.whiteside_pack_name = text_dict['self_pack']
            self.render.blackside_pack_name = text_dict['opponent_pack']
            self.render.side = Side.BLACK  # watch opponent
        else:
            self.local_player = LocalPlayer(Side.BLACK)
            self.online_player = Player(Side.WHITE)
            self.render.whiteside_pack_name = text_dict['opponent_pack']
            self.render.blackside_pack_name = text_dict['self_pack']
            self.render.side = Side.WHITE  # watch opponent

        self.render.process_set_move_player = self.local_player.set_move
        self.render.check_move_func_for_pawn_swap = self.game_controller.check_move
        if self.online_game_was_started is False:
            self.online_game_was_started = True
            self.render.is_game_played = True
            self.render.change_state(self.render, "fsm:GameState")
            self.render.cur_state.update_camera(self.local_player.side)

        self.render.cur_state.check_move_func = self.game_controller.check_move

        if int(text_dict['is_playing']) == 0:
            self.online_game_was_started = False
            self.render.is_game_played = False
            if text_dict['result'] is None:
                self.game_result = None
            else:
                self.game_result = Side(int(text_dict['result']))
                if self.game_result == self.local_player.side:
                    self.render.sound.play(SoundTypes.WIN)
            self.delta_rate = self.rate - int(text_dict['self_rate'])
            self.rate = int(text_dict['self_rate'])

        self.local_player.update_login(self.login)
        self.local_player.update_rate(self.rate)
        self.local_player.init_time_from_str(text_dict['self_time'])

        self.online_player.update_login(text_dict['opponent_login'])
        self.online_player.update_rate(text_dict['opponent_rate'])

        self.online_player.init_time_from_str(text_dict['opponent_time'])

        self.render_update_board()
        self.game_state = GameStates.ONLINE_GAME
        self.server_calculation = False
Esempio n. 13
0
    def step(self, task):
        """
        Main loop function
        :return: NONE.
        """

        if self.render.on_update_now or self.render.is_clearing or self.server_calculation:
            return Task.cont
        self.server_calculation = True
        self.render.on_update_now = True
        if self.game_state == GameStates.OFFLINE_GAME:
            if self.offline_game_played is None:
                self.offline_game_played = True
                self.render_update_board()
            cur_player = self.players[self.player_turn]
            # obtain time
            cur_player.update_time()
            self.render.cur_state.update_game_info(self.players[0].login,
                                                   self.players[0].time_str(),
                                                   self.players[0].rate,
                                                   self.players[1].login,
                                                   self.players[1].time_str(),
                                                   self.players[1].rate)

            move = cur_player.get_move()
            if cur_player.is_time_over():
                self.game_result = self.players[(self.player_turn + 1) %
                                                2].side
                self.delta_rate = 20
                self.offline_game_played = False
                if self.game_result == self.players[(self.player_turn + 1) %
                                                    2].side:
                    self.render.sound.play(SoundTypes.WIN)
            if move is not None:
                pawn_swaped_figure = cur_player.get_pawn_swaped_figure()
                move_res = self.game_controller.check_move(
                    move, cur_player.side)

                if move_res != MoveResult.INCORRECT and self.game_result == -1:
                    self.game_controller.update(move, cur_player.side)

                    if pawn_swaped_figure is not None:
                        self.game_controller.swap_pawn(move.point_to,
                                                       pawn_swaped_figure)
                        move_res = self.game_controller.check_board_res(
                            cur_player.side)
                        assert (move_res != MoveResult.INCORRECT)

                    self.player_turn = (self.player_turn + 1) % 2
                    self.players[self.player_turn].restart_timer()
                    # game over
                    if move_res == MoveResult.MATE:
                        self.game_result = cur_player.side
                        self.delta_rate = 20
                        self.offline_game_played = False
                        if self.game_result == self.players[(self.player_turn +
                                                             1) % 2].side:
                            self.render.sound.play(SoundTypes.WIN)
                    elif move_res == MoveResult.STALEMATE:
                        self.game_result = None
                        self.delta_rate = 0
                        self.offline_game_played = False
                    elif self.current_offline_game_mode is OfflineGameMode.WITH_FRIEND:
                        self.render.cur_state.side = self.players[
                            self.player_turn].side
                        self.render.cur_state.middle_click(steps=30)
                    # play music
                    self.render.sound.play(SoundTypes.MOVE)

                self.render.process_set_move_player = self.players[
                    self.player_turn].set_move
            if move is not None or self.game_result != -1:
                self.render_update_board()

            if self.game_result != -1:
                self.render.cur_state.update_game_result_info(
                    self.game_result, self.delta_rate)
                self.players[0].stop_timer()
                self.players[1].stop_timer()

        elif self.game_state == GameStates.ONLINE_GAME:
            if self.online_game_was_started is None:
                self.render.cur_state.update_camera(self.local_player.side)
                self.online_game_was_started = True
                self.render_update_board()

            if Side(self.current_move) == self.local_player.side:
                self.local_player.update_time()
            else:
                self.online_player.update_time()

            move = self.local_player.get_move()
            if move is not None:
                if Side(self.current_move) == self.local_player.side:
                    pawn_swaped_figure = self.local_player.get_pawn_swaped_figure(
                    )
                    self.local_player.update_time()
                    if self.game_controller.check_move(
                            move,
                            self.local_player.side) != MoveResult.INCORRECT:
                        self.game_controller.update(move,
                                                    self.local_player.side)

                        data_str = "p1={}&p2={}&p3={}&p4={}&swapped_figure=" \
                            .format(move.point_from.x,
                                    move.point_from.y,
                                    move.point_to.x,
                                    move.point_to.y)
                        if pawn_swaped_figure is not None:
                            self.game_controller.swap_pawn(
                                move.point_to, pawn_swaped_figure)
                            move_res = self.game_controller.check_board_res(
                                self.local_player.side)
                            assert (move_res != MoveResult.INCORRECT)
                            data_str += str(pawn_swaped_figure)

                        self.client.send_message('update_board', data_str)
                        self.online_player.restart_timer()
                        # play music
                        self.render.sound.play(SoundTypes.MOVE)
                self.render.process_set_move_player = self.local_player.set_move
                self.render_update_board()

            if self.game_result != -1:
                self.render.cur_state.update_game_result_info(
                    self.game_result, self.delta_rate)
                self.local_player.stop_timer()
                self.online_player.stop_timer()
            else:
                # set text info
                white_login = self.local_player.login
                white_time = self.local_player.time_str()
                white_rate = self.local_player.rate
                black_login = self.online_player.login
                black_time = self.online_player.time_str()
                black_rate = self.online_player.rate
                if self.local_player.side is Side.BLACK:
                    white_login, black_login = black_login, white_login
                    white_time, black_time = black_time, white_time
                    white_rate, black_rate = black_rate, white_rate
                self.render.cur_state.update_game_info(white_login, white_time,
                                                       white_rate, black_login,
                                                       black_time, black_rate)
        else:
            pass

        self.render.on_update_now = False
        self.server_calculation = False
        return Task.cont