Example #1
0
def move(game_token, start, end):
    # aborts if an invalid move. otherwise returns new board state after the move.
    game = Game.query.get(game_token)

    if game:
        if not game.is_full:
            abort(400, "This game needs more players.")

        chess = Chess(game.board)

        for player in game.board['players']:
            if game.current_player != current_user:
                abort(400, "Not your turn cheater!")
        # valid game, check if valid move
        success = chess.move(start, end)

        if not success:
            abort(400, "Moving from {} to {} is an invalid move.".format(start, end))

        data = dict(token=game.id, board=chess.generate_fen())
        response = jsonify(data)
        response.status_code = 200
        return response
    else:
        abort(400, "The game does not exist.")
Example #2
0
def test_get_legal_moves_speed():
    time_dict = {
        "generate": 0,
        "copy": 0,
        "validate": 0,
        "special": 0,
        "full": 0,
    }
    for _ in range(5):
        chess = Chess()
        while chess.is_in_progress:
            chess.move(chess.legal_moves[1])
            # chess.move(random.choice(chess.legal_moves))
            chess_f.get_legal_moves(chess, chess.in_turn, time_dict=time_dict)
    # for i in range(50):
    #     chess_f.get_legal_moves(chess, chess.in_turn, time_dict=time_dict)
    #     chess.move(chess.legal_moves[1])

    total = time_dict["full"]
    # for key in time_dict:
    #     total += time_dict[key]
    print("Total time: ", total, "\n")
    print(time_dict, "\n")
    for key in time_dict:
        time_dict[key] = (time_dict[key] / total) * 100
    print(time_dict)
Example #3
0
def move(game_token, start, end):
    # aborts if an invalid move. otherwise returns new board state after the move.
    game = Game.query.get(game_token)

    if game:
        if not game.is_full:
            abort(400, "This game needs more players.")

        chess = Chess(game.board)

        for player in game.board['players']:
            if game.current_player != current_user:
                abort(400, "Not your turn cheater!")
        # valid game, check if valid move
        success = chess.move(start, end)

        if not success:
            abort(
                400,
                "Moving from {} to {} is an invalid move.".format(start, end))

        data = dict(token=game.id, board=chess.generate_fen())
        response = jsonify(data)
        response.status_code = 200
        return response
    else:
        abort(400, "The game does not exist.")
Example #4
0
def selected(game_token, row, column):
    # db_game = Game.query.get(game_token)
    db_game = Game.query.get(game_token)
    if not db_game:
        abort(400, "That game doesn't exits.")
    board = db_game.board
    game = Chess(existing_board=board)
    index = (int(row), int(column))
    destinations = game.destinations(index)
    requested_index = get_requested_index(request)
    if requested_index:
        if requested_index in destinations:
            # move piece to requested index and re-direct to board
            if game.move(index, requested_index):
                db_game.board = game.export()
                db_game.save()
                url = "chess/game/{}/".format(game_token)
                return redirect(url)
            else:
                print("NOT A VALID MOVE!!!")
        elif game.destinations(requested_index):
            # redirect to a different selected route
            url = "chess/game/{}/selected/{}/{}/".format(game_token, requested_index[0], requested_index[1])
            return redirect(url)
        else:
            # redirect to board
            url = "chess/game/{}/".format(game_token)
            return redirect(url)
    return render_template('selected.html', rows=8, columns=8, board=db_game.piece_locations, images=piece_images, destinations=destinations)
Example #5
0
def test_ab_prune_speed(depth=4):
    chess = Chess()
    succes, msg = chess.move(chess.legal_moves[0])
    print(succes, msg)
    # print(len(chess.legal_moves))
    # depth = 4

    start_time = time.time()
    move, root, time_dict = chess_ai.choose_move_ab(chess,
                                                    depth=depth,
                                                    return_tree=True)
    end_time = time.time()

    move_choise_time = end_time - start_time
    print("Time for depth ", depth, ": ", move_choise_time)

    analysis_dict = {"count": 0, "branch": [[]]}

    chess_ai.count_tree_size(root, analysis_dict, 0)

    print("nodes visited: ", analysis_dict["count"])

    for level, l in enumerate(analysis_dict["branch"]):
        print("Branching factor at level ", level, ": ", sum(l) / len(l))

    print(time_dict)
