tic-tac-toe / app.py
samiasohail25gmailcom's picture
Update app.py
6d77e7d verified
import streamlit as st
st.set_page_config(page_title="Tic Tac Toe", page_icon="โŒ")
st.title("๐ŸŽฎ Tic Tac Toe Game")
st.markdown("Play against a friend! Take turns to mark X and O.")
# Initialize 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
# Function to check winner
def check_winner(board):
wins = [(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 i,j,k in wins:
if board[i] == board[j] == board[k] != "":
return board[i]
if "" not in board:
return "Draw"
return None
# Handle button clicks
def make_move(i):
if st.session_state.board[i] == "" and st.session_state.winner is None:
st.session_state.board[i] = st.session_state.current_player
st.session_state.winner = check_winner(st.session_state.board)
if st.session_state.winner is None:
st.session_state.current_player = "O" if st.session_state.current_player == "X" else "X"
# Display the board
cols = st.columns(3)
for i in range(9):
with cols[i % 3]:
if st.button(st.session_state.board[i] or " ", key=i):
make_move(i)
# Show game status
if st.session_state.winner:
if st.session_state.winner == "Draw":
st.info("It's a draw!")
else:
st.success(f"๐ŸŽ‰ Player {st.session_state.winner} wins!")
if st.button("Play Again"):
st.session_state.board = [""] * 9
st.session_state.current_player = "X"
st.session_state.winner = None
else:
st.write(f"Current Turn: **{st.session_state.current_player}**")