File size: 33,814 Bytes
63fdfdb
65eb8e4
2d70a3f
688c6f3
 
b65a5e5
 
 
63fdfdb
 
 
 
 
 
 
 
 
 
 
688c6f3
b59006d
688c6f3
63fdfdb
b65a5e5
688c6f3
 
 
 
b65a5e5
688c6f3
 
b65a5e5
b59006d
 
b65a5e5
63fdfdb
b65a5e5
 
 
63fdfdb
b59006d
688c6f3
b59006d
63fdfdb
b65a5e5
63fdfdb
b59006d
688c6f3
b59006d
b65a5e5
b59006d
688c6f3
b59006d
 
 
 
63fdfdb
b59006d
 
63fdfdb
 
 
 
 
 
b59006d
688c6f3
b59006d
63fdfdb
b59006d
63fdfdb
 
 
 
b59006d
688c6f3
b59006d
 
 
63fdfdb
 
b59006d
 
 
 
b65a5e5
b59006d
688c6f3
b59006d
b65a5e5
63fdfdb
b59006d
4541cc1
63fdfdb
 
 
 
 
b59006d
4541cc1
63fdfdb
 
b59006d
63fdfdb
 
b59006d
4541cc1
63fdfdb
 
 
 
b59006d
63fdfdb
 
 
b65a5e5
b59006d
4541cc1
63fdfdb
 
191dcb3
5479f95
63fdfdb
 
b65a5e5
63fdfdb
5479f95
0647136
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
0647136
 
 
 
 
 
63fdfdb
 
5c5482b
 
b65a5e5
63fdfdb
 
b65a5e5
63fdfdb
b65a5e5
 
 
5c5482b
 
63fdfdb
 
 
 
5c5482b
63fdfdb
0647136
b59006d
 
4541cc1
63fdfdb
b59006d
 
 
 
 
63fdfdb
b65a5e5
0647136
b59006d
 
 
 
 
63fdfdb
 
0647136
b59006d
 
 
 
 
63fdfdb
 
0647136
b59006d
 
 
 
 
63fdfdb
 
0647136
63fdfdb
 
 
 
 
 
 
 
4541cc1
b59006d
4541cc1
63fdfdb
 
b65a5e5
63fdfdb
 
 
 
b65a5e5
 
63fdfdb
 
 
 
b65a5e5
 
63fdfdb
 
 
 
b65a5e5
191dcb3
 
63fdfdb
 
 
 
 
 
 
 
 
 
5479f95
b59006d
2d70a3f
b59006d
 
4541cc1
b59006d
b65a5e5
b59006d
4541cc1
b59006d
63fdfdb
b59006d
4541cc1
b59006d
b65a5e5
b59006d
4541cc1
b59006d
63fdfdb
b59006d
 
63fdfdb
 
 
 
b59006d
688c6f3
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c5482b
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b59006d
67aee2f
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
0647136
 
63fdfdb
0647136
b65a5e5
0647136
63fdfdb
0647136
 
 
63fdfdb
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
 
 
 
 
0647136
63fdfdb
0647136
 
 
 
63fdfdb
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
b65a5e5
b59006d
 
63fdfdb
 
b59006d
 
 
 
 
 
63fdfdb
 
b65a5e5
 
11450ed
 
0647136
 
b65a5e5
 
b59006d
 
 
 
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b59006d
 
 
 
 
63fdfdb
4541cc1
b59006d
 
63fdfdb
 
b59006d
 
 
4541cc1
b65a5e5
b59006d
 
 
 
 
 
 
63fdfdb
 
 
 
 
5479f95
63fdfdb
 
 
11450ed
0647136
63fdfdb
 
 
 
0647136
63fdfdb
 
 
 
5c5482b
b65a5e5
2d70a3f
4541cc1
b59006d
 
 
 
 
 
63fdfdb
 
 
b59006d
 
 
63fdfdb
 
 
b59006d
 
34f7b23
63fdfdb
 
 
b59006d
b65a5e5
 
63fdfdb
 
c969520
b59006d
 
2d70a3f
b59006d
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11450ed
63fdfdb
 
 
 
 
 
 
 
 
0647136
63fdfdb
 
 
 
 
 
 
 
 
 
0647136
 
63fdfdb
 
 
 
 
b65a5e5
63fdfdb
b59006d
63fdfdb
 
 
c969520
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0647136
63fdfdb
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
b65a5e5
63fdfdb
 
 
 
 
 