Example #6
0
    def __init__(self, point, white):
        if (white == 1):
            Chess.__init__(self, point, "T", white)

        elif (white == 0):
            Chess.__init__(self, point, "t", white)

        self.value = 30
Example #7
0
    def reset(self):
        # 选中棋子位置
        self.choose_pos = None

        # 可以移动的位置
        self.choose_can_move_pos = []

        # 象棋
        fen = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR w - - 0 1"
        self._chs = Chess(fen)
Example #8
0
    def get_destinations(self, request, pk=None):
        game = Game.objects.get(pk=pk)
        if game.ready_to_play:
            chess = Chess(game.data)

            row = int(request.data['row'])
            column = int(request.data['column'])

            destinations = chess.destinations((row, column))
            return Response(destinations)
        return Response("not your turn", status=status.HTTP_400_BAD_REQUEST)
Example #9
0
    def next(self, request, pk=None):
        game = Game.objects.get(pk=pk)

        chess = Chess(game.data)

        chess.next()

        # update db with new board
        game.data = chess.export()
        game.save()
        return Response("success, time to refresh")
Example #10
0
    def __init__(self, point, white):
        if (white == 1):
            Chess.__init__(self, point, "X", white)

        elif (white == 0):
            Chess.__init__(self, point, "x", white)
        self.primitiveMove = []
        for i in range(9):
            for j in range(10):
                self.primitiveMove.append(Point(i, j))
        self.value = 600
Example #11
0
def board(game_token):
    db_game = Game.query.get(game_token)
    game = Chess(existing_board=db_game.board)
    index = get_requested_index(request)
    if index and game.destinations(index):
        url = "chess/game/{}/selected/{}/{}/".format(game_token, index[0], index[1])
        return redirect(url)  # TODO: figure out how to call url_for...
        # return redirect(url_for('selected', game_token=game_token, row=row, column=col))
    if db_game:
        return render_template('board.html', rows=8, columns=8, board=db_game.piece_locations, images=piece_images)
    else:
        abort(400, "That game doesn't exits.")
Example #12
0
    def first(self, request, pk=None):
        game = Game.objects.get(pk=pk)

        chess = Chess(game.data)

        chess.first()

        # update db with new board
        # TODO: how to navigate history without changing current state?
        # TODO: how to differentiate a takeback vs seeing a previous board state?
        game.data = chess.export()
        game.save()
        return Response("success, time to refresh")
Example #13
0
    def promote(self, request, pk=None):
        game = Game.objects.get(pk=pk)
        if not game.is_my_turn(request.user):
            return Response("not your turn",
                            status=status.HTTP_400_BAD_REQUEST)
        chess = Chess(game.data)

        chess.promote((request.data['row'], request.data['column']),
                      request.data['name'])

        # update db with new board
        game.data = chess.export()
        game.save()

        return Response("success, time to refresh")
Example #14
0
    def __init__(self, point, white):
        if (white == 1):
            Chess.__init__(self, point, "K", white)
            self.primitiveMove = []
            for i in range(3, 6, 1):
                for j in range(0, 3, 1):
                    self.primitiveMove.append(Point(i, j))

        elif (white == 0):
            Chess.__init__(self, point, "k", white)
            self.primitiveMove = []
            for i in range(3, 6, 1):
                for j in range(7, 10, 1):
                    self.primitiveMove.append(Point(i, j))

        self.value = 10000
Example #15
0
def configuration_board(request, game_type_id):
    game_type = GameType.objects.get(pk=game_type_id)
    chess = Chess(game_type.rules)
    displayable_board = get_displayable_board(chess.board)

    if request.method == "POST":
        form = GameTypeForm(request.POST, instance=game_type)
        if form.is_valid():
            game_type = form.save()
    else:
        form = GameTypeForm(instance=game_type)

    pieces = get_pieces(game_type.rules)

    url = reverse('chess-configuration-configure-board', args=[game_type.id])

    context = {
        'id': game_type.id,
        'form': form,
        'board': displayable_board,
        'black_pieces': pieces['black'],
        'white_pieces': pieces['white'],
        'url': url,
    }
    return render(request, 'chess/main/configure_board.html', context)
