Python chess.pgn() Examples
The following are 30
code examples of chess.pgn().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
chess
, or try the search function
.

Example #1
Source File: __main__.py From python-chess-annotator with GNU General Public License v3.0 | 6 votes |
def get_nags(judgment): """ Returns a Numeric Annotation Glyph (NAG) according to how much worse the played move was vs the best move """ delta = judgment["playedeval"] - judgment["besteval"] if delta < ERROR_THRESHOLD["BLUNDER"]: return [chess.pgn.NAG_BLUNDER] elif delta < ERROR_THRESHOLD["MISTAKE"]: return [chess.pgn.NAG_MISTAKE] elif delta < ERROR_THRESHOLD["DUBIOUS"]: return [chess.pgn.NAG_DUBIOUS_MOVE] else: return []
Example #2
Source File: server.py From picochess with GNU General Public License v3.0 | 6 votes |
def post(self): action = self.get_argument('action') if action == 'broadcast': fen = self.get_argument('fen') pgn_str = self.get_argument('pgn') result = {'event': 'Broadcast', 'msg': 'Position from Spectators!', 'pgn': pgn_str, 'fen': fen} EventHandler.write_to_clients(result) elif action == 'move': move = chess.Move.from_uci(self.get_argument('source') + self.get_argument('target')) Observable.fire(Event.REMOTE_MOVE(move=move, fen=self.get_argument('fen'))) elif action == 'clockbutton': Observable.fire(Event.KEYBOARD_BUTTON(button=self.get_argument('button'), dev='web')) elif action == 'room': inside = self.get_argument('room') == 'inside' Observable.fire(Event.REMOTE_ROOM(inside=inside)) elif action == 'command': self.process_console_command(self.get_argument('command'))
Example #3
Source File: python_easy_chess_gui.py From Python-Easy-Chess-GUI with GNU Lesser General Public License v3.0 | 6 votes |
def get_players(self, pgn, q): logging.info(f'Enters get_players()') players = [] games = 0 with open(pgn) as h: while True: headers = chess.pgn.read_headers(h) if headers is None: break wp = headers['White'] bp = headers['Black'] players.append(wp) players.append(bp) games += 1 p = list(set(players)) ret = [p, games] q.put(ret)
Example #4
Source File: pgn_to_records.py From Zerofish with MIT License | 6 votes |
def run_pgn (pgn_file, n_games, data_dir): games = 0 while n_games == 0 or games < n_games: game = chess.pgn.read_game(pgn_file) game.headers['Counter'] = games name = '{White}-{Black}-{ECO}-{Date}-{Counter}'.format ( **game.headers ).replace(' ', '_') # Loop exit condition if game is None: break # Run through game generating labels actions, policies, indices, outcome, winner = run_game(game) # Save labels to disk self_play.write_records(data_dir, name, actions, policies, indices, outcome, winner) # games += 1
Example #5
Source File: server.py From syzygy-tables.info with GNU Affero General Public License v3.0 | 5 votes |
def robots(request): return aiohttp.web.Response(text=textwrap.dedent("""\ User-agent: SemrushBot User-agent: SemrushBot-SA User-agent: AhrefsBot User-agent: MegaIndex.ru Disallow: / User-agent: * Disallow: /syzygy-vs-syzygy/ Disallow: /endgames.pgn """))
Example #6
Source File: server.py From syzygy-tables.info with GNU Affero General Public License v3.0 | 5 votes |
def make_app(config): app = aiohttp.web.Application(middlewares=[trust_x_forwarded_for]) app["config"] = config # Check configured base url. assert config.get("server", "base_url").startswith("http") assert config.get("server", "base_url").endswith("/") # Configure templating. app["jinja"] = jinja2.Environment( loader=jinja2.FileSystemLoader("templates"), autoescape=jinja2.select_autoescape(["html"])) app["jinja"].globals["DEFAULT_FEN"] = DEFAULT_FEN app["jinja"].globals["STARTING_FEN"] = chess.STARTING_FEN app["jinja"].globals["development"] = config.getboolean("server", "development") app["jinja"].globals["asset_url"] = asset_url app["jinja"].globals["kib"] = kib # Load stats. with open("stats.json") as f: app["stats"] = json.load(f) # Setup routes. app.router.add_routes(routes) app.router.add_static("/static", "static") app.router.add_route("GET", "/checksums/bytes.tsv", static("checksums/bytes.tsv")) app.router.add_route("GET", "/checksums/tbcheck.txt", static("checksums/tbcheck.txt", content_type="text/plain")) app.router.add_route("GET", "/checksums/PackManifest", static("checksums/PackManifest", content_type="text/plain")) app.router.add_route("GET", "/checksums/B2SUM", static("checksums/B2SUM", content_type="text/plain")) app.router.add_route("GET", "/checksums/MD5SUM", static("checksums/MD5SUM", content_type="text/plain")) app.router.add_route("GET", "/checksums/SHA1SUM", static("checksums/SHA1SUM", content_type="text/plain")) app.router.add_route("GET", "/checksums/SHA256SUM", static("checksums/SHA256SUM", content_type="text/plain")) app.router.add_route("GET", "/checksums/SHA512SUM", static("checksums/SHA512SUM", content_type="text/plain")) app.router.add_route("GET", "/endgames.pgn", static("stats/regular/maxdtz.pgn", content_type="application/x-chess-pgn")) app.router.add_route("GET", "/stats.json", static("stats.json")) return app
Example #7
Source File: __main__.py From python-chess-annotator with GNU General Public License v3.0 | 5 votes |
def parse_args(): """ Define an argument parser and return the parsed arguments """ parser = argparse.ArgumentParser( prog='annotator', description='takes chess games in a PGN file and prints ' 'annotations to standard output') parser.add_argument("--file", "-f", help="input PGN file", required=True, metavar="FILE.pgn") parser.add_argument("--engine", "-e", help="analysis engine (default: %(default)s)", default="stockfish") parser.add_argument("--gametime", "-g", help="how long to spend on each game \ (default: %(default)s)", default="1", type=float, metavar="MINUTES") parser.add_argument("--threads", "-t", help="threads for use by the engine \ (default: %(default)s)", type=int, default=1) parser.add_argument("--verbose", "-v", help="increase verbosity", action="count") return parser.parse_args()
Example #8
Source File: __main__.py From python-chess-annotator with GNU General Public License v3.0 | 5 votes |
def main(): """ Main function - Load games from the PGN file - Annotate each game, and print the game with the annotations """ args = parse_args() setup_logging(args) engine = args.engine.split() pgnfile = args.file try: with open(pgnfile) as pgn: for game in iter(lambda: chess.pgn.read_game(pgn), None): try: analyzed_game = analyze_game(game, args.gametime, engine, args.threads) except KeyboardInterrupt: logger.critical("\nReceived KeyboardInterrupt.") raise except Exception as e: logger.critical("\nAn unhandled exception occurred: {}" .format(type(e))) raise e else: print(analyzed_game, '\n') except PermissionError: errormsg = "Input file not readable. Aborting..." logger.critical(errormsg) raise
Example #9
Source File: proc.py From fastchess with GNU General Public License v3.0 | 5 votes |
def get_games(path, max_size=None): import chess.pgn games = iter(lambda: chess.pgn.read_game(open(path)), None) if max_size is None: yield from games for i, game in enumerate(games): if i >= max_size: break yield game
Example #10
Source File: proc.py From fastchess with GNU General Public License v3.0 | 5 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument('files', help='glob for pgn files, e.g. **/*.pgn', nargs="+") parser.add_argument('-test', help='test out') parser.add_argument('-train', help='train out') parser.add_argument('-ttsplit', default=.8, help='test train split') parser.add_argument('-eval', action='store_true', help='predict eval rather than moves') args = parser.parse_args() work_spark(args) #work_streams(args) print('Done!')
Example #11
Source File: tune.py From fastchess with GNU General Public License v3.0 | 5 votes |
def load_book(path, n_book): if not path.is_file(): print(f'Error: Can\'t open book {path}.') return with open(path, encoding='latin-1') as file: for game in iter((lambda: chess.pgn.read_game(file)), None): board = game.board() for _, move in zip(range(n_book), game.mainline_moves()): board.push(move) yield board
Example #12
Source File: arena.py From fastchess with GNU General Public License v3.0 | 5 votes |
def run_games(self, book, game_id=0, games_played=2): score = 0 games = [] assert games_played % 2 == 0 for r in range(games_played//2): init_board = random.choice(book) for color in [WHITE, BLACK]: white, black = (self.enginea, self.engineb) if color == WHITE \ else (self.engineb, self.enginea) game_round = games_played * game_id + color + 2*r game = chess.pgn.Game({ 'Event': 'Tune.py', 'White': white.id['name'], 'WhiteArgs': repr(white.id['args']), 'Black': black.id['name'], 'BlackArgs': repr(black.id['args']), 'Round': game_round }) games.append(game) # Add book moves game.setup(init_board.root()) node = game for move in init_board.move_stack: node = node.add_variation(move, comment='book') # Run engines async for _play, er in self.play_game(node, game_round, white, black): # If an error occoured, return as much as we got if er is not None: return games, score, er result = game.headers["Result"] if result == '1-0' and color == WHITE or result == '0-1' and color == BLACK: score += 1 if result == '1-0' and color == BLACK or result == '0-1' and color == WHITE: score -= 1 return games, score/games_played, None
Example #13
Source File: pgn.py From picochess with GNU General Public License v3.0 | 5 votes |
def send(self, subject: str, body: str, path: str): """Send the email out.""" if self.email: # check if email adress to send the pgn to is provided if self.mailgun_key: # check if we have mailgun-key available to send the pgn successful self._use_mailgun(subject=subject, body=body) if self.smtp_server: # check if smtp server adress provided self._use_smtp(subject=subject, body=body, path=path)
Example #14
Source File: python_easy_chess_gui.py From Python-Easy-Chess-GUI with GNU Lesser General Public License v3.0 | 5 votes |
def get_tag_date(self): """ Return date in pgn tag date format """ return datetime.today().strftime('%Y.%m.%d')
Example #15
Source File: python_easy_chess_gui.py From Python-Easy-Chess-GUI with GNU Lesser General Public License v3.0 | 5 votes |
def init_game(self): """ Initialize game with initial pgn tag values """ self.game = chess.pgn.Game() self.node = None self.game.headers['Event'] = INIT_PGN_TAG['Event'] self.game.headers['Date'] = self.get_tag_date() self.game.headers['White'] = INIT_PGN_TAG['White'] self.game.headers['Black'] = INIT_PGN_TAG['Black']
Example #16
Source File: Game.py From irwin with GNU Affero General Public License v3.0 | 5 votes |
def fromDict(d: Dict): return Game( id=d['id'], white=d['white'], black=d['black'], pgn=d['pgn'].split(' '), emts=d['emts'], analysis=None if d.get('analysis') is None else [EngineEval.fromDict(a) for a in d['analysis']] )
Example #17
Source File: Game.py From irwin with GNU Affero General Public License v3.0 | 5 votes |
def toJson(self): return { '_id': self.id, 'white': self.white, 'black': self.black, 'pgn': self.pgn, 'emts': self.emts, 'analysis': [EngineEvalBSONHandler.writes(a) for a in self.analysis], 'analysed': len(self.analysis) > 0 }
Example #18
Source File: Game.py From irwin with GNU Affero General Public License v3.0 | 5 votes |
def playable(self): try: from StringIO import StringIO except ImportError: from io import StringIO return read_game(StringIO(" ".join(self.pgn)))
Example #19
Source File: Game.py From irwin with GNU Affero General Public License v3.0 | 5 votes |
def reads(bson: Dict) -> Game: return Game( id = bson['_id'], white = bson.get('white'), black = bson.get('black'), pgn = bson['pgn'], emts = bson['emts'], analysis = [EngineEvalBSONHandler.reads(a) for a in bson.get('analysis', [])])
Example #20
Source File: Game.py From irwin with GNU Affero General Public License v3.0 | 5 votes |
def writes(game: Game) -> Dict: return { 'white': game.white, 'black': game.black, 'pgn': game.pgn, 'emts': game.emts, 'analysis': [EngineEvalBSONHandler.writes(a) for a in game.analysis], 'analysed': len(game.analysis) > 0 }
Example #21
Source File: generate_training_set.py From twitchchess with MIT License | 5 votes |
def get_dataset(num_samples=None): X,Y = [], [] gn = 0 values = {'1/2-1/2':0, '0-1':-1, '1-0':1} # pgn files in the data folder for fn in os.listdir("data"): pgn = open(os.path.join("data", fn)) while 1: game = chess.pgn.read_game(pgn) if game is None: break res = game.headers['Result'] if res not in values: continue value = values[res] board = game.board() for i, move in enumerate(game.mainline_moves()): board.push(move) ser = State(board).serialize() X.append(ser) Y.append(value) print("parsing game %d, got %d examples" % (gn, len(X))) if num_samples is not None and len(X) > num_samples: return X,Y gn += 1 X = np.array(X) Y = np.array(Y) return X,Y
Example #22
Source File: process_data.py From AdversarialChess with MIT License | 5 votes |
def main(): datafile = '../Data/ficsgamesdb_2015_standard2000_nomovetimes_1429742.pgn' playerfile = '../Data/Tal.pgn' gen_board_pair_data(datafile, '../Data/training_data') gen_player_data(playerfile, '../Data/player_data', 'Tal')
Example #23
Source File: pgn_to_records.py From Zerofish with MIT License | 5 votes |
def main (FLAGS, _): # Parse pgn into registry of nodes with open(FLAGS.pgn_file, 'r') as in_file: run_pgn(in_file, FLAGS.n_games, FLAGS.data_path) return 0
Example #24
Source File: Demo_Chess_Board.py From PySimpleGUI with GNU Lesser General Public License v3.0 | 5 votes |
def open_pgn_file(filename): pgn = open(filename) first_game = chess.pgn.read_game(pgn) moves = [move for move in first_game.main_line()] return moves
Example #25
Source File: Demo_Chess_AGAINST_AI.py From PySimpleGUI with GNU Lesser General Public License v3.0 | 5 votes |
def open_pgn_file(filename): pgn = open(filename) first_game = chess.pgn.read_game(pgn) moves = [move for move in first_game.main_line()] return moves
Example #26
Source File: format.py From python-lichess with GNU General Public License v3.0 | 5 votes |
def content_type(self, object_type): if object_type not in (GAME_STREAM_OBJECT, GAME_OBJECT): raise ValueError('PGN format is only valid for games') return 'application/x-chess-pgn'
Example #27
Source File: format.py From python-lichess with GNU General Public License v3.0 | 5 votes |
def content_type(self, object_type): if object_type not in (GAME_STREAM_OBJECT, GAME_OBJECT): raise ValueError('PyChess format is only valid for games') return 'application/x-chess-pgn'
Example #28
Source File: format.py From python-lichess with GNU General Public License v3.0 | 5 votes |
def parse(self, object_type, resp): try: import chess.pgn except ImportError: raise ImportError('PyChess format requires the python-chess package to be installed') if object_type == GAME_STREAM_OBJECT: return (chess.pgn.read_game(StringIO(pgn)) for pgn in stream_pgns(resp)) return chess.pgn.read_game(StringIO(resp.text))
Example #29
Source File: test.py From python-lichess with GNU General Public License v3.0 | 5 votes |
def test_game_pgn(self): pgn = lichess.api.game('Qa7FJNk2', format=lichess.format.PGN) self.assertEqual(pgn[:7], '[Event ')
Example #30
Source File: test.py From python-lichess with GNU General Public License v3.0 | 5 votes |
def test_user_games_single_pgn(self): pgn = lichess.api.user_games('thibault', max=5, format=lichess.format.SINGLE_PGN) lst = list(itertools.islice(pgn, 2)) self.assertEqual(pgn[:7], '[Event ')