Tic-tac-toe / app.py
ositamiles's picture
Create app.py
237bba2 verified
import streamlit as st
import numpy as np
# Initialize session state for the board and player
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 'winner' not in st.session_state:
st.session_state['winner'] = None
if 'draw' not in st.session_state:
st.session_state['draw'] = False
def reset_game():
st.session_state['board'] = np.full((3, 3), ' ')
st.session_state['current_player'] = "X"
st.session_state['winner'] = None
st.session_state['draw'] = False
def check_winner(board, player):
for row in board:
if all([spot == player for spot in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]):
return True
return False
def is_full(board):
return not any([spot == ' ' for row in board for spot in row])
def make_move(row, col):
if st.session_state['board'][row, col] == ' ' and not st.session_state['winner'] and not st.session_state['draw']:
st.session_state['board'][row, col] = st.session_state['current_player']
if check_winner(st.session_state['board'], st.session_state['current_player']):
st.session_state['winner'] = st.session_state['current_player']
elif is_full(st.session_state['board']):
st.session_state['draw'] = True
else:
st.session_state['current_player'] = "O" if st.session_state['current_player'] == "X" else "X"
st.title("Tic Tac Toe")
# Display the board
for i in range(3):
cols = st.columns(3)
for j in range(3):
cols[j].button(st.session_state['board'][i, j], key=f"{i}{j}", on_click=make_move, args=(i, j))
if st.session_state['winner']:
st.success(f"Player {st.session_state['winner']} wins!")
elif st.session_state['draw']:
st.info("The game is a draw!")
if st.button("Reset Game"):
reset_game()