File size: 30,684 Bytes
34aeb9a
 
 
 
 
 
 
a8f0741
 
34aeb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6e59e3
34aeb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6e59e3
a8f0741
 
34aeb9a
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
"""
๐Ÿค– Maze Runner โ€” RL Playground
An interactive, fun maze-solving playground powered by Reinforcement Learning.
Anyone can build a maze, pick a brain, and watch the bot learn to escape.
"""

from __future__ import annotations
import numpy as np
import gradio as gr

from maze.generator import generate_dfs_maze, generate_open_maze
from maze.env import MazeEnv
from agents.qlearning import train_qlearning
from agents.sarsa import train_sarsa
from agents.montecarlo import train_montecarlo
from viz.renderer import (
    make_solution_gif, make_training_chart,
    make_qvalue_heatmap, make_race_chart, score_run,
)

# โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

ALGO_MAP = {
    "๐Ÿง  Q-Learning  (recommended)": "qlearning",
    "๐ŸŽฏ SARSA  (cautious)":          "sarsa",
    "๐ŸŽฒ Monte Carlo  (explorer)":    "montecarlo",
}

DIFFICULTY = {
    "๐Ÿฃ Tiny  (5ร—5)":    5,
    "๐Ÿ‡ Small  (7ร—7)":   7,
    "๐Ÿข Medium  (9ร—9)":  9,
    "๐ŸฆŠ Large  (13ร—13)": 13,
    "๐Ÿ‰ XL  (17ร—17)":    17,
}

MAZE_STYLE = {
    "๐Ÿฐ Corridors  (DFS)": "dfs",
    "๐ŸŒฟ Open Field  (random walls)": "open",
}


def _make_env(size: int, style: str, seed: int) -> MazeEnv:
    if style == "dfs":
        grid = generate_dfs_maze(size, seed=seed)
    else:
        grid = generate_open_maze(size, wall_frac=0.18, seed=seed)
    return MazeEnv(grid)


def _train(env: MazeEnv, algo: str, episodes: int, alpha: float,
           gamma: float, decay: float, seed: int):
    fn = {"qlearning": train_qlearning,
          "sarsa": train_sarsa,
          "montecarlo": train_montecarlo}[algo]
    return fn(env, episodes, alpha, gamma, decay, seed)


def _collect_path(env: MazeEnv, agent) -> list[tuple[int, ...]]:
    state, _ = env.reset()
    path: list[tuple[int, ...]] = [env.start]
    for _ in range(env.n_states * 3):
        action = agent.greedy_action(state)
        state, _, done, _, _ = env.step(action)
        path.append(env._from_state(state))
        if done:
            break
    return path


# โ”€โ”€ Main Playground callback โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def cb_solve(
    difficulty: str,
    maze_style: str,
    algo_label: str,
    episodes: int,
    alpha: float,
    gamma: float,
    decay: float,
    seed: int,
    progress: gr.Progress = gr.Progress(),
):
    progress(0.05, desc="Building mazeโ€ฆ")
    size = DIFFICULTY[difficulty]
    style = MAZE_STYLE[maze_style]
    algo = ALGO_MAP[algo_label]

    env = _make_env(size, style, int(seed))

    progress(0.15, desc=f"Training {algo_label.split('(')[0].strip()}โ€ฆ")
    agent, rewards = _train(env, algo, int(episodes), float(alpha),
                            float(gamma), float(decay), int(seed))

    progress(0.75, desc="Rendering solutionโ€ฆ")
    env2 = _make_env(size, style, int(seed))
    gif_path = make_solution_gif(env2, agent, fps=7, label=algo_label.split("(")[0].strip())

    progress(0.85, desc="Building chartsโ€ฆ")
    env3 = _make_env(size, style, int(seed))
    path = _collect_path(env3, agent)
    sc = score_run(path, env3.goal, rewards, env3.n_states)

    train_fig = make_training_chart({algo_label.split("(")[0].strip(): rewards})

    env4 = _make_env(size, style, int(seed))
    heatmap_fig = make_qvalue_heatmap(env4, agent)

    stats_md = f"""
### {sc['grade']} โ€” {sc['verdict']}

| | |
|---|---|
| **Solved** | {"โœ… Yes" if sc['solved'] else "โŒ No"} |
| **Steps taken** | `{sc['steps']}` |
| **Efficiency score** | `{sc['efficiency']}%` |
| **Avg reward (final 20%)** | `{sc['avg_reward']:.1f}` |
| **Episodes trained** | `{int(episodes)}` |
| **Maze size** | `{env.shape[0]} ร— {env.shape[1]}` cells |

> **Efficiency** compares your bot's path length to the ideal shortest path.
> 100% = perfect. 0% = didn't make it.
"""
    progress(1.0, desc="Done!")
    return gif_path, train_fig, heatmap_fig, stats_md


