import tkinter as tk from PIL import Image, ImageTk import chess Define the initial FEN…
- User
import tkinter as tk from PIL import Image, ImageTk import chess
Define the initial FEN for the chess board
initial_fen = chess.STARTING_FEN game_board = chess.Board(initial_fen) board_images = []
Create a dictionary to map piece symbols to image filenames
PIECE_IMAGES = { "P": "images/Wp.png", "p": "images/bp.png", "R": "images/WR.png", "r": "images/bR.png", "N": "images/WN.png", "n": "images/bN.png", "B": "images/WB.png", "b": "images/bB.png", "Q": "images/WQ.png", "q": "images/bQ.png", "K": "images/WK.png", "k": "images/bK.png" }
Initialize global variables
game_board = chess.Board(initial_fen) board_images = []
window = tk.Tk() window.title("Chess FEN Notation Converter")
Function to draw the chess board
def draw_board(board): global board_images for image in board_images: canvas.delete(image)
codesquare_size = 60 # Size of a square in the board for square in chess.SQUARES: rank = chess.square_rank(square) file = chess.square_file(square) x0 = file * square_size y0 = (7 - rank) * square_size if (rank + file) % 2 == 0: square_color = "white" else: square_color = "light gray" canvas.create_rectangle(x0, y0, x0 + square_size, y0 + square_size, fill=square_color) piece = board.piece_at(square) if piece: image = Image.open(PIECE_IMAGES[str(piece)]).resize((square_size, square_size), Image.Resampling.LANCZOS) photo = ImageTk.PhotoImage(image) board_images.append(photo) canvas.create_image(x0 + square_size // 2, y0 + square_size // 2, image=photo)canvas = tk.Canvas(window, width=480, height=480) canvas.pack()
Function to update the game board with a new move
def update_game_board(move): try: game_move = game_board.parse_san(move) if game_move in game_board.legal_moves: game_board.push(game_move) result_label.config(text=f"FEN Notation: {game_board.fen()}") draw_board(game_board) else: result_label.config(text="Illegal move") except ValueError: result_label.config(text="Invalid move")
move_entry = tk.Entry(window) move_entry.pack()
def submit_move(): move = move_entry.get() update_game_board(move) move_entry.delete(0, tk.END) # Clear the entry after the move
- Assistant
- User
optimize the code
- Assistant
- User
the images are stored in the same directory in an "images" folder. i don't understand this error
/chess/chess/lib/python3.10/site-packages/PIL/Image.py", line 3247, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'images/PP.png'
- Assistant
The error you're encountering indicates that the program is unable to find the image file
images/PP.png. The error message[Errno 2] No such file or directorymeans the path you provided doesn't lead to a file that exists at that location.