pratikshahp commited on
Commit
a220423
·
verified ·
1 Parent(s): dab348b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -126
app.py CHANGED
@@ -1,87 +1,37 @@
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)]
@@ -97,13 +47,15 @@ def handle_move(board, current_player, button_idx, game_status, difficulty):
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":
@@ -113,68 +65,59 @@ def handle_move(board, current_player, button_idx, game_status, difficulty):
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
-
131
- # Build the Gradio UI
132
- with gr.Blocks(css="""
133
- .cell-btn {
134
- height: 100px;
135
- width: 100px;
136
- font-size: 2em;
137
- text-align: center;
138
- }
139
- .winner-highlight {
140
- font-size: 3em;
141
- font-weight: bold;
142
- color: green;
143
- text-align: center;
144
- margin-top: 20px;
145
- }
146
- """) as tic_tac_toe:
147
- gr.Markdown("## Tic-Tac-Toe with AI 🎮")
148
- difficulty = gr.Radio(["easy", "intermediate", "impossible"], value="impossible", label="Difficulty Level")
149
-
150
- # Initialize states
151
- board_state = gr.State([["" for _ in range(3)] for _ in range(3)])
 
 
152
  current_player = gr.State("X")
153
- game_status = gr.Textbox(value="Player 1's turn (X)", label="Game Status", interactive=False)
154
- winner_display = gr.HTML("", elem_classes=["winner-highlight"])
155
-
156
- # Create grid buttons
157
- buttons = []
158
- for i in range(3):
159
- with gr.Row():
160
- for j in range(3):
161
- btn = gr.Button(value="", elem_classes=["cell-btn"])
162
- buttons.append(btn)
163
-
164
- # Update buttons dynamically on click
165
- for idx, btn in enumerate(buttons):
166
- btn.click(
167
- handle_move,
168
- inputs=[board_state, current_player, gr.Number(idx, visible=False), game_status, difficulty],
169
- outputs=[board_state, current_player, game_status, winner_display, *buttons],
170
- )
171
 
172
- # Reset game button
173
  reset_button = gr.Button("Reset Game")
174
- reset_button.click(
175
- initialize_game,
176
- inputs=[],
177
- outputs=[board_state, current_player, game_status, winner_display, *buttons],
178
- )
 
 
 
179
 
180
- tic_tac_toe.launch()
 
1
  import gradio as gr
2
  import random
3
 
4
+
5
+ # Check if there's a winner
 
 
 
 
 
 
 
6
  def check_winner(board):
7
+ for row in board:
8
+ if row[0] == row[1] == row[2] != "":
9
+ return row[0]
10
+ for col in range(3):
11
+ if board[0][col] == board[1][col] == board[2][col] != "":
12
+ return board[0][col]
13
+ if board[0][0] == board[1][1] == board[2][2] != "":
14
  return board[0][0]
15
+ if board[0][2] == board[1][1] == board[2][0] != "":
16
  return board[0][2]
17
  return None
18
 
19
+
20
+ # Check if it's a draw
21
  def check_draw(board):
22
+ for row in board:
23
+ if "" in row:
24
+ return False
25
+ return True
26
 
27
+
28
+ # AI move (random for simplicity)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def get_best_move(board, difficulty):
30
+ empty_cells = [(row, col) for row in range(3) for col in range(3) if board[row][col] == ""]
31
+ return random.choice(empty_cells) if empty_cells else None
32
+
33
+
34
+ # Handle the move
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def handle_move(board, current_player, button_idx, game_status, difficulty):
36
  if "wins" in game_status or "draw" in game_status:
37
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
 
47
  winner = check_winner(board)
48
  if winner:
49
  status = f"Player {1 if winner == 'X' else 2} ({winner}) wins! 🎉"
50
+ winner_message = f"<h1 style='font-size: 2.5em; color: green; text-align: center;'>Player {1 if winner == 'X' else 2} ({winner}) Wins! 🎉</h1>"
51
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
52
+ return board, current_player, status, winner_message, *buttons
53
 
54
  if check_draw(board):
55
  status = "It's a draw! 🤝"
56
+ winner_message = "<h1 style='font-size: 2.5em; color: blue; text-align: center;'>It's a Draw! 🤝</h1>"
57
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
58
+ return board, current_player, status, winner_message, *buttons
59
 
60
  # AI's turn
61
  if current_player == "X":
 
65
  winner = check_winner(board)
66
  if winner:
67
  status = f"AI ({winner}) wins! 🎉"
68
+ winner_message = f"<h1 style='font-size: 2.5em; color: red; text-align: center;'>AI ({winner}) Wins! 🎉</h1>"
69
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
70
+ return board, current_player, status, winner_message, *buttons
71
 
72
  if check_draw(board):
73
  status = "It's a draw! 🤝"
74
+ winner_message = "<h1 style='font-size: 2.5em; color: blue; text-align: center;'>It's a Draw! 🤝</h1>"
75
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"], interactive=False) for i in range(9)]
76
+ return board, current_player, status, winner_message, *buttons
77
 
78
  current_player = "X"
79
  status = f"Player 1's turn (X)"
80
 
81
+ winner_message = "" # No winner yet
82
  buttons = [gr.Button(value=board[i // 3][i % 3], elem_classes=["cell-btn"]) for i in range(9)]
83
+ return board, current_player, status, winner_message, *buttons
84
+
85
+
86
+ # Reset the game
87
+ def reset_game():
88
+ board = [[""] * 3 for _ in range(3)]
89
+ buttons = [gr.Button(value="", elem_classes=["cell-btn"]) for _ in range(9)]
90
+ return board, "X", "Player 1's turn (X)", "", *buttons
91
+
92
+
93
+ # Initial game setup
94
+ board = [[""] * 3 for _ in range(3)]
95
+ buttons = [gr.Button(value="", elem_classes=["cell-btn"]) for _ in range(9)]
96
+
97
+ with gr.Blocks(css=".cell-btn {height: 100px; width: 100px; font-size: 2em; margin: 5px;}") as app:
98
+ gr.Markdown("<h1 style='text-align: center;'>Tic Tac Toe Game</h1>")
99
+ game_status = gr.Textbox("Player 1's turn (X)", interactive=False, label="Game Status")
100
+ winner_display = gr.HTML()
101
+
102
+ with gr.Row():
103
+ button_components = []
104
+ for i in range(3):
105
+ with gr.Row():
106
+ for j in range(3):
107
+ button_components.append(gr.Button("", elem_classes=["cell-btn"], interactive=True))
108
+
109
  current_player = gr.State("X")
110
+ board_state = gr.State([[""] * 3 for _ in range(3)])
111
+ difficulty = gr.Dropdown(choices=["Easy", "Medium", "Hard"], value="Medium", label="AI Difficulty")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
 
113
  reset_button = gr.Button("Reset Game")
114
+ reset_button.click(reset_game, [], outputs=[board_state, current_player, game_status, winner_display, *button_components])
115
+
116
+ for idx, button in enumerate(button_components):
117
+ button.click(
118
+ handle_move,
119
+ inputs=[board_state, current_player, gr.State(idx), game_status, difficulty],
120
+ outputs=[board_state, current_player, game_status, winner_display, *button_components]
121
+ )
122
 
123
+ app.launch()