Spaces:
Build error
Build error
| import gradio as gr | |
| import chess | |
| import random | |
| def init_board(): | |
| # Initialize a new chess board | |
| board = chess.Board() | |
| return board | |
| def make_move(board, move): | |
| try: | |
| board.push_san(move) | |
| except ValueError: | |
| return "Invalid move. Please try again.", board | |
| def computer_move(board, difficulty): | |
| # Simple random AI for the computer move | |
| legal_moves = list(board.legal_moves) | |
| move = random.choice(legal_moves) # Random move as a simple AI example | |
| board.push(move) | |
| return board | |
| def render_chessboard(board): | |
| # Representing the chessboard as a string for simplicity (you can use libraries for a visual rendering) | |
| return str(board) | |
| def play_game(player_move, game_mode, difficulty): | |
| board = init_board() | |
| response = "" | |
| if game_mode == 'Play with Computer': | |
| if player_move: | |
| response, board = make_move(board, player_move) | |
| if board.is_game_over(): | |
| return response + "\nGame Over!", render_chessboard(board) | |
| # Simulate computer move | |
| board = computer_move(board, difficulty) | |
| return response + f"\nComputer Move: {board.peek()}", render_chessboard(board) | |
| elif game_mode == 'Two Player': | |
| player1_move = player_move | |
| if player1_move: | |
| response, board = make_move(board, player1_move) | |
| if board.is_game_over(): | |
| return response + "\nGame Over!", render_chessboard(board) | |
| player2_move = input("Player 2 move (e.g., e7e5): ") # Asking Player 2 | |
| if player2_move: | |
| response, board = make_move(board, player2_move) | |
| return response, render_chessboard(board) | |
| # Define Gradio UI components | |
| def gradio_interface(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 3D Chess Game") | |
| game_mode = gr.Radio(choices=["Play with Computer", "Two Player"], label="Game Mode", value="Play with Computer") | |
| difficulty = gr.Slider(minimum=1, maximum=10, label="Difficulty", value=3) | |
| player_move = gr.Textbox(label="Your move (e.g., e2e4): ") | |
| output_text = gr.Textbox(label="Game Status", interactive=False) | |
| chessboard_output = gr.Textbox(label="Current Board", interactive=False) | |
| # Button for making moves and starting game | |
| play_button = gr.Button("Play Move") | |
| play_button.click( | |
| play_game, | |
| inputs=[player_move, game_mode, difficulty], | |
| outputs=[output_text, chessboard_output] | |
| ) | |
| demo.launch() | |
| # Run Gradio app | |
| if __name__ == "__main__": | |
| gradio_interface() | |