game / app.py
umarcui's picture
Create app.py
f154082 verified
import streamlit as st
# Initialize the board and game state
if "board" not in st.session_state:
st.session_state.board = [""] * 9
st.session_state.current_player = "X"
st.session_state.winner = None
def check_winner(board):
win_conditions = [
[0,1,2], [3,4,5], [6,7,8], # rows
[0,3,6], [1,4,7], [2,5,8], # cols
[0,4,8], [2,4,6] # diagonals
]
for condition in win_conditions:
a, b, c = condition
if board[a] and board[a] == board[b] == board[c]:
return board[a]
if all(cell != "" for cell in board):
return "Draw"
return None
def restart_game():
st.session_state.board = [""] * 9
st.session_state.current_player = "X"
st.session_state.winner = None
st.title("๐ŸŽฎ Tic Tac Toe Game")
st.markdown("Play against a friend in the browser!")
# Game board layout
cols = st.columns(3)
for i in range(3):
for j in range(3):
idx = i * 3 + j
with cols[j]:
if st.button(st.session_state.board[idx] or " ", key=idx, use_container_width=True):
if not st.session_state.board[idx] and not st.session_state.winner:
st.session_state.board[idx] = st.session_state.current_player
st.session_state.winner = check_winner(st.session_state.board)
if not st.session_state.winner:
st.session_state.current_player = "O" if st.session_state.current_player == "X" else "X"
# Display result
if st.session_state.winner:
if st.session_state.winner == "Draw":
st.success("It's a draw!")
else:
st.success(f"Player {st.session_state.winner} wins!")
st.button("๐Ÿ” Restart Game", on_click=restart_game)