Spaces:
Running
Running
Delete app.py
Browse files
app.py
DELETED
@@ -1,698 +0,0 @@
|
|
1 |
-
# app.py - Game-Based Learning Version
|
2 |
-
import streamlit as st
|
3 |
-
import os
|
4 |
-
import time
|
5 |
-
import random
|
6 |
-
import base64
|
7 |
-
import json
|
8 |
-
import requests
|
9 |
-
import re
|
10 |
-
from PIL import Image
|
11 |
-
import io
|
12 |
-
import matplotlib.pyplot as plt
|
13 |
-
import numpy as np
|
14 |
-
import pandas as pd
|
15 |
-
import plotly.express as px
|
16 |
-
import plotly.graph_objects as go
|
17 |
-
|
18 |
-
# Configure Streamlit page
|
19 |
-
st.set_page_config(
|
20 |
-
page_title="StoryCoder - Learn Coding Through Games",
|
21 |
-
page_icon="🧙♂️",
|
22 |
-
layout="wide",
|
23 |
-
initial_sidebar_state="expanded"
|
24 |
-
)
|
25 |
-
|
26 |
-
# Custom CSS for colorful UI
|
27 |
-
st.markdown("""
|
28 |
-
<style>
|
29 |
-
@import url('https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&display=swap');
|
30 |
-
|
31 |
-
:root {
|
32 |
-
--primary: #FF6B6B;
|
33 |
-
--secondary: #4ECDC4;
|
34 |
-
--accent: #FFD166;
|
35 |
-
--dark: #1A535C;
|
36 |
-
--light: #F7FFF7;
|
37 |
-
}
|
38 |
-
|
39 |
-
body {
|
40 |
-
background: linear-gradient(135deg, var(--light) 0%, #E8F4F8 100%);
|
41 |
-
font-family: 'Comic Neue', cursive;
|
42 |
-
}
|
43 |
-
|
44 |
-
.stApp {
|
45 |
-
background: url('https://www.transparenttextures.com/patterns/cartographer.png');
|
46 |
-
}
|
47 |
-
|
48 |
-
.story-box {
|
49 |
-
background-color: white;
|
50 |
-
border-radius: 20px;
|
51 |
-
padding: 25px;
|
52 |
-
box-shadow: 0 8px 16px rgba(26, 83, 92, 0.15);
|
53 |
-
border: 3px solid var(--accent);
|
54 |
-
margin-bottom: 25px;
|
55 |
-
}
|
56 |
-
|
57 |
-
.header {
|
58 |
-
color: var(--dark);
|
59 |
-
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
|
60 |
-
}
|
61 |
-
|
62 |
-
.concept-card {
|
63 |
-
background: linear-gradient(145deg, #ffffff, #f0f0f0);
|
64 |
-
border-radius: 15px;
|
65 |
-
padding: 15px;
|
66 |
-
margin: 10px 0;
|
67 |
-
border-left: 5px solid var(--secondary);
|
68 |
-
box-shadow: 0 4px 8px rgba(0,0,0,0.05);
|
69 |
-
}
|
70 |
-
|
71 |
-
.stButton>button {
|
72 |
-
background: linear-gradient(45deg, var(--primary), var(--secondary));
|
73 |
-
color: white;
|
74 |
-
border-radius: 12px;
|
75 |
-
padding: 10px 24px;
|
76 |
-
font-weight: bold;
|
77 |
-
font-size: 18px;
|
78 |
-
border: none;
|
79 |
-
transition: all 0.3s;
|
80 |
-
}
|
81 |
-
|
82 |
-
.stButton>button:hover {
|
83 |
-
transform: scale(1.05);
|
84 |
-
box-shadow: 0 6px 12px rgba(0,0,0,0.15);
|
85 |
-
}
|
86 |
-
|
87 |
-
.stTextInput>div>div>input {
|
88 |
-
border-radius: 12px;
|
89 |
-
padding: 12px;
|
90 |
-
border: 2px solid var(--accent);
|
91 |
-
}
|
92 |
-
|
93 |
-
.tabs {
|
94 |
-
display: flex;
|
95 |
-
gap: 10px;
|
96 |
-
margin-bottom: 20px;
|
97 |
-
overflow-x: auto;
|
98 |
-
}
|
99 |
-
|
100 |
-
.tab {
|
101 |
-
padding: 10px 20px;
|
102 |
-
background-color: var(--accent);
|
103 |
-
border-radius: 10px;
|
104 |
-
cursor: pointer;
|
105 |
-
font-weight: bold;
|
106 |
-
white-space: nowrap;
|
107 |
-
}
|
108 |
-
|
109 |
-
.tab.active {
|
110 |
-
background-color: var(--secondary);
|
111 |
-
color: white;
|
112 |
-
}
|
113 |
-
|
114 |
-
@media (max-width: 768px) {
|
115 |
-
.tabs {
|
116 |
-
flex-wrap: wrap;
|
117 |
-
}
|
118 |
-
}
|
119 |
-
|
120 |
-
.game-container {
|
121 |
-
background-color: #1a1a2e;
|
122 |
-
border-radius: 15px;
|
123 |
-
padding: 20px;
|
124 |
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
125 |
-
margin-bottom: 25px;
|
126 |
-
position: relative;
|
127 |
-
overflow: hidden;
|
128 |
-
}
|
129 |
-
|
130 |
-
.game-preview {
|
131 |
-
border-radius: 10px;
|
132 |
-
overflow: hidden;
|
133 |
-
margin: 0 auto;
|
134 |
-
display: block;
|
135 |
-
max-width: 100%;
|
136 |
-
}
|
137 |
-
|
138 |
-
.character {
|
139 |
-
font-size: 48px;
|
140 |
-
text-align: center;
|
141 |
-
margin: 10px 0;
|
142 |
-
}
|
143 |
-
|
144 |
-
.game-instructions {
|
145 |
-
background-color: #f0f8ff;
|
146 |
-
border-radius: 15px;
|
147 |
-
padding: 15px;
|
148 |
-
margin: 15px 0;
|
149 |
-
}
|
150 |
-
|
151 |
-
.ai-game {
|
152 |
-
border: 3px solid var(--accent);
|
153 |
-
border-radius: 15px;
|
154 |
-
padding: 15px;
|
155 |
-
background: white;
|
156 |
-
margin: 20px 0;
|
157 |
-
}
|
158 |
-
</style>
|
159 |
-
""", unsafe_allow_html=True)
|
160 |
-
|
161 |
-
# Concept database
|
162 |
-
CONCEPTS = {
|
163 |
-
"loop": {
|
164 |
-
"name": "Loop",
|
165 |
-
"emoji": "🔄",
|
166 |
-
"description": "Loops repeat actions multiple times",
|
167 |
-
"example": "for i in range(5):\n print('Hello!')",
|
168 |
-
"color": "#FF9E6D"
|
169 |
-
},
|
170 |
-
"conditional": {
|
171 |
-
"name": "Conditional",
|
172 |
-
"emoji": "❓",
|
173 |
-
"description": "Conditionals make decisions in code",
|
174 |
-
"example": "if sunny:\n go_outside()\nelse:\n stay_inside()",
|
175 |
-
"color": "#4ECDC4"
|
176 |
-
},
|
177 |
-
"function": {
|
178 |
-
"name": "Function",
|
179 |
-
"emoji": "✨",
|
180 |
-
"description": "Functions are reusable blocks of code",
|
181 |
-
"example": "def greet(name):\n print(f'Hello {name}!')",
|
182 |
-
"color": "#FFD166"
|
183 |
-
},
|
184 |
-
"variable": {
|
185 |
-
"name": "Variable",
|
186 |
-
"emoji": "📦",
|
187 |
-
"description": "Variables store information",
|
188 |
-
"example": "score = 10\nplayer = 'Alex'",
|
189 |
-
"color": "#FF6B6B"
|
190 |
-
},
|
191 |
-
"list": {
|
192 |
-
"name": "List",
|
193 |
-
"emoji": "📝",
|
194 |
-
"description": "Lists store collections of items",
|
195 |
-
"example": "fruits = ['apple', 'banana', 'orange']",
|
196 |
-
"color": "#1A535C"
|
197 |
-
}
|
198 |
-
}
|
199 |
-
|
200 |
-
# Pre-generated game examples
|
201 |
-
GAME_EXAMPLES = {
|
202 |
-
"loop": {
|
203 |
-
"image": "https://i.imgur.com/7zQY1eE.gif",
|
204 |
-
"description": "Collect coins in a looping maze"
|
205 |
-
},
|
206 |
-
"conditional": {
|
207 |
-
"image": "https://i.imgur.com/5X8jYAy.gif",
|
208 |
-
"description": "Avoid obstacles by making decisions"
|
209 |
-
},
|
210 |
-
"function": {
|
211 |
-
"image": "https://i.imgur.com/9zJkQ7P.gif",
|
212 |
-
"description": "Cast spells using reusable functions"
|
213 |
-
}
|
214 |
-
}
|
215 |
-
|
216 |
-
# Initialize Groq client
|
217 |
-
def get_groq_client():
|
218 |
-
api_key = st.secrets.get("GROQ_API_KEY", "")
|
219 |
-
if not api_key:
|
220 |
-
st.warning("Groq API key not found. Some features may be limited.")
|
221 |
-
return None
|
222 |
-
try:
|
223 |
-
from groq import Groq
|
224 |
-
return Groq(api_key=api_key)
|
225 |
-
except ImportError:
|
226 |
-
st.error("Groq library not installed. Please install with `pip install groq`")
|
227 |
-
return None
|
228 |
-
except Exception as e:
|
229 |
-
st.error(f"Error initializing Groq client: {str(e)}")
|
230 |
-
return None
|
231 |
-
|
232 |
-
# Analyze story and identify programming concepts
|
233 |
-
def analyze_story(story):
|
234 |
-
story_lower = story.lower()
|
235 |
-
detected_concepts = []
|
236 |
-
|
237 |
-
# Check for loops
|
238 |
-
if any(word in story_lower for word in ["times", "repeat", "again", "multiple", "many"]):
|
239 |
-
detected_concepts.append("loop")
|
240 |
-
|
241 |
-
# Check for conditionals
|
242 |
-
if any(word in story_lower for word in ["if", "when", "unless", "whether", "decision"]):
|
243 |
-
detected_concepts.append("conditional")
|
244 |
-
|
245 |
-
# Check for functions
|
246 |
-
if any(word in story_lower for word in ["make", "create", "do", "perform", "cast", "spell"]):
|
247 |
-
detected_concepts.append("function")
|
248 |
-
|
249 |
-
# Check for variables
|
250 |
-
if any(word in story_lower for word in ["is", "has", "set to", "value", "store"]):
|
251 |
-
detected_concepts.append("variable")
|
252 |
-
|
253 |
-
# Check for lists
|
254 |
-
if any(word in story_lower for word in ["and", "many", "several", "collection", "items", "group"]):
|
255 |
-
detected_concepts.append("list")
|
256 |
-
|
257 |
-
return list(set(detected_concepts))
|
258 |
-
|
259 |
-
# Extract entities from story using regex
|
260 |
-
def extract_entities(story):
|
261 |
-
entities = {
|
262 |
-
"characters": [],
|
263 |
-
"objects": [],
|
264 |
-
"actions": [],
|
265 |
-
"locations": []
|
266 |
-
}
|
267 |
-
|
268 |
-
# Extract characters (proper nouns)
|
269 |
-
entities["characters"] = list(set(re.findall(r'\b[A-Z][a-z]+\b', story)))
|
270 |
-
|
271 |
-
# Extract objects (nouns after "the")
|
272 |
-
entities["objects"] = list(set(re.findall(r'\bthe\s+(\w+)', story, re.I)))
|
273 |
-
|
274 |
-
# Extract actions (verbs)
|
275 |
-
entities["actions"] = list(set(re.findall(r'\b(\w+ed|\w+ing)\b', story)))
|
276 |
-
|
277 |
-
# Extract locations (nouns after "in", "on", "at")
|
278 |
-
entities["locations"] = list(set(re.findall(r'\b(in|on|at)\s+the?\s?(\w+)', story)))
|
279 |
-
|
280 |
-
# Filter out common words
|
281 |
-
common_words = ["the", "a", "an", "and", "or", "but", "if", "then", "when", "where"]
|
282 |
-
for key in entities:
|
283 |
-
entities[key] = [word for word in entities[key] if word.lower() not in common_words and len(word) > 2]
|
284 |
-
|
285 |
-
return entities
|
286 |
-
|
287 |
-
# Generate game concept using Groq
|
288 |
-
def generate_game_concept(story, concepts, entities):
|
289 |
-
groq_client = get_groq_client()
|
290 |
-
if not groq_client:
|
291 |
-
return {
|
292 |
-
"title": "Adventure Game",
|
293 |
-
"description": "An exciting game based on your story!",
|
294 |
-
"mechanics": "Collect items and avoid obstacles",
|
295 |
-
"code_concepts": ", ".join(concepts),
|
296 |
-
"instructions": "Use arrow keys to move and space to jump"
|
297 |
-
}
|
298 |
-
|
299 |
-
try:
|
300 |
-
prompt = f"""
|
301 |
-
You are a game designer creating educational games for kids aged 6-12.
|
302 |
-
Create a simple 2D game concept based on the following story:
|
303 |
-
|
304 |
-
Story: "{story}"
|
305 |
-
|
306 |
-
Programming concepts to include: {', '.join(concepts)}
|
307 |
-
|
308 |
-
Extracted entities:
|
309 |
-
- Characters: {', '.join(entities['characters'])}
|
310 |
-
- Objects: {', '.join(entities['objects'])}
|
311 |
-
- Actions: {', '.join(entities['actions'])}
|
312 |
-
- Locations: {', '.join([loc[1] for loc in entities['locations']])}
|
313 |
-
|
314 |
-
Respond in JSON format with these keys:
|
315 |
-
- title: Game title (max 5 words)
|
316 |
-
- description: Game description (1-2 sentences)
|
317 |
-
- mechanics: Core game mechanics (1 sentence)
|
318 |
-
- code_concepts: How programming concepts are used in the game
|
319 |
-
- instructions: Simple game controls (max 10 words)
|
320 |
-
"""
|
321 |
-
|
322 |
-
response = groq_client.chat.completions.create(
|
323 |
-
model="llama3-8b-8192",
|
324 |
-
messages=[{"role": "user", "content": prompt}],
|
325 |
-
temperature=0.7,
|
326 |
-
max_tokens=512,
|
327 |
-
response_format={"type": "json_object"}
|
328 |
-
)
|
329 |
-
|
330 |
-
game_data = json.loads(response.choices[0].message.content)
|
331 |
-
return game_data
|
332 |
-
|
333 |
-
except Exception as e:
|
334 |
-
st.error(f"Game concept generation error: {str(e)}")
|
335 |
-
return {
|
336 |
-
"title": "Adventure Game",
|
337 |
-
"description": "An exciting game based on your story!",
|
338 |
-
"mechanics": "Collect items and avoid obstacles",
|
339 |
-
"code_concepts": ", '.join(concepts)",
|
340 |
-
"instructions": "Use arrow keys to move and space to jump"
|
341 |
-
}
|
342 |
-
|
343 |
-
# Generate game code using Groq
|
344 |
-
def generate_game_code(story, game_concept):
|
345 |
-
groq_client = get_groq_client()
|
346 |
-
if not groq_client:
|
347 |
-
return "# Error: Groq client not available", ""
|
348 |
-
|
349 |
-
try:
|
350 |
-
prompt = f"""
|
351 |
-
You are a Python game developer creating educational games for kids using Pygame.
|
352 |
-
Create a simple 2D game based on the following concept:
|
353 |
-
|
354 |
-
Game Title: {game_concept['title']}
|
355 |
-
Description: {game_concept['description']}
|
356 |
-
Mechanics: {game_concept['mechanics']}
|
357 |
-
Instructions: {game_concept['instructions']}
|
358 |
-
|
359 |
-
Requirements:
|
360 |
-
- Use Pygame library
|
361 |
-
- Simple graphics (shapes and colors)
|
362 |
-
- Include at least one character the player controls
|
363 |
-
- Include collectible items
|
364 |
-
- Include obstacles to avoid
|
365 |
-
- Score tracking
|
366 |
-
- Game over condition
|
367 |
-
|
368 |
-
Output ONLY the Python code with no additional text or explanations.
|
369 |
-
"""
|
370 |
-
|
371 |
-
response = groq_client.chat.completions.create(
|
372 |
-
model="llama3-70b-8192",
|
373 |
-
messages=[{"role": "user", "content": prompt}],
|
374 |
-
temperature=0.5,
|
375 |
-
max_tokens=2048
|
376 |
-
)
|
377 |
-
|
378 |
-
game_code = response.choices[0].message.content
|
379 |
-
|
380 |
-
# Clean up the code
|
381 |
-
if "```python" in game_code:
|
382 |
-
game_code = game_code.split("```python")[1].split("```")[0]
|
383 |
-
elif "```" in game_code:
|
384 |
-
game_code = game_code.split("```")[1]
|
385 |
-
|
386 |
-
return game_code, "Success"
|
387 |
-
|
388 |
-
except Exception as e:
|
389 |
-
return f"# Error generating game code\nprint('{str(e)}')", str(e)
|
390 |
-
|
391 |
-
# Generate game preview image using SDXL
|
392 |
-
def generate_game_preview(game_concept):
|
393 |
-
try:
|
394 |
-
prompt = f"Cartoon style 2D game scene: {game_concept['description']}, bright colors, children's book illustration"
|
395 |
-
api_url = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
|
396 |
-
headers = {"Authorization": f"Bearer {st.secrets['HF_API_KEY']}"}
|
397 |
-
payload = {"inputs": prompt}
|
398 |
-
|
399 |
-
response = requests.post(api_url, headers=headers, json=payload)
|
400 |
-
image = Image.open(BytesIO(response.content))
|
401 |
-
|
402 |
-
# Convert to bytes
|
403 |
-
buf = io.BytesIO()
|
404 |
-
image.save(buf, format='PNG')
|
405 |
-
buf.seek(0)
|
406 |
-
return buf
|
407 |
-
|
408 |
-
except Exception as e:
|
409 |
-
st.error(f"Game preview generation error: {str(e)}")
|
410 |
-
return None
|
411 |
-
|
412 |
-
# Create interactive visualization of game mechanics
|
413 |
-
def create_game_visualization(game_concept):
|
414 |
-
try:
|
415 |
-
# Create a simple visualization using Plotly
|
416 |
-
fig = go.Figure()
|
417 |
-
|
418 |
-
# Add player character
|
419 |
-
fig.add_trace(go.Scatter(
|
420 |
-
x=[0.5], y=[0.5],
|
421 |
-
mode='markers+text',
|
422 |
-
marker=dict(size=50, color='blue'),
|
423 |
-
text='Player',
|
424 |
-
textposition='bottom center',
|
425 |
-
name='Player'
|
426 |
-
))
|
427 |
-
|
428 |
-
# Add collectibles
|
429 |
-
for i in range(5):
|
430 |
-
fig.add_trace(go.Scatter(
|
431 |
-
x=[random.uniform(0.2, 0.8)], y=[random.uniform(0.2, 0.8)],
|
432 |
-
mode='markers',
|
433 |
-
marker=dict(size=30, color='gold', symbol='star'),
|
434 |
-
name='Collectible'
|
435 |
-
))
|
436 |
-
|
437 |
-
# Add obstacles
|
438 |
-
for i in range(3):
|
439 |
-
fig.add_trace(go.Scatter(
|
440 |
-
x=[random.uniform(0.1, 0.9)], y=[random.uniform(0.1, 0.9)],
|
441 |
-
mode='markers',
|
442 |
-
marker=dict(size=40, color='red', symbol='x'),
|
443 |
-
name='Obstacle'
|
444 |
-
))
|
445 |
-
|
446 |
-
# Update layout
|
447 |
-
fig.update_layout(
|
448 |
-
title=f"Game Visualization: {game_concept['title']}",
|
449 |
-
xaxis=dict(showgrid=False, zeroline=False, visible=False, range=[0, 1]),
|
450 |
-
yaxis=dict(showgrid=False, zeroline=False, visible=False, range=[0, 1]),
|
451 |
-
showlegend=False,
|
452 |
-
margin=dict(l=20, r=20, t=40, b=20),
|
453 |
-
height=400,
|
454 |
-
paper_bgcolor='rgba(0,0,0,0)',
|
455 |
-
plot_bgcolor='rgba(0,0,0,0)'
|
456 |
-
)
|
457 |
-
|
458 |
-
return fig
|
459 |
-
|
460 |
-
except Exception as e:
|
461 |
-
st.error(f"Visualization error: {str(e)}")
|
462 |
-
return None
|
463 |
-
|
464 |
-
def main():
|
465 |
-
"""Main application function"""
|
466 |
-
st.title("🧙♂️ StoryCoder - Learn Coding Through Games!")
|
467 |
-
st.subheader("Turn your story into a game and discover coding secrets!")
|
468 |
-
|
469 |
-
# Initialize session state
|
470 |
-
if 'story' not in st.session_state:
|
471 |
-
st.session_state.story = ""
|
472 |
-
if 'concepts' not in st.session_state:
|
473 |
-
st.session_state.concepts = []
|
474 |
-
if 'entities' not in st.session_state:
|
475 |
-
st.session_state.entities = {}
|
476 |
-
if 'game_concept' not in st.session_state:
|
477 |
-
st.session_state.game_concept = {}
|
478 |
-
if 'game_code' not in st.session_state:
|
479 |
-
st.session_state.game_code = ""
|
480 |
-
if 'game_preview' not in st.session_state:
|
481 |
-
st.session_state.game_preview = None
|
482 |
-
if 'active_tab' not in st.session_state:
|
483 |
-
st.session_state.active_tab = "story"
|
484 |
-
|
485 |
-
# Create tabs
|
486 |
-
tab_cols = st.columns(5)
|
487 |
-
with tab_cols[0]:
|
488 |
-
if st.button("📖 Create Story"):
|
489 |
-
st.session_state.active_tab = "story"
|
490 |
-
with tab_cols[1]:
|
491 |
-
if st.button("🎮 Game"):
|
492 |
-
st.session_state.active_tab = "game"
|
493 |
-
with tab_cols[2]:
|
494 |
-
if st.button("🔍 Concepts"):
|
495 |
-
st.session_state.active_tab = "concepts"
|
496 |
-
with tab_cols[3]:
|
497 |
-
if st.button("💻 Code"):
|
498 |
-
st.session_state.active_tab = "code"
|
499 |
-
with tab_cols[4]:
|
500 |
-
if st.button("🔄 Reset"):
|
501 |
-
for key in list(st.session_state.keys()):
|
502 |
-
if key != 'active_tab':
|
503 |
-
del st.session_state[key]
|
504 |
-
st.session_state.active_tab = "story"
|
505 |
-
st.rerun()
|
506 |
-
|
507 |
-
# Story creation tab
|
508 |
-
if st.session_state.active_tab == "story":
|
509 |
-
with st.container():
|
510 |
-
st.header("📖 Create Your Story")
|
511 |
-
st.write("Write a short story (2-5 sentences) and I'll turn it into a game!")
|
512 |
-
|
513 |
-
story = st.text_area(
|
514 |
-
"Your story:",
|
515 |
-
height=200,
|
516 |
-
placeholder="Once upon a time, a rabbit named Ruby needed to collect 5 magical carrots in the enchanted forest while avoiding mischievous squirrels...",
|
517 |
-
value=st.session_state.story,
|
518 |
-
key="story_input"
|
519 |
-
)
|
520 |
-
|
521 |
-
if st.button("Create Game!", use_container_width=True):
|
522 |
-
if len(story) < 20:
|
523 |
-
st.error("Your story needs to be at least 20 characters long!")
|
524 |
-
else:
|
525 |
-
st.session_state.story = story
|
526 |
-
with st.spinner("🧠 Analyzing your story..."):
|
527 |
-
st.session_state.concepts = analyze_story(story)
|
528 |
-
st.session_state.entities = extract_entities(story)
|
529 |
-
|
530 |
-
with st.spinner("🎮 Designing your game..."):
|
531 |
-
st.session_state.game_concept = generate_game_concept(
|
532 |
-
story,
|
533 |
-
st.session_state.concepts,
|
534 |
-
st.session_state.entities
|
535 |
-
)
|
536 |
-
|
537 |
-
with st.spinner("👾 Generating game preview..."):
|
538 |
-
st.session_state.game_preview = generate_game_preview(
|
539 |
-
st.session_state.game_concept
|
540 |
-
)
|
541 |
-
|
542 |
-
with st.spinner("💻 Creating game code..."):
|
543 |
-
st.session_state.game_code, error = generate_game_code(
|
544 |
-
story,
|
545 |
-
st.session_state.game_concept
|
546 |
-
)
|
547 |
-
if error:
|
548 |
-
st.error(f"Code generation error: {error}")
|
549 |
-
|
550 |
-
st.session_state.active_tab = "game"
|
551 |
-
st.rerun()
|
552 |
-
|
553 |
-
# Show examples
|
554 |
-
st.subheader("✨ Story Examples")
|
555 |
-
col1, col2, col3 = st.columns(3)
|
556 |
-
with col1:
|
557 |
-
st.caption("Loop Example")
|
558 |
-
st.code('"Ruby the rabbit needs to collect 5 magical carrots that appear every 10 seconds in the enchanted forest"', language="text")
|
559 |
-
st.image(GAME_EXAMPLES["loop"]["image"],
|
560 |
-
use_column_width=True,
|
561 |
-
caption=GAME_EXAMPLES["loop"]["description"])
|
562 |
-
with col2:
|
563 |
-
st.caption("Conditional Example")
|
564 |
-
st.code('"If Alex the wizard sees a dragon, he casts a fire spell, otherwise he walks forward to find treasures"', language="text")
|
565 |
-
st.image(GAME_EXAMPLES["conditional"]["image"],
|
566 |
-
use_column_width=True,
|
567 |
-
caption=GAME_EXAMPLES["conditional"]["description"])
|
568 |
-
with col3:
|
569 |
-
st.caption("Function Example")
|
570 |
-
st.code('"Wizard Lily creates magic spells to solve puzzles - each spell is a special function"', language="text")
|
571 |
-
st.image(GAME_EXAMPLES["function"]["image"],
|
572 |
-
use_column_width=True,
|
573 |
-
caption=GAME_EXAMPLES["function"]["description"])
|
574 |
-
|
575 |
-
# Game tab
|
576 |
-
elif st.session_state.active_tab == "game":
|
577 |
-
st.header("🎮 Your Story Game")
|
578 |
-
|
579 |
-
if not st.session_state.get('story'):
|
580 |
-
st.warning("Please create a story first!")
|
581 |
-
st.session_state.active_tab = "story"
|
582 |
-
st.rerun()
|
583 |
-
|
584 |
-
# Display game concept
|
585 |
-
st.subheader(f"✨ {st.session_state.game_concept.get('title', 'Your Adventure Game')}")
|
586 |
-
st.write(st.session_state.game_concept.get('description', 'An exciting game based on your story!'))
|
587 |
-
|
588 |
-
# Display game preview
|
589 |
-
st.subheader("🖼️ Game Preview")
|
590 |
-
if st.session_state.game_preview:
|
591 |
-
st.image(st.session_state.game_preview, use_container_width=True)
|
592 |
-
else:
|
593 |
-
concept = st.session_state.concepts[0] if st.session_state.concepts else "loop"
|
594 |
-
st.image(GAME_EXAMPLES[concept]["image"],
|
595 |
-
use_container_width=True,
|
596 |
-
caption="Example game preview")
|
597 |
-
|
598 |
-
# Game mechanics visualization
|
599 |
-
st.subheader("🎮 Game Mechanics")
|
600 |
-
if st.session_state.game_concept:
|
601 |
-
fig = create_game_visualization(st.session_state.game_concept)
|
602 |
-
if fig:
|
603 |
-
st.plotly_chart(fig, use_container_width=True)
|
604 |
-
else:
|
605 |
-
st.info("Game mechanics visualization would appear here")
|
606 |
-
|
607 |
-
# Game instructions
|
608 |
-
st.subheader("📜 How to Play")
|
609 |
-
st.markdown(f"""
|
610 |
-
<div class="game-instructions">
|
611 |
-
<h4>Game Controls:</h4>
|
612 |
-
<p>{st.session_state.game_concept.get('instructions', 'Use arrow keys to move and space to jump')}</p>
|
613 |
-
|
614 |
-
<h4>Game Mechanics:</h4>
|
615 |
-
<p>{st.session_state.game_concept.get('mechanics', 'Collect items and avoid obstacles')}</p>
|
616 |
-
|
617 |
-
<h4>Coding Concepts:</h4>
|
618 |
-
<p>{st.session_state.game_concept.get('code_concepts', 'Loops, conditionals, and functions')}</p>
|
619 |
-
</div>
|
620 |
-
""", unsafe_allow_html=True)
|
621 |
-
|
622 |
-
if st.button("Show Coding Secrets!", use_container_width=True):
|
623 |
-
st.session_state.active_tab = "concepts"
|
624 |
-
st.rerun()
|
625 |
-
|
626 |
-
# Concepts tab
|
627 |
-
elif st.session_state.active_tab == "concepts":
|
628 |
-
st.header("🔍 Coding Concepts in Your Game")
|
629 |
-
st.subheader("We used these programming concepts in your game:")
|
630 |
-
|
631 |
-
if not st.session_state.concepts:
|
632 |
-
st.warning("No concepts detected in your story! Try adding words like '3 times', 'if', or 'make'.")
|
633 |
-
else:
|
634 |
-
for concept in st.session_state.concepts:
|
635 |
-
if concept in CONCEPTS:
|
636 |
-
details = CONCEPTS[concept]
|
637 |
-
st.markdown(f"""
|
638 |
-
<div class="concept-card" style="border-left: 5px solid {details['color']};">
|
639 |
-
<div style="display:flex; align-items:center; gap:15px;">
|
640 |
-
<span style="font-size:36px;">{details['emoji']}</span>
|
641 |
-
<h3 style="color:{details['color']};">{details['name']}</h3>
|
642 |
-
</div>
|
643 |
-
<p>{details['description']}</p>
|
644 |
-
<pre style="background:#f0f0f0; padding:10px; border-radius:8px;">{details['example']}</pre>
|
645 |
-
</div>
|
646 |
-
""", unsafe_allow_html=True)
|
647 |
-
|
648 |
-
st.subheader("🎮 How Concepts Are Used in Your Game")
|
649 |
-
st.write(st.session_state.game_concept.get('code_concepts', 'These concepts power the mechanics of your game'))
|
650 |
-
|
651 |
-
if st.button("See the Game Code!", use_container_width=True):
|
652 |
-
st.session_state.active_tab = "code"
|
653 |
-
st.rerun()
|
654 |
-
|
655 |
-
# Code tab
|
656 |
-
elif st.session_state.active_tab == "code":
|
657 |
-
st.header("💻 Game Code")
|
658 |
-
st.write("Here's the Python code for your game. You can run it on your computer!")
|
659 |
-
|
660 |
-
if st.session_state.game_code:
|
661 |
-
st.subheader("🎮 Game Implementation")
|
662 |
-
st.code(st.session_state.game_code, language="python")
|
663 |
-
|
664 |
-
# Download button
|
665 |
-
st.download_button(
|
666 |
-
label="Download Game Code",
|
667 |
-
data=st.session_state.game_code,
|
668 |
-
file_name="story_game.py",
|
669 |
-
mime="text/python",
|
670 |
-
use_container_width=True
|
671 |
-
)
|
672 |
-
|
673 |
-
st.info("💡 How to run your game:")
|
674 |
-
st.markdown("""
|
675 |
-
1. Install Python from [python.org](https://python.org)
|
676 |
-
2. Install Pygame: `pip install pygame`
|
677 |
-
3. Download the code above
|
678 |
-
4. Run it with: `python story_game.py`
|
679 |
-
""")
|
680 |
-
|
681 |
-
st.success("🎉 When you run this code, you'll see your story come to life as a playable game!")
|
682 |
-
|
683 |
-
# Game preview
|
684 |
-
st.subheader("🎮 What Your Game Looks Like")
|
685 |
-
concept = st.session_state.concepts[0] if st.session_state.concepts else "loop"
|
686 |
-
st.image(GAME_EXAMPLES[concept]["image"],
|
687 |
-
caption="Your game will look similar to this",
|
688 |
-
use_column_width=True)
|
689 |
-
else:
|
690 |
-
st.warning("No game code generated yet!")
|
691 |
-
|
692 |
-
if st.button("Create Another Game!", use_container_width=True):
|
693 |
-
st.session_state.active_tab = "story"
|
694 |
-
st.session_state.story = ""
|
695 |
-
st.rerun()
|
696 |
-
|
697 |
-
if __name__ == "__main__":
|
698 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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