本文整理汇总了Python中chess.pgn方法的典型用法代码示例。如果您正苦于以下问题:Python chess.pgn方法的具体用法?Python chess.pgn怎么用?Python chess.pgn使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类chess
的用法示例。
在下文中一共展示了chess.pgn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_nags
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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 []
示例2: post
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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'))
示例3: get_players
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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)
示例4: run_pgn
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例5: robots
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
"""))
示例6: make_app
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例7: parse_args
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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()
示例8: main
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例9: get_games
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例10: main
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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!')
示例11: load_book
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例12: run_games
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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
示例13: send
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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)
示例14: get_tag_date
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
def get_tag_date(self):
""" Return date in pgn tag date format """
return datetime.today().strftime('%Y.%m.%d')
示例15: init_game
# 需要导入模块: import chess [as 别名]
# 或者: from chess import pgn [as 别名]
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']