Build an AI-Powered Space Invaders Game: Integrating LLMs into HTML5 Games with Microsoft Foundry Local
Introduction
What if your game could talk back to you? Imagine playing Space Invaders while an AI commander taunts you during battle, delivers personalized mission briefings, and provides real-time feedback based on your performance. This isn't science fiction it's something you can build today using HTML, JavaScript, and a locally-running AI model.
In this tutorial, we'll explore how to create an HTML5 game with integrated Large Language Model (LLM) features using Microsoft Foundry Local. You'll learn how to combine classic game development with modern AI capabilities, all running entirely on your own machine—no cloud services, no API costs, no internet connection required during gameplay.
We'll be working with the Space Invaders - AI Commander Edition project, which demonstrates exactly how to architect games that leverage local AI. Whether you're a student learning game development, exploring AI integration patterns, or building your portfolio, this guide provides practical, hands-on experience with technologies that are reshaping how we build interactive applications.
What You'll Learn
By the end of this tutorial, you'll understand how to combine traditional web development with local AI inference. These skills transfer directly to building chatbots, interactive tutorials, AI-enhanced productivity tools, and any application where you want intelligent, context-aware responses.
- Set up Microsoft Foundry Local for running AI models on your machine
- Understand the architecture of games that integrate LLM features
- Use GitHub Copilot CLI to accelerate your development workflow
- Implement AI-powered game features like dynamic commentary and adaptive feedback
- Extend the project with your own creative AI features
Why Local AI for Games?
Before diving into the code, let's understand why running AI locally matters for game development. Traditional cloud-based AI services have limitations that make them impractical for real-time gaming experiences.
Latency is the first challenge. Cloud API calls typically take 500ms to several seconds, an eternity in a game running at 60 frames per second. Local inference can respond in tens of milliseconds, enabling AI responses that feel instantaneous and natural. When an enemy ship appears, your AI commander can taunt you immediately, not three seconds later.
Cost is another consideration. Cloud AI services charge per token, which adds up quickly when generating dynamic content during gameplay. Local models have zero per-use cost, once installed, they run entirely on your hardware. This frees you to experiment without worrying about API bills.
Privacy and offline capability complete the picture. Local AI keeps all data on your machine, perfect for games that might handle player information. And since nothing requires internet connectivity, your game works anywhere, on planes, in areas with poor connectivity, or simply when you want to play without network access.
Understanding Microsoft Foundry Local
Microsoft Foundry Local is a runtime that enables you to run small language models (SLMs) directly on your computer. It's designed for developers who want to integrate AI capabilities into applications without requiring cloud infrastructure. Think of it as having a miniature AI assistant living on your laptop.
Foundry Local handles the complex work of loading AI models, managing memory, and processing inference requests through a simple API. You send text prompts, and it returns AI-generated responses, all happening locally on your CPU or GPU. The models are optimized to run efficiently on consumer hardware, so you don't need a supercomputer.
For our Space Invaders game, Foundry Local powers the "AI Commander" feature. During gameplay, the game sends context about what's happening, your score, accuracy, current level, enemies remaining and receives back contextual commentary, taunts, and encouragement. The result feels like playing alongside an AI companion who actually understands the game.
Setting Up Your Development Environment
Let's get your machine ready for AI-powered game development. We'll install Foundry Local, clone the project, and verify everything works. The entire setup takes about 10-15 minutes.
Step 1: Install Microsoft Foundry Local
Foundry Local installation varies by operating system. Open your terminal and run the appropriate command:
# Windows (using winget) winget install Microsoft.FoundryLocal # macOS (using Homebrew) brew install microsoft/foundrylocal/foundrylocal
These commands download and install the Foundry Local runtime along with a default small language model. The installation includes everything needed to run AI inference locally.
Verify the installation by running:
foundry --version
If you see a version number, Foundry Local is ready. If you encounter errors, ensure you have administrator/sudo privileges and that your package manager is up to date.
Step 2: Install Node.js (If Not Already Installed)
Our game's AI features require a small Node.js server to communicate between the browser and Foundry Local. Check if Node.js is installed:
node --version
If you see a version number (v16 or higher recommended), you're set. Otherwise, install Node.js:
# Windows winget install OpenJS.NodeJS.LTS # macOS brew install node # Linux sudo apt install nodejs npm
Node.js provides the JavaScript runtime that powers our proxy server, bridging browser code with the local AI model.
Step 3: Clone the Project
Get the Space Invaders project onto your machine:
git clone https://github.com/leestott/Spaceinvaders-FoundryLocal.git cd Spaceinvaders-FoundryLocal
This downloads all game files, including the HTML interface, game logic, AI integration module, and server code.
Step 4: Install Dependencies and Start the Server
Install the Node.js packages and launch the AI-enabled server:
npm install npm start
The first command downloads required packages (primarily for the proxy server). The second starts the server, which listens for AI requests from the game. You should see output indicating the server is running on port 3001.
Step 5: Play the Game
Open your browser and navigate to:
http://localhost:3001
You should see Space Invaders with "AI: ONLINE" displayed in the game HUD, indicating that AI features are active. Use arrow keys or A/D to move, SPACE to fire, and P to pause. The AI Commander will start providing commentary as you play!
Understanding the Project Architecture
Now that the game is running, let's explore how the different pieces fit together. Understanding this architecture will help you modify the game and apply these patterns to your own projects.
The project follows a clean separation of concerns, with each file handling a specific responsibility:
Spaceinvaders-FoundryLocal/ ├── index.html # Main game page and UI structure ├── styles.css # Retro arcade visual styling ├── game.js # Core game logic and rendering ├── llm.js # AI integration module ├── sound.js # Web Audio API sound effects ├── server.js # Node.js proxy for Foundry Local └── package.json # Project configuration
- index.html: Defines the game canvas and UI elements. It's the entry point that loads all other modules.
- game.js: Contains the game loop, physics, collision detection, scoring, and rendering logic. This is the heart of the game.
- llm.js: Handles all communication with the AI backend. It formats game state into prompts and processes AI responses.
- server.js: A lightweight Express server that proxies requests between the browser and Foundry Local.
- sound.js: Synthesizes retro sound effects using the Web Audio API—no audio files needed!
How the AI Integration Works
The magic of the AI Commander happens through a simple but powerful pattern. Let's trace the flow from gameplay event to AI response.
When something interesting happens in the game, you clear a wave, achieve a combo, or lose a life, the game logic in game.js triggers an AI request. This request includes context about the current game state: your score, accuracy percentage, current level, lives remaining, and what just happened.
The llm.js module formats this context into a prompt. For example, when you clear a wave with 85% accuracy, it might construct:
You are an AI Commander in a Space Invaders game. The player just cleared wave 3 with 85% accuracy. Score: 12,500. Lives: 3. Provide a brief, enthusiastic comment (1-2 sentences).
This prompt travels to server.js, which forwards it to Foundry Local. The AI model processes the prompt and generates a response like: "Impressive accuracy, pilot! Wave 3 didn't stand a chance. Keep that trigger finger sharp!"
The response flows back through the server to the browser, where llm.js passes it to the game. The game displays the message in the HUD, creating the illusion of playing alongside an AI companion.
This entire round trip typically completes in 50-200 milliseconds, fast enough to feel responsive without interrupting gameplay.
Using GitHub Copilot CLI to Explore and Modify the Code
GitHub Copilot CLI accelerates your development workflow by letting you ask questions and generate code directly in your terminal. Let's use it to understand and extend the Space Invaders project.
Installing Copilot CLI
If you haven't installed Copilot CLI yet, here's the quick setup:
# Install GitHub CLI winget install GitHub.cli # Windows brew install gh # macOS # Authenticate with GitHub gh auth login # Add Copilot extension gh extension install github/gh-copilot # Verify installation gh copilot --help
With Copilot CLI ready, you can interact with AI directly from your terminal while working on the project.
Exploring Code with Copilot CLI
Use Copilot to understand unfamiliar code. Navigate to the project directory and try:
gh copilot explain "How does llm.js communicate with the server?"
Copilot analyzes the code and explains the communication pattern, helping you understand the architecture without reading every line manually.
You can also ask about specific functions:
gh copilot explain "What does the generateEnemyTaunt function do?"
This accelerates onboarding to unfamiliar codebases, a valuable skill when working with open source projects or joining teams.
Generating New Features
Want to add a new AI feature? Ask Copilot to help generate the code:
gh copilot suggest "Create a function that asks the AI to generate a mission briefing at the start of each level, including the level number and a random mission objective"
Copilot generates starter code that you can customize and integrate. This combination of AI-powered development tools and AI-integrated gameplay demonstrates how LLMs are transforming both how we build games and how games behave.
Customizing the AI Commander
The default AI Commander provides generic gaming commentary, but you can customize its personality and responses. Open llm.js to find the prompt templates that control AI behavior.
Changing the AI's Personality
The system prompt defines who the AI "is." Find the base prompt and modify it:
// Original const systemPrompt = "You are an AI Commander in a Space Invaders game."; // Customized - Drill Sergeant personality const systemPrompt = `You are Sergeant Blaster, a gruff but encouraging drill sergeant commanding space cadets. Use military terminology, call the player "cadet," and be tough but fair.`; // Customized - Supportive Coach personality const systemPrompt = `You are Coach Nova, a supportive and enthusiastic gaming coach. Use encouraging language, celebrate small victories, and provide gentle guidance when players struggle.`;
These personality changes dramatically alter the game's feel without changing any gameplay code. It's a powerful example of how AI can add variety to games with minimal development effort.
Adding New Commentary Triggers
Currently the AI responds to wave completions and game events. You can add new triggers in game.js:
// Add AI commentary when player achieves a kill streak
if (killStreak >= 5 && !streakCommentPending) {
requestAIComment('killStreak', { count: killStreak });
streakCommentPending = true;
}
// Add AI reaction when player narrowly avoids death
if (nearMissOccurred) {
requestAIComment('nearMiss', { livesRemaining: lives });
}
Each new trigger point adds another opportunity for the AI to engage with the player, making the experience more dynamic and personalized.
Understanding the Game Features
Beyond AI integration, the Space Invaders project demonstrates solid game development patterns worth studying. Let's explore the key features.
Power-Up System
The game includes eight different power-ups, each with unique effects:
- SPREAD (Orange): Fires three projectiles in a spread pattern
- LASER (Red): Powerful beam with high damage
- RAPID (Yellow): Dramatically increased fire rate
- MISSILE (Purple): Homing projectiles that track enemies
- SHIELD (Blue): Grants an extra life
- EXTRA LIFE (Green): Grants two extra lives
- BOMB (Red): Destroys all enemies on screen
- BONUS (Gold): Random score bonus between 250-750 points
Power-ups demonstrate state management, tracking which power-up is active, applying its effects to player actions, and handling timeouts. Study the power-up code in game.js to understand how temporary state modifications work.
Leaderboard System
The game persists high scores using the browser's localStorage API:
// Saving scores
localStorage.setItem('spaceInvadersScores', JSON.stringify(scores));
// Loading scores
const savedScores = localStorage.getItem('spaceInvadersScores');
const scores = savedScores ? JSON.parse(savedScores) : [];
This pattern works for any data you want to persist between sessions—game progress, user preferences, or accumulated statistics. It's a simple but powerful technique for web games.
Sound Synthesis
Rather than loading audio files, the game synthesizes retro sound effects using the Web Audio API in sound.js. This approach has several benefits: no external assets to load, smaller project size, and complete control over sound parameters.
Examine how oscillators and gain nodes combine to create laser sounds, explosions, and victory fanfares. This knowledge transfers directly to any web project requiring audio feedback.
Extending the Project: Ideas for Students
Ready to make the project your own? Here are ideas ranging from beginner-friendly to challenging, each teaching valuable skills.
Beginner: Customize Visual Theme
Modify styles.css to create a new visual theme. Try changing the color scheme from green to blue, or create a "sunset" theme with orange and purple gradients. This builds CSS skills while making the game feel fresh.
Intermediate: Add New Enemy Types
Create a new enemy class in game.js with different movement patterns. Perhaps enemies that move in sine waves, or boss enemies that take multiple hits. This teaches object-oriented programming and game physics.
Intermediate: Expand AI Interactions
Add new AI features like:
- Pre-game mission briefings that set up the story
- Dynamic difficulty hints when players struggle
- Post-game performance analysis and improvement suggestions
- AI-generated names for enemy waves
Advanced: Multiplayer Commentary
Modify the game for two-player support and have the AI provide play-by-play commentary comparing both players' performance. This combines game networking concepts with advanced AI prompting.
Advanced: Voice Integration
Use the Web Speech API to speak the AI Commander's responses aloud. This creates a more immersive experience and demonstrates browser speech synthesis capabilities.
Troubleshooting Common Issues
If something isn't working, here are solutions to common problems.
"AI: OFFLINE" Displayed in Game
This means the game can't connect to the AI server. Check that:
- The server is running (
npm startshows no errors) - You're accessing the game via
http://localhost:3001, not directly opening the HTML file - Foundry Local is installed correctly (
foundry --versionworks)
Server Won't Start
If npm start fails:
- Ensure you ran
npm installfirst - Check that port 3001 isn't already in use by another application
- Verify Node.js is installed (
node --version)
AI Responses Are Slow
Local AI performance depends on your hardware. If responses feel sluggish:
- Close other resource-intensive applications
- Ensure your laptop is plugged in (battery mode may throttle CPU)
- Consider that first requests may be slower as the model loads
Key Takeaways
- Local AI enables real-time game features: Microsoft Foundry Local provides fast, free, private AI inference perfect for gaming applications
- Clean architecture matters: Separating game logic, AI integration, and server code makes projects maintainable and extensible
- AI personality is prompt-driven: Changing a few lines of prompt text completely transforms how the AI interacts with players
- Copilot CLI accelerates learning: Use it to explore unfamiliar code and generate new features quickly
- The patterns transfer everywhere: Skills from this project apply to chatbots, assistants, educational tools, and any AI-integrated application
Conclusion and Next Steps
You've now seen how to integrate AI capabilities into a browser-based game using Microsoft Foundry Local. The Space Invaders project demonstrates that modern AI features don't require cloud services or complex infrastructure, they can run entirely on your laptop, responding in milliseconds.
More importantly, you've learned patterns that extend far beyond gaming. The architecture of sending context to an AI, receiving generated responses, and integrating them into user experiences applies to countless applications: customer support bots, educational tutors, creative writing tools, and accessibility features.
Your next step is experimentation. Clone the repository, modify the AI's personality, add new commentary triggers, or build an entirely new game using these patterns. The combination of GitHub Copilot CLI for development assistance and Foundry Local for runtime AI gives you powerful tools to bring intelligent applications to life.
Start playing, start coding, and discover what you can create when your games can think.
Resources
- Space Invaders - AI Commander Edition Repository - Full source code and documentation
- Play Space Invaders Online - Try the basic version without AI features
- Microsoft Foundry Local Documentation - Official installation and API guide
- GitHub Copilot CLI Documentation - Installation and usage guide
- GitHub Education - Free developer tools for students
- Web Audio API Documentation - Learn about browser sound synthesis
- Canvas API Documentation - Master HTML5 game rendering