def start():
    board = chess.Board()
    white = 1
    moves = 0
    pgn = []
    game = chess.pgn.Game()
    evaluations = []
    sm = 0
    cnt = 0
    while((not board.is_game_over())):
        all_moves = [board.san(i) for i in list(board.legal_moves)]
        root = node()
        root.state = board
        result = mcts_pred(root,board.is_game_over(),white)
        board.push_san(result)
        print(result)
        pgn.append(result)
        white ^= 1
        moves+=1

    print(board)
    print(" ".join(pgn))
    print()
    #print(evaluations)
    print(board.result())
    game.headers["Result"] = board.result()
コード例 #2
0
def read_database(database):                    #Read from a database directory and return the PGN
    pgn = []
    try:
        for i in os.listdir(database):
            pgn.append(open(join(database, i))) #Loop through database for files
    except:
        return None                             #Database cannot be found
    return pgn                                  #Return database as text I/O wrapper in list
コード例 #3
0
ファイル: chess_materialV2.py プロジェクト: mogrilj/ChessV1
def playGame(pauseTime,
             player,
             algorithms,
             showDisplay=False,
             playYourself=False):
    if showDisplay:
        display.start()
    board = chess.Board()
    pgn = []

    print("player is:" + str(player))
    while True:
        #generating moves based on the turn
        if board.turn == bool(player + 1):
            move = algorithms[0].generateMoves(board.fen(), board.turn, player)
        else:
            if not playYourself:

                #move = movesToList(board.legal_moves)[random.randint(0,len(movesToList(board.legal_moves))-1)]
                move = algorithms[1].generateMoves(board.fen(), board.turn,
                                                   -player)
            else:
                while True:
                    moveInput = input("enter your move:")
                    try:
                        move = chess.Move.from_uci(moveInput)
                        print(move)
                        if move in board.legal_moves:
                            break
                        else:
                            print("please enter a legal move!")
                    except ValueError:
                        print("Please enter a real move!")
        #moving, displaying, checking if the game has ended
        time.sleep(pauseTime)
        pgn.append(move)
        board.push(move)
        if showDisplay:
            display.update(board.fen())
        if board.is_checkmate():
            if board.turn == bool(player + 1):
                print("loss")
                return False, pgn, board.fen()

            else:
                print("win")
                return True, pgn, board.fen()

        if board.is_stalemate() or board.is_insufficient_material(
        ) or board.can_claim_threefold_repetition(
        ) or board.is_seventyfive_moves() or board.can_claim_fifty_moves():
            print("No one")
            return None, pgn, board.fen()
コード例 #4
0
def next_pgn(fiter: Iterator) -> List[str]:
    """
    Get next 1-game PGN from a PGN database file.

    :param fiter: file iterator
    """
    pgn = []
    while True:
        # Header doesn't have a fixed size
        # Retrieving header line-by-line
        line = next(fiter)
        if line.startswith('['):
            pgn.append(line.strip())
            continue  # proceed getting the next line

        # Header finished

        # PGNs have empty line between header and SAN
        # that was already consumed by `next(fiter)`;
        # Next line in PGN contains game log in SAN
        # (Standard/Short Algebraic Notation)

        # For PGNs that have SAN separated over several lines
        # (Caissa, Mega), run an inside loop that collects this SAN log
        san = ''
        while True:
            line = next(fiter).strip()
            if not line:
                # Consumed a line between SAN and next PGN header;
                # can return complete PGN
                break
            san += line + ' '

        pgn.append(san.strip())

        return pgn
コード例 #5
0
    
board = chess.Board()
engine = chess.engine.SimpleEngine.popen_uci(r'C:\Users\ishaa\Desktop\chess_engine\stockfish-11-win\Windows\stockfish_20011801_x64.exe')

white = 1
moves = 0
pgn = []
game = chess.pgn.Game()
evaluations = []

while((not board.is_game_over())):
    all_moves = [board.san(i) for i in list(board.legal_moves)]
    if(white):
        result = minimax(board,all_moves,1,board.is_game_over(),1)
        board = result[0]
        pgn.append(result[2])
        board.push_san(result[2])
        white ^= 1
    else:
        result = engine.play(board, chess.engine.Limit(time=0.1))
        pgn.append(board.san(result.move))
        board.push_san(board.san(result.move))
        white ^= 1
    moves+=1
    board_evaluation = evaluate(board.fen().split()[0])
    evaluations.append(board_evaluation)
