pratikshahp commited on
Commit
4ebf9b9
ยท
verified ยท
1 Parent(s): c10d5a1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+
4
+ # Initialize the game board and state
5
+ def initialize_game():
6
+ board = [["" for _ in range(3)] for _ in range(3)]
7
+ current_player = "X"
8
+ status = "Player 1's turn (X)"
9
+ buttons = [gr.Button(value="", elem_classes=["cell-btn"], interactive=True) for _ in range(9)]
10
+ return board, current_player, status, *buttons
11
+
12
+ # Check for a winner
13
+ def check_winner(board):
14
+ for i in range(3):
15
+ if board[i][0] == board[i][1] == board[i][2] and board[i][0] != "":
16
+ return board[i][0]
17
+ if board[0][i] == board[1][i] == board[2][i] and board[0][i] != "":
18
+ return board[0][i]
19
+ if board[0][0] == board[1][1] == board[2][2] and board[0][0] != "":
20
+ return board[0][0]
21
+ if board[0][2] == board[1][1] == board[2][0] and board[0][2] != "":
22
+ return board[0][2]
23
+ return None
24
+
25
+ # Check for a draw
26
+ def check_draw(board):
27
+ return all(cell != "" for row in board for cell in row)
28
+
29
+ # Minimax algorithm for AI's move
30
+ def minimax(board, depth, is_maximizing, difficulty):
31
+ winner = check_winner(board)
32
+ if winner == "X":
33
+ return -10 + depth
34
+ elif winner == "O":
35
+ return 10 - depth
36
+ elif check_draw(board):
37
+ return 0
38
+
39
+ if is_maximizing:
40
+ best = -float('inf')
41
+ for i in range(3):
42
+ for j in range(3):
43
+ if board[i][j] == "":
44
+ board[i][j] = "O"
45
+ best = max(best, minimax(board, depth + 1, False, difficulty))
46
+ board[i][j] = ""
47
+ return best
48
+ else:
49
+ best = float('inf')
50
+ for i in range(3):
51
+ for j in range(3):
52
+ if board[i][j] == "":
53
+ board[i][j] = "X"
54
+ best = min(best, minimax(board, depth + 1, True, difficulty))
55
+ board[i][j] = ""
56
+ return best
57
+
58
+ # Find the best move for AI
59
+ def get_best_move(board, difficulty):
60
+ if difficulty == "easy":
61
+ # Random move for easy level
62
+ empty_cells = [(i, j) for i in range(3) for j in range(3) if board[i][j] == ""]
63
+ if empty_cells:
64
+ return random.choice(empty_cells)
65
+
66
+ if difficulty == "intermediate":
67
+ # Mixed strategy for intermediate
68
+ if random.random() < 0.5:
69
+ return get_best_move(board, "easy")
70
+
71
+ best_val = -float('inf')
72
+ best_move = (-1, -1)
73
+ for i in range(3):
74
+ for j in range(3):
75
+ if board[i][j] == "":
76
+ board[i][j] = "O"
77
+ move_val = minimax(board, 0, False, difficulty)
78
+ board[i][j] = ""
79
+ if move_val > best_val:
80
+ best_move = (i, j)
81
+ best_val = move_val
82
+ return best_move
83
+
84
+ # Handle a move
85
+ def handle_move(board, current_player, button_idx, game_status, difficulty):
86
+ if "wins" in game_status or "draw" in game_status:
87
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
88
+ return board, current_player, game_status, *buttons
89
+
90
+ row, col = divmod(button_idx, 3)
91
+ if board[row][col] != "":
92
+ status = f"Invalid move! Player {1 if current_player == 'X' else 2}'s turn ({current_player})"
93
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"]) for i in range(9)]
94
+ return board, current_player, status, *buttons
95
+
96
+ board[row][col] = current_player
97
+ winner = check_winner(board)
98
+ if winner:
99
+ status = f"Player {1 if winner == 'X' else 2} ({winner}) wins! ๐ŸŽ‰"
100
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
101
+ return board, current_player, status, *buttons
102
+
103
+ if check_draw(board):
104
+ status = "It's a draw! ๐Ÿค"
105
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
106
+ return board, current_player, status, *buttons
107
+
108
+ # AI's turn
109
+ if current_player == "X":
110
+ current_player = "O"
111
+ ai_row, ai_col = get_best_move(board, difficulty)
112
+ board[ai_row][ai_col] = "O"
113
+ winner = check_winner(board)
114
+ if winner:
115
+ status = f"AI ({winner}) wins! ๐ŸŽ‰"
116
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
117
+ return board, current_player, status, *buttons
118
+
119
+ if check_draw(board):
120
+ status = "It's a draw! ๐Ÿค"
121
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
122
+ return board, current_player, status, *buttons
123
+
124
+ current_player = "X"
125
+ status = f"Player 1's turn (X)"
126
+
127
+ buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"]) for i in range(9)]
128
+ return board, current_player, status, *buttons
129
+
130
+ # Build the Gradio UI
131
+ with gr.Blocks(css="""
132
+ .cell-btn {
133
+ height: 100px;
134
+ width: 100px;
135
+ font-size: 2em;
136
+ text-align: center;
137
+ }
138
+ .winner-highlight {
139
+ font-size: 3em;
140
+ font-weight: bold;
141
+ color: green;
142
+ text-align: center;
143
+ margin-top: 20px;
144
+ }
145
+ """) as tic_tac_toe:
146
+ gr.Markdown("## Tic-Tac-Toe with AI ๐ŸŽฎ")
147
+ difficulty = gr.Radio(["easy", "intermediate", "impossible"], value="impossible", label="Difficulty Level")
148
+
149
+ # Initialize states
150
+ board_state = gr.State([["" for _ in range(3)] for _ in range(3)])
151
+ current_player = gr.State("X")
152
+ game_status = gr.Textbox(value="Player 1's turn (X)", label="Game Status", interactive=False)
153
+ winner_display = gr.HTML("", elem_classes=["winner-highlight"])
154
+
155
+ # Create grid buttons
156
+ buttons = []
157
+ for i in range(3):
158
+ with gr.Row():
159
+ for j in range(3):
160
+ btn = gr.Button(value="", elem_classes=["cell-btn"])
161
+ buttons.append(btn)
162
+
163
+ # Update buttons dynamically on click
164
+ for idx, btn in enumerate(buttons):
165
+ btn.click(
166
+ handle_move,
167
+ inputs=[board_state, current_player, gr.Number(idx, visible=False), game_status, difficulty],
168
+ outputs=[board_state, current_player, game_status, winner_display, *buttons],
169
+ )
170
+
171
+ # Reset game button
172
+ reset_button = gr.Button("Reset Game")
173
+ reset_button.click(
174
+ initialize_game,
175
+ inputs=[],
176
+ outputs=[board_state, current_player, game_status, winner_display, *buttons],
177
+ )
178
+
179
+ tic_tac_toe.launch()