Example #16
0
    def __init__(self, point, white):
        if (white == 1):
            Chess.__init__(self, point, "E", white)
            self.primitiveMove = []
            for i in range(0, 9, 1):
                for j in range(0, 5, 1):
                    self.primitiveMove.append(Point(i, j))

        elif (white == 0):
            Chess.__init__(self, point, "e", white)
            self.primitiveMove = []
            for i in range(0, 9, 1):
                for j in range(5, 10, 1):
                    self.primitiveMove.append(Point(i, j))

        self.value = 120
Example #17
0
def play_game(request, game_id):
    game = Game.objects.get(pk=game_id)

    chess = Chess(game.data)
    displayable_board = get_displayable_board(chess.board)
    destinations_url = reverse('move-destinations', args=[game.id])
    move_url = reverse('move-move', args=[game.id])
    promote_url = reverse('move-promote', args=[game.id])
    join_path = reverse('Chess:join-game', args=[game.id])
    join_url = request.build_absolute_uri(join_path)

    promotion_pieces = get_pieces(game.data, ignore=['king', 'pawn'])

    history = get_displayable_history(chess)
    context = {
        'board': displayable_board,
        'destinations_url': destinations_url,
        'move_url': move_url,
        'promote_url': promote_url,
        'rule_summary': game.rule_summary,
        'turn': game.turn_color,
        'history': history,
        'id': game.id,
        'game': game,
        'promotion_pieces': promotion_pieces,
        'join_url': join_url,
        'ready_to_play': game.ready_to_play,
    }
    return render(request, 'chess/main/play_game.html', context)
Example #18
0
 async def send_update(self, game):
     chess = Chess(game.data)
     await self.send(
         text_data=json.dumps({
             'board': get_displayable_board(chess.board),
             'history': get_displayable_history(chess),
             'color': game.turn_color
         }))
Example #19
0
def board(game_token):
    db_game = Game.query.get(game_token)
    game = Chess(existing_board=db_game.board)
    index = get_requested_index(request)
    if index and game.destinations(index):
        url = "chess/game/{}/selected/{}/{}/".format(game_token, index[0],
                                                     index[1])
        return redirect(url)  # TODO: figure out how to call url_for...
        # return redirect(url_for('selected', game_token=game_token, row=row, column=col))
    if db_game:
        return render_template('board.html',
                               rows=8,
                               columns=8,
                               board=db_game.piece_locations,
                               images=piece_images)
    else:
        abort(400, "That game doesn't exits.")
Example #20
0
    def test_get_displayable_board(self):
        chess = Chess()

        actual = get_displayable_board(chess.board)

        for row in "0167":
            for column in range(8):
                key = "{},{}".format(row, column)
                self.assertIn(".svg", actual[key]['image'])
Example #21
0
def create_game(color="white"):
    game_json = Chess().export()
    player_1 = current_user
    player_1 = UserFactory(
    )  # TODO: obviously delete this once it is required that they are signed in.
    game = Game.create(board=game_json,
                       player_1=player_1,
                       player_2=UserFactory())
    url = "chess/game/{}/".format(game.id)
    return redirect(url)
Example #22
0
def test_get_nn_input():
    chess = Chess()
    x = chess_ai.chess_to_nn_input(chess)
    board = chess.board
    for r in range(8):
        for c in range(8):
            arr_start = ((r * 8) + c) * 6
            array_fraction = x[arr_start:arr_start + 6]
            char = chess_util.get_unicode_char(board[r, c])
            print(array_fraction, char)
Example #23
0
    async def chat_message(self, event):
        message = event['message']
        game_id = message['game_id']

        game = await self.get_game(game_id)

        chess = Chess(game.data)

        if not await self.is_my_turn(game_id, self.scope["user"]):
            print("Failed Not my turn")
            await self.send_update(game)
        else:
            chess = Chess(game.data)
            print("Trying to move")
            moved = chess.move(
                self.convert_to_position(message['start']),
                self.convert_to_position(message['destination']))
            print("Successfully moved: " + str(moved))
            await self.save_game(game, chess)
            await self.send_update(game)
