Exemple #1
0
def fmtbrd(board: chess.Board, color):
    flip = True if color == 'black' else False
    colors = {
        'square dark': '#769656',
        'sqaure light': '#eeeed2',
        'arrow green': '#2a52be',
        'arrow blue': '#2a52be',
        'arrow red': '#2a52be',
        'arrow yellow': '#2a52be'
    }
    try:
        last = board.peek().uci()
        arrows = [
            chess.svg.Arrow(chess.parse_square(last[0:2]),
                            chess.parse_square(last[2:4]))
        ]
        f = BytesIO(
            bytes(chess.svg.board(board,
                                  flipped=flip,
                                  colors=colors,
                                  arrows=arrows),
                  encoding='utf-8'))
    except IndexError:
        f = BytesIO(
            bytes(chess.svg.board(board, flipped=flip, colors=colors),
                  encoding='utf-8'))
    f.seek(0)
    new_f = BytesIO()
    drawing = svg2rlg(f)
    renderPM.drawToFile(drawing, new_f)
    new_f.seek(0)
    return discord.File(fp=new_f, filename='board.png')
Exemple #2
0
def exceptions(board, move):
    u = 0
    # Book Moves no começo do jogo é bom
    if board.fullmove_number < 3 and move in [
            "e7e5", "e7e6", "d7d5", "d7d6", "g8f6", "b8c6", "c7c5", "g7g5"
    ]:
        u += 1
    # Se um movimento coloca o rei do adversário em xeque, é muito bom
    if board.gives_check(move):
        u += 5
    # Se um movimento é uma captura, a utilidade dessa captura é o quanto eu ganho com ela
    if board.is_capture(move):
        my = chess.BaseBoard.piece_at(board, chess.parse_square(str(move)[:2]))
        xs = chess.BaseBoard.piece_at(board,
                                      chess.parse_square(str(move)[2:4]))
        if board.is_en_passant(move):
            if my.color == chess.BLACK:
                xs = chess.Piece.from_symbol("P")
            else:
                xs = chess.Piece.from_symbol("p")
        if xs.piece_type - my.piece_type >= 0:
            u += (xs.piece_type - my.piece_type)
    # Se o movimento me leva a um quadrado que está sendo atacado por alguém, é um movimento ruim
    if len(chess.BaseBoard.attacks(board, chess.parse_square(
            str(move)[2:4]))) > 0:
        u -= 1
    # Se o movimento ou o estado já tiver ocorrido nas ultimas 10 rodadas, é um movimento muito ruim
    board.push(move)
    if chess.BaseBoard.board_fen(board) in lastTenStates or str(
            move) in lastTenMoves:
        u -= 10
    board.pop()
    # retorna o resultado da análise dessas exceções
    return u
Exemple #3
0
 def make_move(self,
               is_white: bool,
               from_square: str,
               to_square: str,
               promotion=None):
     piece_positions = self.get_piece_positions(is_white)
     if from_square not in piece_positions:
         raise Exception(
             "Attempted to make move from a square that doesn't have one of the player's pieces."
         )
     square_1 = chess.parse_square(from_square)
     square_2 = chess.parse_square(to_square)
     board = self.get_board()
     move = board.find_move(square_1, square_2)
     board.push(move)
     # insert into DB table
     new_fen = board.fen()
     vals_to_insert = list()
     vals_to_insert.append('NULL')
     vals_to_insert.append(str(int(time.time())))
     vals_to_insert.append("'" + from_square + "'")
     vals_to_insert.append("'" + to_square + "'")
     vals_to_insert.append("'" + new_fen + "'")
     vals_to_insert_appended = " VALUES ( " + ', '.join(
         vals_to_insert) + ')'
     script = "INSERT INTO " + _MOVES_TABLE_NAME + vals_to_insert_appended + ';'
     self.conn.execute(script)
     self.conn.commit()
Exemple #4
0
def attacker(_user_id, _attacker, _color, _square):
    """
    checks whether a piece is being attacked by another piece.
    """
    _board = boards[_user_id]
    _attackers = _board.attackers(convert(_color), chess.parse_square(_square))
    return chess.parse_square(_attacker) in _attackers