print(board)
print(" ".join(pgn))
print()
print(evaluations)
print(board.result())
コード例 #6
0
def game_stats_df(username):
    '''Returns a pandas dataframe containing stats for every game played'''
    
    game_list = get_player_games(username)
    
    player_rating = []
    rating_difference = []
    player_result = []
    opponent_result = []
    player_username = []
    opponent_username = []
    end_time = []
    pgn = []
    eco = []
    time_class = []
    rules = []
    player_color = []
    pieces_diff = []
    pieces_total = []
    pieces_black = []
    pieces_white = []
    url = []

    for i, game in enumerate(game_list):
        
        starting_position = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -'
        
        if (game['rules'] == 'chess') and (game['fen'] != starting_position):
            pgn_data = game['pgn'].split('\n')
            pgn.append(pgn_data[-1])
            eco.append(pgn_data[7].split('"')[-2])
            counts = piece_count(pgn_data[-1])
            pieces_diff.append(counts[0])
            pieces_total.append(counts[1])
            pieces_black.append(counts[2])
            pieces_white.append(counts[3])

        else:
            pgn.append(None)
            eco.append(None)
            pieces_diff.append(None)
            pieces_total.append(None)
            pieces_black.append(None)
            pieces_white.append(None)
            
        if game['black']['username'].lower() == username.lower():
            player_rating.append(game['black']['rating'])
            rating_difference.append(game['black']['rating'] - game['white']['rating'])
            player_result.append(game['black']['result'])
            opponent_result.append(game['white']['result'])
            player_username.append(game['black']['username'])
            player_color.append('black')
            opponent_username.append(game['white']['username'])
        else:
            player_rating.append(game['white']['rating'])
            rating_difference.append(game['white']['rating'] - game['black']['rating'])
            player_result.append(game['white']['result'])
            opponent_result.append(game['black']['result'])
            player_username.append(game['white']['username'])
            player_color.append('white')
            opponent_username.append(game['black']['username'])
            
        end_time.append(pd.to_datetime(game['end_time'], unit='s'))
        time_class.append(game['time_class'])
        rules.append(game['rules'])
        url.append(game['url'])

    df = pd.DataFrame({'player_username': player_username,
                       'player_color': player_color,
                       'player_rating': player_rating,
                       'rating_difference': rating_difference,
                       'player_result': player_result,
                       'opponent_result': opponent_result,
                       'end_time': end_time,
                       'time_class': time_class,
                       'rules': rules,
                       'pgn': pgn,
                       'eco': eco,
                       'opponent_username': opponent_username,
                       'pieces_diff': pieces_diff,
                       'pieces_total': pieces_total,
                       'pieces_black': pieces_black,
                       'pieces_white': pieces_white,})
    
#Create three columns in the data frame indicating a win, draw, or loss with a True or False
    df['win'] = df['player_result'] == 'win'

    draw = {'agreed', 'repetition', 'stalemate',
            'insufficient', '50move', 'timevsinsufficient'}
    
    df['draw'] = df['player_result'].isin(draw)

    lose = {'checkmated', 'timeout', 'resigned', 'lose', 'abandoned',
           'kingofthehill', 'threecheck'}

    df['lose'] = df['player_result'].isin(lose)
    
    return df
コード例 #7
0
moves = 0
pgn = []
game = chess.pgn.Game()
evaluations = []
sm = 0
cnt = 0
while ((not board.is_game_over())):
    all_moves = [board.san(i) for i in list(board.legal_moves)]
    #start = time.time()
    root = node()
    root.state = board
    result = mcts_pred(root, board.is_game_over(), white)
    #sm+=(time.time()-start)
    board.push_san(result)
    #print(result)
    pgn.append(result)
    white ^= 1
    #cnt+=1

    moves += 1
    #board_evaluation = evaluate(board.fen().split()[0])
    #evaluations.append(board_evaluation)
#print("Average Time per move = ",sm/cnt)
print(board)
print(" ".join(pgn))
print()
#print(evaluations)
print(board.result())
game.headers["Result"] = board.result()
#print(game)
engine.quit()