sunbal7's picture
Update app.py
63fdfdb verified
raw
history blame
33.8 kB
# 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()