# โ”€โ”€ Algorithm Race callback โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def cb_race(
    difficulty: str,
    maze_style: str,
    episodes: int,
    run_mc: bool,
    progress: gr.Progress = gr.Progress(),
):
    size = DIFFICULTY[difficulty]
    style = MAZE_STYLE[maze_style]
    seed = 77

    progress(0.1, desc="Training Q-Learningโ€ฆ")
    env_q = _make_env(size, style, seed)
    _, rq = _train(env_q, "qlearning", int(episodes), 0.1, 0.95, 0.995, seed)

    progress(0.4, desc="Training SARSAโ€ฆ")
    env_s = _make_env(size, style, seed)
    _, rs = _train(env_s, "sarsa", int(episodes), 0.1, 0.95, 0.995, seed)

    rc, name_c = None, ""
    if run_mc:
        progress(0.65, desc="Training Monte Carloโ€ฆ")
        env_m = _make_env(size, style, seed)
        _, rc = _train(env_m, "montecarlo", int(episodes), 0.1, 0.95, 0.995, seed)
        name_c = "Monte Carlo"

    progress(0.9, desc="Building race chartโ€ฆ")
    fig = make_race_chart(rq, "Q-Learning", rs, "SARSA", rc, name_c)

    # Winner
    final_q = float(np.mean(rq[-max(1, len(rq)//5):]))
    final_s = float(np.mean(rs[-max(1, len(rs)//5):]))
    scores = {"Q-Learning": final_q, "SARSA": final_s}
    if rc:
        scores["Monte Carlo"] = float(np.mean(rc[-max(1, len(rc)//5):]))
    winner = max(scores, key=lambda k: scores[k])

    result_md = f"""
### ๐Ÿ† Race Result

| Algorithm | Final Score |
|---|---|
{"".join(f"| {'๐Ÿฅ‡ ' if k==winner else ''}{k} | `{v:.1f}` |" + chr(10) for k,v in scores.items())}

**Winner: {winner}** with a final average reward of `{scores[winner]:.1f}`

> All algorithms trained on the same maze with identical hyperparameters.
> Final score = average reward over the last 20% of episodes.
"""
    progress(1.0)
    return fig, result_md


# โ”€โ”€ CSS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

CSS = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&family=JetBrains+Mono:wght@400;600&display=swap');

*, *::before, *::after { box-sizing: border-box; }

body, .gradio-container {
    background: #0d1117 !important;
    color: #c9d1d9 !important;
    font-family: 'Inter', sans-serif !important;
}
.gradio-container { max-width: 1100px !important; margin: 0 auto !important; }

/* Hero */
.hero { text-align:center; padding:2rem 1rem 1rem; }
.hero-title {
    font-size: clamp(2rem, 5vw, 3rem); font-weight: 700;
    background: linear-gradient(135deg, #3fb950, #58a6ff, #ffa657);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
    margin: 0 0 0.4rem;
}
.hero-sub { color: #484f58; font-size: 0.95rem; letter-spacing:0.02em; }

/* Tabs */
.tab-nav { border-bottom: 1px solid #21262d !important; background: transparent !important; }
.tab-nav button {
    font-family: 'Inter', sans-serif !important; font-size: 0.85rem !important;
    font-weight: 500 !important; color: #484f58 !important;
    background: transparent !important; border: none !important;
    padding: 0.7rem 1.1rem !important;
}
.tab-nav button.selected { color: #3fb950 !important; border-bottom: 2px solid #3fb950 !important; }
.tab-nav button:hover { color: #8b949e !important; }

/* Cards */
.info-card {
    background: #161b22; border: 1px solid #21262d; border-radius: 10px;
    padding: 1.1rem;
}
.info-card-icon { font-size: 1.8rem; margin-bottom:0.4rem; }
.info-card-title { font-weight: 600; color: #e6edf3; font-size: 0.95rem; margin-bottom:0.3rem; }
.info-card-body { color: #8b949e; font-size: 0.83rem; line-height: 1.6; }

/* Algo cards */
.algo-card {
    background: #161b22; border: 1px solid #21262d; border-radius: 10px;
    padding: 1rem; margin-bottom: 0.5rem;
}
.algo-name { font-weight: 600; color: #e6edf3; font-size: 0.9rem; }
.algo-desc { color: #8b949e; font-size: 0.8rem; line-height:1.5; margin-top:0.2rem; }
.algo-tag {
    display: inline-block; font-size: 0.68rem; padding: 2px 8px;
    border-radius: 20px; margin-top: 0.4rem;
}
.tag-green  { background:#0d2d17; color:#3fb950; border:1px solid #1a5c2e; }
.tag-blue   { background:#0d1f38; color:#58a6ff; border:1px solid #1a4a7a; }
.tag-orange { background:#2d1c06; color:#ffa657; border:1px solid #5c3a12; }

/* Grade badge */
.grade-badge {
    display:inline-block; font-size:2.5rem; font-weight:700;
    font-family:'JetBrains Mono',monospace;
}

/* Buttons */
button.primary {
    font-family: 'Inter', sans-serif !important; font-weight: 600 !important;
    background: linear-gradient(135deg, #238636, #2ea043) !important;
    color: #ffffff !important; border: none !important;
    border-radius: 6px !important; font-size: 0.9rem !important;
    transition: opacity 0.2s !important;
}
button.primary:hover { opacity: 0.85 !important; }
button.secondary {
    background: #161b22 !important; color: #58a6ff !important;
    border: 1px solid #30363d !important; border-radius: 6px !important;
    font-family: 'Inter', sans-serif !important;
}
button.stop {
    background: #1c0d0d !important; color: #f78166 !important;
    border: 1px solid #6e2b2b !important; border-radius: 6px !important;
}

/* Labels */
label span { font-family:'Inter',sans-serif !important;
             font-size:0.82rem !important; color:#8b949e !important; }

/* Slider */
input[type=range] { -webkit-appearance:none; height:4px;
                    background:#21262d; border-radius:2px; }
input[type=range]::-webkit-slider-thumb {
    -webkit-appearance:none; width:16px; height:16px;
    border-radius:50%; background:#3fb950; cursor:pointer; border:2px solid #0d1117;
}

/* Textarea */
textarea { font-family:'JetBrains Mono',monospace !important;
           font-size:0.82rem !important; background:#0d1117 !important;
           color:#3fb950 !important; border:1px solid #21262d !important;
           border-radius:6px !important; }

/* Markdown */
.gradio-container h2 { color: #3fb950 !important; }
.gradio-container h3 { color: #58a6ff !important; }
.gradio-container p  { color: #8b949e !important; }
table { width:100%; border-collapse:collapse; }
th { background:#161b22; color:#3fb950; font-size:0.78rem;
     text-align:left; padding:8px 12px; border-bottom:1px solid #21262d; }
td { padding:8px 12px; border-bottom:1px solid #0d1117;
     color:#e6edf3; font-size:0.85rem; }
blockquote { border-left:3px solid #3fb950; padding-left:1rem;
             color:#484f58 !important; margin:0.5rem 0; }

footer { display:none !important; }
.gradio-container .block { background:transparent !important; border:none !important; }
"""

# โ”€โ”€ Build UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

with gr.Blocks(title="๐Ÿค– Maze Runner โ€” RL Playground") as demo:

    gr.HTML("""
    <div class="hero">
        <div class="hero-title">๐Ÿค– Maze Runner</div>
        <div class="hero-sub">An AI that learns to escape mazes โ€” watch it happen in real time</div>
    </div>
    """)

    with gr.Tabs():

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        # Tab 1 โ€” Welcome
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐Ÿ  Welcome"):

            gr.HTML("""
            <div style="text-align:center;padding:0.5rem 0 1.5rem;">
                <p style="color:#8b949e;font-size:1rem;max-width:580px;margin:0 auto;">
                    A tiny AI robot is dropped into a maze. It knows nothing.
                    Through thousands of attempts โ€” hitting walls, finding dead ends,
                    occasionally stumbling upon the exit โ€” it slowly builds a mental map
                    and learns the perfect escape route.
                </p>
            </div>
            """)

            gr.HTML("""
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:1.5rem;">
                <div class="info-card">
                    <div class="info-card-icon">๐Ÿ—บ๏ธ</div>
                    <div class="info-card-title">The Maze</div>
                    <div class="info-card-body">
                        A grid of corridors and walls. The bot starts at
                        <strong style="color:#58a6ff">S</strong> and must reach
                        <strong style="color:#f78166">G</strong>.
                        It can only see its own position โ€” no map, no cheating.
                    </div>
                </div>
                <div class="info-card">
                    <div class="info-card-icon">๐Ÿค–</div>
                    <div class="info-card-title">The Bot</div>
                    <div class="info-card-body">
                        At each step it chooses: go up, down, left, or right.
                        Hit a wall? Penalty. Reach the goal? Big reward!
                        It remembers what worked and what didn't.
                    </div>
                </div>
                <div class="info-card">
                    <div class="info-card-icon">๐Ÿง </div>
                    <div class="info-card-title">The Learning</div>
                    <div class="info-card-body">
                        Each attempt updates a "score table" for every
                        position and move. After enough tries, the bot
                        always picks the move with the highest score โ€” the optimal path.
                    </div>
                </div>
            </div>
            """)

            gr.HTML("""
            <div style="background:#161b22;border:1px solid #21262d;border-radius:10px;padding:1.2rem;margin-bottom:1rem;">
                <div style="font-weight:600;color:#e6edf3;margin-bottom:1rem;">๐Ÿง  Choose your Bot's Brain</div>
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:0.8rem;">
                    <div class="algo-card">
                        <div class="algo-name">Q-Learning</div>
                        <div class="algo-desc">
                            Updates its score table <em>immediately</em> after every step.
                            Fast learner. Best for most mazes.
                        </div>
                        <span class="algo-tag tag-green">โšก Recommended</span>
                    </div>
                    <div class="algo-card">
                        <div class="algo-name">SARSA</div>
                        <div class="algo-desc">
                            Updates based on the move it <em>actually took</em> next,
                            not just the best possible. More cautious, avoids risky paths.
                        </div>
                        <span class="algo-tag tag-blue">๐ŸŽฏ Cautious</span>
                    </div>
                    <div class="algo-card">
                        <div class="algo-name">Monte Carlo</div>
                        <div class="algo-desc">
                            Plays out the <em>entire episode</em> first, then
                            updates everything at once. Needs more episodes to converge.
                        </div>
                        <span class="algo-tag tag-orange">๐ŸŽฒ Explorer</span>
                    </div>
                </div>
            </div>
            """)

            gr.HTML("""
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                <div style="background:#0d2d17;border:1px solid #1a5c2e;border-radius:10px;padding:1rem;">
                    <div style="font-weight:600;color:#3fb950;margin-bottom:0.4rem;">๐Ÿ—บ๏ธ How to use this app</div>
                    <ol style="color:#8b949e;font-size:0.85rem;line-height:1.8;margin:0;padding-left:1.2rem;">
                        <li>Go to <strong style="color:#e6edf3">๐ŸŽฎ Playground</strong> tab</li>
                        <li>Pick a difficulty and maze style</li>
                        <li>Choose a brain and hit <strong style="color:#3fb950">Train & Watch!</strong></li>
                        <li>Watch the animated replay</li>
                        <li>Try <strong style="color:#e6edf3">๐Ÿ Algorithm Race</strong> to compare all three</li>
                    </ol>
                </div>
                <div style="background:#0d1f38;border:1px solid #1a4a7a;border-radius:10px;padding:1rem;">
                    <div style="font-weight:600;color:#58a6ff;margin-bottom:0.4rem;">๐Ÿ’ก Fun facts</div>
                    <ul style="color:#8b949e;font-size:0.85rem;line-height:1.8;margin:0;padding-left:1.2rem;">
                        <li>This same idea trains robots, game AIs, and self-driving cars</li>
                        <li>DeepMind's AlphaGo used a version of Q-Learning</li>
                        <li>A 17ร—17 maze has 289 possible positions to learn</li>
                        <li>The bot gets worse before it gets better โ€” that's normal!</li>
                    </ul>
                </div>
            </div>
            """)

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        # Tab 2 โ€” Playground
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐ŸŽฎ Playground"):

            gr.HTML("""
            <div style="padding:0.3rem 0 1rem;">
                <div style="font-size:1.05rem;font-weight:600;color:#e6edf3;">
                    Build a maze, pick a brain, watch it learn
                </div>
                <div style="color:#484f58;font-size:0.85rem;margin-top:0.2rem;">
                    The animated replay shows the final learned path after training.
                </div>
            </div>
            """)

            with gr.Row():
                # โ”€โ”€ Controls โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
                with gr.Column(scale=1, min_width=300):

                    gr.HTML('<div style="font-size:0.75rem;font-weight:600;color:#484f58;text-transform:uppercase;letter-spacing:0.1em;margin-bottom:0.5rem;">๐Ÿ—บ๏ธ MAZE SETUP</div>')

                    difficulty = gr.Radio(
                        list(DIFFICULTY.keys()),
                        value="๐Ÿข Medium  (9ร—9)",
                        label="Difficulty",
                    )
                    maze_style = gr.Radio(
                        list(MAZE_STYLE.keys()),
                        value="๐Ÿฐ Corridors  (DFS)",
                        label="Maze style",
                        info="Corridors = proper winding paths ยท Open = random walls"
                    )

                    gr.HTML('<div style="font-size:0.75rem;font-weight:600;color:#484f58;text-transform:uppercase;letter-spacing:0.1em;margin:0.8rem 0 0.5rem;">๐Ÿง  BOT BRAIN</div>')

                    algo = gr.Radio(
                        list(ALGO_MAP.keys()),
                        value="๐Ÿง  Q-Learning  (recommended)",
                        label="Algorithm",
                    )

                    gr.HTML('<div style="font-size:0.75rem;font-weight:600;color:#484f58;text-transform:uppercase;letter-spacing:0.1em;margin:0.8rem 0 0.5rem;">โš™๏ธ TRAINING</div>')

                    episodes = gr.Slider(100, 3000, value=800, step=100,
                                         label="Training episodes",
                                         info="More = smarter bot, but slower")

                    with gr.Accordion("๐Ÿ”ฌ Advanced settings", open=False):
                        alpha  = gr.Slider(0.01, 0.5,  value=0.1,   step=0.01, label="Learning speed (ฮฑ)")
                        gamma  = gr.Slider(0.5,  0.99, value=0.95,  step=0.01, label="Future planning (ฮณ)")
                        decay  = gr.Slider(0.90, 0.999,value=0.995, step=0.001,label="Exploration decay")
                        seed   = gr.Slider(0,    100,  value=42,    step=1,    label="Random seed")

                    btn_solve = gr.Button("๐Ÿš€ Train & Watch!", variant="primary")

                # โ”€โ”€ Outputs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
                with gr.Column(scale=2):
                    play_stats = gr.Markdown("*Configure your maze and hit Train & Watch!*")

                    with gr.Row():
                        play_gif = gr.Image(
                            label="๐ŸŽฌ Bot solving the maze (animated)",
                            type="filepath", height=360,
                        )

            with gr.Row():
                play_train_fig  = gr.Plot(label="๐Ÿ“ˆ Training progress")
                play_heatmap    = gr.Plot(label="๐ŸŒก๏ธ Q-value map (what the bot learned)")

            # hidden state defaults for advanced
            alpha_h = gr.State(0.1)
            gamma_h = gr.State(0.95)
            decay_h = gr.State(0.995)
            seed_h  = gr.State(42)

            btn_solve.click(
                cb_solve,
                inputs=[difficulty, maze_style, algo, episodes,
                        alpha, gamma, decay, seed],
                outputs=[play_gif, play_train_fig, play_heatmap, play_stats],
            )

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        # Tab 3 โ€” Algorithm Race
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐Ÿ Algorithm Race"):

            gr.HTML("""
            <div style="padding:0.3rem 0 1rem;">
                <div style="font-size:1.05rem;font-weight:600;color:#e6edf3;">
                    Head-to-head: which brain learns fastest?
                </div>
                <div style="color:#484f58;font-size:0.85rem;margin-top:0.2rem;">
                    All algorithms train on the same maze with identical settings โ€”
                    the only variable is the learning strategy.
                </div>
            </div>
            """)

            gr.HTML("""
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:0.8rem;margin-bottom:1rem;">
                <div style="background:#0d2d17;border:1px solid #1a5c2e;border-radius:8px;padding:0.8rem;text-align:center;">
                    <div style="color:#3fb950;font-size:1.2rem;font-weight:700;">Q-Learning</div>
                    <div style="color:#484f58;font-size:0.78rem;margin-top:0.2rem;">Off-policy ยท Fast update ยท Optimistic</div>
                </div>
                <div style="background:#0d1f38;border:1px solid #1a4a7a;border-radius:8px;padding:0.8rem;text-align:center;">
                    <div style="color:#58a6ff;font-size:1.2rem;font-weight:700;">SARSA</div>
                    <div style="color:#484f58;font-size:0.78rem;margin-top:0.2rem;">On-policy ยท Careful update ยท Conservative</div>
                </div>
                <div style="background:#2d1c06;border:1px solid #5c3a12;border-radius:8px;padding:0.8rem;text-align:center;">
                    <div style="color:#ffa657;font-size:1.2rem;font-weight:700;">Monte Carlo</div>
                    <div style="color:#484f58;font-size:0.78rem;margin-top:0.2rem;">Episodic ยท Full return ยท Unbiased</div>
                </div>
            </div>
            """)

            with gr.Row():
                with gr.Column(scale=1, min_width=260):
                    race_diff  = gr.Radio(list(DIFFICULTY.keys()),
                                          value="๐Ÿข Medium  (9ร—9)", label="Maze difficulty")
                    race_style = gr.Radio(list(MAZE_STYLE.keys()),
                                          value="๐Ÿฐ Corridors  (DFS)", label="Maze style")
                    race_eps   = gr.Slider(200, 2000, value=600, step=100,
                                           label="Episodes per algorithm")
                    race_mc    = gr.Checkbox(label="Include Monte Carlo (slower)", value=True)
                    btn_race   = gr.Button("๐Ÿ Start Race!", variant="primary")

                with gr.Column(scale=2):
                    race_result = gr.Markdown("*Click Start Race to run the comparison.*")

            race_fig = gr.Plot(label="Race Results")

            btn_race.click(
                cb_race,
                inputs=[race_diff, race_style, race_eps, race_mc],
                outputs=[race_fig, race_result],
            )

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        # Tab 4 โ€” How it Works
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐Ÿง  How it Works"):

            gr.HTML("""
            <div style="max-width:700px;margin:0 auto;padding:1rem 0;">

            <h2 style="color:#3fb950;font-size:1.3rem;margin-bottom:0.3rem;">The Big Idea</h2>
            <p style="color:#8b949e;line-height:1.7;">
                The bot doesn't know anything about the maze at the start. It just knows
                4 possible moves and gets a number (reward) after each step.
                <strong style="color:#e6edf3">Negative number = bad move. Positive = good move.</strong>
                The goal: find the sequence of moves that gets the most reward.
            </p>

            <h2 style="color:#3fb950;font-size:1.3rem;margin:1.2rem 0 0.3rem;">The Score Table (Q-Table)</h2>
            <p style="color:#8b949e;line-height:1.7;">
                The bot keeps a table with one row per maze cell and 4 columns (one per direction).
                Each entry stores <em>how good it thinks that move is from that cell</em>.
                At the start, everything is 0. After training, the table holds the bot's
                entire learned strategy. The Q-value heatmap in the Playground shows this table visually.
            </p>

            <div style="background:#161b22;border:1px solid #21262d;border-radius:8px;padding:1rem;margin:1rem 0;font-family:'JetBrains Mono',monospace;font-size:0.82rem;color:#3fb950;">
Q[current_cell][move] += learning_speed ร— (<br>
&nbsp;&nbsp;reward_got + future_discount ร— best_Q[next_cell] โˆ’ Q[current_cell][move]<br>
)
            </div>

            <h2 style="color:#3fb950;font-size:1.3rem;margin:1.2rem 0 0.3rem;">Exploration vs Exploitation</h2>
            <p style="color:#8b949e;line-height:1.7;">
                Early in training, the bot tries <strong style="color:#e6edf3">random moves</strong> (exploration)
                โ€” it doesn't know enough to trust its table yet. Over time, it relies more on what
                it's learned (exploitation). This is controlled by <strong style="color:#e6edf3">epsilon (ฮต)</strong>,
                which starts near 1.0 (100% random) and decays toward 0 (always use best known move).
            </p>

            <h2 style="color:#3fb950;font-size:1.3rem;margin:1.2rem 0 0.3rem;">Why does reward go negative first?</h2>
            <p style="color:#8b949e;line-height:1.7;">
                Each step costs โˆ’1 (time penalty) and hitting a wall costs โˆ’5.
                A random bot hits a <em>lot</em> of walls and takes forever to find the exit,
                so early rewards are very negative. As it learns, fewer walls are hit and
                the path shortens โ€” reward climbs toward 0 and eventually turns positive when
                it reliably reaches the goal.
            </p>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.8rem;margin-top:1.2rem;">
                <div style="background:#0d2d17;border:1px solid #1a5c2e;border-radius:8px;padding:0.9rem;">
                    <div style="color:#3fb950;font-weight:600;margin-bottom:0.4rem;">Q-Learning vs SARSA</div>
                    <div style="color:#8b949e;font-size:0.82rem;line-height:1.6;">
                        Q-Learning always updates toward the <em>best possible</em> next action โ€”
                        even if it wouldn't actually take that action. SARSA updates toward
                        the action it <em>will actually take</em>. This makes SARSA more cautious near walls.
                    </div>
                </div>
                <div style="background:#2d1c06;border:1px solid #5c3a12;border-radius:8px;padding:0.9rem;">
                    <div style="color:#ffa657;font-weight:600;margin-bottom:0.4rem;">Why Monte Carlo is slow</div>
                    <div style="color:#8b949e;font-size:0.82rem;line-height:1.6;">
                        MC waits until the episode <em>ends</em> before updating any scores.
                        On large mazes where early episodes never reach the goal,
                        it gets zero signal for a long time. But once it starts solving,
                        its estimates are very accurate.
                    </div>
                </div>
            </div>

            </div>
            """)

    gr.HTML("""
    <div style="text-align:center;color:#21262d;font-size:0.75rem;
                padding:1.5rem 0 0.5rem;border-top:1px solid #161b22;margin-top:1rem;">
        Built with Q-Learning ยท SARSA ยท Monte Carlo ยท Gymnasium ยท Gradio
    </div>
    """)


if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860, share=False, css=CSS)