Advertisement
alkkofficial

Untitled

Apr 7th, 2023 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.55 KB | None | 0 0
  1. # imports
  2. import numpy as np
  3. import torch
  4. import torch.nn as nn
  5. import chess
  6. from chess import Move
  7.  
  8. # set up AI (Sequential NN)
  9.  
  10.  
  11. class Tanh200(nn.Module):
  12. def forward(self, x):
  13. return torch.tanh(x / 200)
  14.  
  15.  
  16. model = nn.Sequential(
  17. nn.Linear(833, 1024),
  18. nn.BatchNorm1d(1024),
  19. nn.ReLU(),
  20. nn.Linear(1024, 512),
  21. nn.Dropout(p=0.25),
  22. nn.BatchNorm1d(512),
  23. nn.LeakyReLU(0.075),
  24. nn.Linear(512, 256),
  25. nn.BatchNorm1d(256),
  26. nn.ReLU(),
  27. nn.Linear(256, 128),
  28. nn.Dropout(p=0.25),
  29. nn.BatchNorm1d(128),
  30. nn.LeakyReLU(0.075),
  31. nn.Linear(128, 64),
  32. nn.ReLU(),
  33. nn.Linear(64, 1),
  34. nn.Dropout(p=0.25),
  35. Tanh200(),
  36. )
  37.  
  38. model.eval()
  39. weights_path = "./zlpro.pt"
  40. state_dict = torch.load(weights_path)
  41. model.load_state_dict(state_dict)
  42.  
  43.  
  44. # set up important functions
  45. # board_data - this function will turn a python-chess board into a matrix for the AI to evaluate
  46. def board_data(board):
  47. board_array = np.zeros((8, 8, 13), dtype=np.int8)
  48. for i in range(64):
  49. piece = board.piece_at(i)
  50. if piece is not None:
  51. color = int(piece.color)
  52. piece_type = piece.piece_type - 1
  53. board_array[i // 8][i % 8][piece_type + 6 * color] = 1
  54. else:
  55. board_array[i // 8][i % 8][-1] = 1
  56. board_array = board_array.flatten()
  57. return board_array
  58.  
  59. def negamax_ab(
  60. board,
  61. alpha,
  62. beta,
  63. move_count,
  64. turn_to_move,
  65. depth=2,
  66. ):
  67. if depth == 0:
  68. move_turn = turn_to_move
  69. matrix_game = np.array([board_data(board)]) # game after one hot encoding
  70. matrix_game = np.concatenate(
  71. (matrix_game, np.array([[move_turn]])), axis=1
  72. ) # have to append the move turn - the AI needs to know this
  73. matrix_game = torch.tensor(matrix_game, dtype=torch.float32)
  74. with torch.no_grad():
  75. best_val = model(matrix_game)
  76. best_val = float(best_val)
  77. return best_val * turn_to_move
  78. child_nodes = list(board.legal_moves)
  79. # child_nodes = ordermoves(child_nodes) # make an ordermove function
  80. best_score = -np.inf
  81. indexer = 0
  82. for child in child_nodes:
  83. test_board = board.copy()
  84. test_board.push(child)
  85. child = board_data(test_board)
  86. score = negamax_ab(
  87. board,
  88. -beta,
  89. -alpha,
  90. move_count,
  91. turn_to_move,
  92. depth - 1,
  93. )
  94. score = -float(score)
  95. best_score = max(best_score, score)
  96. alpha = max(alpha, best_score)
  97. test_board.pop()
  98. if alpha >= beta:
  99. break
  100. indexer += 1
  101. return best_score
  102.  
  103.  
  104. # set up chess game
  105.  
  106. NUMBER_OF_GAMES = 10
  107.  
  108.  
  109. def play_game(NUMBER_OF_GAMES):
  110. for _ in range(NUMBER_OF_GAMES):
  111. board = chess.Board()
  112. legal_moves = board.legal_moves
  113. move_count = 0
  114. for __ in range(3): # random opening, 3 moves
  115. legal_moves = list(board.legal_moves)
  116. chosen_move = np.random.randint(0, len(legal_moves))
  117. board.push(legal_moves[chosen_move])
  118. with open("ai_games.txt", "a+") as f:
  119. f.write(str(legal_moves[chosen_move]))
  120. f.write(" ")
  121. while not board.is_game_over():
  122. if move_count % 2 == 0:
  123. turn_to_move = 1 # white
  124. else:
  125. turn_to_move = -1 # black
  126. legal_moves = list(board.legal_moves)
  127. m_dict = {}
  128. for move in legal_moves:
  129. test_board = board.copy()
  130. test_board.push(move)
  131. move_score = negamax_ab(
  132. test_board, -np.inf, np.inf, move_count, turn_to_move, 3
  133. )
  134. m_dict[str(move)] = move_score
  135. m_dict = {
  136. k: v
  137. for k, v in sorted(
  138. m_dict.items(), key=lambda item: item[1], reverse=True
  139. )
  140. }
  141. m = iter(m_dict)
  142. best_move = next(m)
  143. print("Scores of all moves:", m_dict)
  144. print("Best move:", best_move)
  145. with open("ai_games.txt", "a+") as f:
  146. f.write(best_move)
  147. f.write(" ")
  148. best_move = Move.from_uci(best_move)
  149. board.push(best_move)
  150. move_count += 1
  151. with open("ai_games.txt", "a+") as f:
  152. f.write(board.result())
  153. f.write("\n")
  154.  
  155.  
  156. play_game(NUMBER_OF_GAMES)
  157.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement