OrifjonKenjayev commited on
Commit
3fdb6db
·
verified ·
1 Parent(s): f373d8b

Create app.py

Browse files

Play TicTacToe with AI

Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ import numpy as np
4
+ from tictactoe import X, O, EMPTY, initial_state, result, terminal, winner, minimax
5
+
6
+ def initialize_board():
7
+ return initial_state()
8
+
9
+ def make_move(board_state, row, col, choice):
10
+ if not isinstance(board_state, list):
11
+ board_state = initial_state()
12
+
13
+ # Convert string representation back to None for EMPTY cells
14
+ board = [[cell if cell in [X, O] else EMPTY for cell in row] for row in board_state]
15
+
16
+ # Player move
17
+ if board[row][col] != EMPTY:
18
+ return board_state, "Invalid move! Cell already taken."
19
+
20
+ # Update board with player's move
21
+ board = result(board, (row, col))
22
+
23
+ # Check if game is over after player's move
24
+ if terminal(board):
25
+ game_winner = winner(board)
26
+ if game_winner:
27
+ return board, f"Game Over! {game_winner} wins!"
28
+ return board, "Game Over! It's a tie!"
29
+
30
+ # AI move
31
+ ai_move = minimax(board)
32
+ if ai_move:
33
+ board = result(board, ai_move)
34
+
35
+ # Check if game is over after AI's move
36
+ if terminal(board):
37
+ game_winner = winner(board)
38
+ if game_winner:
39
+ return board, f"Game Over! {game_winner} wins!"
40
+ return board, "Game Over! It's a tie!"
41
+
42
+ return board, f"AI moved to position {ai_move}"
43
+
44
+ return board, "Your turn!"
45
+
46
+ def create_board_interface():
47
+ with gr.Blocks() as demo:
48
+ gr.Markdown("# Tic Tac Toe vs AI")
49
+ gr.Markdown("You play as X, AI plays as O")
50
+
51
+ board_state = gr.State(initialize_board())
52
+ message = gr.Textbox(label="Game Status", value="Your turn!")
53
+
54
+ board = gr.DataFrame(
55
+ value=initialize_board(),
56
+ headers=False,
57
+ datatype=["str", "str", "str"],
58
+ row_count=3,
59
+ col_count=3,
60
+ interactive=False
61
+ )
62
+
63
+ def on_cell_click(evt: gr.SelectData, board_state):
64
+ row, col = evt.index
65
+ new_board, msg = make_move(board_state, row, col, X)
66
+ return new_board, new_board, msg
67
+
68
+ board.select(on_cell_click, [board_state], [board_state, board, message])
69
+
70
+ restart_btn = gr.Button("Restart Game")
71
+
72
+ def restart_game():
73
+ new_board = initialize_board()
74
+ return new_board, new_board, "Your turn!"
75
+
76
+ restart_btn.click(restart_game, None, [board_state, board, message])
77
+
78
+ return demo
79
+
80
+ if __name__ == "__main__":
81
+ demo = create_board_interface()
82
+ demo.launch()