Blog Post

Microsoft Developer Community Blog
13 MIN READ

Teaching AI Development Through Gamification:

Lee_Stott's avatar
Lee_Stott
Icon for Microsoft rankMicrosoft
Feb 12, 2026

Building an Interactive Learning Platform with Foundry Local

Teaching AI Development Through Gamification: Building an Interactive Learning Platform with Foundry Local

Introduction

Learning AI development can feel overwhelming. Developers face abstract concepts like embeddings, prompt engineering, and workflow orchestration—topics that traditional tutorials struggle to make tangible. How do you teach someone what an embedding "feels like" or why prompt engineering matters beyond theoretical examples?

The answer lies in experiential learning through gamification. Instead of reading about AI concepts, what if developers could play a game that teaches these ideas through progressively challenging levels, immediate feedback, and real AI interactions? This article explores exactly that: building an educational adventure game that transforms AI learning from abstract theory into hands-on exploration.

We'll dive into Foundry Local Learning Adventure, a JavaScript-based game that teaches AI fundamentals through five interactive levels. You'll learn how to create engaging educational experiences, integrate local AI models using Foundry Local, design progressive difficulty curves, and build cross-platform applications that run both in browsers and terminals. Whether you're an educator designing technical curriculum or a developer building learning tools, this architecture provides a proven blueprint for gamified technical education.

Why Gamification Works for Technical Learning

Traditional technical education follows a predictable pattern: read documentation, watch tutorials, attempt exercises, struggle with setup, eventually give up. The problem isn't content quality, it's engagement and friction. Gamification addresses both issues simultaneously. By framing learning as progression through levels, you create intrinsic motivation. Each completed challenge feels like unlocking a new ability in a game, triggering the same dopamine response that keeps players engaged in entertainment experiences. Progress is visible, achievements are celebrated, and setbacks feel like natural parts of the journey rather than personal failures.

More importantly, gamification reduces friction. Instead of "install dependencies, configure API keys, read documentation, write code, debug errors," learners simply start the game and begin playing. The game handles setup, provides guardrails, and offers immediate feedback. When a concept clicks, the game celebrates it. When learners struggle, hints appear automatically. For AI development specifically, gamification solves a unique challenge: making probabilistic, non-deterministic systems feel approachable. Traditional programming has clear right and wrong answers, but AI outputs vary. A game can frame this variability as exploration rather than failure, teaching developers to evaluate AI responses critically while maintaining confidence.

Architecture Overview: Dual-Platform Design for Maximum Reach

The Foundry Local Learning Adventure implements a clever dual-platform architecture that runs identically in web browsers and command-line terminals. This design maximizes accessibility, learners can start playing instantly in a browser, then graduate to CLI mode with real AI when they're ready to go deeper.

The web version prioritizes zero-friction onboarding. Open web/index.html directly in any browser, no server, no build step, no dependencies. The game loads immediately with simulated AI responses that teach concepts without requiring Foundry Local installation. Progress saves to localStorage, badges unlock as you complete challenges, and the entire experience works offline after the first load. This version is perfect for classrooms, conference demos, and learners who want to try before committing to local AI setup.

The CLI version provides the full experience with real AI interactions. Built on Node.js, this version connects to Foundry Local for authentic model responses. Instead of simulated answers, learners get actual AI outputs, see real latency measurements, and experience how prompt quality affects results. The terminal interface adds a nostalgic hacker aesthetic that appeals to developers while teaching command-driven AI interaction patterns.

Both versions share the same core game logic, level progression, and learning objectives. The abstraction layer looks like this:

// Shared game core (game/src/levels.js)
export const LEVELS = [
  {
    id: 1,
    title: "Meet the Model",
    objective: "Send your first message to an AI",
    challenge: "Start a conversation with the AI model",
    successCriteria: (response) => response.length > 10,
    hints: ["Just say hello!", "Any friendly greeting works"],
    points: 100
  },
  // ... 4 more levels
];

// Platform-specific AI adapters
// Web version (web/game-web.js)
async function getAIResponse(prompt, level) {
  // Simulated responses that teach concepts
  return simulateResponse(prompt, level);
}

// CLI version (src/game.js)
async function getAIResponse(prompt, level) {
  // Real Foundry Local API calls
  const response = await foundryClient.chat.completions.create({
    model: 'phi-4',
    messages: [{ role: 'user', content: prompt }]
  });
  return response.choices[0].message.content;
}

