def post(self): action = self.get_argument("action") if action == 'broadcast': fen = self.get_argument("fen") move_stack = self.get_argument("moveStack") move_stack = json.loads(move_stack) game = pgn.Game() create_game_header(self, game) tmp = game for move in move_stack: tmp = tmp.add_variation(tmp.board().parse_san(move)) exporter = pgn.StringExporter() game.export(exporter, headers=True, comments=False, variations=False) r = { 'type': 'broadcast', 'msg': 'Received position from Spectators!', 'pgn': str(exporter), 'fen': fen } EventHandler.write_to_clients(r) elif action == 'move': WebServer.fire(Event.REMOTE_MOVE, move=(self.get_argument("source") + self.get_argument("target")), fen=self.get_argument("fen"))
def transfer(game): pgn_game = pgn.Game().from_board(game) create_game_header(pgn_game) return pgn_game.accept( pgn.StringExporter(headers=True, comments=False, variations=False))
def update_headers(cls): g = pgn.Game() create_game_header(cls, g) exp = pgn.StringExporter() g.export(exp, headers=True, comments=False, variations=False) pgn_str = str(exp) EventHandler.write_to_clients({'event': 'header', 'header': pgn_str})
def _transfer(game: chess.Board): pgn_game = pgn.Game().from_board(game) self._build_game_header(pgn_game) self.shared['headers'] = pgn_game.headers return pgn_game.accept( pgn.StringExporter(headers=True, comments=False, variations=False))
def update_headers(): pgn_game = pgn.Game() create_game_header(pgn_game) self.shared['headers'] = pgn_game.headers EventHandler.write_to_clients({ 'event': 'header', 'headers': pgn_game.headers })
def get_output(self, headers, board, real_move_uci, moves): output_headers = {"FEN": board.fen(), **headers} game = pgn.Game(headers=output_headers) best_move = moves[0] game.add_main_variation(Move.from_uci(best_move["pv"]), comment=self.get_comment( best_move, real_move_uci)) for move in moves[1:]: game.add_variation(Move.from_uci(move["pv"]), comment=self.get_comment(move, real_move_uci)) return str(game)
def make_pgn(self,description = None,event = "Beth library development",game_round="1"): pgn_game = pgn.Game() pgn_game.headers["Date"] = datetime.datetime.now().isoformat()[:10] pgn_game.headers["Event"] = event pgn_game.headers["Round"] = game_round pgn_game.headers["Site"] = "Virtual" pgn_game.headers["White"] = str(self.white) pgn_game.headers["Black"] = str(self.black) if description is not None: pgn_game.headers["Description"] = description pgn_game.add_line(self.board.move_stack) return pgn_game
def get_pgn(self): """Returns a string representing the PGN for the current board state (and the moves leading up to it).""" root = pgn.Game() root.headers['Event'] = 'Tarrasch Chess Bot' root.headers['Date'] = datetime.datetime.utcnow().strftime('%Y.%m.%d') root.headers['White'] = self.white_user root.headers['Black'] = self.black_user next = root for move in self.move_stack: next = next.add_main_variation(move) return root.__str__()
def transfer(g): msg_game = copy.deepcopy(g) pgn_game = pgn.Game() moves = [] # go back, to see if the first fen is not standard fen while msg_game.move_stack: moves.insert(0, msg_game.pop()) if msg_game.fen() != chess.STARTING_FEN: pgn_game.setup(msg_game.fen()) create_game_header(self, pgn_game) node = pgn_game for move in moves: node = node.add_variation(move) # transfer game to a pgn string exporter = pgn.StringExporter(headers=True, comments=False, variations=False) return pgn_game.accept(exporter)
def task(self, message): if message == Message.BOOK_MOVE: EventHandler.write_to_clients({ 'event': 'Message', 'msg': 'Book move' }) elif message == Message.START_NEW_GAME: EventHandler.write_to_clients({'event': 'NewGame'}) EventHandler.write_to_clients({ 'event': 'Message', 'msg': 'New game' }) update_headers(self) elif message == Message.SEARCH_STARTED: EventHandler.write_to_clients({ 'event': 'Message', 'msg': 'Thinking..' }) elif message == Message.UCI_OPTION_LIST: self.shared['uci_options'] = message.options elif message == Message.SYSTEM_INFO: self.shared['system_info'] = message.info self.shared['system_info']['old_engine'] = self.shared[ 'system_info']['engine_name'] update_headers(self) elif message == Message.ENGINE_NAME: self.shared['system_info']['engine_name'] = message.ename update_headers(self) elif message == Message.STARTUP_INFO: self.shared['game_info'] = message.info elif message == Message.OPENING_BOOK: # Process opening book self.create_game_info() self.shared['game_info']['book'] = message.book elif message == Message.INTERACTION_MODE: # Process interaction mode self.create_game_info() self.shared['game_info']['mode'] = message.mode if self.shared['game_info']['mode'] == Mode.REMOTE: self.shared['system_info']['engine_name'] = "Remote Player" else: self.shared['system_info']['engine_name'] = self.shared[ 'system_info']['old_engine'] update_headers(self) elif message == Message.PLAY_MODE: # Process play mode self.create_game_info() self.shared['game_info']['play_mode'] = message.play_mode elif message == Message.TIME_CONTROL: self.create_game_info() self.shared['game_info'][ 'time_control_string'] = message.time_control_string elif message == Message.LEVEL: self.shared['game_info']['level'] = message.level update_headers(self) elif message == Message.COMPUTER_MOVE or message == Message.USER_MOVE or message == Message.REVIEW_MODE_MOVE: game = pgn.Game() custom_fen = getattr(message.game, 'custom_fen', None) if custom_fen: game.setup(custom_fen) create_game_header(self, game) tmp = game move_stack = message.game.move_stack for move in move_stack: tmp = tmp.add_variation(move) exporter = pgn.StringExporter() game.export(exporter, headers=True, comments=False, variations=False) fen = message.game.fen() pgn_str = str(exporter) r = {'pgn': pgn_str, 'fen': fen, 'event': "newFEN"} if message == Message.COMPUTER_MOVE: r['move'] = message.result.bestmove.uci() r['msg'] = 'Computer move: ' + str(message.result.bestmove) elif message == Message.USER_MOVE: r['move'] = message.move.uci() r['msg'] = 'User move: ' + str(message.move) if message == Message.REMOTE_MODE_MOVE: r['move'] = 'User move: ' + str(message.move) r['remote_play'] = True self.shared['last_dgt_move_msg'] = r EventHandler.write_to_clients(r)
async def acceptation_bd(msg): id_acceptant = msg.author.id contents = msg.content.split(' ') if (len(contents) == 1): await msg.channel.send( "Erreur : L'identifiant de la partie n'a pas été donné") return id_partie_acceptee = 0 try: id_partie_acceptee = int(contents[1]) except ValueError: msg_retour = "Erreur : la chaîne {0} n'est pas un identifiant de partie valide" await msg.channel.send(msg_retour.format(contents[1])) return # Manipulation de la BD cdesc = psycopg2.connect(**params_db) curs = cdesc.cursor() # chercher dans challenge la partie avec l'identifiant donné + vérifier que l'id acceptant est acceptable modele_req = "SELECT id_j1, id_j2, id_challenge, name_j1 FROM challenges WHERE (id_j2='{0}' OR id_j2 = '0') AND id_challenge = {1};" req = modele_req.format(id_acceptant, str(id_partie_acceptee)) curs.execute(req) res_tuple = curs.fetchone() if (res_tuple == None): await msg.channel.send("Identifiant de la partie non trouvé") return (idj1, idj2, idpartie, name_j1) = res_tuple id_white = idj1 nom_white = name_j1 id_black = str(msg.author.id) nom_black = str(msg.author) if (random.random() < 0.5): id_white = idj2 nom_white = nom_black id_black = idj1 nom_black = name_j1 pgn_game = pgn.Game() requete_deletion_challenge = "DELETE FROM challenges WHERE id_challenge = {0};" requete_ajout_games = "INSERT INTO games (pgn, id_blanc, id_noir, id_partie, nom_blanc, nom_noir) VALUES ('{0}', '{1}', '{2}', {3}, '{4}', '{5}');" requete_del = requete_deletion_challenge.format(idpartie) requete_ajout = requete_ajout_games.format(pgn_game, id_white, id_black, idpartie, nom_white, nom_black) curs.execute(requete_del) curs.execute(requete_ajout) cdesc.commit() curs.close() cdesc.close() message_retour = "La partie opposant {0} avec les blancs, et {1} avec les noirs peut commencer" await msg.channel.send(message_retour.format(nom_white, nom_black))
def _build_headers(): self._create_headers() pgn_game = pgn.Game() self._build_game_header(pgn_game) self.shared['headers'].update(pgn_game.headers)
import chess import chess.polyglot import chess.pgn as p board = chess.Board() print(board, '\n\n') print('**********************\n\n') # importer le fichier __init__() import __init__ as m # tant que le jeu n'est pas terminé, on joue tour = 0 # permet de determiner a qui le tour profondeur = 3 # nom de la sauvegarde nom_sauv = str(input('entrer un nom pour la partie _')) game = p.Game() # etat du jeu while not(board.is_game_over()): cap_K = True if tour % 2 == 0: moves = board.legal_moves maxi = 0 for move in moves : for deplacement in m.polyglot(board): if move == deplacement[0]: if maxi < deplacement[1]: maxi = deplacement[1] move_util = deplacement[0] cap_K = False # print(deplacement[0],deplacement[1]) if cap_K:
async def chess(self, ctx: commands.Context, *args: str): """ `!chess` __`Play chess`__ **Usage:** !chess <user> **Examples:** `!chess abc#1234` starts a game of chess with abc#1234 **Note:** Moves are in standard algebraic notation (e4, Nxf7, etc). """ try: user = await MemberConverter().convert(ctx, " ".join(args)) except BadArgument: return await ctx.send("That user doesn't exist.", delete_after=5) board = chess.Board() game = pgn.Game() node = None players = [ctx.author, user] random.shuffle(players) turn = chess.WHITE game.headers["Date"] = datetime.today().strftime("%Y.%m.%d") game.headers["White"] = players[chess.WHITE].display_name game.headers["Black"] = players[chess.BLACK].display_name def render_board(board: chess.Board) -> BytesIO: boardimg = chess.svg.board( board=board, lastmove=board.peek() if board.move_stack else None, check=board.king(turn) if board.is_check() or board.is_checkmate() else None, flipped=board.turn == chess.BLACK) res = BytesIO() svg2png(bytestring=boardimg, write_to=res) res.seek(0) return res while True: res = render_board(board) if board.outcome() is not None: game.headers["Result"] = board.outcome().result() if board.is_checkmate(): return await ctx.send( f"Checkmate!\n\n{players[not turn].mention} wins.\n{str(game)}", file=discord.File(res, "file.png")) else: return await ctx.send(f"Draw!\n{str(game)}", file=discord.File(res, "file.png")) game_msg = await ctx.send( f"{players[turn].mention}, its your turn." + ("\n\nCheck!" if board.is_check() else ""), file=discord.File(res, "file.png")) try: msg = await self.bot.wait_for( "message", timeout=600, check=lambda msg: msg.channel == ctx.channel and msg.author .id == players[turn].id) except asyncio.TimeoutError: return await ctx.send("Timed out.", delete_after=5) await msg.delete() await game_msg.delete() if msg.content == "exit" or msg.content == "resign": res = render_board(board) game.headers["Result"] = "0-1" if turn else "1-0" await game_msg.delete() return await ctx.send( f"{players[turn].mention} resigned. {players[not turn].mention} wins.\n{str(game)}", file=discord.File(res, "file.png")) try: move = board.push_san(msg.content) except ValueError: continue if not node: node = game.add_variation(move) else: node = node.add_variation(move) turn = not turn
def chess_plugin(client, channel, nick, message, cmd, args): """ Command for helga-chess. Usage: <bigjust> !chess board <helga> <url to dpaste.com> <bigjust> !chess newgame <helga> I chose black, white to move <helga> I chose white, e5 Between each move, the game is saved and persisted on file. board and move commands always assume latest game in the gamefile. Multiple games will be stored per channel/user in history. """ engine = uci.popen_engine(ENGINE) headers = OrderedDict() current_game = None game = load_game(channel) if not game: game = pgn.Game() board = game.end().board() if args[0] in ['newgame', 'move', 'board']: if args[0] == 'board': return 'http://localhost:8080/chess/{}/'.format(channel) if args[0] == 'move': if len(args) < 2: return 'usage: move e3e5' try: board.push(Move.from_uci(args[1])) except ValueError: return 'not a valid move. valid moves: {}'.format(', '.join( [str(move) for move in board.legal_moves])) engine.position(board) move = engine.go(movetime=THINK_TIME).bestmove client.msg(channel, 'my move: {}'.format(str(move))) board.push(move) if args[0] == 'newgame': # setup a new game, choose a random side, persist after # setup(), and possibly first move engine.ucinewgame() board = Board() engine.position(board) next_round, stockfish_level = next_game_stats(channel) bot_turn = randrange(2) if not bot_turn: # we're white headers.update({ 'White': NICK, 'Black': channel, }) best_move = engine.go(movetime=THINK_TIME).bestmove board.push(best_move) next_turn = 'Black' else: headers.update({ 'Black': NICK, 'White': channel, }) next_turn = 'White' now = datetime.datetime.now() headers.update({ 'Date': '{}.{}.{}'.format(now.year, now.month, now.day), 'Round': next_round, 'Event': stockfish_level, }) client.msg(channel, '{} to move'.format(next_turn)) # persist the game game = pgn.Game.from_board(board) game.headers = headers save_game(channel, game)
def __init__(self): self.game = p.Game() self.board = chess.Board() self.svg = chss.board(board=self.board)