File size: 11,316 Bytes
fc46f2c
 
 
5a73433
 
372a5eb
562ba5d
fc46f2c
 
 
5a7773e
 
fc46f2c
 
 
f759b42
5a73433
f759b42
5a73433
 
f759b42
5a73433
fc46f2c
 
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f93878
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f759b42
 
5a73433
3f93878
5a73433
 
 
 
fc46f2c
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea842a4
5a73433
ef0cf30
5a73433
 
 
fc46f2c
5a73433
 
 
 
 
 
 
 
 
 
f759b42
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f93878
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f759b42
5a73433
f759b42
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f93878
5a73433
 
 
 
 
 
 
 
 
3f93878
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
fc46f2c
5a73433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc46f2c
5a73433
fc46f2c
5a73433
f759b42
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import os
import gradio as gr
from llama_cpp import Llama
from huggingface_hub import hf_hub_download#, login
import numpy as np

#login(os.getenv("HF_TOKEN")) my bad now its public

model = Llama(
    model_path=hf_hub_download(
        repo_id=os.environ.get("REPO_ID", "Lyte/QuadConnect2.5-0.5B-v0.0.3b"),
        filename=os.environ.get("MODEL_FILE", "quadconnect_q8_0.gguf"),
    )
)

SYSTEM_PROMPT = """You are a Connect Four player.  Connect Four is played on a 6x7 grid. Given the current board state, predict the next *column* to play in.  Moves are specified by the column letter (a-g). Respond in the following format:
<reasoning>
Explain your reasoning, considering the board state and potential future moves.
</reasoning>
<move>
The column letter (a-g) of your move.
</move>
"""

class ConnectFour:
    def __init__(self):
        self.board = np.zeros((6, 7))
        self.current_player = 1  # 1 for player, 2 for AI
        self.game_over = False
        
    def make_move(self, col):
        if self.game_over:
            return False, -1
            
        # Find the lowest empty row in the selected column
        for row in range(5, -1, -1):
            if self.board[row][col] == 0:
                self.board[row][col] = self.current_player
                return True, row
        return False, -1

    def check_winner(self):
        # Check horizontal
        for row in range(6):
            for col in range(4):
                if (self.board[row][col] != 0 and
                    self.board[row][col] == self.board[row][col+1] == 
                    self.board[row][col+2] == self.board[row][col+3]):
                    return self.board[row][col]
                    
        # Check vertical
        for row in range(3):
            for col in range(7):
                if (self.board[row][col] != 0 and
                    self.board[row][col] == self.board[row+1][col] ==
                    self.board[row+2][col] == self.board[row+3][col]):
                    return self.board[row][col]
                    
        # Check diagonal (positive slope)
        for row in range(3):
            for col in range(4):
                if (self.board[row][col] != 0 and
                    self.board[row][col] == self.board[row+1][col+1] ==
                    self.board[row+2][col+2] == self.board[row+3][col+3]):
                    return self.board[row][col]
                    
        # Check diagonal (negative slope)
        for row in range(3, 6):
            for col in range(4):
                if (self.board[row][col] != 0 and
                    self.board[row][col] == self.board[row-1][col+1] ==
                    self.board[row-2][col+2] == self.board[row-3][col+3]):
                    return self.board[row][col]
                    
        return 0

    def board_to_string(self):
        moves = []
        for row in range(6):
            for col in range(7):
                if self.board[row][col] != 0:
                    col_letter = chr(ord('a') + col)
                    row_num = str(6 - row)  # Convert to 1-based indexing
                    #player = "X" if self.board[row][col] == 1 else "O"
                    moves.append(f"{col_letter}{row_num}")#={player}")
        return ", ".join(moves)

    def parse_ai_move(self, move_str):
        # Parse move like 'a1', 'b3', etc.
        col = ord(move_str[0].lower()) - ord('a')
        return col