Example #24
0
def selected(game_token, row, column):
    # db_game = Game.query.get(game_token)
    db_game = Game.query.get(game_token)
    if not db_game:
        abort(400, "That game doesn't exits.")
    board = db_game.board
    game = Chess(existing_board=board)
    index = (int(row), int(column))
    destinations = game.destinations(index)
    requested_index = get_requested_index(request)
    if requested_index:
        if requested_index in destinations:
            # move piece to requested index and re-direct to board
            if game.move(index, requested_index):
                db_game.board = game.export()
                db_game.save()
                url = "chess/game/{}/".format(game_token)
                return redirect(url)
            else:
                print("NOT A VALID MOVE!!!")
        elif game.destinations(requested_index):
            # redirect to a different selected route
            url = "chess/game/{}/selected/{}/{}/".format(
                game_token, requested_index[0], requested_index[1])
            return redirect(url)
        else:
            # redirect to board
            url = "chess/game/{}/".format(game_token)
            return redirect(url)
    return render_template('selected.html',
                           rows=8,
                           columns=8,
                           board=db_game.piece_locations,
                           images=piece_images,
                           destinations=destinations)
Example #25
0
    def move(self, request, pk=None):
        game = Game.objects.get(pk=pk)
        if not game.is_my_turn(request.user):
            return Response("not your turn",
                            status=status.HTTP_400_BAD_REQUEST)

        chess = Chess(game.data)

        data = request.data
        destination_row = int(data['destination']['row'])
        destination_column = int(data['destination']['column'])
        start_row = int(data['start']['row'])
        start_column = int(data['start']['column'])

        chess.move((start_row, start_column),
                   (destination_row, destination_column))

        # update db with new board
        game.data = chess.export()
        game.save()

        return Response("success, time to refresh")
Example #26
0
def test_chess_move_speed():
    time_dict = {
        "start": 0,
        "is_legal": 0,
        "copy": 0,
        "mid1": 0,
        "castleEnPassantCheck": 0,
        "is_in_check1": 0,
        "get_legal_moves": 0,
        "is_in_check2": 0
    }
    chess = Chess()
    for i in range(35):
        # print(i)
        chess.move(chess.legal_moves[0], time_dict=time_dict)
    total = 0
    for key in time_dict:
        total += time_dict[key]
    print(total)
    print(time_dict)
    for key in time_dict:
        time_dict[key] = (time_dict[key] / total) * 100
    print(time_dict)
Example #27
0
    def test_get_displayable_history_no_capture_history(self):
        chess = Chess()
        chess.move((1, 1), (2, 1))
        chess.move((6, 4), (5, 4))
        chess.move((2, 1), (3, 1))

        actual = get_displayable_history(chess)

        self.assertEqual(
            actual,
            [
                {'name': 'b2 -> b3', 'images': [], 'class': ''},
                {'name': 'e7 -> e6', 'images': [], 'class': ''},
                {'name': 'b3 -> b4', 'images': [], 'class': 'current'},
            ],
        )
Example #28
0
    def test_get_displayable_history_with_capture_history(self):
        chess = Chess()
        chess.move((1, 1), (3, 1))
        chess.move((6, 2), (4, 2))
        chess.move((3, 1), (4, 2))

        actual = get_displayable_history(chess)

        self.assertEqual(
            actual,
            [
                {'name': 'b2 -> b4', 'images': [], 'class': ''},
                {'name': 'c7 -> c5', 'images': [], 'class': ''},
                {
                    'name': 'b4 -> c5',
                    'images': [
                        'https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg'
                    ],
                    'class': 'current',
                },
            ],
        )
Example #29
0
 def __init__(self, point, white):
     white = None
     Chess.__init__(self, point, ".", white)