Exemple #5
0
    def from_pgn(cls, pgn: str) -> Arrow:
        """
        Parses an arrow from the format used by ``[%csl ...]`` and
        ``[%cal ...]`` PGN annotations, e.g., ``Ga1`` or ``Ya2h2``.

        Also allows skipping the color prefix, defaulting to green.

        :raises: :exc:`ValueError` if the format is invalid.
        """
        if pgn.startswith("G"):
            color = "green"
            pgn = pgn[1:]
        elif pgn.startswith("R"):
            color = "red"
            pgn = pgn[1:]
        elif pgn.startswith("Y"):
            color = "yellow"
            pgn = pgn[1:]
        elif pgn.startswith("B"):
            color = "blue"
            pgn = pgn[1:]
        else:
            color = "green"

        tail = chess.parse_square(pgn[:2])
        head = chess.parse_square(pgn[2:]) if len(pgn) > 2 else tail
        return cls(tail, head, color=color)
Exemple #6
0
    def isAlgebraicNotation(alg_notation: str) -> bool:
        try:
            chess.parse_square(alg_notation)
        except ValueError:
            return False

        return True
Exemple #7
0
def merge_processed_moves(first_moves, second_moves):
    bug_board = BughouseBoard()
    all_raw_moves = first_moves + second_moves
    all_raw_moves.sort(key=op.itemgetter(-1))
    all_moves = []
    #this is an assumption, need to really look at time control...
    times = [
        {
            chess.WHITE: 1800,
            chess.BLACK: 1800,
        },
        {
            chess.WHITE: 1800,
            chess.BLACK: 1800,
        },
    ]
    moving_players = [chess.WHITE, chess.WHITE]
    for raw_move in all_raw_moves:
        board_num, hite_name, black_name, white_elo, black_elo, moving_player, move, move_time, total_time = raw_move
        #print(raw_move)

        prev_move_time = times[board_num][moving_player]
        delta_move_time = prev_move_time - move_time
        other_moving_player = moving_players[not board_num]
        times[board_num][moving_player] = move_time
        #times[not board_num][other_moving_player] -= delta_move_time

        #print(board_num, moving_player, move)
        move_obj = chess.Move(
            from_square=chess.parse_square(move["from"])
            if move["from"] != None else chess.A1,
            to_square=chess.parse_square(move["to"]),
            promotion=chess.Piece.from_symbol(move["promotion"]).piece_type
            if move["promotion"] != None else None,
            drop=chess.Piece.from_symbol(move["drop"]).piece_type
            if move["drop"] != None else None,
        )
        #print(move)
        bug_board.move(board_num, move_obj)
        fens = bug_board.get_fens()
        first_board_fen, second_board_fen = fens
        #print(fens)

        processed_move = {
            "board_num": board_num,
            "moving_player": moving_player,
            "from_square": move["from"],
            "to_square": move["to"],
            "drop": move["drop"],
            "promotion": move["promotion"],
            "first_white_time": times[0][chess.WHITE],
            "first_black_time": times[0][chess.BLACK],
            "second_white_time": times[1][chess.WHITE],
            "second_black_time": times[1][chess.BLACK],
            "first_board_fen": first_board_fen,
            "second_board_fen": second_board_fen,
        }
        all_moves.append(processed_move)
    return all_moves
Exemple #8
0
    def make_svg(self, request):
        try:
            board = chess.Board(request.query["fen"])
        except KeyError:
            raise aiohttp.web.HTTPBadRequest(reason="fen required")
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="invalid fen")

        try:
            size = min(max(int(request.query.get("size", 360)), 16), 1024)
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="size is not a number")

        try:
            uci = request.query.get("lastMove") or request.query["lastmove"]
            lastmove = chess.Move.from_uci(uci)
        except KeyError:
            lastmove = None
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="lastMove is not a valid uci move")

        try:
            check = chess.parse_square(request.query["check"])
        except KeyError:
            check = None
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="check is not a valid square name")

        try:
            arrows = [chess.svg.Arrow.from_pgn(s.strip()) for s in request.query.get("arrows", "").split(",") if s.strip()]
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="invalid arrow")

        try:
            squares = chess.SquareSet(chess.parse_square(s.strip()) for s in request.query.get("squares", "").split(",") if s.strip())
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="invalid squares")

        flipped = request.query.get("orientation", "white") == "black"

        coordinates = request.query.get("coordinates", "0") in ["", "1", "true", "True", "yes"]

        try:
            colors = THEMES[request.query.get("colors", "lichess-brown")]
        except KeyError:
            raise aiohttp.web.HTTPBadRequest(reason="theme colors not found")

        return chess.svg.board(board,
                               coordinates=coordinates,
                               flipped=flipped,
                               lastmove=lastmove,
                               check=check,
                               arrows=arrows,
                               squares=squares,
                               size=size,
                               colors=colors)
