Sample_chess / src /streamlit_app.py
pradeep4321's picture
Update src/streamlit_app.py
79b998f verified
import streamlit as st
import chess
import chess.svg
st.set_page_config(page_title="β™ŸοΈ Chess Game", layout="centered")
st.title("β™ŸοΈ Chess Game")
# --- Initialize session ---
if "board" not in st.session_state:
st.session_state.board = chess.Board()
st.session_state.move_history = []
st.session_state.last_move_msg = ""
board = st.session_state.board
# --- Layout ---
col_board, col_controls = st.columns([2, 1])
# ================= BOARD =================
with col_board:
st.subheader("Board")
board_svg = chess.svg.board(board=board, size=500)
st.image(board_svg)
# ================= CONTROLS =================
with col_controls:
st.subheader("Controls")
st.info(f"Turn: {'White' if board.turn else 'Black'}")
squares = [chess.square_name(sq) for sq in chess.SQUARES]
from_sq = st.selectbox("From", squares, key="from")
to_sq = st.selectbox("To", squares, key="to")
if st.button("β™ŸοΈ Move"):
try:
move = chess.Move.from_uci(from_sq + to_sq)
if move in board.legal_moves:
board.push(move)
st.session_state.move_history.append(move.uci())
# βœ… Store message once
st.session_state.last_move_msg = f"Moved: {from_sq} β†’ {to_sq}"
else:
st.session_state.last_move_msg = "❌ Illegal move!"
except:
st.session_state.last_move_msg = "❌ Invalid input!"
# βœ… Show message ONCE (not repeating)
if st.session_state.last_move_msg:
st.success(st.session_state.last_move_msg)
st.session_state.last_move_msg = "" # clear after showing
# --- Buttons ---
col_btn1, col_btn2 = st.columns(2)
with col_btn1:
if st.button("↩️ Undo"):
if board.move_stack:
board.pop()
st.session_state.move_history.pop()
with col_btn2:
if st.button("πŸ”„ Reset"):
st.session_state.board = chess.Board()
st.session_state.move_history = []
# ================= HISTORY =================
st.subheader("πŸ“œ Move History")
if st.session_state.move_history:
st.write(", ".join(st.session_state.move_history))
else:
st.write("No moves yet")
# ================= 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...")