This architecture demonstrates several key principles for educational software:

  • Progressive disclosure: Start simple (web), add complexity optionally (CLI with real AI)
  • Consistent learning outcomes: Both platforms teach the same concepts, just with different implementation details
  • Zero barriers to entry: No installation required eliminates the #1 reason learners abandon technical tutorials
  • Clear upgrade path: Web learners naturally want "the real thing" after completing simulated levels

Level Design: Teaching AI Concepts Through Progressive Challenges

The game's five levels form a carefully designed curriculum that builds AI understanding incrementally. Each level introduces one core concept, provides hands-on practice, and validates learning before proceeding.

Level 1: Meet the Model teaches the fundamental request-response pattern. Learners send their first message to an AI and see it respond. The challenge is deliberately trivial—just say hello—because the goal is building confidence. The level succeeds when the learner realizes "I can talk to an AI and it understands me." This moment of agency sets the foundation for everything else.

The implementation focuses on positive reinforcement:

// Level 1 success handler
function completeLevel1(userPrompt, aiResponse) {
  console.log("\n🎉 SUCCESS! You've made contact with the AI!");
  console.log(`\nYou said: "${userPrompt}"`);
  console.log(`AI responded: "${aiResponse}"`);
  console.log("\n✨ You earned the 'Prompt Apprentice' badge!");
  console.log("🏆 +100 points");
  
  // Show what just happened
  console.log("\n📚 What you learned:");
  console.log("  • AI models communicate through text messages");
  console.log("  • You send a prompt, the AI generates a response");
  console.log("  • This pattern works for any AI-powered application");
  
  // Tease next level
  console.log("\n🎯 Next up: Level 2 - Prompt Mastery");
  console.log("   Learn why some prompts work better than others!");
  
  updateProgress(1, true, 100);
}

This celebration pattern repeats throughout, explicit acknowledgment of success, explanation of what was learned, preview of what's next. It transforms abstract concepts into concrete achievements.

Level 2: Prompt Mastery introduces prompt quality through comparison. The game presents a deliberately poor prompt: "tell me stuff about coding." Learners must rewrite it to be specific, contextual, and actionable. The game runs both prompts, displays results side-by-side, and asks learners to evaluate the difference.

// Level 2 challenge
async function runLevel2() {
  console.log("\n📝 Level 2: Prompt Mastery\n");
  
  const badPrompt = "tell me stuff about coding";
  console.log("❌ Poor prompt example:");
  console.log(`   "${badPrompt}"`);
  console.log("\n   Problems:");
  console.log("   • Too vague - what about coding?");
  console.log("   • No context - skill level? language?");
  console.log("   • Unclear format - list? tutorial? examples?");
  
  console.log("\n✍️  Your turn! Rewrite this to be clear and specific:");
  const userPrompt = await getUserInput();
  
  console.log("\n⚖️  Comparing results...\n");
  
  const badResponse = await getAIResponse(badPrompt, 2);
  const goodResponse = await getAIResponse(userPrompt, 2);
  
  console.log("📊 Bad Prompt Result:");
  console.log(`   ${badResponse.substring(0, 150)}...`);
  console.log(`   Length: ${badResponse.length} chars\n`);
  
  console.log("📊 Your Prompt Result:");
  console.log(`   ${goodResponse.substring(0, 150)}...`);
  console.log(`   Length: ${goodResponse.length} chars\n`);
  
  // Success criteria: longer response + specific keywords
  const success = assessPromptQuality(userPrompt, goodResponse);
  
  if (success) {
    console.log("✅ Your prompt was much better!");
    console.log("   Notice how specificity generated more useful output.");
    completeLevel2();
  } else {
    console.log("💡 Hint: Try adding these elements:");
    console.log("   • What programming language?");
    console.log("   • What's your skill level?");
    console.log("   • What format do you want? (tutorial, examples, etc.)");
  }
}

This comparative approach is powerful, learners don't just read about prompt engineering, they experience its impact directly. The before/after comparison makes quality differences undeniable.

Level 3: Embeddings Explorer demystifies semantic search through practical demonstration. Learners search a knowledge base about Foundry Local using natural language queries. The game shows how embedding similarity works by returning relevant content even when exact keywords don't match.

// Level 3 knowledge base
const knowledgeBase = [
  {
    id: 1,
    content: "Foundry Local runs AI models entirely on your device without internet",
    embedding: [0.23, 0.87, 0.12, ...] // Pre-computed for demo
  },
  {
    id: 2,
    content: "Use embeddings to find semantically similar content",
    embedding: [0.45, 0.21, 0.93, ...]
  },
  // ... more entries
];