Exemple #9
0
 def darJugadaParam(self, move):
     try:
         movida = chess.Move(chess.parse_square(move[0:2]),
                             chess.parse_square(move[2:4]))
         if movida in self.tablero.legal_moves:
             return movida
         else:
             raise Exception
     except:
         return "Jugada inválida"
Exemple #10
0
 def darJugada(self, ins):
     # while True:
     #ins = input("Da la movida que quieras hacer con el formato a1a2\n")
     try:
         movida = chess.Move(chess.parse_square(ins[0:2]),
                             chess.parse_square(ins[2:4]))
         if movida in self.tablero.legal_moves:
             return movida
         else:
             raise Exception
     except:
         #print("Jugada inválida")
         return "Jugada invalida"
Exemple #11
0
    def update_button(self, button):
        self.move_str += button.id
        # print(self.move_str)

        if len(self.move_str) == 4:
            Cache.remove('kv.image')
            Cache.remove('kv.texture')
            move = chess.Move(from_square=chess.parse_square(
                self.move_str[:2]),
                              to_square=chess.parse_square(self.move_str[2:4]))
            move = self.check_pawn_promotion(move)
            print(f"Your move: {move}")
            if move in self.board.legal_moves:
                self.board.push(move)
                [
                    Path(m).unlink(missing_ok=True)
                    for m in list(Path("moves/").glob("chess*"))
                ]
                save_name = f'moves/chess_{str(move)}_{self.board.turn}.png'
                svg2png(bytestring=chess.svg.board(self.board, size=350),
                        write_to=save_name)
                self.rect.source = save_name

                if self.board.is_game_over():
                    return self.declare_winner()

                # ai_move = np.random.choice(list(self.board.legal_moves))
                # ai_move = list(self.board.legal_moves)[0]
                # print(ai_move)
                ai_move = self.engine.make_move(self.board)
                print(f"AI move: {ai_move}")

                if isinstance(ai_move, chess.Move):
                    self.board.push(ai_move)
                else:
                    return self.declare_winner()

                if self.board.is_game_over():
                    return self.declare_winner()
                [
                    Path(m).unlink(missing_ok=True)
                    for m in list(Path("moves/").glob("chess*"))
                ]
                save_name = f'moves/chess_{str(move)}_{self.board.turn}.png'
                svg2png(bytestring=chess.svg.board(self.board, size=350),
                        write_to=save_name)
                self.rect.source = save_name
            self.move_str = ""
Exemple #12
0
def attacks(_user_id, _square):
    """
    displays attacks on a piece.
    """
    _board = boards[_user_id]
    _attacks = _board.attacks(chess.parse_square(_square))
    generate_image(_board, _squares=_attacks)
Exemple #13
0
def attackers(_user_id, _color, _square):
    """
    displays attackers for a piece.
    """
    _board = boards[_user_id]
    squares = _board.attackers(convert(_color), chess.parse_square(_square))
    generate_image(_board, _squares=squares)
