Jotee / app.py
lohanajk-56's picture
Update app.py
4411fcc verified
import streamlit as st
# Initialize game state
if 'board' not in st.session_state:
st.session_state.board = [' ' for _ in range(9)]
if 'current_player' not in st.session_state:
st.session_state.current_player = 'X'
# Function to draw the game board with improved styling
def draw_board():
st.markdown("""
<style>
.board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 10px;
max-width: 300px;
margin: auto;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
height: 80px;
font-size: 2rem;
cursor: pointer;
}
.cell:empty {
background-color: #f2f2f2;
}
.buzzer {
font-size: 1.5rem;
text-align: center;
margin-top: 20px;
font-weight: bold;
}
.result-box {
padding: 20px;
text-align: center;
border: 2px solid black;
background-color: #f0f0f0;
font-size: 1.5rem;
font-weight: bold;
margin-top: 20px;
border-radius: 10px;
}
</style>
""", unsafe_allow_html=True)
# Draw the game board
board_html = '<div class="board">'
for i in range(9):
board_html += f'<div class="cell" onclick="window.location.href=\'#move-{i+1}\'">{st.session_state.board[i]}</div>'
board_html += '</div>'
st.markdown(board_html, unsafe_allow_html=True)
# Function to handle player move
def make_move(move):
if st.session_state.board[move] == ' ':
st.session_state.board[move] = st.session_state.current_player
if st.session_state.current_player == 'X':
st.session_state.current_player = 'O'
else:
st.session_state.current_player = 'X'
# Function to check for winner
def check_winner():
winning_combos = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
for combo in winning_combos:
if st.session_state.board[combo[0]] == st.session_state.board[combo[1]] == st.session_state.board[combo[2]] != ' ':
return st.session_state.board[combo[0]]
if ' ' not in st.session_state.board:
return 'Tie'
return False
# Display turn indicator (buzzer)
def display_turn():
if st.session_state.current_player == 'X':
st.markdown('<div class="buzzer">Person 1 (X) Turn!</div>', unsafe_allow_html=True)
else:
st.markdown('<div class="buzzer">Person 2 (O) Turn!</div>', unsafe_allow_html=True)
# Main game loop
st.title("Tic Tac Toe")
# Create buttons for moves and display turn indicator
move = st.selectbox("Select a move", [1, 2, 3, 4, 5, 6, 7, 8, 9]) - 1
if st.button("Make Move"):
make_move(move)
result = check_winner()
if result:
if result == 'Tie':
st.markdown('<div class="result-box">It\'s a tie!</div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="result-box">Player {result} wins!</div>', unsafe_allow_html=True)
st.session_state.board = [' ' for _ in range(9)]
st.session_state.current_player = 'X'
else:
display_turn()
# Draw the board only if the game is still ongoing
if not check_winner():
draw_board()