GeminiAi commited on
Commit
ffafaf2
·
verified ·
1 Parent(s): f1bb651

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -102
app.py CHANGED
@@ -1,106 +1,84 @@
1
  import gradio as gr
2
  import random
3
 
4
- # Simulated AI models for checkers (replace these with actual AI model imports later)
5
- from transformers import pipeline # Example for using real AI models
6
-
7
- class BasicAI:
8
- def move(self, board):
9
- # Basic AI makes a random valid move
10
- valid_moves = self.get_valid_moves(board)
11
- return random.choice(valid_moves) if valid_moves else None
12
-
13
- def get_valid_moves(self, board):
14
- # Simulate valid moves as random pairs of coordinates
15
- return [(random.randint(0, 7), random.randint(0, 7)) for _ in range(random.randint(1, 5))]
16
-
17
- class AdvancedAI:
18
- def move(self, board):
19
- # Advanced AI prioritizes moves with a placeholder strategy
20
- valid_moves = self.get_valid_moves(board)
21
- return valid_moves[0] if valid_moves else None
22
-
23
- def get_valid_moves(self, board):
24
- # Simulate valid moves as random pairs of coordinates
25
- return [(random.randint(0, 7), random.randint(0, 7)) for _ in range(random.randint(1, 5))]
26
-
27
- # Replace BasicAI and AdvancedAI with actual models (example Hugging Face pipelines)
28
- ai_models = {
29
- "Basic AI": BasicAI(),
30
- "Advanced AI": AdvancedAI(),
31
- "HuggingFace AI 1": pipeline("text-generation", model="gpt2"),
32
- "HuggingFace AI 2": pipeline("text-generation", model="EleutherAI/gpt-neo-1.3B")
33
- }
34
-
35
- def play_ai_vs_ai(ai1_name, ai2_name, rounds):
36
- ai1 = ai_models[ai1_name]
37
- ai2 = ai_models[ai2_name]
38
-
39
- board = [["." for _ in range(8)] for _ in range(8)] # Simplified 8x8 board
40
- history = []
41
-
42
- for i in range(rounds):
43
- ai1_move = ai1.move(board) if hasattr(ai1, 'move') else "Simulated AI 1 Move"
44
- ai2_move = ai2.move(board) if hasattr(ai2, 'move') else "Simulated AI 2 Move"
45
- history.append(f"Round {i + 1}: {ai1_name} -> {ai1_move}, {ai2_name} -> {ai2_move}")
46
-
47
- return "\n".join(history)
48
-
49
- def render_board():
50
- board_html = "<table style='border-collapse: collapse; width: 100px; height: 100px;'>"
51
- for i in range(8):
52
- board_html += "<tr>"
53
- for j in range(8):
54
- color = "#f0d9b5" if (i + j) % 2 == 0 else "#b58863"
55
- board_html += f"<td style='width: 40px; height: 40px; background-color: {color}; border: 1px solid black;'></td>"
56
- board_html += "</tr>"
57
- board_html += "</table>"
58
- return board_html
59
-
60
- # Gradio Interface
61
- def build_interface():
62
- with gr.Blocks() as interface:
63
- gr.Markdown("""
64
- # AI vs AI Checkers Game
65
- Watch different AI models compete against each other in a simulated game of checkers. Select the models and number of rounds to see how they perform!
66
- """)
67
-
68
- with gr.Row():
69
- ai1_dropdown = gr.Dropdown(choices=list(ai_models.keys()), label="Select AI Model for Player 1", value="Basic AI")
70
- ai2_dropdown = gr.Dropdown(choices=list(ai_models.keys()), label="Select AI Model for Player 2", value="Advanced AI")
71
-
72
- rounds_slider = gr.Slider(minimum=1, maximum=20, step=1, value=5, label="Number of Rounds")
73
-
74
- with gr.Row():
75
- start_button = gr.Button("Start AI vs AI")
76
-
77
- output_box = gr.Textbox(label="Game History", lines=10)
78
- board_output = gr.HTML(render_board(), label="Checkers Board")
79
-
80
- start_button.click(
81
- play_ai_vs_ai,
82
- inputs=[ai1_dropdown, ai2_dropdown, rounds_slider],
83
- outputs=[output_box]
84
- )
85
-
86
- gr.HTML("""
87
- <div style='margin-top: 20px;'>
88
- <h3>Game Board</h3>
89
- <div>""" + render_board() + """</div>
90
- </div>
91
- """)
92
-
93
- gr.Markdown("""
94
- ### How It Works
95
- - **Basic AI**: Makes random valid moves.
96
- - **Advanced AI**: Uses a placeholder strategy to prioritize specific moves.
97
- - **HuggingFace AI Models**: These use text generation pipelines for creative move generation.
98
 
99
- Select models, adjust the rounds, and press "Start AI vs AI" to see the results!
100
- """)
101
-
102
- return interface
103
-
104
- # Launch the app
105
- interface = build_interface()
106
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import random
3
 
