Example #1
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 #2
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 #3
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 #4
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 #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.")
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
0
 def setUp(self):
     self.chess = Chess()
Example #23
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 #24
0
    def test_get_displayable_history_empty(self):
        chess = Chess()

        actual = get_displayable_history(chess)

        self.assertEqual(actual, [])
Example #25
0
def _make_context():
    """Return context dict for a shell session so you can access
    app, db, and the User model by default.
    """
    return {'app': app, 'db': db, 'chess': Chess()}