b59006d
2d70a3f
b65a5e5
63fdfdb
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b65a5e5
63fdfdb
 
 
b65a5e5
63fdfdb
 
 
 
 
 
 
 
 
4541cc1
b59006d
 
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# app.py - Learn Python Through Interactive Games
import streamlit as st
import os
import time
import random
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from gtts import gTTS
import base64
import json
import requests
from io import BytesIO
import pygame
import sys
import math
from PIL import Image, ImageDraw
import io

# Configure Streamlit page
st.set_page_config(
    page_title="StoryCoder - Learn Python Through Games",
    page_icon="๐ŸŽฎ",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS with purple/grey color scheme
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&family=Fredoka+One&display=swap');
    
    :root {
        --primary: #7E57C2;
        --secondary: #B39DDB;
        --accent: #D1C4E9;
        --dark: #4527A0;
        --light: #F3E5F5;
        --neutral: #E0E0E0;
    }
    
    body {
        background: linear-gradient(135deg, var(--light) 0%, #EDE7F6 100%);
        font-family: 'Comic Neue', cursive;
        color: #333;
    }
    
    .stApp {
        background: url('https://www.transparenttextures.com/patterns/cartographer.png');
    }
    
    .story-box {
        background-color: white;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 8px 16px rgba(69, 39, 160, 0.15);
        border: 3px solid var(--accent);
        margin-bottom: 25px;
    }
    
    .header {
        color: var(--dark);
        text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
        font-family: 'Fredoka One', cursive;
    }
    
    .concept-card {
        background: linear-gradient(145deg, #ffffff, #f5f5f5);
        border-radius: 15px;
        padding: 20px;
        margin: 15px 0;
        border-left: 5px solid var(--primary);
        box-shadow: 0 4px 12px rgba(126, 87, 194, 0.1);
    }
    
    .stButton>button {
        background: linear-gradient(45deg, var(--primary), var(--secondary));
        color: white;
        border-radius: 20px;
        padding: 12px 28px;
        font-weight: bold;
        font-size: 18px;
        border: none;
        transition: all 0.3s;
        font-family: 'Fredoka One', cursive;
    }
    
    .stButton>button:hover {
        transform: scale(1.05);
        box-shadow: 0 6px 12px rgba(126, 87, 194, 0.2);
    }
    
    .stTextInput>div>div>input {
        border-radius: 15px;
        padding: 14px;
        border: 2px solid var(--accent);
        font-size: 16px;
    }
    
    .tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        overflow-x: auto;
    }
    
    .tab {
        padding: 12px 24px;
        background-color: var(--accent);
        border-radius: 15px;
        cursor: pointer;
        font-weight: bold;
        white-space: nowrap;
        font-family: 'Fredoka One', cursive;
        transition: all 0.3s;
    }
    
    .tab:hover {
        background-color: var(--secondary);
    }
    
    .tab.active {
        background-color: var(--primary);
        color: white;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    @media (max-width: 768px) {
        .tabs {
            flex-wrap: wrap;
        }
    }
    
    .game-container {
        background-color: #f9f5ff;
        border-radius: 20px;
        padding: 25px;
        box-shadow: 0 8px 32px rgba(126, 87, 194, 0.15);
        margin-bottom: 30px;
        position: relative;
        overflow: hidden;
        border: 3px solid var(--accent);
    }
    
    .game-canvas {
        border-radius: 15px;
        overflow: hidden;
        margin: 0 auto;
        display: block;
        max-width: 100%;
        background: #fff;
        box-shadow: 0 6px 16px rgba(0,0,0,0.1);
    }
    
    .character {
        font-size: 48px;
        text-align: center;
        margin: 10px 0;
    }
    
    .audio-player {
        width: 100%;
        margin: 20px 0;
        border-radius: 20px;
        background: #f0f8ff;
        padding: 15px;
    }
    
    .game-preview {
        max-width: 100%;
        border-radius: 15px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
        border: 3px solid var(--accent);
    }
    
    .explanation-box {
        background: linear-gradient(135deg, #f3e5f5, #e8daf0);
        border-radius: 20px;
        padding: 25px;
        margin: 25px 0;
        border-left: 5px solid var(--primary);
        box-shadow: 0 6px 20px rgba(0,0,0,0.08);
    }
    
    .explanation-header {
        color: var(--dark);
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 15px;
    }
    
    .code-block {
        background: #2d2d2d;
        color: #f8f8f2;
        border-radius: 10px;
        padding: 15px;
        font-family: 'Courier New', monospace;
        margin: 15px 0;
        overflow-x: auto;
    }
    
    .concept-highlight {
        background: linear-gradient(120deg, #e0d6f0, #d1c4e9);
        padding: 5px 10px;
        border-radius: 8px;
        font-weight: bold;
        color: var(--dark);
    }
</style>
""", unsafe_allow_html=True)

# Concept database
CONCEPTS = {
    "loop": {
        "name": "Loop",
        "emoji": "๐Ÿ”„",
        "description": "Loops repeat actions multiple times",
        "example": "for i in range(5):\n    print('Hello!')",
        "color": "#7E57C2",
        "explanation": "A loop is like a magic spell that makes something happen again and again. In programming, we use loops when we want to repeat an action multiple times without writing the same code over and over."
    },
    "conditional": {
        "name": "Conditional",
        "emoji": "โ“",
        "description": "Conditionals make decisions in code",
        "example": "if sunny:\n    go_outside()\nelse:\n    stay_inside()",
        "color": "#5E35B1",
        "explanation": "Conditionals are like crossroads in a story where you choose which path to take. In programming, we use 'if' statements to make decisions based on certain conditions, just like choosing what to wear based on the weather."
    },
    "function": {
        "name": "Function",
        "emoji": "โœจ",
        "description": "Functions are reusable blocks of code",
        "example": "def greet(name):\n    print(f'Hello {name}!')",
        "color": "#4527A0",
        "explanation": "Functions are like magic spells you can create and reuse whenever you need them. They help us organize code into reusable blocks so we don't have to write the same thing multiple times."
    },
    "variable": {
        "name": "Variable",
        "emoji": "๐Ÿ“ฆ",
        "description": "Variables store information",
        "example": "score = 10\nplayer = 'Alex'",
        "color": "#7B1FA2",
        "explanation": "Variables are like labeled boxes where you can store information. They help us remember values and use them later in our code, just like remembering a character's name in a story."
    },
    "list": {
        "name": "List",
        "emoji": "๐Ÿ“",
        "description": "Lists store collections of items",
        "example": "fruits = ['apple', 'banana', 'orange']",
        "color": "#6A1B9A",
        "explanation": "Lists are like magical scrolls that can hold multiple items. In programming, we use lists to store collections of related things, like a wizard's inventory of potions."
    }
}

# Game templates
GAME_TEMPLATES = {
    "loop": {
        "name": "Loop Adventure",
        "description": "Help the character repeat actions multiple times to achieve a goal",
        "color": "#7E57C2",
        "instructions": "Press the action button multiple times to complete the task!"
    },
    "conditional": {
        "name": "Decision Quest",
        "description": "Make choices based on conditions to progress through the story",
        "color": "#5E35B1",
        "instructions": "Choose the correct path based on the conditions you see!"
    },
    "function": {
        "name": "Magic Function",
        "description": "Create and use reusable actions to solve challenges",
        "color": "#4527A0",
        "instructions": "Create your function then use it whenever needed!"
    }
}

# Game assets
GAME_ASSETS = {
    "player": "๐Ÿ‘ฆ",
    "obstacle": "๐ŸŒต",
    "goal": "๐Ÿ†",
    "enemy": "๐Ÿ‰",
    "item": "โญ",
    "path": "๐ŸŸฉ",
    "wall": "โฌ›"
}

def analyze_story(story):
    """Analyze story and identify programming concepts"""
    story_lower = story.lower()
    detected_concepts = []
    
    # Check for loops
    if any(word in story_lower for word in ["times", "repeat", "again", "multiple"]):
        detected_concepts.append("loop")
    
    # Check for conditionals
    if any(word in story_lower for word in ["if", "when", "unless", "whether"]):
        detected_concepts.append("conditional")
    
    # Check for functions
    if any(word in story_lower for word in ["make", "create", "do", "perform", "cast"]):
        detected_concepts.append("function")
    
    # Check for variables
    if any(word in story_lower for word in ["is", "has", "set to", "value"]):
        detected_concepts.append("variable")
    
    # Check for lists
    if any(word in story_lower for word in ["and", "many", "several", "collection", "items"]):
        detected_concepts.append("list")
    
    return list(set(detected_concepts))

def extract_count_from_story(story):
    """Extract a number from the story to use in games"""
    for word in story.split():
        if word.isdigit():
            return min(int(word), 10)
    return 3  # Default value

def create_game_preview(concept):
    """Create a preview image for the game"""
    width, height = 400, 300
    img = Image.new('RGB', (width, height), color=(243, 229, 245))
    draw = ImageDraw.Draw(img)
    
    # Draw game elements based on concept
    if concept == "loop":
        # Draw a path with repeated obstacles
        for i in range(5):
            x = 80 + i * 60
            y = 150
            draw.rectangle([x, y, x+30, y+30], fill=(126, 87, 194))
            draw.text((x+10, y+5), GAME_ASSETS["obstacle"], fill=(255, 255, 255), font_size=20)
        
        # Draw player and goal
        draw.text((50, 150), GAME_ASSETS["player"], fill=(69, 39, 160), font_size=30)
        draw.text((350, 150), GAME_ASSETS["goal"], fill=(255, 193, 7), font_size=30)
        
        # Draw title
        draw.text((100, 50), "Loop Adventure", fill=(69, 39, 160), font_size=25)
    
    elif concept == "conditional":
        # Draw two paths
        draw.rectangle([100, 100, 180, 180], fill=(93, 64, 155))
        draw.rectangle([220, 100, 300, 180], fill=(93, 64, 155))
        
        # Draw weather symbols
        draw.text((130, 110), "โ˜€๏ธ", fill=(255, 255, 0), font_size=30)
        draw.text((250, 110), "๐ŸŒง๏ธ", fill=(100, 181, 246), font_size=30)
        
        # Draw items
        draw.text((130, 150), "๐Ÿ˜Ž", fill=(255, 255, 255), font_size=30)
        draw.text((250, 150), "โ˜‚๏ธ", fill=(255, 255, 255), font_size=30)
        
        # Draw title
        draw.text((120, 50), "Decision Quest", fill=(69, 39, 160), font_size=25)
    
    else:  # function
        # Draw magic wand and effects
        draw.text((100, 150), "๐Ÿช„", fill=(126, 87, 194), font_size=40)
        
        # Draw magic effects
        for i in range(3):
            x = 180 + i * 60
            y = 150
            draw.ellipse([x, y, x+40, y+40], fill=(179, 157, 219))
            draw.text((x+10, y+5), "โœจ", fill=(255, 255, 255), font_size=30)
        
        # Draw title
        draw.text((130, 50), "Magic Function", fill=(69, 39, 160), font_size=25)
    
    # Convert to bytes
    buf = io.BytesIO()
    img.save(buf, format='PNG')
    buf.seek(0)
    return buf

def text_to_speech(text, filename="explanation.wav"):
    """Convert text to speech using gTTS"""
    try:
        tts = gTTS(text=text, lang='en')
        tts.save(filename)
        return filename
    except Exception as e:
        st.error(f"Audio creation error: {str(e)}")
        return None

def autoplay_audio(file_path):
    """Autoplay audio in Streamlit"""
    with open(file_path, "rb") as f:
        data = f.read()
        b64 = base64.b64encode(data).decode()
        md = f"""
            <audio autoplay>
            <source src="data:audio/wav;base64,{b64}" type="audio/wav">
            </audio>
            """
        st.markdown(md, unsafe_allow_html=True)

def generate_concept_explanation(story, concept):
    """Generate a detailed explanation of the programming concept with examples"""
    concept_info = CONCEPTS.get(concept, {})
    count = extract_count_from_story(story)
    
    explanation = f"""
    Let me explain what's happening in your story and how it relates to programming!
    
    Your story: "{story[:100]}..."
    
    This story demonstrates the programming concept of: <span class="concept-highlight">{concept_info.get('name', 'Programming')}</span>
    
    {concept_info.get('explanation', 'This is a fundamental programming concept.')}
    
    In your game:
    - You'll see how {concept_info.get('name', 'this concept')} works in action
    - The game is designed around the idea from your story
    
    How it works in code:
    We use {concept_info.get('name', 'this concept')} like this:
    """
    
    # Add code example
    explanation += f"""<div class="code-block">{concept_info.get('example', 'Example code will appear here')}</div>"""
    
    explanation += f"""
    In real life, you might use this concept when:
    - Creating games with repeating actions (loops)
    - Making decisions in apps (conditionals)
    - Building reusable components (functions)
    
    As you play the game, think about how the concept is being used!
    """
    
    return explanation

def create_loop_game(story):
    """Create a loop-based game"""
    actions_needed = extract_count_from_story(story)
    
    # Initialize session state for game
    if 'loop_count' not in st.session_state:
        st.session_state.loop_count = 0
        st.session_state.game_complete = False
    
    # Game layout
    st.subheader("๐Ÿ”„ Loop Adventure Game")
    st.write(f"**Story:** {story[:100]}{'...' if len(story) > 100 else ''}")
    st.write("**Instructions:** Press the action button repeatedly to complete the task!")
    
    # Create game grid
    grid_html = "<div style='display: flex; justify-content: center; margin: 20px 0;'>"
    
    # Player position
    player_pos = min(st.session_state.loop_count, actions_needed)
    player_offset = player_pos * (100 // actions_needed)
    
    # Draw game path
    grid_html += f"<div style='position: relative; width: 400px; height: 100px; background: #EDE7F6; border-radius: 10px; border: 2px solid {CONCEPTS['loop']['color']}'>"
    
    # Draw path
    grid_html += f"<div style='position: absolute; top: 40px; left: 0; width: 100%; height: 20px; background: {CONCEPTS['loop']['color']}; border-radius: 10px;'></div>"
    
    # Draw obstacles
    for i in range(actions_needed):
        grid_html += f"<div style='position: absolute; top: 30px; left: {i * (400 // actions_needed)}px; font-size: 24px;'>๐ŸŒต</div>"
    
    # Draw player
    grid_html += f"<div style='position: absolute; top: 20px; left: {player_offset}px; font-size: 36px;'>๐Ÿ‘ฆ</div>"
    
    # Draw goal
    grid_html += f"<div style='position: absolute; top: 20px; left: 380px; font-size: 36px;'>๐Ÿ†</div>"
    
    grid_html += "</div></div>"
    
    st.markdown(grid_html, unsafe_allow_html=True)
    
    # Action button
    if st.session_state.game_complete:
        st.success("๐ŸŽ‰ You completed the game! Great job using loops!")
        if st.button("Play Again", key="loop_restart"):
            st.session_state.loop_count = 0
            st.session_state.game_complete = False
            st.rerun()
    else:
        if st.button(f"Perform Action ({st.session_state.loop_count}/{actions_needed})", key="loop_action"):
            st.session_state.loop_count += 1
            if st.session_state.loop_count >= actions_needed:
                st.session_state.game_complete = True
            st.rerun()

def create_conditional_game(story):
    """Create a conditional-based game"""
    # Initialize session state for game
    if 'conditional_choice' not in st.session_state:
        st.session_state.conditional_choice = None
        st.session_state.game_complete = False
        st.session_state.weather = random.choice(["sunny", "rainy"])
    
    # Game layout
    st.subheader("โ“ Decision Quest Game")
    st.write(f"**Story:** {story[:100]}{'...' if len(story) > 100 else ''}")
    st.write("**Instructions:** Choose the correct item based on the weather condition!")
    
    # Display weather
    col1, col2 = st.columns([1, 2])
    with col1:
        st.subheader("Current Weather:")
        if st.session_state.weather == "sunny":
            st.markdown("<div style='font-size: 48px; text-align: center;'>โ˜€๏ธ</div>", unsafe_allow_html=True)
            st.write("It's a sunny day!")
        else:
            st.markdown("<div style='font-size: 48px; text-align: center;'>๐ŸŒง๏ธ</div>", unsafe_allow_html=True)
            st.write("It's a rainy day!")
    
    with col2:
        st.subheader("Choose Your Item:")
        
        if not st.session_state.game_complete:
            if st.button("๐Ÿ˜Ž Sunglasses", key="sunglasses", use_container_width=True):
                st.session_state.conditional_choice = "sunglasses"
                st.session_state.game_complete = True
                st.rerun()
            
            if st.button("โ˜‚๏ธ Umbrella", key="umbrella", use_container_width=True):
                st.session_state.conditional_choice = "umbrella"
                st.session_state.game_complete = True
                st.rerun()
        else:
            if st.session_state.weather == "sunny" and st.session_state.conditional_choice == "sunglasses":
                st.success("๐ŸŽ‰ Correct choice! You wore sunglasses on a sunny day!")
            elif st.session_state.weather == "rainy" and st.session_state.conditional_choice == "umbrella":
                st.success("๐ŸŽ‰ Correct choice! You took an umbrella on a rainy day!")
            else:
                st.error("โŒ Oops! That wasn't the right choice for this weather.")
            
            if st.button("Play Again", key="conditional_restart"):
                st.session_state.conditional_choice = None
                st.session_state.game_complete = False
                st.session_state.weather = random.choice(["sunny", "rainy"])
                st.rerun()

def create_function_game(story):
    """Create a function-based game"""
    actions_needed = extract_count_from_story(story)
    
    # Initialize session state for game
    if 'function_created' not in st.session_state:
        st.session_state.function_created = False
        st.session_state.function_used = 0
        st.session_state.game_complete = False
    
    # Game layout
    st.subheader("โœจ Magic Function Game")
    st.write(f"**Story:** {story[:100]}{'...' if len(story) > 100 else ''}")
    st.write("**Instructions:** Create your function then use it to solve the challenge!")
    
    # Game area
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("Your Function")
        if not st.session_state.function_created:
            st.write("Create your magic function:")
            if st.button("โœจ Create Magic Function", key="create_func", use_container_width=True):
                st.session_state.function_created = True
                st.rerun()
        else:
            st.success("Function created!")
            st.code("def magic_spell():\n    print('โœจ Magic happens!')", language="python")
    
    with col2:
        st.subheader("Cast Your Spell")
        if st.session_state.function_created:
            st.write(f"Use your function to complete the task ({st.session_state.function_used}/{actions_needed}):")
            if st.button("๐Ÿ”ฎ Cast Spell", key="cast_spell", use_container_width=True):
                st.session_state.function_used += 1
                if st.session_state.function_used >= actions_needed:
                    st.session_state.game_complete = True
                st.rerun()
            
            # Visual effects
            effect_html = "<div style='text-align: center; margin-top: 20px;'>"
            for i in range(st.session_state.function_used):
                effect_html += "<span style='font-size: 36px; margin: 5px;'>โœจ</span>"
            effect_html += "</div>"
            st.markdown(effect_html, unsafe_allow_html=True)
    
    if st.session_state.game_complete:
        st.success("๐ŸŽ‰ You completed the game by reusing your function! Great job!")
        if st.button("Play Again", key="function_restart"):
            st.session_state.function_created = False
            st.session_state.function_used = 0
            st.session_state.game_complete = False
            st.rerun()

def main():
    """Main application function"""
    st.title("๐ŸŽฎ StoryCoder - Learn Python Through Games!")
    st.subheader("Turn your story into a game and discover coding secrets with interactive gameplay!")
    
    # Initialize session state
    if 'story' not in st.session_state:
        st.session_state.story = ""
    if 'concepts' not in st.session_state:
        st.session_state.concepts = []
    if 'game_type' not in st.session_state:
        st.session_state.game_type = None
    if 'concept_explanation' not in st.session_state:
        st.session_state.concept_explanation = ""
    if 'audio_file' not in st.session_state:
        st.session_state.audio_file = None
    if 'explanation_audio' not in st.session_state:
        st.session_state.explanation_audio = None
    if 'active_tab' not in st.session_state:
        st.session_state.active_tab = "story"
    
    # Create tabs
    tabs = st.empty()
    tab_cols = st.columns(5)
    with tab_cols[0]:
        if st.button("๐Ÿ“– Create Story"):
            st.session_state.active_tab = "story"
    with tab_cols[1]:
        if st.button("๐ŸŽฎ Play Game"):
            st.session_state.active_tab = "game"
    with tab_cols[2]:
        if st.button("๐Ÿ” Concepts"):
            st.session_state.active_tab = "concepts"
    with tab_cols[3]:
        if st.button("๐Ÿ’ก Explain"):
            st.session_state.active_tab = "explain"
    with tab_cols[4]:
        if st.button("๐Ÿ”„ Reset"):
            st.session_state.story = ""
            st.session_state.concepts = []
            st.session_state.game_type = None
            st.session_state.concept_explanation = ""
            st.session_state.audio_file = None
            st.session_state.explanation_audio = None
            st.session_state.active_tab = "story"
    
    # Story creation tab
    if st.session_state.active_tab == "story":
        with st.container():
            st.header("๐Ÿ“– Create Your Story")
            st.write("Write a short story (2-5 sentences) and I'll turn it into an interactive game!")
            
            story = st.text_area(
                "Your story:",
                height=200,
                placeholder="Once upon a time, a rabbit hopped 3 times to reach a carrot...",
                value=st.session_state.story,
                key="story_input"
            )
            
            if st.button("Create Game!", use_container_width=True):
                if len(story) < 10:
                    st.error("Your story needs to be at least 10 characters long!")
                else:
                    st.session_state.story = story
                    with st.spinner("๐Ÿง  Analyzing your story for coding concepts..."):
                        st.session_state.concepts = analyze_story(story)
                    
                    if not st.session_state.concepts:
                        st.warning("No coding concepts detected! Using a default game.")
                        st.session_state.game_type = "loop"
                    else:
                        st.session_state.game_type = st.session_state.concepts[0]
                    
                    with st.spinner("๐ŸŽฎ Creating your interactive game..."):
                        # Just a delay for effect
                        time.sleep(1)
                    
                    with st.spinner("๐Ÿง  Generating concept explanation..."):
                        st.session_state.concept_explanation = generate_concept_explanation(
                            story, 
                            st.session_state.game_type
                        )
                    
                    with st.spinner("๐Ÿ”Š Creating audio narration..."):
                        st.session_state.audio_file = text_to_speech(
                            f"Your story: {story}. Let's play a game to learn programming!"
                        )
                    
                    st.session_state.active_tab = "game"
                    st.rerun()
            
            # Show examples
            st.subheader("โœจ Story Examples")
            col1, col2, col3 = st.columns(3)
            with col1:
                st.caption("Loop Example")
                st.code('"A dragon breathes fire 5 times at the castle"', language="text")
                st.image(create_game_preview("loop"), 
                         use_container_width=True, 
                         caption="Loop Adventure Game Preview")
            with col2:
                st.caption("Conditional Example")
                st.code('"If it rains, the cat stays inside, else it goes out"', language="text")
                st.image(create_game_preview("conditional"), 
                         use_container_width=True, 
                         caption="Decision Quest Game Preview")
            with col3:
                st.caption("Function Example")
                st.code('"A wizard casts a spell to make flowers grow"', language="text")
                st.image(create_game_preview("function"), 
                         use_container_width=True, 
                         caption="Magic Function Game Preview")
    
    # Game tab
    elif st.session_state.active_tab == "game":
        st.header(f"๐ŸŽฎ Your Story Game: {GAME_TEMPLATES.get(st.session_state.game_type, {}).get('name', 'Coding Adventure')}")
        
        if not st.session_state.story:
            st.warning("Please create a story first!")
            st.session_state.active_tab = "story"
            st.rerun()
        
        # Display game based on concept
        if st.session_state.game_type == "loop":
            create_loop_game(st.session_state.story)
        elif st.session_state.game_type == "conditional":
            create_conditional_game(st.session_state.story)
        elif st.session_state.game_type == "function":
            create_function_game(st.session_state.story)
        else:
            # Default to loop game
            create_loop_game(st.session_state.story)
        
        # Concept explanation section
        if st.session_state.concept_explanation:
            st.subheader("๐ŸŽ“ What You're Learning")
            concept = st.session_state.game_type
            details = CONCEPTS.get(concept, {})
            
            st.markdown(f"""
            <div class="explanation-box">
                <div class="explanation-header">
                    <span style="font-size:36px;">{details.get('emoji', 'โœจ')}</span>
                    <h3>Learning {details.get('name', 'Programming')} Concept</h3>
                </div>
                <p>{st.session_state.concept_explanation}</p>
            </div>
            """, unsafe_allow_html=True)
            
            # Generate explanation audio if not already generated
            if not st.session_state.explanation_audio:
                with st.spinner("๐Ÿ”Š Creating concept explanation audio..."):
                    st.session_state.explanation_audio = text_to_speech(
                        st.session_state.concept_explanation.replace('<span class="concept-highlight">', '')
                                                             .replace('</span>', '')
                                                             .replace('<div class="code-block">', '')
                                                             .replace('</div>', ''),
                        "concept_explanation.wav"
                    )
            
            if st.session_state.explanation_audio:
                st.markdown("### ๐Ÿ”Š Concept Explanation")
                with open(st.session_state.explanation_audio, "rb") as f:
                    audio_bytes = f.read()
                st.audio(audio_bytes, format='audio/wav')
                
                if st.button("โ–ถ๏ธ Play Explanation", use_container_width=True):
                    autoplay_audio(st.session_state.explanation_audio)
    
    # Concepts tab
    elif st.session_state.active_tab == "concepts":
        st.header("๐Ÿ” Coding Concepts in Your Story")
        
        if not st.session_state.concepts:
            st.warning("No concepts detected in your story! Try adding words like '3 times', 'if', or 'make'.")
        else:
            st.subheader("We used these programming concepts in your game:")
            for concept in st.session_state.concepts:
                if concept in CONCEPTS:
                    details = CONCEPTS[concept]
                    st.markdown(f"""
                    <div class="concept-card">
                        <div style="display:flex; align-items:center; gap:15px;">
                            <span style="font-size:36px;">{details['emoji']}</span>
                            <h3 style="color:{details['color']};">{details['name']}</h3>
                        </div>
                        <p>{details['description']}</p>
                        <div class="code-block">{details['example']}</div>
                        <p><strong>Explanation:</strong> {details.get('explanation', 'Learn how this concept works!')}</p>
                    </div>
                    """, unsafe_allow_html=True)
        
        # Play explanation if available
        if st.session_state.explanation_audio:
            st.subheader("๐Ÿ”Š Concept Explanation")
            with open(st.session_state.explanation_audio, "rb") as f:
                audio_bytes = f.read()
            st.audio(audio_bytes, format='audio/wav')
            
            if st.button("โ–ถ๏ธ Play Full Explanation", use_container_width=True):
                autoplay_audio(st.session_state.explanation_audio)
    
    # Explanation tab
    elif st.session_state.active_tab == "explain":
        st.header("๐Ÿ’ก Interactive Concept Explanation")
        
        if not st.session_state.concept_explanation:
            st.warning("Please create a story first to generate explanations!")
            st.session_state.active_tab = "story"
            st.rerun()
        
        st.subheader("๐Ÿง  Deep Dive into Programming Concepts")
        
        if st.session_state.concepts:
            concept = st.session_state.concepts[0]
            details = CONCEPTS.get(concept, {})
            
            st.markdown(f"""
            <div class="explanation-box">
                <div class="explanation-header">
                    <span style="font-size:36px;">{details.get('emoji', 'โœจ')}</span>
                    <h3>Understanding {details.get('name', 'Programming')} Concept</h3>
                </div>
                <p>{st.session_state.concept_explanation}</p>
            </div>
            """, unsafe_allow_html=True)
            
            # Visual example
            st.subheader("๐ŸŽฎ How It Works in Your Game")
            if concept == "loop":
                st.image("https://media.giphy.com/media/3o7abKhOpu0NwenH3O/giphy.gif", 
                         use_column_width=True, caption="Loop Concept in Action")
            elif concept == "conditional":
                st.image("https://media.giphy.com/media/l0HlG8vJXW0X5yX4s/giphy.gif", 
                         use_column_width=True, caption="Conditional Concept in Action")
            else:
                st.image("https://media.giphy.com/media/3o7TKsQ8UQ4l4LhGz6/giphy.gif", 
                         use_column_width=True, caption="Function Concept in Action")
            
            # Real-world examples
            st.subheader("๐ŸŒ Real-World Examples")
            if concept == "loop":
                st.write("- Video games that have repeating levels or enemies")
                st.write("- Apps that process multiple items (like photos in a gallery)")
                st.write("- Animations that need to run continuously")
            elif concept == "conditional":
                st.write("- Weather apps that show different outfits based on temperature")
                st.write("- Games that change difficulty based on player skill")
                st.write("- Apps that display different content based on user preferences")
            else:
                st.write("- Calculator apps with reusable operations")
                st.write("- Games with special moves that can be used repeatedly")
                st.write("- Websites with reusable components like buttons and menus")
            
            # Play explanation audio
            if st.session_state.explanation_audio:
                st.subheader("๐Ÿ”Š Listen to the Explanation")
                with open(st.session_state.explanation_audio, "rb") as f:
                    audio_bytes = f.read()
                st.audio(audio_bytes, format='audio/wav')
                
                if st.button("โ–ถ๏ธ Play Explanation", use_container_width=True):
                    autoplay_audio(st.session_state.explanation_audio)

if __name__ == "__main__":
    main()