def generate_image(_board, _squares=None): """ Generate SVG string of the board. """ if _squares: get_image(svg.board(_board, squares=_squares, size=350)) else: get_image(svg.board(_board, size=350))
def render(self, board): """This function clears and renders the board in a jupyter cell output.""" display.clear_output(wait=True) display.display( SVG( svg.board(board, size=400, lastmove=board.move_stack[-1] if board.move_stack != [] else None))) time.sleep(self.delay)
def chess_board_webhook(request, client, channel=None): request.setHeader('Content-Type', 'text/html') game = load_game(channel) if not game: raise HttpError(404) board = game.end().board() board_svg = svg.board(board=board, flipped=not board.turn, size=500) return '<html><body>{}</body></html>'.format(board_svg)
async def show_updated_board(self, channel: TextChannel): cursor = self.client.connection.cursor(buffered=True) get_puzzle = "SELECT channel_puzzles.PuzzleId, puzzles.FEN, channel_puzzles.Moves, puzzles.Moves " \ "FROM channel_puzzles LEFT JOIN puzzles ON channel_puzzles.PuzzleId = puzzles.PuzzleId " \ "WHERE ChannelId = %s;" cursor.execute(get_puzzle, (str(channel.id), )) try: puzzle_id, fen, moves, all_moves = cursor.fetchall()[0] moves = moves.split() all_moves = all_moves.split() except IndexError: return # No active puzzle board = chess.Board(fen) played_moves_uci = all_moves[:-(len(moves))] move = None for m in played_moves_uci: move = board.parse_uci(m) board.push(move) color = 'black' if ' w ' in fen else 'white' # Other way around in the original puzzle fen (before first play) image = svg.board(board, lastmove=move, colors={ 'square light': '#f2d0a2', 'square dark': '#aa7249' }, flipped=(color == 'black')) svg2png(bytestring=str(image), write_to=f'{self.client.config.base_dir}/media/board.png', parent_width=1000, parent_height=1000) embed = discord.Embed( title=f"Updated board ({color} to play)\n(puzzle ID: {puzzle_id})", url=f'https://lichess.org/training/{puzzle_id}', colour=0xeeeeee if color == 'white' else 0x000000) puzzle = discord.File( f'{self.client.config.base_dir}/media/board.png', filename="board.png") # load puzzle as Discord file embed.set_image(url="attachment://board.png") await channel.send(file=puzzle, embed=embed) # Delete puzzle image os.remove(f'{self.client.config.base_dir}/media/board.png') self.client.connection.commit() cursor.close()
async def view(self, ctx): if self.chessBoard: # Generate and format board image img = BytesIO() svg = StringIO( chess_svg.board(board=self.chessBoard, style='text{fill:white}')) renderPM.drawToFile(svg2rlg(svg), img, fmt='PNG', bg=0x36393f) img.seek(0) # Send board image to discord await ctx.send(file=discord.File(fp=img, filename='chessboard.png') )
def svg_board_image(board, arrows, last_move): svg_str = str( svg.board(board, size=200, arrows=arrows, lastmove=last_move, coordinates=SHOW_BOARD_COORDINATES)) svg_str = svg_str.replace('height="200"', 'height="100%"') svg_str = svg_str.replace('width="200"', 'width="100%"') svg_byte = svg_str.encode() encoded = base64.b64encode(svg_byte) svg_board = 'data:image/svg+xml;base64,{}'.format(encoded.decode()) return (svg_board)
def _position_to_image(board, size, color): """ Produce an image for every move :board: object for the board moves :size: size of the board :color: color of the chess board """ css = {'green': 'css/green.css', 'blue': 'css/blue.css'} css_content = None if color != 'brown': css_content = open(css[color]).read() svg_file = svg.board(board, size=size, style=css_content) bytes = cairosvg.svg2png(bytestring=svg_file, border=False) return imageio.imread(bytes, format="PNG")
def run(self): ## Now start the engine s_time = time.time() fnumber = 0 move_count = 0 while (True): if (self.board.is_game_over()): if (self.board.is_stalemate()): self.winner = {"game_result": "Stalemate"} if (self.board.is_insufficient_material()): self.winner = {"game_result": "Insufficient material"} if (self.board.is_repetition()): self.winner = {"game_result": "Repetition"} if (self.board.is_checkmate()): ass_win = 1 if (len(self.ProcessedData) % 2 == 0): ass_win += 1 self.winner = { "game_result": " Winner is Player " + str(ass_win) } ret, image = self.vid_cap.read() if (ret == False or move_count >= len(self.anno)): break self.RealFrame = image.copy() fnumber += 1 chance = self.anno[move_count] frame_no = chance[0] move = chance[1] if (frame_no == fnumber): move_count += 1 try: self.board.push_san(move) info = self.engine.analyse(self.board, chess.engine.Limit(depth=20)) move = str(move) time_of_move = str(int(time.time() - s_time)) depth = str(info["depth"]) pov_score = str(info["score"]) best_counter_move = str(info["pv"][0].uci()) print("Chance ==> " + str(move_count)) except Exception as e: print(e) print(frame_no) print(self.board) print(move) break iboard = chess.Board(self.board.fen()) squares = iboard.attacks(chess.E4) final_board = str(svg.board(board=iboard, squares=squares)) chance_data = { "boardSVG": final_board, "moveNo": str(move_count), "timeOfMove": time_of_move, "move": move, "depthOfSearch": depth, "Score": pov_score, "bestCounterMove": best_counter_move } self.ProcessedData = chance_data.copy() self.engine.quit()
for i, chance in enumerate(anno): frame_no = chance[0] move = chance[1] try: board.push_san(move) info = engine.analyse(board, chess.engine.Limit(depth=20)) move = str(move) time_of_move = int(time.time() - s_time) depth = info["depth"] pov_score = info["score"] best_counter_move = info["pv"][0].uci() print("Time : " + str(time_of_move) + " Move : " + str(move) + " Depth : " + str(depth) + " Best Counter Move : " + str(best_counter_move) + " Score : " + str(pov_score)) except Exception as e: print("Game end") print(e) engine.quit() iboard = chess.Board(board.fen()) squares = iboard.attacks(chess.E4) final_board = str(svg.board(board=iboard, squares=squares)) try: sys.exit() except Exception as e: print(e) # print(type(final_board)) # # print(final_board)
brd.set_fen(fen) bb = chess.BaseBoard() bb.set_board_fen(brd.board_fen()) pcmap = bb.piece_map() repres = [] for i in range(64): if i in pcmap: repres.append(pcmap[i].symbol()) else: repres.append('.') strrepres = ''.join([elem for elem in repres]) return strrepres for line in cpgn: if ind % 90 == 0: fen = line.split(' ')[1] representation = reprgener(fen) with open('board.svg', 'w') as svgbrd: svgbrd.write(svg.board(chess.Board(fen))) locked = int(input('Locked?')) doc = doc.append( pd.DataFrame([[representation, fen, locked]], columns=['Repr', 'Fen', 'Locked'])) doc.index = [ind for ind in range(len(doc.axes[0]))] doc.to_excel('NeuralNNTf.xlsx', sheet_name='LockedPos') with open('checkpoint.txt', 'w') as newcpgn: newcpgn.write(''.join(map(str, ecpgn))) del ecpgn[0] ind += 1
async def show_puzzle(self, context: Context, puzzle_id: Optional[str] = None) -> None: """ Show a Lichess puzzle. If a puzzle ID is given, show that puzzle. If the user if connected, show a puzzle with a rating around their puzzle rating. Otherwise show a random puzzle. @param context: ~Context: The context of the command @param puzzle_id: Optional[str]: Optional puzzle ID @return: """ cursor = self.client.connection.cursor(buffered=True) connected = True if puzzle_id is None: try: # Try fetch a puzzle near the user's puzzle rating discord_uid = str(context.message.author.id) cursor.execute(f"SELECT Rating FROM users WHERE DiscordUid = %s", (discord_uid,)) rating = cursor.fetchall()[0][0] # raises IndexError if user does not exist in table if rating == -1: raise ValueError # Random PuzzleId puzzle_query = "WITH filtered AS (SELECT * FROM puzzles WHERE Rating BETWEEN %s AND %s) " \ "SELECT PuzzleId, FEN, Moves, Rating, Themes " \ "FROM filtered " \ "JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM filtered)) AS rand_id) " \ "AS tmp " \ "WHERE filtered.id >= tmp.rand_id " \ "ORDER BY filtered.id ASC LIMIT 1;" query_data = (rating-50, rating+100) except (IndexError, ValueError) as e: if isinstance(e, IndexError): connected = False # User has not connected their Lichess account # Grab a random puzzle efficiently puzzle_query = "SELECT PuzzleId, FEN, Moves, Rating, Themes " \ "FROM puzzles " \ "JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM puzzles)) AS rand_id) " \ "AS tmp " \ "WHERE puzzles.id >= tmp.rand_id " \ "LIMIT 1;" query_data = tuple() cursor.execute(puzzle_query, query_data) puzzle_id, fen, moves, rating, themes = cursor.fetchall()[0] moves = moves.split() else: get_puzzle = "SELECT FEN, Moves, Rating, Themes FROM puzzles WHERE PuzzleId = %s;" cursor.execute(get_puzzle, (puzzle_id,)) try: fen, moves, rating, themes = cursor.fetchall()[0] moves = moves.split() except IndexError: embed = discord.Embed(title="Puzzle command", colour=0xff0000) embed.add_field(name=f"Oops!", value=f"I can't find a puzzle with puzzle id **{puzzle_id}**.\n" f"Command usage:\n" f"`{self.client.prfx(context)}puzzle` → show a random puzzle, or one near your " f"puzzle rating when connected with `{self.client.prfx(context)}connect`\n" f"`{self.client.prfx(context)}puzzle [id]` → show a particular puzzle\n" f"`{self.client.prfx(context)}puzzle rating1-rating2` → show a random puzzle " f"with a rating between rating1 and rating2.") await context.send(embed=embed) return # Play the initial move that starts the puzzle board = chess.Board(fen) initial_move_uci = moves.pop(0) move = board.parse_uci(initial_move_uci) initial_move_san = board.san(move) board.push(move) fen = board.fen() color = 'white' if ' w ' in fen else 'black' # Create svg image from board image = svg.board(board, lastmove=move, colors={'square light': '#f2d0a2', 'square dark': '#aa7249'}, flipped=(color == 'black')) # Save puzzle image as png svg2png(bytestring=str(image), write_to=f'{self.client.config.base_dir}/media/puzzle.png', parent_width=1000, parent_height=1000) embed = discord.Embed(title=f"Find the best move for {color}!\n(puzzle ID: {puzzle_id})", url=f'https://lichess.org/training/{puzzle_id}', colour=0xeeeeee if color == 'white' else 0x000000 ) puzzle = discord.File(f'{self.client.config.base_dir}/media/puzzle.png', filename="puzzle.png") # load puzzle as Discord file embed.set_image(url="attachment://puzzle.png") embed.add_field(name=f"Answer with `{self.client.prfx(context)}answer` / `{self.client.prfx(context)}a`", value=f"Answer using SAN ({initial_move_san}) or UCI ({initial_move_uci}) notation\n" f"Puzzle difficulty rating: ||**{rating}**||") if not connected: embed.add_field(name=f"Get relevant puzzles:", value=f"Connect your Lichess account with `{self.client.prfx(context)}connect` to get " f"puzzles around your puzzle rating!") msg = await context.send(file=puzzle, embed=embed) # send puzzle # Keep track of this puzzle in this channel. channel_puzzle = ("INSERT INTO channel_puzzles " "(ChannelId, PuzzleId, Moves, FEN, MessageId) " "VALUES (%s, %s, %s, %s, %s) " "ON DUPLICATE KEY UPDATE PuzzleId = VALUES(PuzzleId), " "Moves = VALUES(Moves), FEN = VALUES(FEN), MessageId = VALUES(MessageId)") data_puzzle = (str(context.message.channel.id), str(puzzle_id), ' '.join(moves), str(fen), str(msg.id)) cursor.execute(channel_puzzle, data_puzzle) # Delete puzzle image os.remove(f'{self.client.config.base_dir}/media/puzzle.png') self.client.connection.commit() cursor.close()
def save_pic(board): pic = svg.board(board=board) with open('board.svg', 'w') as f: f.write(pic)