async function searchKnowledge(query) {
  console.log(`\n🔍 Searching for: "${query}"\n`);
  
  // In real version, get embedding from Foundry Local
  // In web version, use pre-computed embeddings
  const queryEmbedding = await getEmbedding(query);
  
  // Calculate similarity to all knowledge base entries
  const results = knowledgeBase.map(item => ({
    ...item,
    similarity: cosineSimilarity(queryEmbedding, item.embedding)
  }))
  .sort((a, b) => b.similarity - a.similarity)
  .slice(0, 3);
  
  console.log("📑 Top matches:\n");
  results.forEach((result, index) => {
    console.log(`${index + 1}. (${(result.similarity * 100).toFixed(1)}% match)`);
    console.log(`   ${result.content}\n`);
  });
  
  return results;
}

Learners query things like "How do I run AI offline?" and discover content about Foundry Local's offline capabilities—even though the word "offline" appears nowhere in the result. This concrete demonstration of semantic understanding beats any theoretical explanation.

Level 4: Workflow Wizard teaches AI pipeline composition. Learners build a three-step workflow: summarize text → extract keywords → generate questions. Each step uses the previous output as input, demonstrating how complex AI tasks decompose into chains of simpler operations.

// Level 4 workflow execution
async function runWorkflow(inputText) {
  console.log("⚙️  Starting 3-step workflow...\n");
  
  // Step 1: Summarize
  console.log("📝 Step 1: Summarizing text...");
  const summary = await getAIResponse(
    `Summarize this in 2 sentences: ${inputText}`,
    4
  );
  console.log(`   Result: ${summary}\n`);
  
  // Step 2: Extract keywords (uses summary output)
  console.log("🔑 Step 2: Extracting key terms...");
  const keywords = await getAIResponse(
    `Extract 5 important keywords from: ${summary}`,
    4
  );
  console.log(`   Keywords: ${keywords}\n`);
  
  // Step 3: Generate questions (uses keywords)
  console.log("❓ Step 3: Generating study questions...");
  const questions = await getAIResponse(
    `Create 3 quiz questions about these topics: ${keywords}`,
    4
  );
  console.log(`   Questions:\n${questions}\n`);
  
  console.log("✅ Workflow complete!");
  console.log("\n💡 Notice how each step built on the previous output.");
  console.log("   This is how production AI applications work!");
}

This level bridges the gap between "toy examples" and real applications. Learners see firsthand how combining simple AI operations creates sophisticated functionality.

Level 5: Build Your Own Tool challenges learners to create a custom function that AI can invoke. This introduces agentic AI patterns where models don't just generate text, they take actions.

// Level 5 tool creation
function createTool() {
  console.log("🔧 Level 5: Build Your Own Tool\n");
  console.log("Create a JavaScript function the AI can use.");
  console.log("Example: A calculator, weather lookup, or data formatter\n");
  
  console.log("Template:");
  console.log(`
function myTool(param1, param2) {
  // Your code here
  return result;
}
  `);
  
  const userCode = getUserToolCode();
  
  // Register tool with AI system
  registerTool({
    name: "user_custom_tool",
    description: "A tool created by the learner",
    function: eval(userCode) // Sandboxed in real version
  });
  
  // Give AI a task that requires the tool
  console.log("\n🤖 AI is now trying to use your tool...");
  const response = await getAIResponseWithTools(
    "Use the custom tool to solve this problem: ...",
    availableTools
  );
  
  console.log(`\nAI called your tool and got: ${response}`);
  console.log("🎉 Congratulations! You've extended AI capabilities!");
}

Completing this level marks true understanding—learners aren't just using AI, they're shaping what it can do. This empowerment is the ultimate goal of technical education.

Building the Web Version: Zero-Install Educational Experience

The web version demonstrates how to create educational software that requires absolutely zero setup. This is critical for workshops, classroom settings, and casual learners who won't commit to installation until they see value.

The architecture is deliberately simple vanilla JavaScript, no build tools, no package managers:

