TwoPlayerChess / app.py
awacke1's picture
Create app.py
1822f98 verified
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()