Build a tic tac toe app
To upload files, please first save the app
import streamlit as st
import numpy as np
# Initialize game state
if 'board' not in st.session_state:
st.session_state.board = np.full((3, 3), ' ')
if 'current_player' not in st.session_state:
st.session_state.current_player = 'X'
if 'game_over' not in st.session_state:
st.session_state.game_over = False
# Function to check for winner
def check_winner(board):
# Check rows, columns and diagonals
for i in range(3):
if board[i, 0] == board[i, 1] == board[i, 2] != ' ':
return board[i, 0]
if board[0, i] == board[1, i] == board[2, i] != ' ':
return board[0, i]
if board[0, 0] == board[1, 1] == board[2, 2] != ' ':
return board[0, 0]
if board[0, 2] == board[1, 1] == board[2, 0] != ' ':
return board[0, 2]
if ' ' not in board:
return 'Tie'
return None
# Function to reset game
def reset_game():
st.session_state.board = np.full((3, 3), ' ')
st.session_state.current_player = 'X'
st.session_state.game_over = False
# Title
st.title('Tic Tac Toe')
# Game board display
cols = st.columns([1, 2, 1])
with cols[1]:
for i in range(3):
cols = st.columns(3)
for j in range(3):
if st.button(st.session_state.board[i, j], key=f'cell_{i}_{j}',
disabled=st.session_state.game_over or st.session_state.board[i, j] != ' '):
st.session_state.board[i, j] = st.session_state.current_player
winner = check_winner(st.session_state.board)
if winner:
st.session_state.game_over = True
else:
st.session_state.current_player = 'O' if st.session_state.current_player == 'X' else 'X'
st.rerun()
# Game status
if st.session_state.game_over:
winner = check_winner(st.session_state.board)
if winner == 'Tie':
st.write('Game Over: It\'s a tie!')
else:
st.write(f'Game Over: Player {winner} wins!')
else:
st.write(f'Current player: {st.session_state.current_player}')
# Reset button
if st.button('Reset Game'):
reset_game()
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?