Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Эй, надо написать chess-бота с GU-интерфейсом на ткинтере с применением алгоритма альфа-бета отсечения,
- # белыми играю я. Всё скинь мне в одном файле
- # Давайте создадим шахматного бота с графическим интерфейсом на tkinter и алгоритмом альфа-бета отсечения.
- # В этом примере вы будете играть белыми, а бот будет использовать альфа-бета отсечение для игры черными.
- #Вот пример кода, который объединяет всё в одном файле:
- import tkinter as tk
- import chess
- import chess.svg
- class ChessBoard:
- def __init__(self):
- self.board = chess.Board()
- def generate_legal_moves(self):
- return list(self.board.legal_moves)
- def apply_move(self, move):
- if move in self.board.legal_moves:
- self.board.push(move)
- else:
- raise ValueError("Invalid move")
- def undo_move(self):
- if len(self.board.move_stack) > 0:
- self.board.pop()
- else:
- raise ValueError("No move to undo")
- def is_game_over(self):
- return self.board.is_game_over()
- def evaluate_board(self):
- piece_values = {
- chess.PAWN: 1,
- chess.KNIGHT: 3,
- chess.BISHOP: 3,
- chess.ROOK: 5,
- chess.QUEEN: 9,
- chess.KING: 0
- }
- score = 0
- for piece in chess.PIECE_TYPES:
- for square in chess.SQUARES:
- piece_at_square = self.board.piece_at(square)
- if piece_at_square:
- score += piece_values.get(piece_at_square.piece_type,
- 0) if piece_at_square.color == chess.WHITE else -piece_values.get(
- piece_at_square.piece_type, 0)
- return score
- def alpha_beta(board, depth, alpha, beta, maximizing_player):
- if depth == 0 or board.is_game_over():
- return board.evaluate_board()
- if maximizing_player:
- max_eval = float('-inf')
- for move in board.generate_legal_moves():
- board.apply_move(move)
- eval = alpha_beta(board, depth - 1, alpha, beta, False)
- board.undo_move()
- max_eval = max(max_eval, eval)
- alpha = max(alpha, eval)
- if beta <= alpha:
- break
- return max_eval
- else:
- min_eval = float('inf')
- for move in board.generate_legal_moves():
- board.apply_move(move)
- eval = alpha_beta(board, depth - 1, alpha, beta, True)
- board.undo_move()
- min_eval = min(min_eval, eval)
- beta = min(beta, eval)
- if beta <= alpha:
- break
- return min_eval
- def best_move(board, depth):
- best_move = None
- best_value = float('-inf') if board.board.turn == chess.WHITE else float('inf')
- for move in board.generate_legal_moves():
- board.apply_move(move)
- move_value = alpha_beta(board, depth - 1, float('-inf'), float('inf'), not board.board.turn == chess.WHITE)
- board.undo_move()
- if (board.board.turn == chess.WHITE and move_value > best_value) or (
- board.board.turn == chess.BLACK and move_value < best_value):
- best_value = move_value
- best_move = move
- return best_move
- class ChessGUI:
- def __init__(self, root):
- self.board = ChessBoard()
- self.root = root
- self.root.title("Chess Game")
- self.selected_square = None
- self.create_widgets()
- self.draw_board()
- def create_widgets(self):
- self.canvas = tk.Canvas(self.root, width=400, height=400)
- self.canvas.pack()
- self.canvas.bind("<Button-1>", self.on_square_click)
- self.undo_button = tk.Button(self.root, text="Undo", command=self.undo_move)
- self.undo_button.pack(side=tk.LEFT)
- self.exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
- self.exit_button.pack(side=tk.RIGHT)
- self.new_game_button = tk.Button(self.root, text="New Game", command=self.new_game)
- self.new_game_button.pack(side=tk.LEFT)
- self.draw_board()
- def draw_board(self):
- self.canvas.delete("all")
- self.square_size = 50
- colors = ["#DDB88C", "#A66D4F"]
- for row in range(8):
- for col in range(8):
- x1 = col * self.square_size
- y1 = row * self.square_size
- x2 = x1 + self.square_size
- y2 = y1 + self.square_size
- color = colors[(row + col) % 2]
- self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="black")
- piece = self.board.board.piece_at(chess.square(col, 7 - row))
- if piece:
- self.draw_piece(piece, col, row)
- def draw_piece(self, piece, col, row):
- x = col * self.square_size + self.square_size // 2
- y = row * self.square_size + self.square_size // 2
- piece_unicode = self.get_piece_unicode(piece)
- self.canvas.create_text(x, y, text=piece_unicode, font=("Arial", 24))
- def get_piece_unicode(self, piece):
- piece_map = {
- chess.PAWN: '♙' if piece.color == chess.WHITE else '♟',
- chess.KNIGHT: '♘' if piece.color == chess.WHITE else '♞',
- chess.BISHOP: '♗' if piece.color == chess.WHITE else '♝',
- chess.ROOK: '♖' if piece.color == chess.WHITE else '♜',
- chess.QUEEN: '♕' if piece.color == chess.WHITE else '♛',
- chess.KING: '♔' if piece.color == chess.WHITE else '♚',
- }
- return piece_map.get(piece.piece_type, '')
- def on_square_click(self, event):
- col = event.x // self.square_size
- row = 7 - (event.y // self.square_size)
- square = chess.square(col, row)
- if self.selected_square is None:
- if self.board.board.piece_at(square) and self.board.board.turn == chess.WHITE:
- self.selected_square = square
- else:
- move = chess.Move(self.selected_square, square)
- if move in self.board.generate_legal_moves():
- self.board.apply_move(move)
- self.selected_square = None
- self.draw_board()
- if not self.board.is_game_over():
- self.bot_move()
- else:
- self.selected_square = None
- print("Invalid move")
- def bot_move(self):
- if not self.board.is_game_over():
- move = best_move(self.board, depth = 3)
- if move:
- self.board.apply_move(move)
- self.draw_board()
- else:
- print("Bot has no valid moves!")
- def undo_move(self):
- self.board.undo_move()
- self.draw_board()
- def new_game(self):
- self.board = ChessBoard()
- self.draw_board()
- if __name__ == "__main__":
- root = tk.Tk()
- app = ChessGUI(root)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement