File size: 2,199 Bytes
1822f98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import chess
import chess.svg

def main():
    st.set_page_config(page_title="Streamlit Chess", layout="wide")
    st.title("Streamlit Chess")

    # Initialize the chess board
    if 'board' not in st.session_state:
        st.session_state.board = chess.Board()
        st.session_state.selected_square = None

    # Create two columns
    col1, col2 = st.columns([3, 1])

    with col1:
        # Display the chess board
        svg = chess.svg.board(st.session_state.board, size=700)
        st.image(svg)

        # Handle clicks on the board
        clicked = st.button("Click to select/move")
        if clicked:
            handle_click()

    with col2:
        # Display game status
        st.subheader("Game Status")
        st.write(f"Turn: {'White' if st.session_state.board.turn else 'Black'}")
        st.write(f"Check: {'Yes' if st.session_state.board.is_check() else 'No'}")
        st.write(f"Game Over: {'Yes' if st.session_state.board.is_game_over() else 'No'}")

        if st.session_state.board.is_game_over():
            st.write(f"Result: {st.session_state.board.result()}")

        # Reset button
        if st.button("Reset Game"):
            st.session_state.board = chess.Board()
            st.session_state.selected_square = None
            st.experimental_rerun()

def handle_click():
    # Get the mouse position
    pos = st.experimental_get_query_params().get("pos", [""])[0]
    if not pos:
        return

    # Convert mouse position to chess square
    x, y = map(int, pos.split(","))
    file = int(x * 8 / 700)
    rank = 7 - int(y * 8 / 700)
    square = chess.square(file, rank)

    if st.session_state.selected_square is None:
        # Select the piece
        if st.session_state.board.piece_at(square):
            st.session_state.selected_square = square
    else:
        # Try to move the piece
        move = chess.Move(st.session_state.selected_square, square)
        if move in st.session_state.board.legal_moves:
            st.session_state.board.push(move)
        st.session_state.selected_square = None

    # Force a rerun to update the board
    st.experimental_rerun()

if __name__ == "__main__":
    main()