def board(self): """ Gets the starting position of the game as a bitboard. Unless the `SetUp` and `FEN` header tags are set this is the default starting position. """ if "FEN" in self.headers and "SetUp" in self.headers and self.headers["SetUp"] == "1": return chess.Bitboard(self.headers["FEN"]) else: return chess.Bitboard()
def process_game(game): ''' print Game data and moves ''' game = " ".join(game) game = re.sub("\d+\.", " ", game).strip() moves = re.split("\s+", game) board = chess.Bitboard() end = moves[-1] moves = moves[:-1] after_board = board for move in moves: before_board = deepcopy(after_board) mv = board.push_san(move) after_board = board counter = 0 for pos in CHESS_HASH: if str(after_board.piece_at(CHESS_HASH[pos])) != \ str(before_board.piece_at(CHESS_HASH[pos])): ''' sys.stdout.write("%s\t%s\t%s\n"%(pos, \ before_board.piece_at(CHESS_HASH[pos]),\ after_board.piece_at(CHESS_HASH[pos]))) ''' counter += 1 sys.stdout.write("%s\t%s\t%s\n" % (before_board, after_board, counter))
def get_position_features(): n = 0 print( "material_balance1,material_count1,material_balance2,material_count2") with open("../Raw/data_uci.pgn", "r") as f: for line in f: if re.match("[a-h1-8]{4}", line): n += 1 moves = line.strip().split() moves.pop() # We don't want the score. number_of_moves = len(moves) board = chess.Bitboard() last_move = moves.pop() for move in moves: # This is actually an half move. move = move.lower() # python.chess does not like capitals. board.push(chess.Move.from_uci(move)) set1 = "{},{}".format(*evaluate_position(board)) last_move = last_move.lower() board.push(chess.Move.from_uci(last_move)) set2 = "{},{}".format(*evaluate_position(board)) print((set1 + "," + set2)) # Limit (for now) the number of games that are explored. if limit and n == 1: break
def generateFEN(boardMove): board = chess.Bitboard(getFENFromFile()) piece = getSquareNumber(boardMove[0], boardMove[2]) square = getSquareNumber(boardMove[4], boardMove[6]) board.push_san(board.san(chess.Move(piece, square))) fen = board.fen() writeBoardFENToFile(fen) return fen
def scholar_mate(): board = chess.Bitboard() board.push_san("e4") board.push_san("e5") board.push_san("Qh5") board.push_san("Nc6") board.push_san("Bc4") board.push_san("Nf6") board.push_san("Qxf7") assert board.is_checkmate()
def is_game_over(play_str): try: plays = sum([x.split() for x in re.split("[0-9]*\.", play_str) if x], [])[:-1] board = chess.Bitboard() for play in plays: board.push_san(play) return board.is_game_over() except: #print play_str #print plays #print "PLAY: "+play raise
def convert_image_to_bitboard_2(im): board = chess.Bitboard() board.clear() for i in xrange(BOARD_SIZE[0]): for j in xrange(BOARD_SIZE[1]): index_piece = np.where(im[(i, j)] != 0) index_piece = index_piece[0] new_coords = flatten_coord2d((7 - i, j)) if index_piece.shape != (0, ): piece = INDEX_TO_PIECE[index_piece[0] / 2] if im[(i, j, index_piece[0] / 2)] == -1: piece = piece.lower() board.set_piece_at(new_coords, chess.Piece.from_symbol(piece)) return board
def setup(self, board): """ Setup a specific starting position. This sets (or resets) the `SetUp` and `FEN` header tags. """ try: fen = board.fen() except AttributeError: fen = chess.Bitboard(board).fen() if fen == chess.STARTING_FEN: del self.headers["SetUp"] del self.headers["FEN"] else: self.headers["SetUp"] = "1" self.headers["FEN"] = fen
def print_game(game): ''' print Game data and moves ''' game = " ".join(game) game = re.sub("\d+\.", " ", game).strip() moves = re.split("\s+", game) board = chess.Bitboard() end = moves[-1] moves = moves[:-1] after_str = str(board) for move in moves: before_str = after_str mv = board.push_san(move) after_str = str(board) # Piece that moved piece = board.piece_at(mv.to_square) sys.stdout.write("%s\t%s\t%s\n" % (piece, before_str, after_str))
def print_game(game): ''' print Game data and moves ''' game = " ".join(game) game = re.sub("\d+\.", " ", game).strip() moves = re.split("\s+", game) board = chess.Bitboard() end = moves[-1] moves = moves[:-1] after_str = str(board) for move in moves: mv = board.push_san(move) after_str = str(board) # Piece that moved #piece = board.piece_at(mv.to_square) sys.stdout.write( "%s\t%s\t%s\t%s\n" % (after_str, board.is_game_over(), board.is_checkmate(), board.is_stalemate()))
print "Finished loading the PGN file." print "Total number of games: %d" % len(games) # Move-out X_train, y_train = [], [] # Move-in p1_X, p2_X, p3_X = [], [], [] p4_X, p5_X, p6_X = [], [], [] p1_y, p2_y, p3_y = [], [], [] p4_y, p5_y, p6_y = [], [], [] for index, game in enumerate(games): if index % 100 == 0: print "Processed %d games out of %d" % (index, NUM_GAMES) board = chess.Bitboard() moves = game.moves for move_index, move in enumerate(moves): if move[0].isalpha(): # check if move is SAN from_to_chess_coords = board.parse_san(move) from_to_chess_coords = str(from_to_chess_coords) from_chess_coords = from_to_chess_coords[:2] to_chess_coords = from_to_chess_coords[2:4] from_coords = chess_coord_to_coord2d(from_chess_coords) to_coords = chess_coord_to_coord2d(to_chess_coords) if move_index % 2 == 0: im = convert_bitboard_to_image(board)
def main(): fens = [x.split("\t")[0] for x in open("position_scores.txt").readlines()] for fen in fens: print(fen, chess.Bitboard(fen).is_check())
def move_from_uci(): board = chess.Bitboard() assert not chess.Move.from_uci("a8a1") in board.legal_moves
def play_immortal_game(): bitboard = chess.Bitboard() # 1.e4 e5 bitboard.push_san("e4") bitboard.push_san("e5") # 2.f4 exf4 bitboard.push_san("f4") bitboard.push_san("exf4") # 3.Bc4 Qh4+ bitboard.push_san("Bc4") bitboard.push_san("Qh4+") # 4.Kf1 b5?! bitboard.push_san("Kf1") bitboard.push_san("b5") # 5.Bxb5 Nf6 bitboard.push_san("Bxb5") bitboard.push_san("Nf6") # 6.Nf3 Qh6 bitboard.push_san("Nf3") bitboard.push_san("Qh6") # 7.d3 Nh5 bitboard.push_san("d3") bitboard.push_san("Nh5") # 8.Nh4 Qg5 bitboard.push_san("Nh4") bitboard.push_san("Qg5") # 9.Nf5 c6 bitboard.push_san("Nf5") bitboard.push_san("c6") # 10.g4 Nf6 bitboard.push_san("g4") bitboard.push_san("Nf6") # 11.Rg1! cxb5? bitboard.push_san("Rg1") bitboard.push_san("cxb5") # 12.h4! Qg6 bitboard.push_san("h4") bitboard.push_san("Qg6") # 13.h5 Qg5 bitboard.push_san("h5") bitboard.push_san("Qg5") # 14.Qf3 Ng8 bitboard.push_san("Qf3") bitboard.push_san("Ng8") # 15.Bxf4 Qf6 bitboard.push_san("Bxf4") bitboard.push_san("Qf6") # 16.Nc3 Bc5 bitboard.push_san("Nc3") bitboard.push_san("Bc5") # 17.Nd5 Qxb2 bitboard.push_san("Nd5") bitboard.push_san("Qxb2") # 18.Bd6! Bxg1? bitboard.push_san("Bd6") bitboard.push_san("Bxg1") # 19.e5! Qxa1+ bitboard.push_san("e5") bitboard.push_san("Qxa1+") # 20.Ke2 Na6 bitboard.push_san("Ke2") bitboard.push_san("Na6") # 21.Nxg7+ Kd8 bitboard.push_san("Nxg7+") bitboard.push_san("Kd8") # 22.Qf6+! Nxf6 bitboard.push_san("Qf6+") bitboard.push_san("Nxf6") # 23.Be7# 1-0 bitboard.push_san("Be7#") assert bitboard.is_checkmate()
def evaluation(): train_color = randint(0, 1) if train_color == 0: model1path = '.\models\model_train.h5' model2path = '.\models\model_live.h5' print('Evaluation network plays as White. Current generator network ' 'plays as Black.') player_1 = 'Evaluator' player_2 = 'Generator' else: model1path = '.\models\model_live.h5' model2path = '.\models\model_train.h5' print('Current generator network plays as White. Evaluation network ' 'plays as Black.') player_1 = 'Generator' player_2 = 'Evaluator' # Initialize neural network daemon for both players pipes_net1 = [] pipes_sim1 = [] pipes_net2 = [] pipes_sim2 = [] for worker in range(cpu_count() - 2): # Player 1 pipes p1, p2 = Pipe() pipes_net1.append(p1) pipes_sim1.append(p2) # Player 2 pipes p3, p4 = Pipe() pipes_net2.append(p3) pipes_sim2.append(p4) nn_p1 = Process(target=nn_daemon, args=(model1path, pipes_net1)) nn_p2 = Process(target=nn_daemon, args=(model2path, pipes_net2)) nn_p1.daemon = True nn_p2.daemon = True nn_p1.start() nn_p2.start() # Initialize board and game variables poss_moves = all_possible_moves() board = chess.Bitboard() p1tree = SearchTree() p2tree = SearchTree() move = 1 T = 0.1 # Temperature coefficient is low for entire evaluation # Start daemon feats = features(board.fen()) feats = feats.reshape(1, 14, 8, 8) pipes_sim1[0].send(feats) pipes_sim2[0].send(feats) while not pipes_sim1[0].poll(): time.sleep(0.0000001) while not pipes_sim2[0].poll(): time.sleep(0.0000001) prior_, value_ = pipes_sim1[0].recv() prior_, value_ = pipes_sim2[0].recv() del prior_ del value_ # Play game and record board state features for each move print('Game start.') while True: # Player 1 move print(player_1, 'is thinking...') p1move, pi, p1tree, index, Q = mcts(board, poss_moves, pipes_sim1, T=T, tree=p1tree) board.push(chess.Move.from_uci(p1move)) print(board) print(player_1, ': ', move, '. ', p1move, ' | Q: ', Q, '\n', sep='') # Game ending conditions if board.is_game_over(): if board.is_checkmate(): winner = 0 print('Winner:', player_1) break else: winner = -1 print('Game drawn.') break if move != 1: p2tree = p2tree.nodes[index] # Player 2 move print(player_2, 'is thinking...') p2move, pi, p2tree, index, Q = mcts(board, poss_moves, pipes_sim2, T=T, tree=p2tree) board.push(chess.Move.from_uci(p2move)) print(board) print(player_2, ': ', move, '... ', p2move, ' | Q: ', Q, '\n', sep='') if board.is_game_over(): if board.is_checkmate(): winner = 1 print('Winner:', player_2) break else: winner = -1 print('Game drawn.') break # Check if game is over by length if move == 100: winner = -1 print('Game drawn by length.') break # Update Player 1 decision tree with Player 2's move p1tree = p1tree.nodes[index] move += 1 # Kill neural network daemons nn_p1.terminate() nn_p2.terminate() # Determine trained network's performance if winner == -1: return 0.5 elif winner == train_color: return 1 else: return 0
def self_play(): game_start = time.time() # Initialize neural network daemon modelpath = '.\models\model_live.h5' pipes_net = [] pipes_sim = [] for worker in range(cpu_count() - 1): p1, p2 = Pipe() pipes_net.append(p1) pipes_sim.append(p2) nn_p = Process(target=nn_daemon, args=(modelpath, pipes_net)) nn_p.daemon = True nn_p.start() # Initialize board and begin recording features for each board state poss_moves = all_possible_moves() board = chess.Bitboard() game_record = [[board.fen()], [], []] p1tree = SearchTree() p2tree = SearchTree() move = 1 T = 1 # Start daemon feats = features(board.fen()) feats = feats.reshape(1, 14, 8, 8) pipes_sim[0].send(feats) while not pipes_sim[0].poll(): time.sleep(0.0000001) prior_, value_ = pipes_sim[0].recv() del prior_ del value_ # Play game and record board state features for each move print('Game start.') while True: # Determine temperature coefficient by game length if move > 10: T = 0.1 # Player 1 move print('Player 1 is thinking...') p1move, pi, p1tree, index, Q = mcts(board, poss_moves, pipes_sim, T=T, tree=p1tree) board.push(chess.Move.from_uci(p1move)) game_record[0].append(board.fen()) game_record[1].append(deepcopy(pi)) print(board) print('Player 1: ', move, '. ', p1move, ' | Q: ', Q, '\n', sep='') # Game ending conditions if board.is_game_over(): if board.is_checkmate(): winner = 0 print('Winner: White.') print('Game duration:', time.time() - game_start, 'seconds. \n') break else: winner = -1 print('Game drawn.') print('Game duration:', time.time() - game_start, 'seconds. \n') break if move != 1: # Update Player 2's decision tree with Player 1's move p2tree = p2tree.nodes[index] # Player 2 move print('Player 2 is thinking...') p2move, pi, p2tree, index, Q = mcts(board, poss_moves, pipes_sim, T=T, tree=p2tree) board.push(chess.Move.from_uci(p2move)) game_record[0].append(board.fen()) game_record[1].append(deepcopy(pi)) print(board) print('Player 2: ', move, '... ', p2move, ' | Q: ', Q, '\n', sep='') if board.is_game_over(): if board.is_checkmate(): winner = 1 print('Winner: Black.') print('Game duration:', time.time() - game_start, 'seconds.\n') break else: winner = -1 print('Game drawn.') print('Game duration:', time.time() - game_start, 'seconds.\n') break # Check if game is over by length if move == 100: winner = -1 print('Game drawn by length.') print('Game duration:', time.time() - game_start, 'seconds. \n') break # Update Player 1 decision tree with Player 2's move p1tree = p1tree.nodes[index] move += 1 # Kill neural network daemon nn_p.terminate() # Delete final board state from game record del game_record[0][-1] # Assign rewards and penalties if winner == 0: # Reward Player 1, penalize Player 2 Z = np.zeros(len(game_record[0])) Z[::2] = 1 Z[1::2] = -1 for z in Z.tolist(): game_record[2].append(z) elif winner == 1: # Penalize Player 1, penalize Player 2 Z = np.zeros(len(game_record[0])) Z[::2] = -1 Z[1::2] = 1 for z in Z.tolist(): game_record[2].append(z) else: # Slightly penalize draws Z = np.full(len(game_record[0]), -0.25) for z in Z.tolist(): game_record[2].append(z) return game_record, winner