<!-- game/web/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Foundry Local Learning Adventure</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="game-container">
    <header>
      <h1>🎮 Foundry Local Learning Adventure</h1>
      <div class="progress-bar">
        <span id="level-indicator">Level 1 of 5</span>
        <span id="points-display">0 points</span>
      </div>
    </header>
    
    <main id="game-content">
      <!-- Level content loads here dynamically -->
    </main>
    
    <div class="controls">
      <button id="hint-btn">💡 Hint</button>
      <button id="progress-btn">📊 Progress</button>
    </div>
  </div>
  
  <script type="module" src="game-web.js"></script>
</body>
</html>

The JavaScript uses ES6 modules for clean organization without requiring a build step:

// game/web/game-web.js
import { LEVELS } from './game-data.js';
import { simulateAI } from './ai-simulator.js';

class LearningAdventure {
  constructor() {
    this.currentLevel = 1;
    this.progress = this.loadProgress();
    this.initializeUI();
  }
  
  loadProgress() {
    const saved = localStorage.getItem('learning-adventure-progress');
    return saved ? JSON.parse(saved) : {
      completedLevels: [],
      totalPoints: 0,
      badges: []
    };
  }
  
  saveProgress() {
    localStorage.setItem(
      'learning-adventure-progress',
      JSON.stringify(this.progress)
    );
  }
  
  async startLevel(levelNumber) {
    const level = LEVELS[levelNumber - 1];
    this.renderLevel(level);
    
    // Listen for user input
    document.getElementById('submit-btn').addEventListener('click', async () => {
      const userInput = document.getElementById('user-input').value;
      await this.handleUserInput(userInput, level);
    });
  }
  
  async handleUserInput(input, level) {
    // Show loading state
    this.showLoading(true);
    
    // Simulate AI response (web version)
    const response = await simulateAI(input, level.id);
    
    // Display response
    this.displayResponse(response);
    
    // Check success criteria
    if (level.successCriteria(response)) {
      this.completeLevel(level);
    } else {
      this.showHint(level.hints[0]);
    }
    
    this.showLoading(false);
  }
  
  completeLevel(level) {
    // Update progress
    this.progress.completedLevels.push(level.id);
    this.progress.totalPoints += level.points;
    this.progress.badges.push(level.badge);
    this.saveProgress();
    
    // Show celebration
    this.showSuccess(level);
    
    // Unlock next level
    if (level.id < 5) {
      this.unlockLevel(level.id + 1);
    } else {
      this.showGameComplete();
    }
  }
  
  showSuccess(level) {
    const modal = document.createElement('div');
    modal.className = 'success-modal';
    modal.innerHTML = `
      <div class="modal-content">
        <h2>🎉 Level Complete!</h2>
        <p>${level.title} - <strong>${level.points} points</strong></p>
        <div class="badge-earned">
          ${level.badge.emoji} ${level.badge.name}
        </div>
        <h3>What You Learned:</h3>
        <ul>
          ${level.learnings.map(l => `<li>${l}</li>`).join('')}
        </ul>
        <button onclick="this.closest('.success-modal').remove()">
          Continue to Next Level →
        </button>
      </div>
    `;
    document.body.appendChild(modal);
  }
}

// Start the game
const game = new LearningAdventure();
game.startLevel(1);

This architecture teaches several patterns for web-based educational tools:

  • LocalStorage for persistence: Progress survives page refreshes without requiring accounts or databases
  • ES6 modules for organization: Clean separation of concerns without build complexity
  • Simulated AI for offline operation: Scripted responses teach concepts without requiring API access
  • Progressive enhancement: Basic functionality works everywhere, enhanced features activate when available
  • Celebration animations: Visual feedback reinforces learning milestones

Implementing the CLI Version with Real AI Integration

The CLI version provides the authentic AI development experience. This version requires Node.js and Foundry Local, but rewards setup effort with genuine model interactions.

Installation uses a startup script that handles prerequisites:

#!/bin/bash
# scripts/start-game.sh

echo "🎮 Starting Foundry Local Learning Adventure..."

# Check Node.js
if ! command -v node &> /dev/null; then
  echo "❌ Node.js not found. Install from https://nodejs.org/"
  exit 1
fi

# Check Foundry Local
if ! command -v foundry &> /dev/null; then
  echo "❌ Foundry Local not found."
  echo "   Install: winget install Microsoft.FoundryLocal"
  exit 1
fi

# Start Foundry service
echo "🚀 Starting Foundry Local service..."
foundry service start

# Wait for service
sleep 2

# Load model
echo "📦 Loading Phi-4 model..."
foundry model load phi-4

# Install dependencies
echo "📥 Installing game dependencies..."
npm install

