Spaces:
Build error
Build error
File size: 2,659 Bytes
b6f392c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 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()
|