Exemplo n.º 1
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)
Exemplo n.º 2
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'},
            ],
        )
Exemplo n.º 3
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)
Exemplo n.º 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)
Exemplo n.º 5
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.")
Exemplo n.º 6
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)
Exemplo n.º 7
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.")
Exemplo n.º 8
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")
Exemplo n.º 9
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',
                },
            ],
        )
Exemplo n.º 10
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)
Exemplo n.º 11
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)
Exemplo n.º 12
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()