def create_interface():
    game = ConnectFour()
    
    css = """
    .connect4-board {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 8px;
        max-width: 600px;
        margin: 10px auto;
        background: #2196F3;
        padding: 15px;
        border-radius: 15px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }
    .connect4-cell {
        aspect-ratio: 1;
        background: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2em;
    }
    .player1 { background: #f44336 !important; }
    .player2 { background: #ffc107 !important; }
    #ai-status {
        font-size: 1.2em;
        margin: 10px 0;
        color: #2196F3;
        font-weight: bold;
    }
    #ai-reasoning {
        background: #22004d;
        border-radius: 10px;
        padding: 15px;
        margin: 15px 0;
        font-family: monospace;
        min-height: 100px;
    }
    .reasoning-box {
        border-left: 4px solid #2196F3;
        padding-left: 15px;
        margin: 10px 0;
        background: #22004d;
        border-radius: 0 10px 10px 0;
    }
    #column-buttons {
        display: flex;
        justify-content: center;
        align-items: anchor-center;
        max-width: 600px;
        margin: 0 auto;
        padding: 0 15px;
    }
    #column-buttons button {
      margin: 0px 5px;
    }
    div.svelte-1nguped {
      display: block;
    }
    """

    with gr.Blocks(css=css) as interface:
        gr.Markdown("# ๐ŸŽฎ Connect Four vs AI")
        gr.Markdown("### This is just a quick prototype for now, and the current model was trained just for 200 steps to test the concept, the reward functions were flawed, update coming soon!")
        
        with gr.Row():
            with gr.Column(scale=2):
                # Status display
                status = gr.Markdown("Your turn! Click a button to drop your piece!", elem_id="ai-status")
                
                # Column buttons
                with gr.Group(elem_id="column-buttons", elem_classes=["fitter"]):
                    col_buttons = []
                    for i in range(7):
                        btn = gr.Button(f"โฌ‡๏ธ {i+1}", scale=1)
                        col_buttons.append(btn)
                
                # Game board
                board_display = gr.HTML(render_board(), elem_id="board-display")
                reset_btn = gr.Button("๐Ÿ”„ New Game", variant="primary")
            
        with gr.Column(scale=1):
            # AI reasoning display
            gr.Markdown("### ๐Ÿค– AI's Thoughts")
            reasoning_display = gr.HTML(
                value='<div id="ai-reasoning">Waiting for your move...</div>',
                elem_id="ai-reasoning-container"
                )

        def handle_move(col):
            if game.game_over:
                return [
                    render_board(game.board),
                    "Game is over! Click New Game to play again.",
                    '<div id="ai-reasoning">Game Over!</div>'
                ]
            
            # Player move
            success, row = game.make_move(col)
            if not success:
                return [
                    render_board(game.board),
                    "Column is full! Try another one.",
                    '<div id="ai-reasoning">Invalid move!</div>'
                ]
            
            # Check for winner
            winner = game.check_winner()
            if winner == 1:
                game.game_over = True
                return [
                    render_board(game.board),
                    "๐ŸŽ‰ You win! ๐ŸŽ‰",
                    '<div id="ai-reasoning">Congratulations! You won!</div>'
                ]
            
            # AI move
            game.current_player = 2
            board_state = game.board_to_string()

            prompt = f"Current Board: {board_state}. Make a move."
            #print(prompt)
            
            # Get AI response
            response = model.create_chat_completion(
                messages=[
                    {"role": "system", "content": SYSTEM_PROMPT},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_tokens=512
            )
            
            ai_response = response['choices'][0]['message']['content']
            
            # Extract reasoning and move
            try:
                reasoning = ai_response.split("<reasoning>")[1].split("</reasoning>")[0].strip()
                move_str = ai_response.split("<move>")[1].split("</move>")[0].strip()
                ai_col = game.parse_ai_move(move_str)
                
                # Format reasoning for display
                reasoning_html = f'''
                <div id="ai-reasoning">
                    <div class="reasoning-box">
                        <p><strong>๐Ÿค” Reasoning:</strong></p>
                        <p>{reasoning}</p>
                        <p><strong>๐Ÿ“ Move chosen:</strong> {move_str}</p>
                    </div>
                </div>
                '''
                
                success, _ = game.make_move(ai_col)
                if success:
                    # Check for AI winner
                    winner = game.check_winner()
                    if winner == 2:
                        game.game_over = True
                        return [
                            render_board(game.board),
                            "๐Ÿค– AI wins! Better luck next time!",
                            reasoning_html
                        ]
                else:
                    return [
                        render_board(game.board),
                        "AI made invalid move! You win by default!",
                        '<div id="ai-reasoning">AI made an invalid move!</div>'
                    ]
            except Exception as e:
                game.game_over = True
                return [
                    render_board(game.board),
                    "AI error occurred! You win by default!",
                    f'<div id="ai-reasoning">Error: {str(e)}</div>'
                ]
            
            game.current_player = 1
            return [render_board(game.board), "Your turn!", reasoning_html]

        def reset_game():
            game.board = np.zeros((6, 7))
            game.current_player = 1
            game.game_over = False
            return [
                render_board(),
                "Your turn! Click a button to drop your piece!",
                '<div id="ai-reasoning">New game started! Make your move...</div>'
            ]

        # Event handlers
        for i, btn in enumerate(col_buttons):
            btn.click(
                fn=handle_move,
                inputs=[gr.Number(value=i, visible=False)],
                outputs=[board_display, status, reasoning_display]
            )
        
        reset_btn.click(
            fn=reset_game,
            outputs=[board_display, status, reasoning_display]
        )
        
    return interface

def render_board(board=None):
    if board is None:
        board = np.zeros((6, 7))
        
    html = '<div class="connect4-board">'
    
    for row in range(6):
        for col in range(7):
            cell_class = "connect4-cell"
            content = "โšช"
            
            if board[row][col] == 1:
                cell_class += " player1"
                content = "๐Ÿ”ด"
            elif board[row][col] == 2:
                cell_class += " player2"
                content = "๐ŸŸก"
                
            html += f'<div class="{cell_class}">{content}</div>'
    
    html += "</div>"
    return html

# Launch the interface
if __name__ == "__main__":
    interface = create_interface()
    interface.launch()