Example #30
0
class ChessWindow(object):
    def __init__(self):
        ''' 初始化 '''
        # 窗口
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        self._bottom_img, rc = widget_load_image("images/bottom.bmp")
        self._header_img, rc = widget_load_image("images/header.bmp")
        self._footer_img, rc = widget_load_image("images/footer.bmp")
        self._ground_img, rc = widget_load_image("images/ground.bmp")
        self._mark_img, rc = widget_load_image("images/cur_mark.bmp", 0xffffff)
        self._can_move_img, rc = widget_load_image("images/cur_move.bmp",
                                                   0xffffff)
        self._chessman_img = widget_load_chessman_image()

        # 初始化界面
        self.window.fill((0, 0, 0))
        self.window.blit(self._bottom_img, (0, 0))
        self.window.blit(self._header_img, (30, 20))
        self.window.blit(self._footer_img, (30, 550))

        # 操作面板
        self.oper_panel = OperatePanel(self.window, BOARD_TOP // 2,
                                       BOARD_WIDTH + BOARD_LEFT)

        # 选中棋子位置
        self.choose_pos = None

        # 可以移动的位置
        self.choose_can_move_pos = []

        # 象棋
        self._chs = None

        # 棋盘是否反转
        self._is_reverse = 0

        self.reset()

    def reset(self):
        # 选中棋子位置
        self.choose_pos = None

        # 可以移动的位置
        self.choose_can_move_pos = []

        # 象棋
        fen = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR w - - 0 1"
        self._chs = Chess(fen)

    def get_chess(self):
        return self._chs

    def convert_pos_2d(self, pos):
        row = pos // 16 - 3
        col = pos % 16 - 3
        if (self._is_reverse):
            row = BOARD_MAX_ROW - row - 1
            col = BOARD_MAX_COL - col - 1
        return (row, col)

    def convert_2d_pos(self, d2):
        (row, col) = d2
        if (self._is_reverse):
            row = BOARD_MAX_ROW - row - 1
            col = BOARD_MAX_COL - col - 1
        pos = (row + 3) * 16 + (col + 3)
        return pos

    def reverse_board(self):
        self._is_reverse = 1 - self._is_reverse

        # 选中棋子位置反转
        if self.choose_pos != None:
            row = BOARD_MAX_ROW - self.choose_pos[0] - 1
            col = BOARD_MAX_COL - self.choose_pos[1] - 1
            self.choose_pos = (row, col)

        # 可以移动的位置反转
        if self.choose_can_move_pos != None:
            pos_list = []
            for pos in self.choose_can_move_pos:
                row = BOARD_MAX_ROW - pos[0] - 1
                col = BOARD_MAX_COL - pos[1] - 1
                pos_list.append((row, col))
            self.choose_can_move_pos = pos_list

    def get_2d_board(self):
        array_2d = [[0] * (BOARD_MAX_COL) for i in range(BOARD_MAX_ROW)]
        for index in range(16, len(self._chs.piece)):
            k = self._chs.piece[index]
            if k:
                i = k // 16 - 3
                j = k % 16 - 3
                if (self._is_reverse):
                    i = BOARD_MAX_ROW - i - 1
                    j = BOARD_MAX_COL - j - 1
                array_2d[i][j] = index
        return array_2d

    def _refresh_chessman(self):
        ''' 刷新所有棋子 '''

        board_2d = self.get_2d_board()
        for i in range(len(board_2d)):
            for j in range(len(board_2d[i])):
                pc = board_2d[i][j]
                pc_char = int2fen_char(pc)
                if isinstance(pc_char, str):
                    row = i
                    col = j
                    left = col * BOARD_GAP + BOARD_LEFT
                    top = row * BOARD_GAP + BOARD_TOP
                    if pc_char.isupper():
                        pc_char = "w_" + pc_char
                    else:
                        pc_char = "b_" + pc_char
                    # 显示每个棋子图片
                    self.window.blit(self._chessman_img[pc_char], (left, top))

    def _refresh_last_move(self):
        if len(self._chs.movestack) > 0:
            stack_head = self._chs.movestack[-1]
            last_move = []

            (pos_row, pos_col) = self.convert_pos_2d(stack_head.from_pos)
            last_move.append((pos_row, pos_col))
            (pos_row, pos_col) = self.convert_pos_2d(stack_head.to_pos)
            last_move.append((pos_row, pos_col))

            for pos in last_move:
                left = pos[1] * BOARD_GAP + BOARD_LEFT
                top = pos[0] * BOARD_GAP + BOARD_TOP
                self.window.blit(self._mark_img, (left, top))

    def redraw_borad(self):
        ''' 根据每个单元格对应的棋子重绘棋盘 '''

        # 显示背景
        self.window.blit(self._ground_img, (30, 30))

        # 显示所有棋子
        self._refresh_chessman()

        # 显示上一步走法
        self._refresh_last_move()

        # 标记选中的棋子
        if self.choose_pos != None:
            row = self.choose_pos[0]
            col = self.choose_pos[1]
            left = col * BOARD_GAP + BOARD_LEFT
            top = row * BOARD_GAP + BOARD_TOP
            self.window.blit(self._mark_img, (left, top))

        # 可走的位置
        if self.choose_can_move_pos != None:
            for pos in self.choose_can_move_pos:
                row = pos[0]
                col = pos[1]
                left = col * BOARD_GAP + BOARD_LEFT
                top = row * BOARD_GAP + BOARD_TOP
                self.window.blit(self._can_move_img, (left, top))

        # 刷新操作面板
        self.oper_panel.refresh()

    def _choose_chessman(self, row, col):
        ''' 选择棋子 '''

        board_2d = self.get_2d_board()
        if board_2d[row][col] != 0:
            side = self._chs.get_side()
            pos = self.convert_2d_pos((row, col))
            pc = self._chs.get_board()[pos]
            if self._chs.is_match_side_pc(side, pc):
                self.choose_pos = (row, col)
                self.choose_can_move_pos = []
                for k in self._chs.get_can_move_list(pos):
                    self.choose_can_move_pos.append(self.convert_pos_2d(k))

    def move_chessman(self, row, col):
        ''' 移动棋子 '''

        if (row >= 0 and row < 10) and (col >= 0 and col < 9):
            pos = self.convert_2d_pos((row, col))
            board = self._chs.get_board()
            if self.choose_pos != None:
                m = ChessboardMove()
                m.from_pos = self.convert_2d_pos(self.choose_pos)
                m.to_pos = pos
                if self._chs.check_move(m):
                    # 移动
                    self._chs.make_move(m)
                    self.choose_pos = None
                    self.choose_can_move_pos = []
                else:
                    self._choose_chessman(row, col)
            else:
                self._choose_chessman(row, col)
