# 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(""" """, 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""" """ 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: {concept_info.get('name', 'Programming')} {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"""
{concept_info.get('example', 'Example code will appear here')}
""" 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 = "
" # 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"
" # Draw path grid_html += f"
" # Draw obstacles for i in range(actions_needed): grid_html += f"
🌵
" # Draw player grid_html += f"
👦
" # Draw goal grid_html += f"
🏆
" grid_html += "
" 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("
☀️
", unsafe_allow_html=True) st.write("It's a sunny day!") else: st.markdown("
🌧️
", 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 = "
" for i in range(st.session_state.function_used): effect_html += "" effect_html += "
" 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"""
{details.get('emoji', '✨')}

Learning {details.get('name', 'Programming')} Concept

{st.session_state.concept_explanation}

""", 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('', '') .replace('', '') .replace('
', '') .replace('
', ''), "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"""
{details['emoji']}

{details['name']}

{details['description']}

{details['example']}

Explanation: {details.get('explanation', 'Learn how this concept works!')}

""", 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"""
{details.get('emoji', '✨')}

Understanding {details.get('name', 'Programming')} Concept

{st.session_state.concept_explanation}

""", 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()