Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import chess | |
| import chess.svg | |
| st.set_page_config(page_title="Chess Game", layout="wide") | |
| # ================= CSS (compact layout) ================= | |
| st.markdown(""" | |
| <style> | |
| .block-container { | |
| padding-top: 1rem; | |
| padding-bottom: 1rem; | |
| } | |
| /* Reduce spacing between columns */ | |
| div[data-testid="column"] { | |
| padding: 0 !important; | |
| } | |
| div[data-testid="stHorizontalBlock"] { | |
| gap: 5px !important; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| st.title("โ๏ธ Chess Game") | |
| # ================= INIT ================= | |
| if "board" not in st.session_state: | |
| st.session_state.board = chess.Board() | |
| st.session_state.selected = None | |
| st.session_state.message = "" | |
| board = st.session_state.board | |
| # ================= HANDLE CLICK ================= | |
| def select_square(square): | |
| if st.session_state.selected is None: | |
| piece = board.piece_at(square) | |
| if piece and piece.color == board.turn: | |
| st.session_state.selected = square | |
| else: | |
| move = chess.Move(st.session_state.selected, square) | |
| if move in board.legal_moves: | |
| board.push(move) | |
| st.session_state.message = "โ Move played" | |
| else: | |
| st.session_state.message = "โ Illegal move" | |
| st.session_state.selected = None | |
| # ================= LAYOUT ================= | |
| col_board, col_controls = st.columns([2.3, 1]) | |
| # ================= BOARD ================= | |
| with col_board: | |
| st.subheader(f"Turn: {'White' if board.turn else 'Black'}") | |
| selected_square = st.session_state.selected | |
| svg_board = chess.svg.board( | |
| board=board, | |
| size=720, # ๐ฅ big board for better UX | |
| lastmove=board.peek() if board.move_stack else None, | |
| squares=[selected_square] if selected_square else [] | |
| ) | |
| st.image(svg_board) | |
| # ================= CONTROLS ================= | |
| with col_controls: | |
| st.subheader("๐ฎ Controls") | |
| for row in range(7, -1, -1): | |
| cols = st.columns(8) | |
| for col in range(8): | |
| square = chess.square(col, row) | |
| name = chess.square_name(square) | |
| if cols[col].button(name, key=name): | |
| select_square(square) | |
| if st.session_state.message: | |
| st.success(st.session_state.message) | |
| st.session_state.message = "" | |
| st.markdown("---") | |
| if st.button("โฉ๏ธ Undo"): | |
| if board.move_stack: | |
| board.pop() | |
| if st.button("๐ Reset"): | |
| st.session_state.board = chess.Board() | |
| st.session_state.selected = None | |
| # ================= STATUS ================= | |
| st.subheader("Game Status") | |
| if board.is_checkmate(): | |
| st.error("โ๏ธ Checkmate!") | |
| elif board.is_stalemate(): | |
| st.warning("Stalemate!") | |
| elif board.is_check(): | |
| st.warning("Check!") | |
| else: | |
| st.success("Game in progress...") |