Example #31
0
 def setUp(self):
     self.chess = Chess()
Example #32
0
class TestChess(unittest.TestCase):

    def setUp(self):
        self.chess = Chess()

    def _print(self):
        print(self.chess)

    def _move(self, origin, destination):
        self.chess.move(origin, destination)

    def test_piece_color_and_type(self):
        self.assertRaises(ValueError, Pawn, "string")
        p = Pawn(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.PAWN)
        self.assertEqual(p.color, Color.WHITE)
        self.assertEqual(p.has_moved, False)
        self.assertEqual(str(p), "P")
        p = Pawn(Color.BLACK)
        self.assertEqual(p.color, Color.BLACK)
        self.assertEqual(str(p), "p")
        self.assertEqual(p.has_moved, False)
        p = Knight(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.KNIGHT)
        self.assertEqual(str(p), "N")
        p = Bishop(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.BISHOP)
        self.assertEqual(str(p), "B")
        p = Rook(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.ROOK)
        self.assertEqual(str(p), "R")
        p = Queen(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.QUEEN)
        self.assertEqual(str(p), "Q")
        p = King(Color.WHITE)
        self.assertEqual(p.type, Piece_Type.KING)
        self.assertEqual(str(p), "K")
        self.assertEqual(p.has_moved, False)

    def test_pawn_valid_moves_no_capture(self):
        # white move - two squares
        pos = Coordinate.e2
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.e3, Coordinate.e4])
        self.assertEqual(moves, answer)
        # black move - two squares
        self._move(Coordinate.e2, Coordinate.e4)
        self.assertEqual(self.chess.pieces[Coordinate.e4].has_moved, True)
        pos = Coordinate.e7
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.e6, Coordinate.e5])
        self.assertEqual(moves, answer)
        # blocked white pawn
        self._move(Coordinate.e7, Coordinate.e5)
        self.assertEqual(self.chess.pieces[Coordinate.e5].has_moved, True)
        pos = Coordinate.e4
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set()
        self.assertEqual(moves, answer)
        # blocked black pawn
        pos = Coordinate.e5
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        self.assertEqual(moves, answer)
        # white move - pawn that moved previously
        self._move(Coordinate.a2, Coordinate.a3)
        pos = Coordinate.a3
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.a4])
        self.assertEqual(moves, answer)
        # black move - pawn that moved previously
        self._move(Coordinate.b7, Coordinate.b5)
        pos = Coordinate.b5
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.b4])
        self.assertEqual(moves, answer)
        # white move - second square not empty
        self._move(Coordinate.a3, Coordinate.a4)
        self._move(Coordinate.b5, Coordinate.b4)
        pos = Coordinate.b2
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.b3])
        self.assertEqual(moves, answer)
        # black move - second square not empty
        self._move(Coordinate.a4, Coordinate.a5)
        pos = Coordinate.a7
        moves = self.chess.valid_moves_for_piece_at_coordinate(pos)
        answer = set([Coordinate.a6])
        self.assertEqual(moves, answer)

    def test_pawn_valid_moves_capture(self):
        # white one capture available
        self._move(Coordinate.e2, Coordinate.e4)
        self._move(Coordinate.f7, Coordinate.f5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.e5, Coordinate.f5])
        self.assertEqual(moves, answer)
        # black one capture available
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.f5)
        answer = set([Coordinate.e4, Coordinate.f4])
        self.assertEqual(moves, answer)
        # black two captures available
        self._move(Coordinate.g2, Coordinate.g4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.f5)
        answer = set([Coordinate.e4, Coordinate.f4, Coordinate.g4])
        self.assertEqual(moves, answer)
        # white two captures available
        self._move(Coordinate.d7, Coordinate.d5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.d5, Coordinate.e5, Coordinate.f5])
        self.assertEqual(moves, answer)

    def test_en_passant_white(self):
        # white right
        self._move(Coordinate.e2, Coordinate.e4)
        self._move(Coordinate.a7, Coordinate.a6)
        self._move(Coordinate.e4, Coordinate.e5)
        self._move(Coordinate.f7, Coordinate.f5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e5)
        answer = set([Coordinate.e6, Coordinate.f6])
        self.assertEqual(moves, answer)
        # en passant gone after move is made
        self._move(Coordinate.a2, Coordinate.a3)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e5)
        answer = set([Coordinate.e6])
        self.assertEqual(moves, answer)
        # white left
        self._move(Coordinate.a3, Coordinate.a4)
        self._move(Coordinate.d7, Coordinate.d5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e5)
        answer = set([Coordinate.d6, Coordinate.e6])
        self.assertEqual(moves, answer)
        # en passant gone after move is made
        self._move(Coordinate.a4, Coordinate.a5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e5)
        answer = set([Coordinate.e6])
        self.assertEqual(moves, answer)

    def test_en_passant_black(self):
        # black right
        self._move(Coordinate.a2, Coordinate.a3)
        self._move(Coordinate.e7, Coordinate.e5)
        self._move(Coordinate.a3, Coordinate.a4)
        self._move(Coordinate.e5, Coordinate.e4)
        self._move(Coordinate.f2, Coordinate.f4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.e3, Coordinate.f3])
        self.assertEqual(moves, answer)
        # en passant gone after move is made
        self._move(Coordinate.a4, Coordinate.a5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.e3])
        self.assertEqual(moves, answer)
        # black left
        self._move(Coordinate.a7, Coordinate.a6)
        self._move(Coordinate.d2, Coordinate.d4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.d3, Coordinate.e3])
        self.assertEqual(moves, answer)
        # en passant gone after move is made
        self._move(Coordinate.b2, Coordinate.b3)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.e4)
        answer = set([Coordinate.e3])
        self.assertEqual(moves, answer)

    def test_pawn_squares_attacked(self):
        # center
        pos = Coordinate.e2
        attacked = self.chess.squares_attacked_by_piece_at_coordinate(pos)
        answer = set([Coordinate.d3, Coordinate.f3])
        self.assertEqual(attacked, answer)
        # edge
        pos = Coordinate.a2
        attacked = self.chess.squares_attacked_by_piece_at_coordinate(pos)
        answer = set([Coordinate.b3])
        self.assertEqual(attacked, answer)

    def test_knight_valid_moves(self):
        # white edge
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.b1)
        answer = set([Coordinate.a3, Coordinate.c3])
        self.assertEqual(moves, answer)
        # black edge
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.b8)
        answer = set([Coordinate.a6, Coordinate.c6])
        self.assertEqual(moves, answer)
        # white center
        self._move(Coordinate.b1, Coordinate.c3)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.c3)
        answer = set([Coordinate.b5, Coordinate.d5, # top
                      Coordinate.b1, # btm
                      Coordinate.a4, # left
                      Coordinate.e4]) # right
        self.assertEqual(moves, answer)
        # black center
        self._move(Coordinate.b8, Coordinate.c6)   
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.c6)
        answer = set([Coordinate.b8, # top
                      Coordinate.b4, Coordinate.d4, # btm
                      Coordinate.a5, # left
                      Coordinate.e5]) # right
        self.assertEqual(moves, answer)
        # white attacking pieces
        self._move(Coordinate.c3, Coordinate.d5)
        attacked = self.chess.squares_attacked_by_piece_at_coordinate(Coordinate.d5)
        answer = set([Coordinate.c7, Coordinate.e7, # top
                      Coordinate.f4, Coordinate.f6, # right
                      Coordinate.c3, Coordinate.e3, # btm
                      Coordinate.b4, Coordinate.b6]) # left
        self.assertEqual(attacked, answer)

    def test_knight_squares_attacked(self):
        # white edge
        pos = Coordinate.b1
        attacked = self.chess.squares_attacked_by_piece_at_coordinate(pos)
        answer = set([Coordinate.a3, Coordinate.c3, Coordinate.d2])
        self.assertEqual(attacked, answer)
        # white center
        self._move(Coordinate.b1, Coordinate.c3)
        pos = Coordinate.c3
        attacked = self.chess.squares_attacked_by_piece_at_coordinate(pos)
        answer = set([Coordinate.b5, Coordinate.d5, # top
                      Coordinate.e2, Coordinate.e4, # right
                      Coordinate.b1, Coordinate.d1, # btm
                      Coordinate.a2, Coordinate.a4]) # left
        self.assertEqual(attacked, answer)

    def test_bishop_valid_moves_white(self):
        # no moves
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.c1)
        answer = set()
        self.assertEqual(moves, answer)
        # one lane
        self._move(Coordinate.e2, Coordinate.e4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.f1)
        answer = set([Coordinate.e2, 
                      Coordinate.d3, 
                      Coordinate.c4, 
                      Coordinate.b5, 
                      Coordinate.a6])
        self.assertEqual(moves, answer)
        # one lane with capture
        self._move(Coordinate.a7, Coordinate.a6)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.f1)
        self.assertEqual(moves, answer)
        # four lanes with capture
        self._move(Coordinate.f1, Coordinate.b5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.b5)
        answer = set([Coordinate.c6, 
                      Coordinate.d7,
                      Coordinate.c4,
                      Coordinate.d3,
                      Coordinate.e2,
                      Coordinate.f1,
                      Coordinate.a4,
                      Coordinate.a6])
        self.assertEqual(moves, answer)

    def test_bishop_valid_moves_black(self):
        # no moves
        self._move(Coordinate.e2, Coordinate.e4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.c8)
        answer = set()
        self.assertEqual(moves, answer)
        # one lane
        self._move(Coordinate.e7, Coordinate.e5)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.f8)
        answer = set([Coordinate.e7, 
                      Coordinate.d6, 
                      Coordinate.c5, 
                      Coordinate.b4, 
                      Coordinate.a3])
        self.assertEqual(moves, answer)
        # four lanes
        self._move(Coordinate.f8, Coordinate.b4)
        moves = self.chess.valid_moves_for_piece_at_coordinate(Coordinate.b4)
        answer = set([Coordinate.c5,
                      Coordinate.d6,
                      Coordinate.e7,
                      Coordinate.f8,
                      Coordinate.c3,
                      Coordinate.d2,
                      Coordinate.a3,
                      Coordinate.a5])
        self.assertEqual(moves, answer)

        self._print()
Example #33
0
from board.board import Board
from chess.chess import Chess, WIN
from minimax.algorithm import minimax


def redraw_game_window(win, game):
    win.fill((255, 255, 179))
    run = game.move(win)
    game.draw(win)
    pygame.display.update()
    return run


board = Board((102, 51, 0))
board.create_board()
chess_game = Chess(board)
RUN = True
DEPTH = 2

# mainloop

if __name__ == "__main__":

    while RUN:

        RUN = redraw_game_window(WIN, chess_game)

        if chess_game.turn_color == chess_game.ai_color:
            if chess_game.check_if_ai_checkmated_or_draw(WIN):
                RUN = chess_game.end_game(WIN)
            else:
Example #34
0
 def __init__(self, point, white):
     if (white == 1):
         Chess.__init__(self, point, "K", white)
     elif (white == 0):
         Chess.__init__(self, point, "k", white)
Example #35
0
 def setUp(self):
     self.chess = Chess()