4
+ # Initialize board, pieces, and game state
5
+ class CheckersGame:
6
+ def __init__(self):
7
+ self.board = self.create_board()
8
+ self.turn = 'white' # White goes first
9
+ self.game_over = False
10
+
11
+ def create_board(self):
12
+ board = [['' for _ in range(8)] for _ in range(8)]
13
+ # Initialize the pieces
14
+ for row in range(3):
15
+ for col in range(row % 2, 8, 2):
16
+ board[row][col] = 'red'
17
+ for row in range(5, 8):
18
+ for col in range(row % 2, 8, 2):
19
+ board[row][col] = 'white'
20
+ return board
21
+
22
+ def make_move(self):
23
+ # AI logic: Random move for the sake of simplicity
24
+ if self.game_over:
25
+ return self.board, "Game Over! Restart to play again."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ valid_moves = self.get_valid_moves(self.turn)
28
+ if valid_moves:
29
+ move = random.choice(valid_moves)
30
+ self.board[move[2]][move[3]] = self.board[move[0]][move[1]]
31
+ self.board[move[0]][move[1]] = ''
32
+ self.turn = 'white' if self.turn == 'red' else 'red'
33
+ return self.board, f"{self.turn.capitalize()} moved."
34
+ else:
35
+ self.game_over = True
36
+ return self.board, f"Game Over! {self.turn.capitalize()} has no moves left."
37
+
38
+ def get_valid_moves(self, color):
39
+ valid_moves = []
40
+ for row in range(8):
41
+ for col in range(8):
42
+ if self.board[row][col] == color:
43
+ # Check all directions for valid moves (simplified)
44
+ directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
45
+ for dr, dc in directions:
46
+ new_row, new_col = row + dr, col + dc
47
+ if 0 <= new_row < 8 and 0 <= new_col < 8 and self.board[new_row][new_col] == '':
48
+ valid_moves.append((row, col, new_row, new_col))
49
+ return valid_moves
50
+
51
+ def render_board(self):
52
+ board_repr = ''
53
+ for row in self.board:
54
+ board_repr += ' '.join([cell[0].upper() if cell else '.' for cell in row]) + '\n'
55
+ return board_repr
56
+
57
+ # Create a Checkers game instance
58
+ game = CheckersGame()
59
+
60
+ # Function to handle the game move and display
61
+ def play_checkers():
62
+ board, status = game.make_move()
63
+ return game.render_board(), status
64
+
65
+ # Gradio interface
66
+ def create_ui():
67
+ with gr.Blocks() as demo:
68
+ gr.Markdown("## AI vs AI - Watch the Game!")
69
+
70
+ # Display the board and game status
71
+ with gr.Row():
72
+ board_display = gr.Textbox(label="Game Board", interactive=False, value=game.render_board())
73
+ game_status = gr.Textbox(label="Game Status", interactive=False, value="Game is running...")
74
+
75
+ # Button to simulate a move and update the board
76
+ play_button = gr.Button("AI makes a move")
77
+ play_button.click(play_checkers, outputs=[board_display, game_status])
78
+
79
+ return demo
80
+
81
+ # Launch the Gradio app
82
+ if __name__ == "__main__":
83
+ ui = create_ui()
84
+ ui.launch(share=True)