# Start game
echo "✅ Launching game..."
npm start

The game logic integrates with Foundry Local using the official SDK:

// game/src/game.js
import { FoundryLocalClient } from 'foundry-local-sdk';
import readline from 'readline/promises';

const client = new FoundryLocalClient({
  endpoint: 'http://127.0.0.1:5272' // Default Foundry Local port
});

async function getAIResponse(prompt, level) {
  try {
    const startTime = Date.now();
    
    const completion = await client.chat.completions.create({
      model: 'phi-4',
      messages: [
        {
          role: 'system',
          content: `You are Sage, a friendly AI mentor teaching ${LEVELS[level-1].title}.`
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.7,
      max_tokens: 300
    });
    
    const latency = Date.now() - startTime;
    
    console.log(`\n⏱️  AI responded in ${latency}ms`);
    return completion.choices[0].message.content;
    
  } catch (error) {
    console.error('❌ AI error:', error.message);
    console.log('💡 Falling back to demo mode...');
    return getDemoResponse(prompt, level);
  }
}

async function playLevel(levelNumber) {
  const level = LEVELS[levelNumber - 1];
  
  console.clear();
  console.log(`\n${'='.repeat(60)}`);
  console.log(`   Level ${levelNumber}: ${level.title}`);
  console.log(`${'='.repeat(60)}\n`);
  console.log(`🎯 ${level.objective}\n`);
  console.log(`📚 ${level.description}\n`);
  
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  
  const userPrompt = await rl.question('Your prompt: ');
  rl.close();
  
  console.log('\n🤖 AI is thinking...');
  const response = await getAIResponse(userPrompt, levelNumber);
  
  console.log(`\n📨 AI Response:\n${response}\n`);
  
  // Evaluate success
  if (level.successCriteria(response, userPrompt)) {
    celebrateSuccess(level);
    updateProgress(levelNumber);
    
    if (levelNumber < 5) {
      const playNext = await askYesNo('Play next level?');
      if (playNext) {
        await playLevel(levelNumber + 1);
      }
    } else {
      showGameComplete();
    }
  } else {
    console.log(`\n💡 Hint: ${level.hints[0]}\n`);
    const retry = await askYesNo('Try again?');
    if (retry) {
      await playLevel(levelNumber);
    }
  }
}

The CLI version adds several enhancements that deepen learning:

  • Latency visibility: Display response times so learners understand local vs cloud performance differences
  • Graceful fallback: If Foundry Local fails, switch to demo mode automatically rather than crashing
  • Interactive prompts: Use readline for natural command-line interaction patterns
  • Progress persistence: Save to JSON files so learners can pause and resume
  • Command history: Log all prompts and responses for learners to review their progression

Key Takeaways and Educational Design Principles

Building effective educational software for technical audiences requires balancing several competing concerns: accessibility vs authenticity, simplicity vs depth, guidance vs exploration. The Foundry Local Learning Adventure succeeds by making deliberate architectural choices that prioritize learner experience.

Key principles demonstrated:

  • Zero-friction starts win: The web version eliminates all setup barriers, maximizing the chance learners will actually begin
  • Progressive challenge curves build confidence: Each level introduces exactly one new concept, building on previous knowledge
  • Immediate feedback accelerates learning: Learners know instantly if they succeeded, with clear explanations of why
  • Real tools create transferable skills: CLI version uses professional developer tools (Node, real APIs) that apply beyond the game
  • Celebration creates emotional investment: Badges, points, and success animations transform learning into achievement
  • Dual platforms expand reach: Web attracts casual learners, CLI converts them to serious practitioners

To extend this approach for your own educational projects, consider:

  • Domain-specific challenges: Adapt level structure to your technical domain (e.g., API design, database optimization, security practices)
  • Multiplayer competitions: Add leaderboards and time trials to introduce social motivation
  • Adaptive difficulty: Track learner performance and adjust challenge difficulty dynamically
  • Sandbox modes: After completing the curriculum, provide free-play areas for experimentation
  • Community sharing: Let learners share custom levels or challenges they've created

The complete implementation with all levels, both web and CLI versions, comprehensive tests, and deployment guides is available at github.com/leestott/FoundryLocal-LearningAdventure. You can play the web version immediately at leestott.github.io/FoundryLocal-LearningAdventure or clone the repository to experience the full CLI version with real AI.

Resources and Further Reading

Updated Jan 30, 2026
Version 1.0
No CommentsBe the first to comment