How to use the chess.pgn function in chess

To help you get started, we’ve selected a few chess examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SamRagusa / Batch-First / batch_first / anns / database_creator.py View on Github external
def game_iterator(pgn_filename):
    """
    Iterates through the games stored on the given pgn file (as python-chess Game objects).
    """
    with open(pgn_filename) as pgn_file:
        while True:
            game = chess.pgn.read_game(pgn_file)
            if game is None:
                break

            yield game
github rpdelaney / python-chess-annotator / annotator / engeval / __init__.py View on Github external
def get_nags(self):
        """
        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 < self.THRESHOLD["BLUNDER"]:
            return [chess.pgn.NAG_BLUNDER]
        elif delta < self.THRESHOLD["MISTAKE"]:
            return [chess.pgn.NAG_MISTAKE]
        elif delta < self.THRESHOLD["DUBIOUS"]:
            return [chess.pgn.NAG_DUBIOUS_MOVE]
        else:
            return []
github rpdelaney / python-chess-annotator / annotator.py View on Github external
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 < -300:
        return [chess.pgn.NAG_BLUNDER]
    elif delta < -150:
        return [chess.pgn.NAG_MISTAKE]
    elif delta < -75:
        return [chess.pgn.NAG_DUBIOUS_MOVE]
    else:
        return []
github fsmosca / Python-Easy-Chess-GUI / python_easy_chess_gui.py View on Github external
def set_new_game(self):
        """ Initialize new game but save old pgn tag values"""
        old_event = self.game.headers['Event']
        old_white = self.game.headers['White']
        old_black = self.game.headers['Black']
        
        # Define a game object for saving game in pgn format
        self.game = chess.pgn.Game()
        
        self.game.headers['Event'] = old_event
        self.game.headers['Date'] = self.get_tag_date()
        self.game.headers['White'] = old_white
        self.game.headers['Black'] = old_black
github lazydroid / deep-murasaki / play.py View on Github external
def game():
	gn_current = chess.pgn.Game()

	maxn = 10 ** (2.0 + random.random() * 1.0) # max nodes for sunfish

	print 'maxn %f' % maxn

	player_a = Murasaki()
#	player_b = Human()
	player_b = Sunfish(maxn=maxn)

	times = {'A': 0.0, 'B': 0.0}

	while True:
		for side, player in [('A', player_a), ('B', player_b)]:
			t0 = time.time()
			try:
				gn_current = player.move(gn_current)
github FTdiscovery / 64CrazyhouseDeepLearning / ServerTraining.py View on Github external
print("best accuracy: ", bestAccuracy, "% correct.")

    print("Updated!")
    torch.save(model, saveDirectory)


train = True
if train:

    pgnGames = list(pathlib.Path('lichessdatabase').glob('*.pgn'))
    listOfMoves = []
    for i in range(len(pgnGames)):
        pgn = open(pgnGames[i])
        for k in range(190000):  # 190,000 assures all games are looked at.
            try:
                game = chess.pgn.read_game(pgn)
                whiteElo = int(game.headers["WhiteElo"])
                blackElo = int(game.headers["BlackElo"])
                benchmark = 2450
                if whiteElo >= benchmark and blackElo >= benchmark:
                    print(whiteElo)
                    print(blackElo)
                    board = game.board()
                    singleGame = []
                    for move in game.main_line():
                        board.push(move)
                        singleGame.append(move.uci())
                    listOfMoves.append(singleGame)
                    print(pgnGames[i])
            except:
                print("", end="")
github rpdelaney / python-chess-annotator / annotator.py View on Github external
            for game in iter(lambda: chess.pgn.read_game(pgn), None):
                try:
github fsmosca / chess-artist / chess-artist.py View on Github external
def CreatePuzzle(self):
        """
        Generate chess position puzzle or test positions from a given pgn file.
        
        Analyze position in the game from pgn file, record its pvmove and score
        for the early part of analysis and final bestmove and bestscore after
        the search. If pvmove and bestmove are not the same and score of
        bestmove is higher than score at pvmove then save this as a test
        position.
        """
        print('Creating test positions ...')
        with open(self.infn) as h:
            game = chess.pgn.read_game(h)
            while game:
                gameNode = game        
                while gameNode.variations:
                    board = gameNode.board()
                    fmvn = board.fullmove_number
                    
                    nextNode = gameNode.variation(0)
                    
                    if fmvn < 12:
                        gameNode = nextNode
                        continue

                    fen = board.fen()
                    print('analyzing fen %s ...' % fen)
                    
                    bestMove, bestScore, pvMove, pvScore = \

chess

A chess library with move generation and validation, Polyglot opening book probing, PGN reading and writing, Gaviota tablebase probing, Syzygy tablebase probing, and XBoard/UCI engine communication.

GPL-3.0
Latest version published 10 months ago

Package Health Score

72 / 100
Full package analysis