Exemple #14
0
def get_eval_data(args, eval_examples):
    random.seed(42)
    output_dir = args.output_dir
    output_file_end = path.join(output_dir, f"end_{args.prefix_size}.jsonl")
    output_file_start = path.join(output_dir,
                                  f"start_{args.prefix_size}.jsonl")

    with open(output_file_end, 'w') as end_w, open(output_file_start,
                                                   'w') as start_w:
        for info_dict in eval_examples:
            output_dict = OrderedDict()
            output_dict["prefix"] = info_dict["prefix"]
            output_dict["oracle_prefix"] = info_dict["oracle_prefix"]

            # Ending Square tasks
            # Moves starting with actual starting square
            output_dict["piece_type"] = info_dict["actual_piece_type"]
            output_dict["starting_square"] = info_dict[
                "actual_starting_square"]
            output_dict["ending_square"] = info_dict[
                "actual_ending_square"]  # ExM
            output_dict["legal_ending_square"] =\
                info_dict["legal_ending_square"][output_dict["starting_square"]]  # LgM

            # Other LgM
            all_start_squares = list(info_dict["legal_ending_square"].keys())
            all_start_squares.remove(output_dict["starting_square"])
            # Sort before random choice to ensure reproducibility
            other_starting_square = random.choice(sorted(all_start_squares))
            piece_type_at_other_square = info_dict["board"].piece_type_at(
                chess.parse_square(other_starting_square))
            output_dict["other_piece_type"] = chess.PIECE_SYMBOLS[
                piece_type_at_other_square].upper()
            output_dict["other_starting_square"] = other_starting_square
            output_dict["other_ending_square"] = info_dict[
                "legal_ending_square"][other_starting_square]
            end_w.write(json.dumps(output_dict) + "\n")

            # Starting square data
            output_dict = OrderedDict()
            output_dict["prefix"] = info_dict["prefix"]
            output_dict["oracle_prefix"] = info_dict["oracle_prefix"]

            # Moves for the given piece type
            output_dict["piece_type"] = info_dict["actual_piece_type"]
            output_dict["starting_square"] = info_dict[
                "actual_starting_square"]  # ExM
            # LgM - convert set to list
            output_dict["legal_starting_square"] = list(
                info_dict["legal_starting_square"][output_dict["piece_type"]])

            # Other LgM
            all_piece_types = list(info_dict["legal_starting_square"].keys())
            all_piece_types.remove(info_dict["actual_piece_type"])
            other_piece_type = random.choice(sorted(all_piece_types))
            output_dict["other_piece_type"] = other_piece_type
            # set to list
            output_dict["other_starting_square"] = list(
                info_dict["legal_starting_square"][other_piece_type])
            start_w.write(json.dumps(output_dict) + "\n")
Exemple #15
0
def findMove():
    # set counter for resUP
    global moveCounter
    moveCounter += 1

    move_found = compareImages(MyMovePath)
    while not move_found:
        print("ERROR images are the same, trying again")
        time.sleep(1.5)
        move_found = compareImages(MyMovePath)

    #find the opponents move origin
    cv2_px = cv2Move("OpMove.png", "pieceImages\Highlight.png", 0.97)
    chess_str_1 = PxtoGrid(cv2_px[0], cv2_px[1])

    #find the corresponding piece move
    chess_square_index = chess.parse_square(chess_str_1)
    if board.piece_at(chess_square_index) is None:
        playsound('Warning.mp3')
        Op_piece_moved = input(
            "Base move missed, what square did it originate from:")
        time.sleep(3)
    else:
        Op_piece_moved = board.piece_at(chess_square_index).symbol().lower()
    print(str(Op_piece_moved))
    print(Op_piece_moved, "was moved by opponent with comparison file at ",
          imageDict[Op_piece_moved][0])

    targetPath = "pieceImages\\" + imageDict[Op_piece_moved][0]
    cv2_px = cv2Move("OpMove.png", targetPath, imageDict[Op_piece_moved][1])
    chess_str_2 = PxtoGrid(cv2_px[0], cv2_px[1])
    full_str = chess_str_1 + chess_str_2
    print('Resolved string', full_str)
    return full_str
Exemple #16
0
    def moves_to_consider(self, board):
        vis_board = board.copy()

        new_game = FogChess(board)
        if board.turn:
            our_board = new_game.white_board
        else:
            our_board = new_game.black_board
        if our_board in moves_to_consider:
            return moves_to_consider[our_board]

        for i in range(0, len(our_board), 2):
            if our_board[i] == "?":
                vis_board.remove_piece_at(
                    chess.parse_square(index_to_chess_pos[i]))

        move_scores = {}
        for move in board.pseudo_legal_moves:
            h = self.move_heuristic(move, vis_board)
            move_scores[move] = h
        # print("moves considered")
        moves_to_consider[our_board] = list(
            dict(
                sorted(move_scores.items(), key=itemgetter(1),
                       reverse=True)[:NUM_MOVES_CONSIDERING]).keys())
        return moves_to_consider[our_board]
