Example #1
0
    async def show_hint(self, channel: TextChannel):
        cursor = self.client.connection.cursor(buffered=True)

        get_puzzle = "SELECT c.PuzzleId, c.fen, puzzles.Themes, c.Moves " \
                     "FROM channel_puzzles AS c LEFT JOIN puzzles ON c.PuzzleId = puzzles.PuzzleId " \
                     "WHERE ChannelId = %s;"
        cursor.execute(get_puzzle, (str(channel.id), ))

        try:
            puzzle_id, fen, themes, moves = cursor.fetchall()[0]
            moves = moves.split()
            with open(f"{self.client.config.base_dir}/src/themes.json",
                      "r") as f:
                themes_dict = json.loads(f.read())
            themes = list(
                filter(
                    None,
                    [themes_dict.get(theme, None)
                     for theme in themes.split()]))
        except IndexError:
            return  # No active puzzle

        board = chess.Board(fen)
        next_move_uci = moves[0]
        move = board.parse_uci(next_move_uci)
        piece_to_move = chess.piece_name(board.piece_type_at(
            move.from_square)).capitalize()

        embed = Embed(title="Hints :bulb:", colour=0xff781f)
        embed.add_field(name="Piece to move", value=f"||{piece_to_move}||")
        embed.add_field(name="Puzzle themes",
                        value="||" + ", ".join(themes) + "||",
                        inline=False)
        await channel.send(embed=embed)
Example #2
0
def piece_code(piece_type):
    fullname = chess.piece_name(piece_type)
    if fullname == 'knight':
        return 'N'
    if fullname == 'pawn':
        return 'p'
    return fullname[0].upper()
def promote_test():
    """ Detects promotion """
    hi = HardwareImplementation()
    while True:
        piece = hi.promotion_piece()
        print(chess.piece_name(piece))
        sleep(1)
Example #4
0
def post_options(board, tweet_id):
	order = [chess.QUEEN, chess.KING, chess.ROOK, chess.BISHOP, chess.KNIGHT, chess.PAWN]
	moves = {chess.piece_name(p).title(): [] for p in order}
	piece_map = board.piece_map()

	for m in list(board.legal_moves):
		piece = chess.piece_name(piece_map[m.from_square].piece_type).title()
		moves[piece].append(m)

	poll_ids = []

	for p in moves:
		if len(moves[p]) <= 0:
			continue

		op = []
		for m in moves[p]:
			f = chess.square_name(m.from_square).upper()
			t = chess.square_name(m.to_square).upper()
			if m.promotion:
				prom = chess.piece_name(m.promotion).title()
				op.append(move_msg_prom.format(p, f, t, prom))
				continue
			op.append(move_msg.format(p, f, t))

		# Make sure we don't leave a poll with only 1 options (tweeter doesn't accept this)
		if len(op) % 4 == 1:
			op.append(filler_text)

		op = [op[i:i + 4] for i in range(0, len(op), 4)]

		head_tweet_id = post_tweet(p + " Moves:", reply_id=tweet_id, entries=op.pop(0))
		if not head_tweet_id:
			poll_ids.append(tweet_id)
			panic_clean_tweets(poll_ids)

		poll_ids.append(head_tweet_id)
		for poll_ops in op:
			head_tweet_id = post_tweet(p + " cont...", reply_id=head_tweet_id, entries=poll_ops)
			if not head_tweet_id:
				poll_ids.append(tweet_id)
				panic_clean_tweets(poll_ids)
			poll_ids.append(head_tweet_id)

	return poll_ids
Example #5
0
    def __move_to_words(self, board, move):
        start_square = move.from_square
        starting_square_string = self.__chessSquareToCoordinate(start_square)
        end_square = move.to_square
        end_square_string = self.__chessSquareToCoordinate(end_square)
        chess_piece = board.piece_map()[start_square]
        chess_piece_name = chess.piece_name(chess_piece.piece_type)
        chess_piece_colour = "White" if chess_piece.color else "Black"

        return chess_piece_colour + " " + chess_piece_name + " move from " + starting_square_string + " to " + end_square_string
