# app.py - Fixed Version with Free Models import streamlit as st import os import time import random import json import base64 import requests import re from PIL import Image import io import matplotlib.pyplot as plt from transformers import pipeline, set_seed # Configure Streamlit page st.set_page_config( page_title="StoryCoder - Learn Coding Through Games", page_icon="🎮", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS for game-themed UI st.markdown(""" """, unsafe_allow_html=True) # Initialize session state def init_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_scenario' not in st.session_state: st.session_state.game_scenario = "" if 'game_code' not in st.session_state: st.session_state.game_code = "" if 'game_explanation' not in st.session_state: st.session_state.game_explanation = "" if 'game_preview' not in st.session_state: st.session_state.game_preview = None if 'active_tab' not in st.session_state: st.session_state.active_tab = "story" if 'loading' not in st.session_state: st.session_state.loading = False # Concept database CONCEPTS = { "loop": { "name": "Loop", "emoji": "🔄", "description": "Loops repeat actions multiple times", "example": "for i in range(5):\n print('Hello!')", "color": "#FF9E6D", "game_example": "Repeating a jump 5 times to cross a river" }, "conditional": { "name": "Conditional", "emoji": "❓", "description": "Conditionals make decisions in code", "example": "if sunny:\n go_outside()\nelse:\n stay_inside()", "color": "#4ECDC4", "game_example": "Choosing different paths based on obstacles" }, "function": { "name": "Function", "emoji": "✨", "description": "Functions are reusable blocks of code", "example": "def greet(name):\n print(f'Hello {name}!')", "color": "#FFD166", "game_example": "Creating a jump function used multiple times" }, "variable": { "name": "Variable", "emoji": "📦", "description": "Variables store information", "example": "score = 10\nplayer = 'Alex'", "color": "#FF6B6B", "game_example": "Keeping track of collected stars" }, "list": { "name": "List", "emoji": "📝", "description": "Lists store collections of items", "example": "fruits = ['apple', 'banana', 'orange']", "color": "#1A535C", "game_example": "Storing collected treasures in a backpack" } } # Load text generation model @st.cache_resource(show_spinner=False) def load_text_generator(): """Load a lightweight text generation model""" try: return pipeline('text-generation', model='gpt2', framework='pt', device=-1) except: return None # Analyze story and extract concepts 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", "decide"]): 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", "score"]): 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)) # Generate game scenario using free models def generate_game_scenario(story, concepts): """Generate a game scenario based on the story and concepts""" # Create a simple template-based scenario concept_names = [CONCEPTS[c]['name'] for c in concepts] concept_list = ", ".join(concept_names) return f""" Game Title: {story[:15]} Adventure Game Objective: Complete challenges based on the story: {story[:100]}... Characters: - Hero: The main character from your story - Helper: A friendly guide who explains coding concepts - Villain: A character that creates obstacles (if applicable) Game Mechanics: 1. The player controls the hero using arrow keys 2. Collect items mentioned in the story 3. Avoid obstacles and solve simple puzzles 4. Helper characters appear to teach {concept_list} Coding Concepts: This game teaches {concept_list} through: - Using loops to repeat actions - Making decisions with conditionals - Creating reusable functions - Tracking progress with variables - Managing collections with lists Visual Description: Colorful 3D world with cartoon-style characters, vibrant landscapes, and magical effects. """ # Generate game code explanation def generate_game_explanation(story, concepts, game_scenario): """Generate explanation of game code""" # Create simple explanation based on concepts concept_explanations = "\n".join( [f"- {CONCEPTS[c]['name']}: {CONCEPTS[c]['game_example']}" for c in concepts] ) return f""" In this game based on your story "{story[:20]}...", we use programming concepts to make it work: {concept_explanations} As you play the game, think about: 1. How the game uses these concepts to create challenges 2. How you might change the code to make the game easier or harder The code brings your story to life in a 3D game world! """ # Generate simple game code def generate_game_code(story, concepts): """Generate simple PyGame code for the game""" # Generate a unique game based on story keywords keywords = re.findall(r'\b\w{4,}\b', story)[:3] player_char = keywords[0] if keywords else "hero" collect_item = keywords[1] if len(keywords) > 1 else "star" obstacle = keywords[2] if len(keywords) > 2 else "rock" return f""" # {story[:30]} Adventure Game import pygame import random import sys # Initialize pygame pygame.init() # Game setup WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("{player_char.capitalize()} Adventure") clock = pygame.time.Clock() # Colors BACKGROUND = (173, 216, 230) # Light blue PLAYER_COLOR = (255, 0, 0) # Red GOAL_COLOR = (255, 223, 0) # Gold OBSTACLE_COLOR = (139, 69, 19) # Brown TEXT_COLOR = (0, 0, 0) # Black # Player setup player_size = 50 player_x = 100 player_y = HEIGHT // 2 player_speed = 5 # Goal setup goal_size = 40 goal_x = WIDTH - 150 goal_y = HEIGHT // 2 # Variables concept: Tracking score score = 0 font = pygame.font.SysFont(None, 36) # List concept: Creating obstacles obstacles = [] for i in range(5): obstacles.append([ random.randint(200, WIDTH - 100), random.randint(50, HEIGHT - 100), random.randint(20, 50), random.randint(20, 50) ]) # Game loop running = True while running: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Player movement keys = pygame.key.get_pressed() if keys[pygame.K_UP]: player_y -= player_speed if keys[pygame.K_DOWN]: player_y += player_speed if keys[pygame.K_LEFT]: player_x -= player_speed if keys[pygame.K_RIGHT]: player_x += player_speed # Boundary checking player_x = max(0, min(WIDTH - player_size, player_x)) player_y = max(0, min(HEIGHT - player_size, player_y)) # Collision detection with goal player_rect = pygame.Rect(player_x, player_y, player_size, player_size) goal_rect = pygame.Rect(goal_x, goal_y, goal_size, goal_size) # Conditional concept: Check for collision if player_rect.colliderect(goal_rect): # Function concept: Increase score score += 1 # Move goal to new position goal_x = random.randint(100, WIDTH - 100) goal_y = random.randint(50, HEIGHT - 100) # Drawing screen.fill(BACKGROUND) # Draw obstacles for obstacle in obstacles: pygame.draw.rect(screen, OBSTACLE_COLOR, (obstacle[0], obstacle[1], obstacle[2], obstacle[3])) # Draw player and goal pygame.draw.rect(screen, PLAYER_COLOR, (player_x, player_y, player_size, player_size)) pygame.draw.rect(screen, GOAL_COLOR, (goal_x, goal_y, goal_size, goal_size)) # Display score score_text = font.render(f"{collect_item.capitalize()}s: {{score}}", True, TEXT_COLOR) screen.blit(score_text, (20, 20)) # Display story title title_text = font.render(f"{player_char.capitalize()} Adventure", True, TEXT_COLOR) screen.blit(title_text, (WIDTH // 2 - 100, 20)) # Display instructions help_text = font.render("Arrow keys to move - Collect the gold squares!", True, TEXT_COLOR) screen.blit(help_text, (WIDTH // 2 - 200, HEIGHT - 40)) # Update display pygame.display.flip() clock.tick(60) pygame.quit() sys.exit() """ # Generate game preview visualization def generate_game_preview(): """Generate a visual preview of the game""" try: # Create a simple visualization fig, ax = plt.subplots(figsize=(10, 6)) ax.set_facecolor('#a2d2ff') ax.set_xlim(0, 10) ax.set_ylim(0, 6) # Draw game elements ax.text(5, 5, "Your Adventure", fontsize=20, ha='center', color='#9b5de5') ax.plot([1, 9], [3, 3], 'k-', linewidth=2) # Ground # Player character ax.plot(2, 3.5, 'ro', markersize=15) ax.text(2, 4, 'Player', ha='center') # Goal ax.plot(8, 3.5, 'yo', markersize=15) ax.text(8, 4, 'Goal', ha='center') # Obstacles for i in range(3): x = random.uniform(3, 7) y = random.uniform(3.2, 4) ax.plot(x, y, 's', color='#8d99ae', markersize=12) ax.text(x, y+0.3, 'Obstacle', ha='center', fontsize=8) # Path ax.plot([2, 8], [3.5, 3.5], 'y--', linewidth=2) ax.axis('off') ax.set_title("Game Preview - Move player to collect goals while avoiding obstacles", fontsize=14) # Save to bytes buf = io.BytesIO() plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') buf.seek(0) return buf except Exception as e: st.error(f"Preview generation error: {str(e)}") return None # Main application function def main(): init_session_state() st.title("🎮 StoryCoder - Learn Coding Through Games!") st.subheader("Turn your story into a 3D game and discover coding secrets!") # Create tabs st.markdown('
pip install pygame
python your_game.py
{details['description']}
In your game: {details['game_example']}
{details['example']}
pip install pygame
my_game.py
python my_game.py