Exemple #17
0
def handle_move(move):
    global user_ids
    print(move)
    board = user_ids[request.sid]
    if board.is_game_over():
        print('game over')
        emit('move_validation', {'valid': False})
    game_move = chess.Move(chess.parse_square(move['from_square']),
                           chess.parse_square(move['to_square']),
                           promotion=5)
    if game_move in board.legal_moves:
        board.push(random.choice(list(board.legal_moves)))
        print(board.fen())
        emit('botMove', {'fen': board.fen()})
    else:
        print('invalid move')
        emit('move_validation', {'valid': False})
Exemple #18
0
 def check_pawn_promotion(self, move):
     move_str = str(move)
     move_from = move_str[:2]
     piece_to_move = str(self.board.piece_at(chess.parse_square(move_from)))
     if piece_to_move not in ["p", "P"]:
         return move
     move_to = move_str[2:]
     if move_from[1] in ["2", "7"] and move_to[1] in ["1", "8"]:
         move.promotion = chess.QUEEN
     return move
Exemple #19
0
def mostraTabuleiroBonitinho():
    colunas = ["a", "b",  "c",  "d",  "e",  "f",  "g",  "h"]

    print("""   a  b  c  d  e  f  g  h """)
    for linha in range(8,0,-1):
        print(f"{linha} ", end='', flush=True)
        for coluna in colunas:
            square = chess.parse_square(coluna + linha.__str__())
            print(f"{BACKGROUND[square % 2, linha % 2]}{acharPeca(square)}", Style.RESET_ALL, end='', flush=True)
        print()
Exemple #20
0
 def test_trapped(self):
     self.assertFalse(
         util.is_trapped(
             chess.Board("q3k3/7p/8/4N2q/3PP3/4B3/8/4K2R b - - 0 1"),
             parse_square("h5")))
     self.assertTrue(
         util.is_trapped(
             chess.Board("q3k3/7p/8/4N2q/3PP3/4B3/7R/4K2R b - - 0 1"),
             parse_square("h5")))
     self.assertFalse(
         util.is_trapped(
             chess.Board("q3k3/7p/8/4N2b/3PP3/4B3/7R/4K2R b - - 0 1"),
             parse_square("h5")))
     self.assertFalse(
         util.is_trapped(
             chess.Board("4k3/7p/8/4N2q/3PP2p/4B3/8/4K3 b - - 0 1"),
             parse_square("h5")))
     self.assertTrue(
         util.is_trapped(chess.Board("8/3P4/8/4N2b/7p/6N1/8/4K3 b - - 0 1"),
                         parse_square("h5")))
Exemple #21
0
def sortPerPiece(legalMoves):
    pieces = []
    for _ in range(7):
        pieces.append([])

    for move in legalMoves:
        square = chess.parse_square(move[:2])
        p = jogo.board.piece_at(square)
        pieces[p.piece_type].append(move)

    for piece in range(1, 7):
        print(f"{ev.pieceName[piece]} = {pieces[piece]}")
Exemple #22
0
def helper_adv(G, piece, square_name, node_name):
    board = chess.Board(None)
    piece = chess.Piece.from_symbol(piece)
    square = chess.parse_square(square_name)
    board.set_piece_at(square, piece)
    attacks = board.attacks(square)

    for sq in attacks:
        square_name = chess.square_name(sq)
        for node in G.nodes():
            if node.endswith(square_name):
                G.add_edge(node, node_name)