Example #6
0
def parse_piece(piece):

    if piece is None:
        return {}
    else:
        piece_type = piece.piece_type

        data = {
            "color": "WHITE" if piece.color else "BLACK",
            "type": piece_type,
            "name": piece_name(piece_type),
            "symbol": piece_symbol(piece_type),
            "value": PIECE_VALUES[piece_type],
        }

        return data
Example #7
0
            def format_coord(x, y):
                x, y = int(round(x)), int(round(y))

                x_ = x % widthx
                y_ = y % widthy
                piece_type = (y_ + 16) // 64
                piece_name = "{} {}".format(
                    "white" if x_ // (widthx // 2) == 0 else "black",
                    chess.piece_name(piece_type + 1))

                x_ = x_ % (widthx // 2)
                y_ = (y_ + 16) % 64 if y_ >= 48 else y_ + 8
                if default_order:
                    # Piece centric, flipped king.
                    piece_square_name = chess.square_name(x_ // 8 + 8 *
                                                          (7 - y_ // 8))
                    king_square_name = chess.square_name(7 - (x_ % 8) + 8 *
                                                         (y_ % 8))
                else:
                    # King centric.
                    if piece_type == 0:
                        piece_square_name = chess.square_name(x_ % 8 + 8 *
                                                              (6 -
                                                               ((y_ - 8) % 6)))
                        king_square_name = chess.square_name(x_ // 8 + 8 *
                                                             (7 -
                                                              (y_ - 8) // 6))
                    else:
                        piece_square_name = chess.square_name(x_ % 8 + 8 *
                                                              (7 - (y_ % 8)))
                        king_square_name = chess.square_name(x_ // 8 + 8 *
                                                             (7 - y_ // 8))

                neuron_id = int(numx * (y // widthy) + x // widthx)
                if self.args.sort_input_neurons:
                    neuron_label = "sorted neuron {} (original {})".format(
                        neuron_id, self.sorted_input_neurons[neuron_id])
                else:
                    neuron_label = "neuron {}".format(neuron_id)

                return "{}, {} on {}, white king on {}".format(
                    neuron_label, piece_name, piece_square_name,
                    king_square_name)
Example #8
0
    def promotion_piece(self) -> chess.Piece:
        """ Which piece to promote to

        Reads input button to select promotion piece, writes selected piece to display and waits for confirmation

        :return: Piece to promote to
        """
        piece = chess.QUEEN
        while True:
            if self._perform_safe(getattr)(self._buttons[0], 'value'):
                piece = chess.QUEEN

            if self._perform_safe(getattr)(self._buttons[1], 'value'):
                piece = chess.ROOK

            if self._perform_safe(getattr)(self._buttons[2], 'value'):
                piece = chess.BISHOP

            if self._perform_safe(getattr)(self._buttons[3], 'value'):
                piece = chess.KNIGHT

            self.display(chess.piece_name(piece))
            if self._perform_safe(getattr)(self._buttons[4], 'value'):
                return piece
Example #9
0
    buffer = io.BytesIO()
    svg2png(bytestring=chessboard_svg, write_to=buffer) # Chessboard to PNG in memory
    chessboard = Image.open(buffer)

    new_im = Image.new('RGB', (1920, 1080))
    new_im.paste(chessboard, (0,0,400,400))
    if image:
        new_im.paste(image, (400,0))
    if is_check:
        new_im.paste(images["king_under_threat"], (0, 400))
    new_im.save(filename)

board = first_game.board()
svg = chess.svg.board(board=board)
render_image("render/0.jpg", svg)

audio = AudioSegment.silent(duration=1000)

moves = list(first_game.mainline_moves())
for i, move in enumerate(tqdm(moves)):
    board.push(move)
    if board.is_game_over():
        print(board.result())
    piece_type = chess.piece_name(board.piece_type_at(move.to_square))
    svg = chess.svg.board(board=board, lastmove=move, size=400)
    render_image(f"render/{i + 1}.jpg", svg, images[piece_type], board.is_check())
    clip = audio_clips[piece_type]
    if board.is_check():
        clip = clip.overlay(audio_clips["alert"])
    audio += clip
audio.export("audio.mp3", format="mp3")
Example #10
0
for move in board.legal_moves:
	if move.promotion == None or move.promotion == 5:
		entry = move.from_square * 73 + move.to_square
	else:
		diff = abs(move.from_square-move.to_square) - 8
		if diff < 0:
			diff = 1
		elif diff > 0:
			diff = 2
		entry = move.from_square*73 + 63 + diff*3 + (move.promotion-1)
	lmvs[entry] = move
	print('{0} - {1}, {2}, {3}, {4}'.format(move, move.from_square,move.to_square, move.promotion, move.uci()))
	print(entry)


chess.piece_name(4)


chessenv = Game()
memory = Memory(config.MEMORY_SIZE)
memory.commit_stmemory(env.identities,env.gameState,env.actionSpace)
memory.stmemory


pool = multiprocessing.Pool(2)
out = zip(pool.map(_selfplay, range(0, 2)))
t = tuple(out)

len(t)

chessenv.action_size
Example #11
0
async def run_engine(uid, ws):
    game: GameObject = games[uid]
    board = game.board.copy()
    await start_engine(game, ws)
    if not game.should_run():
        return

    # Reset old arrows when engine is about to run
    game.arrows.clear()
    # print(board)
    limit: chess.engine.Limit = chess.engine.Limit()
    use_depth = settings.config.getboolean("gui", "use_depth")
    use_time = settings.config.getboolean("gui", "use_time")
    use_nodes = settings.config.getboolean("gui", "use_nodes")
    if use_depth:
        limit.depth = settings.config.getint("gui", "depth")
    if use_time:
        limit.time = settings.config.getfloat("gui", "time")
    if use_nodes:
        limit.nodes = settings.config.getint("gui", "nodes")

    if not use_depth and not use_time and not use_nodes:
        limit.depth = 8
        await ws.send(
            serialize_message("error",
                              "No limit set, using default depth of 8"))

    if settings.config.getboolean("gui", "clear_log"):
        try:
            debug_log_file = settings.engine_config.get(
                "engine", "debug log file")
            open(debug_log_file, "w").close()
        except Exception:
            pass

    # Set latest ECO for current board
    eco_name = eco.get_name(board.epd())
    if eco_name != "":
        game.eco = eco_name

    # Look for opening moves from books
    opening_moves = []
    if settings.config.getboolean("gui", "use_book"):
        bookfiles = books.load_books("books")
        for bookfile in bookfiles:
            read_book(bookfile, opening_moves, board, [], 0)

    if len(opening_moves) > 0:
        opening_moves = sorted(opening_moves,
                               key=lambda x: sum([y.weight for y in x]),
                               reverse=True)

        best_san = board.san(opening_moves[0][0].move)
        best_piece = chess.piece_name(
            board.piece_at(
                opening_moves[0][0].move.from_square).piece_type).capitalize()
        mate_in = None

        opening_dict = defaultdict(list)

        for move, *reply in opening_moves:
            reply = reply[0] if len(reply) > 0 else None
            raw_keys = [x.raw_move for x in opening_dict]
            raw_key = move.raw_move

            # If the raw has already been added
            if raw_key in raw_keys:
                # No need to do anything if there is no reply anyway
                if reply:
                    # Find the raw move and append reply to there instead
                    existing_key = None
                    for key in opening_dict:
                        if key.raw_move == raw_key:
                            existing_key = key
                    if existing_key:
                        # Check if the list contains raw_move of the reply already
                        raw_moves = [
                            x.raw_move for x in opening_dict[existing_key]
                        ]
                        raw_move = reply.raw_move
                        if raw_move not in raw_moves:
                            opening_dict[key].append(reply)
            else:
                if reply:
                    opening_dict[move].append(reply)
                else:
                    opening_dict[move] = []

        multi_pv = []
        list_index = 0
        for move, replies in opening_dict.items():
            list_index += 1
            score = move.weight
            pv = []
            lan = []
            pv.append(board.san(move.move))
            lan.append(board.lan(move.move))
            arrow = drawing.get_arrow(move.move, board.turn, 0)
            game.arrows[list_index].append(arrow)
            board.push(move.move)
            # Get EPD after the first push is moved
            epd = board.epd()
            opponents_turn = board.turn
            for reply in replies:
                pv.append(board.san(reply.move))
                lan.append(board.lan(reply.move))
                arrow = drawing.get_arrow(reply.move, opponents_turn, 1)
                game.arrows[list_index].append(arrow)
            # Unwind the move stack
            board.pop()
            line = {
                "multipv": list_index,
                "score": score,
                "pv": pv,
                "lan": lan,
                "eco": eco.get_name(epd),
            }

            multi_pv.append(line)
        await ws.send(
            serialize_message(
                "multipv", {
                    "multipv": multi_pv,
                    "turn": board.turn,
                    "current_eco": game.eco,
                    "book": True,
                    "best_piece": best_piece
                }))
    else:
        # If there no opening moves were found, use engine to analyse instead
        if game.engine is None:
            print(
                "Trying to analyse but engine has not been initialized, check engine path."
            )
            await ws.send(
                serialize_message(
                    "error",
                    "Trying to analyse but engine has not been initialized, check engine path."
                ))
            return

        multi_pv = settings.config.getint("gui", "multipv")
        print("Starting analysis with limit", limit, "for", multi_pv, "pv(s)")
        try:
            game.analysing = True
            results = await game.engine.analyse(board=board,
                                                limit=limit,
                                                multipv=multi_pv,
                                                game=uid,
                                                info=chess.engine.INFO_ALL)
        except Exception as err:
            print("Engine analysis failed.")
            if DEBUG:
                print(err)
            return
        finally:
            game.analysing = False

        if results is None or results[0] is None:
            print("Analysis stopped before results, returning...")
            return

        best_move = results[0].pv[0]
        best_san = board.san(best_move)
        best_piece = chess.piece_name(
            board.piece_at(best_move.from_square).piece_type).capitalize()
        mate_in = results[0].score.relative.moves if results[0].score.is_mate(
        ) else None

        multipv_data = []
        for multi_pv in results:
            move_counter = 0
            pv = []
            lan_pv = []
            epd = ""

            for index, move in enumerate(multi_pv.pv):
                san = board.san(move)
                lan = board.lan(move)
                arrow = drawing.get_arrow(move, board.turn, move_counter // 2)
                pv_index = 1 if multi_pv.multipv is None else multi_pv.multipv
                game.arrows[pv_index].append(arrow)

                pv.append(san)
                lan_pv.append(lan)
                board.push(move)

                # Get EPD for the first move
                if index == 0:
                    epd = board.epd()

                move_counter += 1

            for _ in range(move_counter):
                board.pop()

            if multi_pv.score.is_mate():
                score = "#" + str(multi_pv.score.relative.moves)
            else:
                score = multi_pv.score.relative.cp

            unit = {
                "multipv": multi_pv.multipv,
                "pv": pv,
                "lan": lan_pv,
                "score": score,
                "eco": eco.get_name(epd),
            }
            multipv_data.append(unit)
        await ws.send(
            serialize_message(
                "multipv",
                {
                    "multipv": multipv_data,
                    "turn": board.turn,
                    "current_eco": game.eco,
                    "book": False,
                    "best_piece": best_piece
                },
            ))

    if DEBUG:
        print(
            "Best move:", best_piece if settings.config.getboolean(
                "gui", "piece_only") else best_san)
        if mate_in is not None:
            print("Mate in", mate_in)

    if settings.config.getboolean("gui", "draw_board"):
        svg = drawing.draw_svg_board(game, 1)
        await ws.send(serialize_message("board", svg))

    if settings.config.getboolean("gui", "use_voice"):
        if settings.config.getboolean("gui", "piece_only"):
            voice.say(best_piece, True)
        else:
            voice.say(best_san, False)
    game.missed_moves = False
def sequenceGenerator(uciMove, board):
    '''
    INPUT: 
        uciMove -> Move in UCI format to analyze it. 
        board -> Game state, this is a chess.Board() object.
    OUTPUT:
        result -> Is empty if a valid move is not detected, if it is detected then it is a dictionary data structure with two values:
            "seq": String with a sequence of chess coordinates to guide th robot movement.
            "type": String with type of movement, Castling-Promotion-Move-Capture-Passant.
    '''
    result = {}
    move = chess.Move.from_uci(uciMove)
    first = uciMove[:2]
    second = uciMove[2:4]
    last = uciMove[-1]
    graveyard = "k0"

    if last < '1' or last > '8':  # Promotion Evaluation: Check if last char is a letter.
        if board.is_capture(move):
            result["seq"] = second + graveyard + first + second
        else:
            result["seq"] = first + second
        result["type"] = "Promotion"
    elif board.turn and uciMove == "e1g1" and chess.piece_name(
            board.piece_type_at(chess.SQUARE_NAMES.index(
                "e1"))) == "king":  #White King side castling
        result["seq"] = first + second + "h1f1"
        result["type"] = "White King Side Castling"
    elif board.turn and uciMove == "e1c1" and chess.piece_name(
            board.piece_type_at(chess.SQUARE_NAMES.index(
                "e1"))) == "king":  #White Queen side castling
        result["seq"] = first + second + "a1d1"
        result["type"] = "White Queen Side Castling"
    elif not board.turn and uciMove == "e8g8" and chess.piece_name(
            board.piece_type_at(chess.SQUARE_NAMES.index(
                "e8"))) == "king":  #Black King side castling
        result["seq"] = first + second + "h8f8"
        result["type"] = "Black King Side Castling"
    elif not board.turn and uciMove == "e8c8" and chess.piece_name(
            board.piece_type_at(chess.SQUARE_NAMES.index(
                "e8"))) == "king":  #Black Queen side castling
        result["seq"] = first + second + "a8d8"
        result["type"] = "White Queen Side Castling"
    elif board.is_en_passant(move):  # En Passant
        if board.turn:
            squareFile = chess.square_file(chess.SQUARE_NAMES.index(first))
            squareRank = chess.square_rank(chess.SQUARE_NAMES.index(first))
            result["seq"] = chess.SQUARE_NAMES[chess.square(
                squareFile - 1, squareRank)] + graveyard + first + second
            result["type"] = "Passant"
        else:
            squareFile = chess.square_file(chess.SQUARE_NAMES.index(first))
            squareRank = chess.square_rank(chess.SQUARE_NAMES.index(first))
            result["seq"] = chess.SQUARE_NAMES[chess.square(
                squareFile + 1, squareRank)] + graveyard + first + second
            result["type"] = "Passant"
    elif board.is_capture(move):  # Capture move
        result["seq"] = second + graveyard + first + second
        result["type"] = "Capture"
    else:  # Normal move
        result["seq"] = uciMove
        result["type"] = "Move"

    return result
Example #13
0
    def piece_to_name(self, piece):
        name = chess.piece_name(piece.piece_type)
        color = "_w" if piece.color == chess.WHITE else "_b"

        return f"{name}{color}"