Create a Streamlit app that runs a game of tic-tac-toe with an AI opponent.
To upload files, please first save the app
import numpy as np
import random
# Initialize board
if 'board' not in st.session_state:
st.session_state.board = np.zeros((3, 3))
# Function to check for a win
def check_win(board, player):
for row in range(3):
if np.all(board[row] == player):
return True
for col in range(3):
if np.all(board[:, col] == player):
return True
if np.all(np.diagonal(board) == player) or np.all(np.diagonal(np.fliplr(board)) == player):
return True
return False
# AI move
def ai_move(board):
empty_positions = [(i, j) for i in range(3) for j in range(3) if board[i, j] == 0]
if empty_positions:
move = random.choice(empty_positions)
board[move] = -1
# UI Layout
st.title('Tic Tac Toe vs AI')
# Player move
selected_cell = st.selectbox('Select your move:', [(i, j) for i in range(3) for j in range(3)], index=0)
if st.button('Make Move'):
if board[selected_cell] == 0:
board[selected_cell] = 1 # Player move
if not check_win(board, 1):
ai_move(board) # AI move
# Display board
st.write(np.where(board == 1, 'X', np.where(board == -1, 'O', ' ')))
# Check for win
if check_win(board, 1):
st.success('You win!')
elif check_win(board, -1):
st.error('AI wins!')
elif np.all(board != 0):
st.warning('It is a draw!')
# Reset game
if st.button('Reset Game'):
st.session_state.board = np.zeros((3, 3))
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?