Exemple #23
0
    def shalloweval(self, piececolor):
        if (self.draw):
            return 0

        eval = 0
        is_endgame = self.e.is_endgame(self.getfen())
        valfinder = SquareValue()
        #loop through each square of the board
        #If a piece exists, add it's value to the eval
        outcome = self.board.outcome(claim_draw=False)
        if (outcome):
            if (outcome.winner == piececolor):  #bot wins
                eval = 20000
            elif (outcome.winner == (not piececolor)):  #opponent wins
                eval = -20000
            else:
                eval = 0
        else:
            i = 0
            while (i < 64):
                piece = self.getpiece(i)
                if (piece):
                    value = valfinder.getpiecevalue(i, piececolor, piece,
                                                    is_endgame)
                    eval += value
                    if ((piece.piece_type > 1) and piece.piece_type < 6):
                        if (piece.color != self.board.turn):
                            attackers = list(
                                self.board.attackers(
                                    (not (piece.color)),
                                    chess.parse_square(chess.square_name(i))))
                            #defenders = list(self.board.attackers((piece.color), chess.parse_square(chess.square_name(i))))
                            j = 0
                            while (j < len(attackers)):
                                #if len(defenders) == 0:
                                #    eval -= value
                                #    break
                                att = abs(
                                    valfinder.getpiecevalue(
                                        attackers[j], piececolor,
                                        self.board.piece_at(attackers[j]),
                                        is_endgame))
                                #att = self.getpiece(attackers[j]).piece_type
                                if (abs(value) > att):
                                    #if piece.piece_type >= att:
                                    if (abs(value) - abs(att) >= 100):
                                        eval -= value
                                        break
                                j += 1

                i = i + 1
        return eval
Exemple #24
0
def findmove():
    # Find available moves in sorted order
    l = []
    # Start with last best moves follow up              ✓

    # With current scoring, this is slower
    # Prioritize capture of last moved piece            ✓
    if len(board.move_stack) > 0:
        last = str(board.peek())
        piece = chess.parse_square(last[2:4])
        froms = board.attackers(board.turn, piece)
        move = [chess.Move(i, piece) for i in froms]
        l.extend([m for m in move if board.is_legal(m)])

    ours = [board.pieces(j, board.turn) for j in range(1, 7)]
    for ptypes in ours:
        for froms in ptypes:
            # Killer moves: capture threatining pieces  ✓
            attackers = board.attackers(not board.turn, froms)
            attacks = board.attacks(froms)
            moves = [
                chess.Move(froms, to) for to in attacks
                if attackers.__contains__(to)
            ]
            # Other captures: if you can capture do it  ✓
            moves.extend([
                chess.Move(froms, to) for to in attacks
                if not attackers.__contains__(to)
            ])
            l.extend([move for move in moves if board.is_legal(move)])
    # Pawn promotion: try to promte pawn                ✓/✓
    if board.turn:
        moves = [
            chess.Move(pawn, pawn + 8, 5) for pawn in ours[0] if pawn >= 8 * 6
        ]
    else:
        moves = [
            chess.Move(pawn, pawn - 8, 5) for pawn in ours[0] if pawn < 8 * 2
        ]
    l.extend([m for m in moves if board.is_legal(m)])

    # All other moves ✓
    ll = list(board.legal_moves)
    l.extend(ll)
    l = list(OrderedDict.fromkeys(l))

    if len(l) is not len(ll):  # Checks if list has illegal moves
        print("Illigal move detected", len(ll), len(l))
        l = [i for i in l if board.is_legal(i)]
    return l
Exemple #25
0
def get_move_direction(move):
    print(move)
    turn = board.turn

    tile1 = move[0:2]
    tile2 = move[2:4]
    ptile1 = chess.parse_square(tile1)
    ptile2 = chess.parse_square(tile2)

    # print(f'color {board.color_at(ptile1)}')
    # print(f'color {board.color_at(ptile2)}')
    print(f'turn {turn}, tile1 {tile1}, tile2 {tile2}')

    if turn:
        #     White's turn, white possible moves: W -> B or W -> None
        zerotile = (tile1 if board.color_at(ptile1) else tile2)
        onetile = (tile2 if board.color_at(ptile1) else tile1)
    else:
        zerotile = (tile1 if not board.color_at(ptile1) else tile2)
        onetile = (tile2 if not board.color_at(ptile1) else tile1)

    move = f'{zerotile}{onetile}'
    print(f'Move direction: {move}')
    return move
