umarcui commited on
Commit
f154082
·
verified ·
1 Parent(s): 9493e32

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ # Initialize the board and game state
4
+ if "board" not in st.session_state:
5
+ st.session_state.board = [""] * 9
6
+ st.session_state.current_player = "X"
7
+ st.session_state.winner = None
8
+
9
+ def check_winner(board):
10
+ win_conditions = [
11
+ [0,1,2], [3,4,5], [6,7,8], # rows
12
+ [0,3,6], [1,4,7], [2,5,8], # cols
13
+ [0,4,8], [2,4,6] # diagonals
14
+ ]
15
+ for condition in win_conditions:
16
+ a, b, c = condition
17
+ if board[a] and board[a] == board[b] == board[c]:
18
+ return board[a]
19
+ if all(cell != "" for cell in board):
20
+ return "Draw"
21
+ return None
22
+
23
+ def restart_game():
24
+ st.session_state.board = [""] * 9
25
+ st.session_state.current_player = "X"
26
+ st.session_state.winner = None
27
+
28
+ st.title("🎮 Tic Tac Toe Game")
29
+ st.markdown("Play against a friend in the browser!")
30
+
31
+ # Game board layout
32
+ cols = st.columns(3)
33
+ for i in range(3):
34
+ for j in range(3):
35
+ idx = i * 3 + j
36
+ with cols[j]:
37
+ if st.button(st.session_state.board[idx] or " ", key=idx, use_container_width=True):
38
+ if not st.session_state.board[idx] and not st.session_state.winner:
39
+ st.session_state.board[idx] = st.session_state.current_player
40
+ st.session_state.winner = check_winner(st.session_state.board)
41
+ if not st.session_state.winner:
42
+ st.session_state.current_player = "O" if st.session_state.current_player == "X" else "X"
43
+
44
+ # Display result
45
+ if st.session_state.winner:
46
+ if st.session_state.winner == "Draw":
47
+ st.success("It's a draw!")
48
+ else:
49
+ st.success(f"Player {st.session_state.winner} wins!")
50
+
51
+ st.button("🔁 Restart Game", on_click=restart_game)