Exemple #26
0
 def update_board(self, board_pos):
     for coord in self.BOARD_COORDS.keys():
         piece = board_pos.piece_at(chess.parse_square(coord))
         vec_coords = self.BOARD_COORDS[coord]
         pygame.draw.rect(
             self.WIN, vec_coords[1],
             pygame.Rect(vec_coords[0], (CELL_SIZE, CELL_SIZE)))
         if piece is None:
             pass
         else:
             piece_code = PIECE_TRANSLATION[str(piece)]
             piece_img = pygame.transform.scale(
                 pygame.image.load(
                     os.path.join(ASSETS_DIR, piece_code + '.png')),
                 (CELL_SIZE, CELL_SIZE))
             self.WIN.blit(piece_img, vec_coords[0])
     pygame.display.update()
Exemple #27
0
def open_board(game):
    board = game.board
    board.clear()
    white_king = chess.Piece(6, True)
    black_king = chess.Piece(6, False)
    board.set_piece_at(chess.parse_square("a1"), white_king)
    board.set_piece_at(chess.parse_square("h8"), black_king)

    white_queen = chess.Piece(5, True)
    black_queen = chess.Piece(5, False)
    white_knight = chess.Piece(2, True)
    black_knight = chess.Piece(2, False)
    board.set_piece_at(chess.parse_square("b1"), white_queen)
    board.set_piece_at(chess.parse_square("g8"), black_queen)
    board.set_piece_at(chess.parse_square("b2"), white_knight)
    board.set_piece_at(chess.parse_square("g7"), black_knight)

    white_bishop = chess.Piece(3, True)
    black_bishop = chess.Piece(3, False)
    board.set_piece_at(chess.parse_square("a2"), white_bishop)
    board.set_piece_at(chess.parse_square("h7"), black_bishop)
Exemple #28
0
def test_simulate_move(
    move_history: str,
    requested_move: str,
    expected_taken_move: str,
    expected_capture_square: Optional[str],
):
    board = chess.Board()
    for move in move_history.split():
        move = chess.Move.from_uci(move)
        assert move == chess.Move.null() or board.is_pseudo_legal(
            move
        ), f"Move history is invalid! Move {move} is not pseudo-legal on board\n{board}"
        board.push(move)
    assert simulate_move(board, chess.Move.from_uci(requested_move)) == (
        chess.Move.from_uci(expected_taken_move),
        None
        if expected_capture_square is None
        else chess.parse_square(expected_capture_square),
    )
Exemple #29
0
def black_checkmate(game):
    board = game.board
    board.clear()
    board.turn = False

    white_pawn1 = chess.Piece(1, True)
    white_pawn2 = chess.Piece(1, True)
    white_knight = chess.Piece(2, True)
    white_king = chess.Piece(6, True)
    black_king = chess.Piece(6, False)
    black_rook = chess.Piece(4, False)

    board.set_piece_at(chess.parse_square("a2"), white_pawn1)
    board.set_piece_at(chess.parse_square("b2"), white_pawn2)
    board.set_piece_at(chess.parse_square("a1"), white_king)
    board.set_piece_at(chess.parse_square("b3"), white_knight)
    board.set_piece_at(chess.parse_square("h8"), black_king)
    board.set_piece_at(chess.parse_square("h7"), black_rook)
Exemple #30
0
    async def game_update(self, member, move):
        if member == self.current_turn:
            try:
                square = chess.parse_square(move[:2])
                color = self.board.color_at(square=square)
            except ValueError:
                return "Invalid Move"

            if (member == self.playerTwo and color) or (
                member == self.playerOne and not color
            ):
                try:
                    self.board.push_san(move)
                except ValueError:
                    return "Invalid Move"

                self.swap_turns()
                p, r = self.check_end()

                winner, loser, tie = None, None, False
                if p != 0:
                    if p == 1:
                        tie = True
                    else:
                        winner, loser = p[0]

                    await self.end_game(winner=winner, loser=loser, tie=tie)

                content, embed = self.create_content_embed(
                    winner=winner, tie=tie, result=r
                )
                await self.update_message(content=content, embed=embed)
                return
            else:
                return "Not Your Piece"
        else:
            return "It's Not Your Turn"