pedagogy changes

pull/1585/head
chris 2 months ago
parent 429a03b56a
commit 3067636ae6

@ -802,7 +802,7 @@ You've covered a lot of ground today, and that's something to be proud of! Now c
## 🚀 Your Programming Journey Timeline
### 🕐 **What You Can Do in the Next 5 Minutes**
### **What You Can Do in the Next 5 Minutes**
- [ ] Bookmark 2-3 programming language websites that caught your attention
- [ ] Download Visual Studio Code if you haven't already
- [ ] Open your browser's DevTools (F12) and click around any website

@ -6,6 +6,44 @@ In this lesson, we'll explore how frameworks like LangChain can turn what used t
By the time we're done, you'll know when to reach for frameworks instead of raw API calls, how to use their abstractions effectively, and how to build AI applications that are ready for real-world use. Let's explore what AI frameworks can do for your projects.
## ⚡ What You Can Do in the Next 5 Minutes
**Quick Start Pathway for Busy Developers**
```mermaid
flowchart LR
A[⚡ 5 minutes] --> B[Install LangChain]
B --> C[Create ChatOpenAI client]
C --> D[Send first prompt]
D --> E[See framework power]
```
- **Minute 1**: Install LangChain: `pip install langchain langchain-openai`
- **Minute 2**: Set up your GitHub token and import the ChatOpenAI client
- **Minute 3**: Create a simple conversation with system and human messages
- **Minute 4**: Add a basic tool (like an add function) and see AI tool calling
- **Minute 5**: Experience the difference between raw API calls and framework abstraction
**Quick Test Code**:
```python
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
llm = ChatOpenAI(
api_key=os.environ["GITHUB_TOKEN"],
base_url="https://models.github.ai/inference",
model="openai/gpt-4o-mini"
)
response = llm.invoke([
SystemMessage(content="You are a helpful coding assistant"),
HumanMessage(content="Explain Python functions briefly")
])
print(response.content)
```
**Why This Matters**: In 5 minutes, you'll experience how AI frameworks transform complex AI integration into simple method calls. This is the foundation that powers production AI applications.
## Why choose a framework?
So you're ready to build an AI app - awesome! But here's the thing: you've got several different paths you can take, and each one has its own pros and cons. It's kind of like choosing between walking, biking, or driving to get somewhere - they'll all get you there, but the experience (and effort) will be totally different.
@ -46,6 +84,31 @@ graph TD
**Bottom line**: Like choosing between a craftsman's specialized tools and a complete workshop, it's about matching the tool to the task. Frameworks excel for complex, feature-rich applications, while direct APIs work well for straightforward use cases.
## 🗺️ Your Learning Journey Through AI Framework Mastery
```mermaid
journey
title From Raw APIs to Production AI Applications
section Framework Foundations
Understand abstraction benefits: 4: You
Master LangChain basics: 6: You
Compare approaches: 7: You
section Conversation Systems
Build chat interfaces: 5: You
Implement memory patterns: 7: You
Handle streaming responses: 8: You
section Advanced Features
Create custom tools: 6: You
Master structured output: 8: You
Build document systems: 8: You
section Production Applications
Combine all features: 7: You
Handle error scenarios: 8: You
Deploy complete systems: 9: You
```
**Your Journey Destination**: By the end of this lesson, you'll have mastered AI framework development and be able to build sophisticated, production-ready AI applications that rival commercial AI assistants.
## Introduction
In this lesson, we'll learn to:
@ -54,6 +117,59 @@ In this lesson, we'll learn to:
- Address common problems like chat conversations, tool usage, memory and context.
- Leverage this to build AI apps.
## 🧠 AI Framework Development Ecosystem
```mermaid
mindmap
root((AI Frameworks))
Abstraction Benefits
Code Simplification
Unified APIs
Built-in Error Handling
Consistent Patterns
Reduced Boilerplate
Multi-Model Support
Provider Agnostic
Easy Switching
Fallback Options
Cost Optimization
Core Components
Conversation Management
Message Types
Memory Systems
Context Tracking
History Persistence
Tool Integration
Function Calling
API Connections
Custom Tools
Workflow Automation
Advanced Features
Structured Output
Pydantic Models
JSON Schemas
Type Safety
Validation Rules
Document Processing
Embeddings
Vector Stores
Similarity Search
RAG Systems
Production Patterns
Application Architecture
Modular Design
Error Boundaries
Async Operations
State Management
Deployment Strategies
Scalability
Monitoring
Performance
Security
```
**Core Principle**: AI frameworks abstract complexity while providing powerful abstractions for conversation management, tool integration, and document processing, enabling developers to build sophisticated AI applications with clean, maintainable code.
## Your first AI prompt
Let's start with the fundamentals by creating your first AI application that sends a question and gets an answer back. Like Archimedes discovering the principle of displacement in his bath, sometimes the simplest observations lead to the most powerful insights - and frameworks make these insights accessible.
@ -217,6 +333,30 @@ Welcome aboard, Chris! It's always a pleasure to meet those who share a passion
If you are interested in space exploration, consider education and training in the sciences, engineering, or diplomacy. The values of curiosity, resilience, and teamwork are crucial in Starfleet. Should you ever find yourself on a starship, remember to uphold the principles of the Federation: peace, understanding, and respect for all beings. Your journey can lead you to remarkable adventures, whether in the stars or on the ground. Engage!
```
```mermaid
sequenceDiagram
participant User
participant App
participant LangChain
participant AI
User->>App: "Tell me about you"
App->>LangChain: [SystemMessage, HumanMessage]
LangChain->>AI: Formatted conversation
AI->>LangChain: Captain Picard response
LangChain->>App: AIMessage object
App->>User: Display response
Note over App: Add AIMessage to conversation
User->>App: "Can I join your crew?"
App->>LangChain: [SystemMessage, HumanMessage, AIMessage, HumanMessage]
LangChain->>AI: Full conversation context
AI->>LangChain: Contextual response
LangChain->>App: New AIMessage
App->>User: Display contextual response
```
I'll take that as a maybe ;)
## Streaming responses
@ -249,6 +389,19 @@ for chunk in llm.stream("Write a short story about a robot learning to code"):
> 💡 **User Experience Tip**: Streaming really shines when you're dealing with longer responses like code explanations, creative writing, or detailed tutorials. Your users will love seeing progress instead of staring at a blank screen!
### 🎯 Pedagogical Check-in: Framework Abstraction Benefits
**Pause and Reflect**: You've just experienced the power of AI framework abstractions. Compare what you've learned to raw API calls from previous lessons.
**Quick Self-Assessment**:
- Can you explain how LangChain simplifies conversation management compared to manual message tracking?
- What's the difference between `invoke()` and `stream()` methods, and when would you use each?
- How does the framework's message type system improve code organization?
**Real-World Connection**: The abstraction patterns you've learned (message types, streaming interfaces, conversation memory) are used in every major AI application - from ChatGPT's interface to GitHub Copilot's code assistance. You're mastering the same architectural patterns used by professional AI development teams.
**Challenge Question**: How would you design a framework abstraction for handling different AI model providers (OpenAI, Anthropic, Google) with a single interface? Consider the benefits and trade-offs.
## Prompt templates
Prompt templates work like the rhetorical structures used in classical oratory - think of how Cicero would adapt his speech patterns for different audiences while maintaining the same persuasive framework. They let you create reusable prompts where you can swap out different pieces of information without rewriting everything from scratch. Once you set up the template, you just fill in the variables with whatever values you need.
@ -471,6 +624,33 @@ TOOL CALL: Chuck Norris once rode a nine foot grizzly bear through an automatic
CONTENT:
```
```mermaid
flowchart TD
A[User Query: "Tell me a joke about animals"] --> B[LangChain Analysis]
B --> C{Tool Available?}
C -->|Yes| D[Select joke tool]
C -->|No| E[Generate direct response]
D --> F[Extract Parameters]
F --> G[Call joke(category="animals")]
G --> H[API Request to chucknorris.io]
H --> I[Return joke content]
I --> J[Display to user]
E --> K[AI-generated response]
K --> J
subgraph "Tool Definition Layer"
L[TypedDict Schema]
M[Function Implementation]
N[Parameter Validation]
end
D --> L
F --> N
G --> M
```
Here's the code in its entirety:
```python
@ -589,6 +769,31 @@ for loader in [pdf_loader, csv_loader, json_loader, web_loader]:
- **Make** recommendation systems that suggest truly relevant content
- **Automatically** organize and categorize your content
```mermaid
flowchart LR
A[Documents] --> B[Text Splitter]
B --> C[Create Embeddings]
C --> D[Vector Store]
E[User Query] --> F[Query Embedding]
F --> G[Similarity Search]
G --> D
D --> H[Relevant Documents]
H --> I[AI Response]
subgraph "Vector Space"
J[Document A: [0.1, 0.8, 0.3...]]
K[Document B: [0.2, 0.7, 0.4...]]
L[Query: [0.15, 0.75, 0.35...]]
end
C --> J
C --> K
F --> L
G --> J
G --> K
```
## Building a complete AI application
Now we'll integrate everything you've learned into a comprehensive application - a coding assistant that can answer questions, use tools, and maintain conversation memory. Like how the printing press combined existing technologies (movable type, ink, paper, and pressure) into something transformative, we'll combine our AI components into something practical and useful.
@ -704,6 +909,20 @@ graph TD
- **Follows** predictable interaction patterns
- **Manages** error handling and complex workflows automatically
### 🎯 Pedagogical Check-in: Production AI Architecture
**Architecture Understanding**: You've built a complete AI application that combines conversation management, tool calling, and structured workflows. This represents production-level AI application development.
**Key Concepts Mastered**:
- **Class-Based Architecture**: Organized, maintainable AI application structure
- **Tool Integration**: Custom functionality beyond conversation
- **Memory Management**: Persistent conversation context
- **Error Handling**: Robust application behavior
**Industry Connection**: The architecture patterns you've implemented (conversation classes, tool systems, memory management) are the same patterns used in enterprise AI applications like Slack's AI assistant, GitHub Copilot, and Microsoft Copilot. You're building with professional-grade architectural thinking.
**Reflection Question**: How would you extend this application to handle multiple users, persistent storage, or integration with external databases? Consider scalability and state management challenges.
## Assignment: Build your own AI-powered study assistant
**Objective**: Create an AI application that helps students learn programming concepts by providing explanations, code examples, and interactive quizzes.
@ -780,6 +999,65 @@ response = assistant.chat("Explain how Python functions work")
- Create a knowledge base from course materials using embeddings
- Add progress tracking and personalized learning paths
## 📈 Your AI Framework Development Mastery Timeline
```mermaid
timeline
title Production AI Framework Development Journey
section Framework Foundations
Understanding Abstractions
: Master framework vs API decisions
: Learn LangChain core concepts
: Implement message type systems
Basic Integration
: Connect to AI providers
: Handle authentication
: Manage configuration
section Conversation Systems
Memory Management
: Build conversation history
: Implement context tracking
: Handle session persistence
Advanced Interactions
: Master streaming responses
: Create prompt templates
: Implement structured output
section Tool Integration
Custom Tool Development
: Design tool schemas
: Implement function calling
: Handle external APIs
Workflow Automation
: Chain multiple tools
: Create decision trees
: Build agent behaviors
section Production Applications
Complete System Architecture
: Combine all framework features
: Implement error boundaries
: Create maintainable code
Enterprise Readiness
: Handle scalability concerns
: Implement monitoring
: Build deployment strategies
```
**🎓 Graduation Milestone**: You've successfully mastered AI framework development using the same tools and patterns that power modern AI applications. These skills represent the cutting edge of AI application development and prepare you for building enterprise-grade intelligent systems.
**🔄 Next Level Capabilities**:
- Ready to explore advanced AI architectures (agents, multi-agent systems)
- Prepared to build RAG systems with vector databases
- Equipped to create multi-modal AI applications
- Foundation set for AI application scaling and optimization
## Summary
🎉 You've now mastered the fundamentals of AI framework development and learned how to build sophisticated AI applications using LangChain. Like completing a comprehensive apprenticeship, you've acquired a substantial toolkit of skills. Let's review what you've accomplished.

@ -498,6 +498,35 @@ HTML has been the foundation of the web for over 30 years, evolving from a simpl
- What new HTML features are being proposed for future versions?
- How does semantic HTML contribute to web accessibility and SEO?
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open DevTools (F12) and inspect the HTML structure of your favorite website
- [ ] Create a simple HTML file with basic tags: `<h1>`, `<p>`, and `<img>`
- [ ] Validate your HTML using the W3C HTML Validator online
- [ ] Try adding a comment to your HTML using `<!-- comment -->`
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and review semantic HTML concepts
- [ ] Build a simple webpage about yourself using proper HTML structure
- [ ] Experiment with different heading levels and text formatting tags
- [ ] Add images and links to practice multimedia integration
- [ ] Research HTML5 features you haven't tried yet
### 📅 **Your Week-Long HTML Journey**
- [ ] Complete the terrarium project assignment with semantic markup
- [ ] Create an accessible webpage using ARIA labels and roles
- [ ] Practice form creation with various input types
- [ ] Explore HTML5 APIs like localStorage or geolocation
- [ ] Study responsive HTML patterns and mobile-first design
- [ ] Review other developers' HTML code for best practices
### 🌟 **Your Month-Long Web Foundation**
- [ ] Build a portfolio website showcasing your HTML mastery
- [ ] Learn HTML templating with a framework like Handlebars
- [ ] Contribute to open source projects by improving HTML documentation
- [ ] Master advanced HTML concepts like custom elements
- [ ] Integrate HTML with CSS frameworks and JavaScript libraries
- [ ] Mentor others learning HTML fundamentals
## 🎯 Your HTML Mastery Timeline
```mermaid

@ -624,6 +624,35 @@ Practice these concepts with these engaging, hands-on games:
For comprehensive CSS fundamentals, complete this Microsoft Learn module: [Style your HTML app with CSS](https://docs.microsoft.com/learn/modules/build-simple-website/4-css-basics/?WT.mc_id=academic-77807-sagibbon)
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open DevTools and inspect CSS styles on any website using the Elements panel
- [ ] Create a simple CSS file and link it to an HTML page
- [ ] Try changing colors using different methods: hex, RGB, and named colors
- [ ] Practice the box model by adding padding and margin to a div
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and review CSS fundamentals
- [ ] Style your HTML page with fonts, colors, and spacing
- [ ] Create a simple layout using flexbox or grid
- [ ] Experiment with CSS transitions for smooth effects
- [ ] Practice responsive design with media queries
### 📅 **Your Week-Long CSS Adventure**
- [ ] Complete the terrarium styling assignment with creative flair
- [ ] Master CSS Grid by building a photo gallery layout
- [ ] Learn CSS animations to bring your designs to life
- [ ] Explore CSS preprocessors like Sass or Less
- [ ] Study design principles and apply them to your CSS
- [ ] Analyze and recreate interesting designs you find online
### 🌟 **Your Month-Long Design Mastery**
- [ ] Build a complete responsive website design system
- [ ] Learn CSS-in-JS or utility-first frameworks like Tailwind
- [ ] Contribute to open source projects with CSS improvements
- [ ] Master advanced CSS concepts like CSS custom properties and containment
- [ ] Create reusable component libraries with modular CSS
- [ ] Mentor others learning CSS and share design knowledge
## 🎯 Your CSS Mastery Timeline
```mermaid

@ -663,6 +663,35 @@ We used pointer events for maximum flexibility, but web development offers multi
> 🎯 **Learning Strategy**: The best way to solidify these concepts is through practice. Try building variations of draggable interfaces each project will teach you something new about user interaction and DOM manipulation.
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open browser DevTools and type `document.querySelector('body')` in the console
- [ ] Try changing a webpage's text using `innerHTML` or `textContent`
- [ ] Add a click event listener to any button or link on a webpage
- [ ] Inspect the DOM tree structure using the Elements panel
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and review DOM manipulation concepts
- [ ] Create an interactive webpage that responds to user clicks
- [ ] Practice event handling with different event types (click, mouseover, keypress)
- [ ] Build a simple to-do list or counter using DOM manipulation
- [ ] Explore the relationship between HTML elements and JavaScript objects
### 📅 **Your Week-Long JavaScript Journey**
- [ ] Complete the interactive terrarium project with drag-and-drop functionality
- [ ] Master event delegation for efficient event handling
- [ ] Learn about the event loop and asynchronous JavaScript
- [ ] Practice closures by building modules with private state
- [ ] Explore modern DOM APIs like Intersection Observer
- [ ] Build interactive components without using frameworks
### 🌟 **Your Month-Long JavaScript Mastery**
- [ ] Create a complex single-page application using vanilla JavaScript
- [ ] Learn a modern framework (React, Vue, or Angular) and compare it to vanilla DOM
- [ ] Contribute to open source JavaScript projects
- [ ] Master advanced concepts like web components and custom elements
- [ ] Build performant web applications with optimal DOM patterns
- [ ] Teach others about DOM manipulation and JavaScript fundamentals
## 🎯 Your JavaScript DOM Mastery Timeline
```mermaid

@ -1,19 +1,132 @@
# Event-Driven Programming - Build a Typing Game
```mermaid
journey
title Your Typing Game Development Journey
section Foundation
Plan game structure: 3: Student
Design user interface: 4: Student
Setup HTML elements: 4: Student
section Functionality
Handle user input: 4: Student
Track timing: 5: Student
Calculate accuracy: 5: Student
section Features
Add visual feedback: 5: Student
Implement game logic: 5: Student
Polish experience: 5: Student
```
## Introduction
Here's something every developer knows but rarely talks about: typing fast is a superpower! 🚀 Think about it - the faster you can get your ideas from your brain to your code editor, the more your creativity can flow. It's like having a direct pipeline between your thoughts and the screen.
```mermaid
pie title Game Features
"Real-time Feedback" : 25
"Performance Tracking" : 20
"Interactive UI" : 20
"Timer System" : 15
"Quote Management" : 10
"Results Display" : 10
```
Want to know one of the best ways to level up this skill? You guessed it - we're going to build a game!
```mermaid
flowchart LR
A[Player starts game] --> B[Random quote displayed]
B --> C[Player types characters]
C --> D{Character correct?}
D -->|Yes| E[Green highlight]
D -->|No| F[Red highlight]
E --> G[Update accuracy]
F --> G
G --> H{Quote complete?}
H -->|No| C
H -->|Yes| I[Calculate WPM]
I --> J[Display results]
J --> K[Play again?]
K -->|Yes| B
K -->|No| L[Game over]
style A fill:#e1f5fe
style D fill:#fff3e0
style E fill:#e8f5e8
style F fill:#ffebee
style I fill:#f3e5f5
```
> Let's create an awesome typing game together!
Ready to put all those JavaScript, HTML, and CSS skills you've been learning to work? We're going to build a typing game that'll challenge you with random quotes from the legendary detective [Sherlock Holmes](https://en.wikipedia.org/wiki/Sherlock_Holmes). The game will track how fast and accurately you can type - and trust me, it's more addictive than you might think!
```mermaid
mindmap
root((Typing Game Development))
User Interface
Input Elements
Visual Feedback
Responsive Design
Accessibility
Game Logic
Quote Selection
Timer Management
Accuracy Tracking
Score Calculation
Event Handling
Keyboard Input
Button Clicks
Real-time Updates
Game State Changes
Performance Metrics
Words Per Minute
Character Accuracy
Error Tracking
Progress Display
User Experience
Immediate Feedback
Clear Instructions
Engaging Content
Achievement System
```
![demo](images/demo.gif)
## What You'll Need to Know
```mermaid
flowchart TD
A[User Action] --> B{Event Type?}
B -->|Key Press| C[Keyboard Event]
B -->|Button Click| D[Mouse Event]
B -->|Timer| E[Time Event]
C --> F[Check Character]
D --> G[Start/Reset Game]
E --> H[Update Timer]
F --> I{Correct?}
I -->|Yes| J[Highlight Green]
I -->|No| K[Highlight Red]
J --> L[Update Score]
K --> L
L --> M[Check Game State]
G --> N[Generate New Quote]
H --> O[Display Time]
M --> P{Game Complete?}
P -->|Yes| Q[Show Results]
P -->|No| R[Continue Game]
style A fill:#e1f5fe
style F fill:#e8f5e8
style I fill:#fff3e0
style Q fill:#f3e5f5
```
Before we dive in, make sure you're comfortable with these concepts (don't worry if you need a quick refresher - we've all been there!):
- Creating text input and button controls
@ -25,10 +138,144 @@ Before we dive in, make sure you're comfortable with these concepts (don't worry
If any of these feel a bit rusty, that's totally fine! Sometimes the best way to solidify your knowledge is by jumping into a project and figuring things out as you go.
### 🔄 **Pedagogical Check-in**
**Foundation Assessment**: Before starting development, ensure you understand:
- ✅ How HTML forms and input elements work
- ✅ CSS classes and dynamic styling
- ✅ JavaScript event listeners and handlers
- ✅ Array manipulation and random selection
- ✅ Time measurement and calculations
**Quick Self-Test**: Can you explain how these concepts work together in an interactive game?
- **Events** trigger when users interact with elements
- **Handlers** process those events and update game state
- **CSS** provides visual feedback for user actions
- **Timing** enables performance measurement and game progression
```mermaid
quadrantChart
title Typing Game Skills Development
x-axis Beginner --> Expert
y-axis Static --> Interactive
quadrant-1 Advanced Games
quadrant-2 Real-time Apps
quadrant-3 Basic Pages
quadrant-4 Interactive Sites
HTML Forms: [0.3, 0.2]
CSS Styling: [0.4, 0.3]
Event Handling: [0.7, 0.8]
Game Logic: [0.8, 0.9]
Performance Tracking: [0.9, 0.7]
```
## Let's Build This Thing!
[Creating a typing game by using event driven programming](./typing-game/README.md)
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open your browser console and try listening for keyboard events with `addEventListener`
- [ ] Create a simple HTML page with an input field and test typing detection
- [ ] Practice string manipulation by comparing typed text with target text
- [ ] Experiment with `setTimeout` to understand timing functions
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand event-driven programming
- [ ] Build a basic version of the typing game with word validation
- [ ] Add visual feedback for correct and incorrect typing
- [ ] Implement a simple scoring system based on speed and accuracy
- [ ] Style your game with CSS to make it visually appealing
### 📅 **Your Week-Long Game Development**
- [ ] Complete the full typing game with all features and polish
- [ ] Add difficulty levels with varying word complexity
- [ ] Implement user statistics tracking (WPM, accuracy over time)
- [ ] Create sound effects and animations for better user experience
- [ ] Make your game mobile-responsive for touch devices
- [ ] Share your game online and gather feedback from users
### 🌟 **Your Month-Long Interactive Development**
- [ ] Build multiple games exploring different interaction patterns
- [ ] Learn about game loops, state management, and performance optimization
- [ ] Contribute to open source game development projects
- [ ] Master advanced timing concepts and smooth animations
- [ ] Create a portfolio showcasing various interactive applications
- [ ] Mentor others interested in game development and user interaction
## 🎯 Your Typing Game Mastery Timeline
```mermaid
timeline
title Game Development Learning Progression
section Setup (10 minutes)
Project Structure: HTML foundation
: CSS styling setup
: JavaScript file creation
section User Interface (20 minutes)
Interactive Elements: Input fields
: Button controls
: Display areas
: Responsive layout
section Event Handling (25 minutes)
User Interaction: Keyboard events
: Mouse events
: Real-time feedback
: State management
section Game Logic (30 minutes)
Core Functionality: Quote generation
: Character comparison
: Accuracy calculation
: Timer implementation
section Performance Tracking (35 minutes)
Metrics & Analytics: WPM calculation
: Error tracking
: Progress visualization
: Results display
section Polish & Enhancement (45 minutes)
User Experience: Visual feedback
: Sound effects
: Animations
: Accessibility features
section Advanced Features (1 week)
Extended Functionality: Difficulty levels
: Leaderboards
: Custom quotes
: Multiplayer options
section Professional Skills (1 month)
Game Development: Performance optimization
: Code architecture
: Testing strategies
: Deployment patterns
```
### 🛠️ Your Game Development Toolkit Summary
After completing this project, you'll have mastered:
- **Event-Driven Programming**: Responsive user interfaces that react to input
- **Real-Time Feedback**: Instant visual and performance updates
- **Performance Measurement**: Accurate timing and scoring systems
- **Game State Management**: Controlling application flow and user experience
- **Interactive Design**: Creating engaging, addictive user experiences
- **Modern Web APIs**: Utilizing browser capabilities for rich interactions
- **Accessibility Patterns**: Inclusive design for all users
**Real-World Applications**: These skills directly apply to:
- **Web Applications**: Any interactive interface or dashboard
- **Educational Software**: Learning platforms and skill assessment tools
- **Productivity Tools**: Text editors, IDEs, and collaboration software
- **Gaming Industry**: Browser games and interactive entertainment
- **Mobile Development**: Touch-based interfaces and gesture handling
**Next Level**: You're ready to explore advanced game frameworks, real-time multiplayer systems, or complex interactive applications!
## Credits
Written with ♥️ by [Christopher Harrison](http://www.twitter.com/geektrainer)

@ -1,5 +1,22 @@
# Browser Extension Project Part 1: All about Browsers
```mermaid
journey
title Your Browser Extension Development Journey
section Foundation
Understand browsers: 3: Student
Learn extension types: 4: Student
Setup development: 4: Student
section Development
Build interface: 4: Student
Add functionality: 5: Student
Handle data: 5: Student
section Integration
Test in browser: 5: Student
Debug issues: 4: Student
Polish experience: 5: Student
```
![Browser sketchnote](../../sketchnotes/browser.jpg)
> Sketchnote by [Wassim Chegham](https://dev.to/wassimchegham/ever-wondered-what-happens-when-you-type-in-a-url-in-an-address-bar-in-a-browser-3dob)
@ -15,6 +32,36 @@ Before we build your first extension, let's understand how browsers work. Just a
By the end of this lesson, you'll understand browser architecture and have started building your first extension.
```mermaid
mindmap
root((Browser Architecture))
Core Components
Rendering Engine
JavaScript Engine
Network Stack
Storage APIs
User Interface
Address Bar
Tab Management
Bookmarks
Extension Icons
Extension System
Manifest Files
Content Scripts
Background Pages
Popup Windows
Security Model
Same-Origin Policy
Permissions API
Content Security
Isolated Worlds
Development Tools
DevTools Integration
Debug Console
Performance Monitor
Extension Inspector
```
## Understanding Web Browsers
A web browser is essentially a sophisticated document interpreter. When you type "google.com" into the address bar, the browser performs a complex series of operations - requesting content from servers worldwide, then parsing and rendering that code into the interactive web pages you see.
@ -34,15 +81,21 @@ The process between entering a URL and seeing a webpage involves several coordin
sequenceDiagram
participant User
participant Browser
participant Extension
participant DNS
participant Server
User->>Browser: Types URL and presses Enter
Browser->>Extension: Trigger beforeRequest event
Extension->>Extension: Check if URL needs modification
Browser->>DNS: Looks up server IP address
DNS->>Browser: Returns IP address
Browser->>Server: Requests web page content
Server->>Browser: Sends HTML, CSS, and JavaScript
Browser->>Extension: Trigger beforeResponse event
Extension->>Extension: Modify content if needed
Browser->>User: Renders complete web page
Extension->>User: Show extension UI updates
```
**Here's what this process accomplishes:**
@ -90,6 +143,26 @@ Browser extensions solve common web browsing challenges by adding functionality
This concept mirrors how early computer pioneers like Douglas Engelbart envisioned augmenting human capabilities with technology - extensions augment your browser's basic functionality.
```mermaid
quadrantChart
title Browser Extension Categories
x-axis Simple --> Complex
y-axis Personal Use --> Professional Tools
quadrant-1 Developer Tools
quadrant-2 Enterprise Solutions
quadrant-3 Personal Utilities
quadrant-4 Productivity Apps
Ad Blockers: [0.3, 0.2]
Password Managers: [0.7, 0.3]
Color Pickers: [0.4, 0.8]
Code Formatters: [0.8, 0.9]
Note Taking: [0.6, 0.5]
Video Downloaders: [0.5, 0.2]
Time Trackers: [0.7, 0.6]
Screenshot Tools: [0.4, 0.4]
```
**Popular extension categories and their benefits:**
- **Productivity Tools**: Task managers, note-taking apps, and time trackers that help you stay organized
- **Security Enhancements**: Password managers, ad blockers, and privacy tools that protect your data
@ -98,6 +171,20 @@ This concept mirrors how early computer pioneers like Douglas Engelbart envision
**Reflection Question**: What are your favorite browser extensions? What specific tasks do they perform, and how do they improve your browsing experience?
### 🔄 **Pedagogical Check-in**
**Browser Architecture Understanding**: Before moving to extension development, ensure you can:
- ✅ Explain how browsers process web requests and render content
- ✅ Identify the main components of browser architecture
- ✅ Understand how extensions integrate with browser functionality
- ✅ Recognize the security model that protects users
**Quick Self-Test**: Can you trace the path from typing a URL to seeing a webpage?
1. **DNS lookup** converts URL to IP address
2. **HTTP request** fetches content from server
3. **Parsing** processes HTML, CSS, and JavaScript
4. **Rendering** displays the final webpage
5. **Extensions** can modify content at multiple steps
## Installing and Managing Extensions
Understanding the extension installation process helps you anticipate the user experience when people install your extension. The installation process is standardized across modern browsers, with minor variations in interface design.
@ -110,6 +197,26 @@ Understanding the extension installation process helps you anticipate the user e
When you're developing and testing your own extensions, follow this workflow:
```mermaid
flowchart TD
A[Write Code] --> B[Build Extension]
B --> C{First Install?}
C -->|Yes| D[Load Unpacked]
C -->|No| E[Reload Extension]
D --> F[Test Functionality]
E --> F
F --> G{Working Correctly?}
G -->|No| H[Debug Issues]
G -->|Yes| I[Ready for Users]
H --> A
I --> J[Publish to Store]
style A fill:#e1f5fe
style F fill:#e8f5e8
style I fill:#f3e5f5
style J fill:#fff3e0
```
```bash
# Step 1: Build your extension
npm run build
@ -164,6 +271,20 @@ Before beginning development, let's gather the required resources and dependenci
Understanding the project structure helps organize development work efficiently. Like how the Library of Alexandria was organized for easy knowledge retrieval, a well-structured codebase makes development more efficient:
```mermaid
fileStructure
project-root
dist
manifest.json
index.html
background.js
main.js
src
index.js
package.json
webpack.config.js
```
```
project-root/
├── dist/ # Built extension files
@ -286,6 +407,19 @@ At this point, you can test your extension:
- **Set up** a modern development workflow using industry-standard tools
- **Prepared** the foundation for adding interactive JavaScript functionality
### 🔄 **Pedagogical Check-in**
**Extension Development Progress**: Verify your understanding before continuing:
- ✅ Can you explain the purpose of each file in the project structure?
- ✅ Do you understand how the build process transforms your source code?
- ✅ Why do we separate configuration and results into different UI sections?
- ✅ How does the form structure support both usability and accessibility?
**Development Workflow Understanding**: You should now be able to:
1. **Modify** HTML and CSS for your extension interface
2. **Run** the build command to compile your changes
3. **Reload** the extension in your browser to test updates
4. **Debug** issues using browser developer tools
You've completed the first phase of browser extension development. Like how the Wright brothers first needed to understand aerodynamics before achieving flight, understanding these foundational concepts prepares you for building more complex interactive features in the next lesson.
## GitHub Copilot Agent Challenge 🚀
@ -316,6 +450,109 @@ In this lesson you learned a little about the history of the web browser; take t
[An interview with Tim Berners-Lee](https://www.theguardian.com/technology/2019/mar/12/tim-berners-lee-on-30-years-of-the-web-if-we-dream-a-little-we-can-get-the-web-we-want)
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open Chrome/Edge extensions page (chrome://extensions) and explore what you have installed
- [ ] Look at your browser's DevTools Network tab while loading a webpage
- [ ] Try viewing page source (Ctrl+U) to see HTML structure
- [ ] Inspect any webpage element and modify its CSS in DevTools
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand browser fundamentals
- [ ] Create a basic manifest.json file for a browser extension
- [ ] Build a simple "Hello World" extension that shows a popup
- [ ] Test loading your extension in developer mode
- [ ] Explore the browser extension documentation for your target browser
### 📅 **Your Week-Long Extension Journey**
- [ ] Complete a functional browser extension with real utility
- [ ] Learn about content scripts, background scripts, and popup interactions
- [ ] Master browser APIs like storage, tabs, and messaging
- [ ] Design user-friendly interfaces for your extension
- [ ] Test your extension across different websites and scenarios
- [ ] Publish your extension to the browser's extension store
### 🌟 **Your Month-Long Browser Development**
- [ ] Build multiple extensions solving different user problems
- [ ] Learn advanced browser APIs and security best practices
- [ ] Contribute to open source browser extension projects
- [ ] Master cross-browser compatibility and progressive enhancement
- [ ] Create extension development tools and templates for others
- [ ] Become a browser extension expert who helps other developers
## 🎯 Your Browser Extension Mastery Timeline
```mermaid
timeline
title Browser Extension Development Progression
section Foundation (15 minutes)
Browser Understanding: Core architecture
: Rendering process
: Extension integration points
section Setup (20 minutes)
Development Environment: Project structure
: Build tools configuration
: Browser developer mode
: Extension loading process
section Interface Design (25 minutes)
User Experience: HTML structure
: CSS styling
: Form validation
: Responsive design
section Core Functionality (35 minutes)
JavaScript Integration: Event handling
: API interactions
: Data storage
: Error handling
section Browser APIs (45 minutes)
Platform Integration: Permissions system
: Storage APIs
: Tab management
: Context menus
section Advanced Features (1 week)
Professional Extensions: Background scripts
: Content scripts
: Cross-browser compatibility
: Performance optimization
section Publishing (2 weeks)
Distribution: Store submission
: Review process
: User feedback
: Update management
section Expert Level (1 month)
Extension Ecosystem: Advanced APIs
: Security best practices
: Enterprise features
: Framework integration
```
### 🛠️ Your Extension Development Toolkit Summary
After completing this lesson, you now have:
- **Browser Architecture Knowledge**: Understanding of rendering engines, security models, and extension integration
- **Development Environment**: Modern toolchain with Webpack, NPM, and debugging capabilities
- **UI/UX Foundation**: Semantic HTML structure with progressive disclosure patterns
- **Security Awareness**: Understanding of browser permissions and safe development practices
- **Cross-Browser Concepts**: Knowledge of compatibility considerations and testing approaches
- **API Integration**: Foundation for working with external data sources
- **Professional Workflow**: Industry-standard development and testing procedures
**Real-World Applications**: These skills directly apply to:
- **Web Development**: Single-page applications and progressive web apps
- **Desktop Applications**: Electron and web-based desktop software
- **Mobile Development**: Hybrid apps and web-based mobile solutions
- **Enterprise Tools**: Internal productivity applications and workflow automation
- **Open Source**: Contributing to browser extension projects and web standards
**Next Level**: You're ready to add interactive functionality, work with browser APIs, and create extensions that solve real user problems!
## Assignment
[Restyle your extension](assignment.md)

@ -1,5 +1,22 @@
# Browser Extension Project Part 2: Call an API, use Local Storage
```mermaid
journey
title Your API Integration & Storage Journey
section Foundation
Setup DOM references: 3: Student
Add event listeners: 4: Student
Handle form submission: 4: Student
section Data Management
Implement local storage: 4: Student
Build API calls: 5: Student
Handle async operations: 5: Student
section User Experience
Add error handling: 5: Student
Create loading states: 4: Student
Polish interactions: 5: Student
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/25)
@ -14,6 +31,36 @@ API integration might sound complex, but it's really just teaching your code how
By the end of this lesson, you'll have a browser extension that fetches real data, stores user preferences, and provides a smooth experience. Let's get started!
```mermaid
mindmap
root((Dynamic Extensions))
DOM Manipulation
Element Selection
Event Handling
State Management
UI Updates
Local Storage
Data Persistence
Key-Value Pairs
Session Management
User Preferences
API Integration
HTTP Requests
Authentication
Data Parsing
Error Handling
Async Programming
Promises
Async/Await
Error Catching
Non-blocking Code
User Experience
Loading States
Error Messages
Smooth Transitions
Data Validation
```
✅ Follow the numbered segments in the appropriate files to know where to place your code
## Set up the elements to manipulate in the extension
@ -22,6 +69,33 @@ Before your JavaScript can manipulate the interface, it needs references to spec
In your `index.js` file, we'll create `const` variables that capture references to each important form element. This is similar to how scientists label their equipment - instead of searching through the entire laboratory each time, they can directly access what they need.
```mermaid
flowchart LR
A[JavaScript Code] --> B[document.querySelector]
B --> C[CSS Selectors]
C --> D[HTML Elements]
D --> E[".form-data"]
D --> F[".region-name"]
D --> G[".api-key"]
D --> H[".loading"]
D --> I[".errors"]
D --> J[".result-container"]
E --> K[Form Element]
F --> L[Input Field]
G --> M[Input Field]
H --> N[UI Element]
I --> O[UI Element]
J --> P[UI Element]
style A fill:#e1f5fe
style D fill:#e8f5e8
style K fill:#fff3e0
style L fill:#fff3e0
style M fill:#fff3e0
```
```javascript
// form fields
const form = document.querySelector('.form-data');
@ -49,6 +123,29 @@ const clearBtn = document.querySelector('.clear-btn');
Now we'll make your extension respond to user actions. Event listeners are your code's way of monitoring user interactions. Think of them like the operators in early telephone exchanges - they listened for incoming calls and connected the right circuits when someone wanted to make a connection.
```mermaid
sequenceDiagram
participant User
participant Form
participant JavaScript
participant API
participant Storage
User->>Form: Fills out region/API key
User->>Form: Clicks submit
Form->>JavaScript: Triggers submit event
JavaScript->>JavaScript: handleSubmit(e)
JavaScript->>Storage: Save user preferences
JavaScript->>API: Fetch carbon data
API->>JavaScript: Returns data
JavaScript->>Form: Update UI with results
User->>Form: Clicks clear button
Form->>JavaScript: Triggers click event
JavaScript->>Storage: Clear saved data
JavaScript->>Form: Reset to initial state
```
```javascript
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
@ -63,6 +160,16 @@ init();
✅ Notice the shorthand arrow function syntax used here. This modern JavaScript approach is cleaner than traditional function expressions, but both work equally well!
### 🔄 **Pedagogical Check-in**
**Event Handling Understanding**: Before moving to initialization, ensure you can:
- ✅ Explain how `addEventListener` connects user actions to JavaScript functions
- ✅ Understand why we pass the event object `(e)` to handler functions
- ✅ Recognize the difference between `submit` and `click` events
- ✅ Describe when the `init()` function runs and why
**Quick Self-Test**: What would happen if you forgot `e.preventDefault()` in a form submission?
*Answer: The page would reload, losing all JavaScript state and interrupting the user experience*
## Build the initialization and reset functions
Let's create the initialization logic for your extension. The `init()` function is like a ship's navigation system checking its instruments - it determines the current state and adjusts the interface accordingly. It checks if someone has used your extension before and loads their previous settings.
@ -128,6 +235,30 @@ function reset(e) {
You can view your stored data by opening browser Developer Tools (F12), navigating to the **Application** tab, and expanding the **Local Storage** section.
```mermaid
stateDiagram-v2
[*] --> CheckStorage: Extension starts
CheckStorage --> FirstTime: No stored data
CheckStorage --> Returning: Data found
FirstTime --> ShowForm: Display setup form
ShowForm --> UserInput: User enters data
UserInput --> SaveData: Store in localStorage
SaveData --> FetchAPI: Get carbon data
Returning --> LoadData: Read from localStorage
LoadData --> FetchAPI: Get carbon data
FetchAPI --> ShowResults: Display data
ShowResults --> UserAction: User interacts
UserAction --> Reset: Clear button clicked
UserAction --> ShowResults: View data
Reset --> ClearStorage: Remove saved data
ClearStorage --> FirstTime: Back to setup
```
![Local storage pane](images/localstorage.png)
> ⚠️ **Security Consideration**: In production applications, storing API keys in LocalStorage poses security risks since JavaScript can access this data. For learning purposes, this approach works fine, but real applications should use secure server-side storage for sensitive credentials.
@ -192,6 +323,36 @@ Now we'll connect your extension to external data sources through APIs. This tra
[APIs](https://www.webopedia.com/TERM/A/API.html) are how different applications communicate with each other. Think of them like the telegraph system that connected distant cities in the 19th century - operators would send requests to distant stations and receive responses with the requested information. Every time you check social media, ask a voice assistant a question, or use a delivery app, APIs are facilitating these data exchanges.
```mermaid
flowchart TD
A[Your Extension] --> B[HTTP Request]
B --> C[CO2 Signal API]
C --> D{Valid Request?}
D -->|Yes| E[Query Database]
D -->|No| F[Return Error]
E --> G[Carbon Data]
G --> H[JSON Response]
H --> I[Your Extension]
F --> I
I --> J[Update UI]
subgraph "API Request"
K[Headers: auth-token]
L[Parameters: countryCode]
M[Method: GET]
end
subgraph "API Response"
N[Carbon Intensity]
O[Fossil Fuel %]
P[Timestamp]
end
style C fill:#e8f5e8
style G fill:#fff3e0
style I fill:#e1f5fe
```
**Key concepts about REST APIs:**
- **REST** stands for 'Representational State Transfer'
- **Uses** standard HTTP methods (GET, POST, PUT, DELETE) to interact with data
@ -214,6 +375,33 @@ Here's a quick video about `async`:
> 🎥 Click the image above for a video about async/await.
### 🔄 **Pedagogical Check-in**
**Async Programming Understanding**: Before diving into the API function, verify you understand:
- ✅ Why we use `async/await` instead of blocking the entire extension
- ✅ How `try/catch` blocks handle network errors gracefully
- ✅ The difference between synchronous and asynchronous operations
- ✅ Why API calls can fail and how to handle those failures
**Real-World Connection**: Consider these everyday async examples:
- **Ordering food**: You don't wait by the kitchen - you get a receipt and continue other activities
- **Sending emails**: Your email app doesn't freeze while sending - you can compose more emails
- **Loading web pages**: Images load progressively while you can already read the text
**API Authentication Flow**:
```mermaid
sequenceDiagram
participant Ext as Extension
participant API as CO2 Signal API
participant DB as Database
Ext->>API: Request with auth-token
API->>API: Validate token
API->>DB: Query carbon data
DB->>API: Return data
API->>Ext: JSON response
Ext->>Ext: Update UI
```
Create the function to fetch and display carbon usage data:
```javascript
@ -283,6 +471,38 @@ async function displayCarbonUsage(apiKey, region) {
✅ This function demonstrates several important web development concepts - communicating with external servers, handling authentication, processing data, updating interfaces, and managing errors gracefully. These are fundamental skills that professional developers use regularly.
```mermaid
flowchart TD
A[Start API Call] --> B[Fetch Request]
B --> C{Network Success?}
C -->|No| D[Network Error]
C -->|Yes| E{Response OK?}
E -->|No| F[API Error]
E -->|Yes| G[Parse JSON]
G --> H{Valid Data?}
H -->|No| I[Data Error]
H -->|Yes| J[Update UI]
D --> K[Show Error Message]
F --> K
I --> K
J --> L[Hide Loading]
K --> L
style A fill:#e1f5fe
style J fill:#e8f5e8
style K fill:#ffebee
style L fill:#f3e5f5
```
### 🔄 **Pedagogical Check-in**
**Complete System Understanding**: Verify your mastery of the entire flow:
- ✅ How DOM references enable JavaScript to control the interface
- ✅ Why local storage creates persistence between browser sessions
- ✅ How async/await makes API calls without freezing the extension
- ✅ What happens when API calls fail and how errors are handled
- ✅ Why user experience includes loading states and error messages
🎉 **What you've accomplished:** You've created a browser extension that:
- **Connects** to the internet and retrieves real environmental data
- **Persists** user settings between sessions
@ -329,6 +549,109 @@ After your research, identify what characteristics make an API developer-friendl
You learned about LocalStorage and APIs in this lesson, both very useful for the professional web developer. Can you think about how these two things work together? Think about how you would architect a web site that would store items to be used by an API.
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open DevTools Application tab and explore localStorage on any website
- [ ] Create a simple HTML form and test form validation in the browser
- [ ] Try storing and retrieving data using localStorage in the browser console
- [ ] Inspect form data being submitted using the Network tab
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand form handling concepts
- [ ] Build a browser extension form that saves user preferences
- [ ] Implement client-side form validation with helpful error messages
- [ ] Practice using the chrome.storage API for extension data persistence
- [ ] Create a user interface that responds to saved user settings
### 📅 **Your Week-Long Extension Building**
- [ ] Complete a full-featured browser extension with form functionality
- [ ] Master different storage options: local, sync, and session storage
- [ ] Implement advanced form features like autocomplete and validation
- [ ] Add import/export functionality for user data
- [ ] Test your extension thoroughly across different browsers
- [ ] Polish your extension's user experience and error handling
### 🌟 **Your Month-Long Web API Mastery**
- [ ] Build complex applications using various browser storage APIs
- [ ] Learn about offline-first development patterns
- [ ] Contribute to open source projects involving data persistence
- [ ] Master privacy-focused development and GDPR compliance
- [ ] Create reusable libraries for form handling and data management
- [ ] Share knowledge about web APIs and extension development
## 🎯 Your Extension Development Mastery Timeline
```mermaid
timeline
title API Integration & Storage Learning Progression
section DOM Fundamentals (15 minutes)
Element References: querySelector mastery
: Event listener setup
: State management basics
section Local Storage (20 minutes)
Data Persistence: Key-value storage
: Session management
: User preference handling
: Storage inspection tools
section Form Handling (25 minutes)
User Input: Form validation
: Event prevention
: Data extraction
: UI state transitions
section API Integration (35 minutes)
External Communication: HTTP requests
: Authentication patterns
: JSON data parsing
: Response handling
section Async Programming (40 minutes)
Modern JavaScript: Promise handling
: Async/await patterns
: Error management
: Non-blocking operations
section Error Handling (30 minutes)
Robust Applications: Try/catch blocks
: User-friendly messages
: Graceful degradation
: Debugging techniques
section Advanced Patterns (1 week)
Professional Development: Caching strategies
: Rate limiting
: Retry mechanisms
: Performance optimization
section Production Skills (1 month)
Enterprise Features: Security best practices
: API versioning
: Monitoring & logging
: Scalable architecture
```
### 🛠️ Your Full-Stack Development Toolkit Summary
After completing this lesson, you now have:
- **DOM Mastery**: Precise element targeting and manipulation
- **Storage Expertise**: Persistent data management with localStorage
- **API Integration**: Real-time data fetching and authentication
- **Async Programming**: Non-blocking operations with modern JavaScript
- **Error Handling**: Robust applications that gracefully handle failures
- **User Experience**: Loading states, validation, and smooth interactions
- **Modern Patterns**: fetch API, async/await, and ES6+ features
**Professional Skills Gained**: You've implemented patterns used in:
- **Web Applications**: Single-page apps with external data sources
- **Mobile Development**: API-driven apps with offline capabilities
- **Desktop Software**: Electron apps with persistent storage
- **Enterprise Systems**: Authentication, caching, and error handling
- **Modern Frameworks**: React/Vue/Angular data management patterns
**Next Level**: You're ready to explore advanced topics like caching strategies, real-time WebSocket connections, or complex state management!
## Assignment
[Adopt an API](assignment.md)

@ -1,5 +1,22 @@
# Browser Extension Project Part 3: Learn about Background Tasks and Performance
```mermaid
journey
title Your Performance Optimization Journey
section Foundation
Learn browser tools: 3: Student
Understand profiling: 4: Student
Identify bottlenecks: 4: Student
section Extension Features
Build color system: 4: Student
Create background tasks: 5: Student
Update icons dynamically: 5: Student
section Optimization
Monitor performance: 5: Student
Debug issues: 4: Student
Polish experience: 5: Student
```
Ever wonder what makes some browser extensions feel snappy and responsive while others seem sluggish? The secret lies in what's happening behind the scenes. While users click around your extension's interface, there's a whole world of background processes quietly managing data fetching, icon updates, and system resources.
This is our final lesson in the browser extension series, and we're going to make your carbon footprint tracker work smoothly. You'll add dynamic icon updates and learn how to spot performance issues before they become problems. It's like tuning a race car - small optimizations can make a huge difference in how everything runs.
@ -16,6 +33,36 @@ In our previous lessons, you built a form, connected it to an API, and tackled a
Now we need to add the finishing touches - like making that extension icon change colors based on the carbon data. This reminds me of how NASA had to optimize every system on the Apollo spacecraft. They couldn't afford any wasted cycles or memory because lives depended on performance. While our browser extension isn't quite that critical, the same principles apply - efficient code creates better user experiences.
```mermaid
mindmap
root((Performance & Background Tasks))
Browser Performance
Rendering Pipeline
Asset Optimization
DOM Manipulation
JavaScript Execution
Profiling Tools
Developer Tools
Performance Tab
Timeline Analysis
Bottleneck Detection
Extension Architecture
Background Scripts
Content Scripts
Message Passing
Icon Management
Optimization Strategies
Code Splitting
Lazy Loading
Caching
Resource Compression
Visual Feedback
Dynamic Icons
Color Coding
Real-time Updates
User Experience
```
## Web Performance Basics
When your code runs efficiently, people can actually *feel* the difference. You know that moment when a page loads instantly or an animation flows smoothly? That's good performance at work.
@ -28,6 +75,38 @@ The topic of how to make your websites blazingly fast on all kinds of devices, f
The first step in optimizing your site is understanding what's actually happening under the hood. Fortunately, your browser comes with powerful detective tools built right in.
```mermaid
flowchart LR
A[HTML] --> B[Parse]
B --> C[DOM Tree]
D[CSS] --> E[Parse]
E --> F[CSSOM]
G[JavaScript] --> H[Execute]
C --> I[Render Tree]
F --> I
H --> I
I --> J[Layout]
J --> K[Paint]
K --> L[Composite]
L --> M[Display]
subgraph "Critical Rendering Path"
N["1. Parse HTML"]
O["2. Parse CSS"]
P["3. Execute JS"]
Q["4. Build Render Tree"]
R["5. Layout Elements"]
S["6. Paint Pixels"]
T["7. Composite Layers"]
end
style M fill:#e8f5e8
style I fill:#fff3e0
style H fill:#ffebee
```
To open Developer Tools in Edge, click those three dots in the top right corner, then go to More Tools > Developer Tools. Or use the keyboard shortcut: `Ctrl` + `Shift` + `I` on Windows or `Option` + `Command` + `I` on Mac. Once you're there, click on the Performance tab - this is where you'll do your investigation.
**Here's your performance detective toolkit:**
@ -56,6 +135,39 @@ Check the Event Log pane to see if any event took longer than 15 ms:
✅ Get to know your profiler! Open the developer tools on this site and see if there are any bottlenecks. What's the slowest-loading asset? The fastest?
```mermaid
flowchart TD
A[Open DevTools] --> B[Navigate to Performance Tab]
B --> C[Click Record Button]
C --> D[Perform Actions]
D --> E[Stop Recording]
E --> F{Analyze Results}
F --> G[Check Timeline]
F --> H[Review Network]
F --> I[Examine Scripts]
F --> J[Identify Paint Events]
G --> K{Long Tasks?}
H --> L{Large Assets?}
I --> M{Render Blocking?}
J --> N{Expensive Paints?}
K -->|Yes| O[Optimize JavaScript]
L -->|Yes| P[Compress Assets]
M -->|Yes| Q[Add Async/Defer]
N -->|Yes| R[Simplify Styles]
O --> S[Test Again]
P --> S
Q --> S
R --> S
style A fill:#e1f5fe
style F fill:#fff3e0
style S fill:#e8f5e8
```
## What to Look For When Profiling
Running the profiler is just the beginning - the real skill is knowing what those colorful charts are actually telling you. Don't worry, you'll get the hang of reading them. Experienced developers have learned to spot the warning signs before they become full-blown problems.
@ -90,6 +202,22 @@ Let's talk about the usual suspects - the performance troublemakers that tend to
✅ Try some sites on a [Site Speed Test website](https://www.webpagetest.org/) to learn more about the common checks that are done to determine site performance.
### 🔄 **Pedagogical Check-in**
**Performance Understanding**: Before building extension features, ensure you can:
- ✅ Explain the critical rendering path from HTML to pixels
- ✅ Identify common performance bottlenecks in web applications
- ✅ Use browser developer tools to profile page performance
- ✅ Understand how asset size and DOM complexity affect speed
**Quick Self-Test**: What happens when you have render-blocking JavaScript?
*Answer: The browser must download and execute the script before it can continue parsing HTML and rendering the page*
**Real-World Performance Impact**:
- **100ms delay**: Users notice the slowdown
- **1 second delay**: Users start losing focus
- **3+ seconds**: 40% of users abandon the page
- **Mobile networks**: Performance matters even more
Now that you have an idea of how the browser renders the assets you send to it, let's look at the last few things you need to do to complete your extension:
### Create a function to calculate color
@ -98,6 +226,32 @@ Now we'll create a function that turns numerical data into meaningful colors. Th
This function will take the CO2 data from our API and determine what color best represents the environmental impact. It's similar to how scientists use color-coding in heat maps to visualize complex data patterns - from ocean temperatures to star formation. Let's add this to `/src/index.js`, right after those `const` variables we set up earlier:
```mermaid
flowchart LR
A[CO2 Value] --> B[Find Closest Scale Point]
B --> C[Get Scale Index]
C --> D[Map to Color]
D --> E[Send to Background]
subgraph "Color Scale"
F["0-150: Green (Clean)"]
G["150-600: Yellow (Moderate)"]
H["600-750: Orange (High)"]
I["750+: Brown (Very High)"]
end
subgraph "Message Passing"
J[Content Script]
K[chrome.runtime.sendMessage]
L[Background Script]
M[Icon Update]
end
style A fill:#e1f5fe
style D fill:#e8f5e8
style E fill:#fff3e0
```
```javascript
function calculateColor(value) {
// Define CO2 intensity scale (grams per kWh)
@ -144,6 +298,25 @@ The `chrome.runtime` [API](https://developer.chrome.com/extensions/runtime) is l
✅ If you're developing this browser extension for Edge, it might surprise you that you're using a chrome API. The newer Edge browser versions run on the Chromium browser engine, so you can leverage these tools.
```mermaid
architecture-beta
group browser(logos:chrome)[Browser]
service popup(logos:html5)[Popup UI] in browser
service content(logos:javascript)[Content Script] in browser
service background(database)[Background Script] in browser
service api(logos:api)[External API] in browser
popup:R -- L:content
content:R -- L:background
background:T -- B:api
content:T -- B:api
junction junctionCenter in browser
popup:R -- L:junctionCenter
junctionCenter:R -- L:background
```
> **Pro Tip**: If you want to profile a browser extension, launch the dev tools from within the extension itself, as it is its own separate browser instance. This gives you access to extension-specific performance metrics.
### Set a default icon color
@ -222,6 +395,36 @@ function drawIcon(value) {
✅ You'll learn more about the Canvas API in the [Space Game lessons](../../6-space-game/2-drawing-to-canvas/README.md).
```mermaid
sequenceDiagram
participant CS as Content Script
participant BG as Background Script
participant Canvas as OffscreenCanvas
participant Browser as Browser Icon
CS->>BG: sendMessage({action: 'updateIcon', color})
BG->>Canvas: new OffscreenCanvas(200, 200)
Canvas->>Canvas: getContext('2d')
Canvas->>Canvas: beginPath() + fillStyle + arc()
Canvas->>Canvas: fill() + getImageData()
Canvas->>BG: Return image data
BG->>Browser: chrome.action.setIcon(imageData)
Browser->>Browser: Update toolbar icon
```
### 🔄 **Pedagogical Check-in**
**Complete Extension Understanding**: Verify your mastery of the entire system:
- ✅ How does message passing work between different extension scripts?
- ✅ Why do we use OffscreenCanvas instead of regular Canvas for performance?
- ✅ What role does the Chrome Runtime API play in extension architecture?
- ✅ How does the color calculation algorithm map data to visual feedback?
**Performance Considerations**: Your extension now demonstrates:
- **Efficient messaging**: Clean communication between script contexts
- **Optimized rendering**: OffscreenCanvas prevents UI blocking
- **Real-time updates**: Dynamic icon changes based on live data
- **Memory management**: Proper cleanup and resource handling
**Time to test your extension:**
- **Build** everything with `npm run build`
- **Reload** your extension in the browser (don't forget this step)
@ -260,6 +463,126 @@ Consider signing up for a [performance newsletter](https://perf.email/)
Investigate some of the ways that browsers gauge web performance by looking through the performance tabs in their web tools. Do you find any major differences?
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open browser Task Manager (Shift+Esc in Chrome) to see extension resource usage
- [ ] Use DevTools Performance tab to record and analyze webpage performance
- [ ] Check the browser's Extensions page to see which extensions impact startup time
- [ ] Try disabling extensions temporarily to see performance differences
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand performance concepts
- [ ] Implement a background script for your browser extension
- [ ] Learn to use browser.alarms for efficient background tasks
- [ ] Practice message passing between content scripts and background scripts
- [ ] Measure and optimize your extension's resource usage
### 📅 **Your Week-Long Performance Journey**
- [ ] Complete a high-performance browser extension with background functionality
- [ ] Master service workers and modern extension architecture
- [ ] Implement efficient data synchronization and caching strategies
- [ ] Learn advanced debugging techniques for extension performance
- [ ] Optimize your extension for both functionality and resource efficiency
- [ ] Create comprehensive tests for extension performance scenarios
### 🌟 **Your Month-Long Optimization Mastery**
- [ ] Build enterprise-grade browser extensions with optimal performance
- [ ] Learn about Web Workers, Service Workers, and modern web performance
- [ ] Contribute to open source projects focused on performance optimization
- [ ] Master browser internals and advanced debugging techniques
- [ ] Create performance monitoring tools and best practices guides
- [ ] Become a performance expert who helps optimize web applications
## 🎯 Your Browser Extension Mastery Timeline
```mermaid
timeline
title Complete Extension Development Progression
section Performance Fundamentals (20 minutes)
Browser Profiling: DevTools mastery
: Timeline analysis
: Bottleneck identification
: Critical rendering path
section Background Tasks (25 minutes)
Extension Architecture: Message passing
: Background scripts
: Runtime API usage
: Cross-context communication
section Visual Feedback (30 minutes)
Dynamic UI: Color calculation algorithms
: Canvas API integration
: Icon generation
: Real-time updates
section Performance Optimization (35 minutes)
Efficient Code: Async operations
: Memory management
: Resource cleanup
: Performance monitoring
section Production Ready (45 minutes)
Polish & Testing: Cross-browser compatibility
: Error handling
: User experience
: Performance validation
section Advanced Features (1 week)
Extension Ecosystem: Chrome Web Store
: User feedback
: Analytics integration
: Update management
section Professional Development (2 weeks)
Enterprise Extensions: Team collaboration
: Code reviews
: CI/CD pipelines
: Security audits
section Expert Mastery (1 month)
Platform Expertise: Advanced Chrome APIs
: Performance optimization
: Architecture patterns
: Open source contribution
```
### 🛠️ Your Complete Extension Development Toolkit
After completing this trilogy, you now have mastered:
- **Browser Architecture**: Deep understanding of how extensions integrate with browser systems
- **Performance Profiling**: Ability to identify and fix bottlenecks using developer tools
- **Async Programming**: Modern JavaScript patterns for responsive, non-blocking operations
- **API Integration**: External data fetching with authentication and error handling
- **Visual Design**: Dynamic UI updates and Canvas-based graphics generation
- **Message Passing**: Inter-script communication in extension architectures
- **User Experience**: Loading states, error handling, and intuitive interactions
- **Production Skills**: Testing, debugging, and optimization for real-world deployment
**Real-World Applications**: Your extension development skills apply directly to:
- **Progressive Web Apps**: Similar architecture and performance patterns
- **Electron Desktop Apps**: Cross-platform applications using web technologies
- **Mobile Hybrid Apps**: Cordova/PhoneGap development using web APIs
- **Enterprise Web Applications**: Complex dashboard and productivity tools
- **Chrome DevTools Extensions**: Advanced developer tooling and debugging
- **Web API Integration**: Any application that communicates with external services
**Professional Impact**: You can now:
- **Build** production-ready browser extensions from concept to deployment
- **Optimize** web application performance using industry-standard profiling tools
- **Architect** scalable systems with proper separation of concerns
- **Debug** complex async operations and cross-context communication
- **Contribute** to open source extension projects and browser standards
**Next Level Opportunities**:
- **Chrome Web Store Developer**: Publish extensions for millions of users
- **Web Performance Engineer**: Specialize in optimization and user experience
- **Browser Platform Developer**: Contribute to browser engine development
- **Extension Framework Creator**: Build tools that help other developers
- **Developer Relations**: Share knowledge through teaching and content creation
🌟 **Achievement Unlocked**: You've built a complete, functional browser extension that demonstrates professional development practices and modern web standards!
## Assignment
[Analyze a site for performance](assignment.md)

@ -1,5 +1,22 @@
# Build a Space Game Part 1: Introduction
```mermaid
journey
title Your Game Development Journey
section Foundation
Learn game architecture: 3: Student
Understand inheritance: 4: Student
Explore composition: 4: Student
section Communication
Build pub/sub system: 4: Student
Design event flow: 5: Student
Connect components: 5: Student
section Application
Create game objects: 5: Student
Implement patterns: 5: Student
Plan game structure: 5: Student
```
![Space game animation showing gameplay](../images/pewpew.gif)
Just like NASA's mission control coordinates multiple systems during a space launch, we're going to build a space game that demonstrates how different parts of a program can work together seamlessly. While creating something you can actually play, you'll learn essential programming concepts that apply to any software project.
@ -8,6 +25,36 @@ We'll explore two fundamental approaches to organizing code: inheritance and com
By the end of this series, you'll understand how to build applications that can scale and evolve whether you're developing games, web applications, or any other software system.
```mermaid
mindmap
root((Game Architecture))
Object Organization
Inheritance
Composition
Class Hierarchies
Behavior Mixing
Communication Patterns
Pub/Sub System
Event Emitters
Message Passing
Loose Coupling
Game Objects
Properties (x, y)
Behaviors (move, collide)
Lifecycle Management
State Management
Design Patterns
Factory Functions
Observer Pattern
Component System
Event-Driven Architecture
Scalability
Modular Design
Maintainable Code
Testing Strategies
Performance Optimization
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/29)
@ -31,6 +78,45 @@ Despite their visual differences, these objects often share fundamental behavior
✅ Think about a game like Pac-Man. Can you identify the four object types listed above in this game?
```mermaid
classDiagram
class GameObject {
+x: number
+y: number
+type: string
+exists_somewhere()
}
class MovableObject {
+moveTo(x, y)
+can_move_around()
}
class TemporaryObject {
+lifespan: number
+has_lifespan()
}
class InteractiveObject {
+onCollision()
+reacts_to_stuff()
}
GameObject <|-- MovableObject
GameObject <|-- TemporaryObject
GameObject <|-- InteractiveObject
MovableObject <|-- Hero
MovableObject <|-- Enemy
MovableObject <|-- Bullet
TemporaryObject <|-- PowerUp
TemporaryObject <|-- Explosion
InteractiveObject <|-- Collectible
InteractiveObject <|-- Obstacle
```
### Expressing Behavior Through Code
Now that you understand the common behaviors game objects share, let's explore how to implement these behaviors in JavaScript. You can express object behavior through methods attached to either classes or individual objects, and there are several approaches to choose from.
@ -182,6 +268,26 @@ const tree = createStatic(0, 0, 'Tree');
**Which Pattern Should You Choose?**
**Which Pattern Should You Choose?**
```mermaid
quadrantChart
title Code Organization Patterns
x-axis Simple --> Complex
y-axis Rigid --> Flexible
quadrant-1 Advanced Composition
quadrant-2 Hybrid Approaches
quadrant-3 Basic Inheritance
quadrant-4 Modern Composition
Class Inheritance: [0.3, 0.2]
Interface Implementation: [0.6, 0.4]
Mixin Patterns: [0.7, 0.7]
Pure Composition: [0.8, 0.9]
Factory Functions: [0.5, 0.8]
Prototype Chain: [0.4, 0.3]
```
> 💡 **Pro Tip**: Both patterns have their place in modern JavaScript development. Classes work well for clearly defined hierarchies, while composition shines when you need maximum flexibility.
>
**Here's when to use each approach:**
@ -190,6 +296,22 @@ const tree = createStatic(0, 0, 'Tree');
- **Consider** your team's preferences and project requirements
- **Remember** that you can mix both approaches in the same application
### 🔄 **Pedagogical Check-in**
**Object Organization Understanding**: Before moving to communication patterns, ensure you can:
- ✅ Explain the difference between inheritance and composition
- ✅ Identify when to use classes vs factory functions
- ✅ Understand how the `super()` keyword works in inheritance
- ✅ Recognize the benefits of each approach for game development
**Quick Self-Test**: How would you create a Flying Enemy that can both move and fly?
- **Inheritance approach**: `class FlyingEnemy extends Movable`
- **Composition approach**: `{ ...movable, ...flyable, ...gameObject }`
**Real-World Connection**: These patterns appear everywhere:
- **React Components**: Props (composition) vs class inheritance
- **Game Engines**: Entity-component systems use composition
- **Mobile Apps**: UI frameworks often use inheritance hierarchies
## Communication Patterns: The Pub/Sub System
As applications grow complex, managing communication between components becomes challenging. The publish-subscribe pattern (pub/sub) solves this problem using principles similar to radio broadcasting one transmitter can reach multiple receivers without knowing who's listening.
@ -198,6 +320,30 @@ Consider what happens when a hero takes damage: the health bar updates, sound ef
**Pub/Sub** stands for 'publish-subscribe'
```mermaid
flowchart TD
A[Hero Takes Damage] --> B[Publish: HERO_DAMAGED]
B --> C[Event System]
C --> D[Health Bar Subscriber]
C --> E[Sound System Subscriber]
C --> F[Visual Effects Subscriber]
C --> G[Achievement System Subscriber]
D --> H[Update Health Display]
E --> I[Play Damage Sound]
F --> J[Show Red Flash]
G --> K[Check Survival Achievements]
style A fill:#ffebee
style B fill:#e1f5fe
style C fill:#e8f5e8
style H fill:#fff3e0
style I fill:#fff3e0
style J fill:#fff3e0
style K fill:#fff3e0
```
### Understanding the Pub/Sub Architecture
The pub/sub pattern keeps different parts of your application loosely coupled, meaning they can work together without being directly dependent on each other. This separation makes your code more maintainable, testable, and flexible to changes.
@ -306,6 +452,26 @@ window.addEventListener('keydown', (event) => {
- **Allows** multiple systems to respond to the same keyboard events
- **Makes** it easy to change key bindings or add new input methods
```mermaid
sequenceDiagram
participant User
participant Keyboard
participant EventEmitter
participant Hero
participant SoundSystem
participant Camera
User->>Keyboard: Presses ArrowLeft
Keyboard->>EventEmitter: emit('HERO_MOVE_LEFT')
EventEmitter->>Hero: Move left 5 pixels
EventEmitter->>SoundSystem: Play footstep sound
EventEmitter->>Camera: Follow hero
Hero->>Hero: Update position
SoundSystem->>SoundSystem: Play audio
Camera->>Camera: Adjust viewport
```
> 💡 **Pro Tip**: The beauty of this pattern is flexibility! You can easily add sound effects, screen shake, or particle effects by simply adding more event listeners no need to modify the existing keyboard or movement code.
>
**Here's why you'll love this approach:**
@ -326,6 +492,24 @@ The pub/sub pattern maintains simplicity as applications grow in complexity. Whe
- **Keeps** message payloads simple and focused
- **Documents** your message types for team collaboration
### 🔄 **Pedagogical Check-in**
**Event-Driven Architecture Understanding**: Verify your grasp of the complete system:
- ✅ How does the pub/sub pattern prevent tight coupling between components?
- ✅ Why is it easier to add new features with event-driven architecture?
- ✅ What role does the EventEmitter play in the communication flow?
- ✅ How do message constants prevent bugs and improve maintainability?
**Design Challenge**: How would you handle these game scenarios with pub/sub?
1. **Enemy dies**: Update score, play sound, spawn power-up, remove from screen
2. **Level complete**: Stop music, show UI, save progress, load next level
3. **Power-up collected**: Enhance abilities, update UI, play effect, start timer
**Professional Connection**: This pattern appears in:
- **Frontend Frameworks**: React/Vue event systems
- **Backend Services**: Microservice communication
- **Game Engines**: Unity's event system
- **Mobile Development**: iOS/Android notification systems
---
## GitHub Copilot Agent Challenge 🚀
@ -350,6 +534,120 @@ Consider how the pub-sub pattern can enhance game architecture. Identify which c
Learn more about Pub/Sub by [reading about it](https://docs.microsoft.com/azure/architecture/patterns/publisher-subscriber/?WT.mc_id=academic-77807-sagibbon).
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open any HTML5 game online and inspect its code using DevTools
- [ ] Create a simple HTML5 Canvas element and draw a basic shape
- [ ] Try using `setInterval` to create a simple animation loop
- [ ] Explore the Canvas API documentation and try a drawing method
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand game development concepts
- [ ] Set up your game project structure with HTML, CSS, and JavaScript files
- [ ] Create a basic game loop that updates and renders continuously
- [ ] Draw your first game sprites on the canvas
- [ ] Implement basic asset loading for images and sounds
### 📅 **Your Week-Long Game Creation**
- [ ] Complete the full space game with all planned features
- [ ] Add polished graphics, sound effects, and smooth animations
- [ ] Implement game states (start screen, gameplay, game over)
- [ ] Create a scoring system and player progress tracking
- [ ] Make your game responsive and accessible across devices
- [ ] Share your game online and gather feedback from players
### 🌟 **Your Month-Long Game Development**
- [ ] Build multiple games exploring different genres and mechanics
- [ ] Learn a game development framework like Phaser or Three.js
- [ ] Contribute to open source game development projects
- [ ] Master advanced game programming patterns and optimization
- [ ] Create a portfolio showcasing your game development skills
- [ ] Mentor others interested in game development and interactive media
## 🎯 Your Game Development Mastery Timeline
```mermaid
timeline
title Game Architecture Learning Progression
section Object Patterns (20 minutes)
Code Organization: Class inheritance
: Composition patterns
: Factory functions
: Behavior mixing
section Communication Systems (25 minutes)
Event Architecture: Pub/Sub implementation
: Message design
: Event emitters
: Loose coupling
section Game Object Design (30 minutes)
Entity Systems: Property management
: Behavior composition
: State handling
: Lifecycle management
section Architecture Patterns (35 minutes)
System Design: Component systems
: Observer pattern
: Command pattern
: State machines
section Advanced Concepts (45 minutes)
Scalable Architecture: Performance optimization
: Memory management
: Modular design
: Testing strategies
section Game Engine Concepts (1 week)
Professional Development: Scene graphs
: Asset management
: Rendering pipelines
: Physics integration
section Framework Mastery (2 weeks)
Modern Game Development: React game patterns
: Canvas optimization
: WebGL basics
: PWA games
section Industry Practices (1 month)
Professional Skills: Team collaboration
: Code reviews
: Game design patterns
: Performance profiling
```
### 🛠️ Your Game Architecture Toolkit Summary
After completing this lesson, you now have:
- **Design Pattern Mastery**: Understanding of inheritance vs composition trade-offs
- **Event-Driven Architecture**: Pub/sub implementation for scalable communication
- **Object-Oriented Design**: Class hierarchies and behavior composition
- **Modern JavaScript**: Factory functions, spread syntax, and ES6+ patterns
- **Scalable Architecture**: Loose coupling and modular design principles
- **Game Development Foundation**: Entity systems and component patterns
- **Professional Patterns**: Industry-standard approaches to code organization
**Real-World Applications**: These patterns directly apply to:
- **Frontend Frameworks**: React/Vue component architecture and state management
- **Backend Services**: Microservice communication and event-driven systems
- **Mobile Development**: iOS/Android app architecture and notification systems
- **Game Engines**: Unity, Unreal, and web-based game development
- **Enterprise Software**: Event sourcing and distributed system design
- **API Design**: RESTful services and real-time communication
**Professional Skills Gained**: You can now:
- **Design** scalable software architectures using proven patterns
- **Implement** event-driven systems that handle complex interactions
- **Choose** appropriate code organization strategies for different scenarios
- **Debug** and maintain loosely coupled systems effectively
- **Communicate** technical decisions using industry-standard terminology
**Next Level**: You're ready to implement these patterns in a real game, explore advanced game development topics, or apply these architectural concepts to web applications!
🌟 **Achievement Unlocked**: You've mastered fundamental software architecture patterns that power everything from simple games to complex enterprise systems!
## Assignment
[Mock up a game](assignment.md)

@ -1,11 +1,58 @@
# Build a Space Game Part 2: Draw Hero and Monsters to Canvas
```mermaid
journey
title Your Canvas Graphics Journey
section Foundation
Understand Canvas API: 3: Student
Learn coordinate system: 4: Student
Draw basic shapes: 4: Student
section Image Handling
Load game assets: 4: Student
Handle async loading: 5: Student
Position sprites: 5: Student
section Game Rendering
Create game screen: 5: Student
Build formations: 5: Student
Optimize performance: 4: Student
```
The Canvas API is one of web development's most powerful features for creating dynamic, interactive graphics right in your browser. In this lesson, we'll transform that blank HTML `<canvas>` element into a game world filled with heroes and monsters. Think of the canvas as your digital art board where code becomes visual.
We're building on what you learned in the previous lesson, and now we'll dive into the visual aspects. You'll learn how to load and display game sprites, position elements precisely, and create the visual foundation for your space game. This bridges the gap between static web pages and dynamic, interactive experiences.
By the end of this lesson, you'll have a complete game scene with your hero ship positioned correctly and enemy formations ready for battle. You'll understand how modern games render graphics in browsers and gain skills to create your own interactive visual experiences. Let's explore canvas graphics and bring your space game to life!
```mermaid
mindmap
root((Canvas Graphics))
Canvas Element
HTML5 Feature
2D Context
Coordinate System
Pixel Control
Drawing Operations
Basic Shapes
Text Rendering
Image Display
Path Drawing
Asset Management
Image Loading
Async Operations
Error Handling
Performance
Game Rendering
Sprite Positioning
Formation Layout
Scene Composition
Frame Updates
Visual Effects
Colors & Styles
Transformations
Animations
Layering
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/31)
@ -35,11 +82,49 @@ Now that you know what the canvas element is, let's explore actually drawing on
The canvas uses Cartesian coordinates with an x-axis (horizontal) and y-axis (vertical) to position everything you draw. But here's the key difference: unlike the coordinate system from math class, the origin point `(0,0)` starts at the top-left corner, with x-values increasing as you move right and y-values increasing as you move down. This approach dates back to early computer displays where electron beams scanned from top to bottom, making top-left the natural starting point.
```mermaid
quadrantChart
title Canvas Coordinate System
x-axis Left --> Right (X increases)
y-axis Top --> Bottom (Y increases)
quadrant-1 Quadrant 1
quadrant-2 Quadrant 2
quadrant-3 Quadrant 3
quadrant-4 Quadrant 4
Origin (0,0): [0.1, 0.1]
Hero Center: [0.5, 0.8]
Enemy Formation: [0.3, 0.2]
Power-up: [0.7, 0.6]
UI Elements: [0.9, 0.1]
```
![the canvas's grid](canvas_grid.png)
> Image from [MDN](https://developer.mozilla.org/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes)
To draw on the canvas element, you'll follow the same three-step process that forms the foundation of all canvas graphics. Once you do this a few times, it becomes second nature:
```mermaid
flowchart LR
A[HTML Canvas Element] --> B[Get Canvas Reference]
B --> C[Get 2D Context]
C --> D[Drawing Operations]
D --> E[Draw Shapes]
D --> F[Draw Text]
D --> G[Draw Images]
D --> H[Apply Styles]
E --> I[Render to Screen]
F --> I
G --> I
H --> I
style A fill:#e1f5fe
style C fill:#e8f5e8
style I fill:#fff3e0
```
1. **Get a reference** to your Canvas element from the DOM (just like any other HTML element)
2. **Get the 2D rendering context** this provides all the drawing methods
3. **Start drawing!** Use the context's built-in methods to create your graphics
@ -74,12 +159,51 @@ You can draw all sorts of things with the Canvas API like:
✅ Try it! You know how to draw a rectangle, can you draw a circle to a page? Take a look at some interesting Canvas drawings on CodePen. Here's a [particularly impressive example](https://codepen.io/dissimulate/pen/KrAwx).
### 🔄 **Pedagogical Check-in**
**Canvas Fundamentals Understanding**: Before moving to image loading, ensure you can:
- ✅ Explain how the canvas coordinate system differs from mathematical coordinates
- ✅ Understand the three-step process for canvas drawing operations
- ✅ Identify what the 2D rendering context provides
- ✅ Describe how fillStyle and fillRect work together
**Quick Self-Test**: How would you draw a blue circle at position (100, 50) with radius 25?
```javascript
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(100, 50, 25, 0, 2 * Math.PI);
ctx.fill();
```
**Canvas Drawing Methods You Now Know**:
- **fillRect()**: Draws filled rectangles
- **fillStyle**: Sets colors and patterns
- **beginPath()**: Starts new drawing paths
- **arc()**: Creates circles and curves
## Load and Draw an Image Asset
Drawing basic shapes is useful for getting started, but most games need actual images! Sprites, backgrounds, and textures are what give games their visual appeal. Loading and displaying images on the canvas works differently than drawing geometric shapes, but it's straightforward once you understand the process.
We need to create an `Image` object, load our image file (this happens asynchronously, meaning "in the background"), and then draw it to the canvas once it's ready. This approach ensures your images display properly without blocking your application while they load.
```mermaid
sequenceDiagram
participant JS as JavaScript
participant Img as Image Object
participant Server as File Server
participant Canvas as Canvas Context
JS->>Img: new Image()
JS->>Img: Set src property
Img->>Server: Request image file
Server->>Img: Return image data
Img->>JS: Trigger onload event
JS->>Canvas: drawImage(img, x, y)
Canvas->>Canvas: Render to screen
Note over JS,Canvas: Async loading prevents UI blocking
```
### Basic Image Loading
```javascript
@ -161,6 +285,31 @@ async function renderGameScreen() {
- We **plop** the monster image at the top-left corner to start our enemy formation
- We **catch** any errors that might happen during loading or rendering
```mermaid
flowchart TD
A[Load Assets] --> B{All Images Loaded?}
B -->|No| C[Show Loading]
B -->|Yes| D[Get Canvas Context]
C --> B
D --> E[Clear Screen]
E --> F[Draw Background]
F --> G[Draw Enemy Formation]
G --> H[Draw Hero Ship]
H --> I[Apply Visual Effects]
I --> J[Render Frame]
subgraph "Rendering Pipeline"
K[Asset Management]
L[Scene Composition]
M[Drawing Operations]
N[Frame Output]
end
style A fill:#e1f5fe
style J fill:#e8f5e8
style I fill:#fff3e0
```
## Now It's Time to Start Building Your Game
Now we'll put everything together to create the visual foundation of your space game. You have a solid understanding of canvas fundamentals and image loading techniques, so this hands-on section will guide you through building a complete game screen with properly positioned sprites.
@ -246,6 +395,33 @@ const STOP_X = START_X + FORMATION_WIDTH;
- We **calculate** how wide our whole formation will be
- We **figure out** where to start and stop so the formation looks centered
```mermaid
flowchart LR
A["Canvas Width: 1024px"] --> B["Formation Width: 490px"]
B --> C["Start X: 267px"]
C --> D["Enemy Spacing: 98px"]
subgraph "5x5 Enemy Formation"
E["Row 1: Y=0"]
F["Row 2: Y=50"]
G["Row 3: Y=100"]
H["Row 4: Y=150"]
I["Row 5: Y=200"]
end
subgraph "Column Spacing"
J["Col 1: X=267"]
K["Col 2: X=365"]
L["Col 3: X=463"]
M["Col 4: X=561"]
N["Col 5: X=659"]
end
style A fill:#e1f5fe
style B fill:#e8f5e8
style C fill:#fff3e0
```
Then, create nested loops to draw the enemy formation:
```javascript
@ -262,6 +438,25 @@ for (let x = START_X; x < STOP_X; x += ENEMY_SPACING) {
- We **draw** each enemy sprite at the exact x,y coordinates we calculated
- Everything stays **evenly spaced** so it looks professional and organized
### 🔄 **Pedagogical Check-in**
**Game Rendering Mastery**: Verify your understanding of the complete rendering system:
- ✅ How does async image loading prevent UI blocking during game startup?
- ✅ Why do we calculate enemy formation positions using constants instead of hardcoding?
- ✅ What role does the 2D rendering context play in drawing operations?
- ✅ How do nested loops create organized sprite formations?
**Performance Considerations**: Your game now demonstrates:
- **Efficient asset loading**: Promise-based image management
- **Organized rendering**: Structured drawing operations
- **Mathematical positioning**: Calculated sprite placement
- **Error handling**: Graceful failure management
**Visual Programming Concepts**: You've learned:
- **Coordinate systems**: Translating math to screen positions
- **Sprite management**: Loading and displaying game graphics
- **Formation algorithms**: Mathematical patterns for organized layouts
- **Async operations**: Modern JavaScript for smooth user experience
## Result
The finished result should look like so:
@ -296,6 +491,126 @@ You've learned about drawing with the 2D-focused Canvas API; take a look at the
Learn more about the Canvas API by [reading about it](https://developer.mozilla.org/docs/Web/API/Canvas_API).
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open the browser console and create a canvas element with `document.createElement('canvas')`
- [ ] Try drawing a rectangle using `fillRect()` on a canvas context
- [ ] Experiment with different colors using `fillStyle` property
- [ ] Draw a simple circle using the `arc()` method
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand canvas fundamentals
- [ ] Create a canvas drawing application with multiple shapes and colors
- [ ] Implement image loading and sprite rendering for your game
- [ ] Build a simple animation that moves objects across the canvas
- [ ] Practice canvas transformations like scaling, rotation, and translation
### 📅 **Your Week-Long Canvas Journey**
- [ ] Complete the space game with polished graphics and sprite animations
- [ ] Master advanced canvas techniques like gradients, patterns, and compositing
- [ ] Create interactive visualizations using canvas for data representation
- [ ] Learn about canvas optimization techniques for smooth performance
- [ ] Build a drawing or painting application with various tools
- [ ] Explore creative coding patterns and generative art with canvas
### 🌟 **Your Month-Long Graphics Mastery**
- [ ] Build complex visual applications using Canvas 2D and WebGL
- [ ] Learn graphics programming concepts and shader basics
- [ ] Contribute to open source graphics libraries and visualization tools
- [ ] Master performance optimization for graphics-intensive applications
- [ ] Create educational content about canvas programming and computer graphics
- [ ] Become a graphics programming expert who helps others create visual experiences
## 🎯 Your Canvas Graphics Mastery Timeline
```mermaid
timeline
title Canvas API Learning Progression
section Canvas Fundamentals (15 minutes)
Basic Operations: Element reference
: 2D context access
: Coordinate system
: Simple shape drawing
section Drawing Techniques (20 minutes)
Graphics Primitives: Rectangles and circles
: Colors and styles
: Text rendering
: Path operations
section Image Handling (25 minutes)
Asset Management: Image object creation
: Async loading patterns
: Error handling
: Performance optimization
section Game Graphics (30 minutes)
Sprite Rendering: Positioning algorithms
: Formation calculations
: Scene composition
: Frame rendering
section Advanced Techniques (40 minutes)
Visual Effects: Transformations
: Animations
: Layering
: State management
section Performance (35 minutes)
Optimization: Efficient drawing
: Memory management
: Frame rate control
: Asset caching
section Professional Skills (1 week)
Production Graphics: WebGL integration
: Canvas libraries
: Game engines
: Cross-platform considerations
section Advanced Graphics (1 month)
Specialized Applications: Data visualization
: Interactive art
: Real-time effects
: 3D graphics
```
### 🛠️ Your Canvas Graphics Toolkit Summary
After completing this lesson, you now have:
- **Canvas API Mastery**: Complete understanding of 2D graphics programming
- **Coordinate Mathematics**: Precise positioning and layout algorithms
- **Asset Management**: Professional image loading and error handling
- **Rendering Pipeline**: Structured approach to scene composition
- **Game Graphics**: Sprite positioning and formation calculations
- **Async Programming**: Modern JavaScript patterns for smooth performance
- **Visual Programming**: Translating mathematical concepts to screen graphics
**Real-World Applications**: Your Canvas skills directly apply to:
- **Data Visualization**: Charts, graphs, and interactive dashboards
- **Game Development**: 2D games, simulations, and interactive experiences
- **Digital Art**: Creative coding and generative art projects
- **UI/UX Design**: Custom graphics and interactive elements
- **Educational Software**: Visual learning tools and simulations
- **Web Applications**: Dynamic graphics and real-time visualizations
**Professional Skills Gained**: You can now:
- **Build** custom graphics solutions without external libraries
- **Optimize** rendering performance for smooth user experiences
- **Debug** complex visual problems using browser developer tools
- **Design** scalable graphics systems using mathematical principles
- **Integrate** Canvas graphics with modern web application frameworks
**Canvas API Methods You've Mastered**:
- **Element Management**: getElementById, getContext
- **Drawing Operations**: fillRect, drawImage, fillStyle
- **Asset Loading**: Image objects, Promise patterns
- **Mathematical Positioning**: Coordinate calculations, formation algorithms
**Next Level**: You're ready to add animation, user interaction, collision detection, or explore WebGL for 3D graphics!
🌟 **Achievement Unlocked**: You've built a complete game rendering system using fundamental Canvas API techniques!
## Assignment
[Play with the Canvas API](assignment.md)

@ -1,5 +1,22 @@
# Build a Space Game Part 3: Adding Motion
```mermaid
journey
title Your Game Animation Journey
section Movement Basics
Understand motion principles: 3: Student
Learn coordinate updates: 4: Student
Implement basic movement: 4: Student
section Player Controls
Handle keyboard events: 4: Student
Prevent default behaviors: 5: Student
Create responsive controls: 5: Student
section Game Systems
Build game loop: 5: Student
Manage object lifecycle: 5: Student
Implement pub/sub pattern: 5: Student
```
Think about your favorite games what makes them captivating isn't just pretty graphics, it's the way everything moves and responds to your actions. Right now, your space game is like a beautiful painting, but we're about to add movement that brings it to life.
When NASA's engineers programmed the guidance computer for the Apollo missions, they faced a similar challenge: how do you make a spacecraft respond to pilot input while automatically maintaining course corrections? The principles we'll learn today echo those same concepts managing player-controlled movement alongside automatic system behaviors.
@ -8,6 +25,36 @@ In this lesson, you'll learn how to make spaceships glide across the screen, res
By the end, you'll have players flying their hero ship around the screen while enemy vessels patrol overhead. More importantly, you'll understand the core principles that power game movement systems.
```mermaid
mindmap
root((Game Animation))
Movement Types
Player Controlled
Automatic Motion
Physics Based
Scripted Paths
Event Handling
Keyboard Input
Mouse Events
Touch Controls
Default Prevention
Game Loop
Update Logic
Render Frame
Clear Canvas
Frame Rate Control
Object Management
Position Updates
Collision Detection
Lifecycle Management
State Tracking
Communication
Pub/Sub Pattern
Event Emitters
Message Passing
Loose Coupling
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/33)
@ -23,6 +70,27 @@ Making objects move on a computer screen is simpler than you might think. Rememb
Moving things on screen is like creating a flipbook animation you need to follow these three simple steps:
```mermaid
flowchart LR
A["Frame N"] --> B["Update Positions"]
B --> C["Clear Canvas"]
C --> D["Draw Objects"]
D --> E["Frame N+1"]
E --> F{Continue?}
F -->|Yes| B
F -->|No| G["Game Over"]
subgraph "Animation Cycle"
H["1. Calculate new positions"]
I["2. Erase previous frame"]
J["3. Render new frame"]
end
style B fill:#e1f5fe
style C fill:#ffebee
style D fill:#e8f5e8
```
1. **Update the position** Change where your object should be (maybe move it 5 pixels to the right)
2. **Erase the old frame** Clear the screen so you don't see ghostly trails everywhere
3. **Draw the new frame** Put your object in its new spot
@ -84,6 +152,25 @@ For key events there are two properties on the event you can use to see what key
✅ Key event manipulation is useful outside of game development. What other uses can you think of for this technique?
```mermaid
sequenceDiagram
participant User
participant Browser
participant EventSystem
participant GameLogic
participant Hero
User->>Browser: Presses ArrowUp key
Browser->>EventSystem: keydown event
EventSystem->>EventSystem: preventDefault()
EventSystem->>GameLogic: emit('KEY_EVENT_UP')
GameLogic->>Hero: hero.y -= 5
Hero->>Hero: Update position
Note over Browser,GameLogic: Event flow prevents browser defaults
Note over GameLogic,Hero: Pub/sub pattern enables clean communication
```
### Special keys: a heads up!
Some keys have built-in browser behaviors that can interfere with your game. Arrow keys scroll the page and spacebar jumps down behaviors you don't want when someone is trying to pilot their spaceship.
@ -115,6 +202,22 @@ window.addEventListener('keydown', onKeyDown);
- **Allows** other keys to function normally
- **Uses** `e.preventDefault()` to stop the browser's built-in behavior
### 🔄 **Pedagogical Check-in**
**Event Handling Understanding**: Before moving to automatic movement, ensure you can:
- ✅ Explain the difference between `keydown` and `keyup` events
- ✅ Understand why we prevent default browser behaviors
- ✅ Describe how event listeners connect user input to game logic
- ✅ Identify which keys might interfere with game controls
**Quick Self-Test**: What would happen if you didn't prevent default behavior for arrow keys?
*Answer: The browser would scroll the page, interfering with game movement*
**Event System Architecture**: You now understand:
- **Window-level listening**: Capturing events at the browser level
- **Event object properties**: `key` strings vs `keyCode` numbers
- **Default prevention**: Stopping unwanted browser behaviors
- **Conditional logic**: Responding to specific key combinations
## Game induced movement
Now let's talk about objects that move without player input. Think about enemy ships cruising across the screen, bullets flying in straight lines, or clouds drifting in the background. This autonomous movement makes your game world feel alive even when nobody's touching the controls.
@ -144,6 +247,31 @@ This concept reminds me of how early film animators like Walt Disney had to redr
Here's what a game loop can typically look like, expressed in code:
```mermaid
flowchart TD
A["Start Game Loop"] --> B["Clear Canvas"]
B --> C["Fill Background"]
C --> D["Update Game Objects"]
D --> E["Draw Hero"]
E --> F["Draw Enemies"]
F --> G["Draw UI Elements"]
G --> H["Wait for Next Frame"]
H --> I{Game Running?}
I -->|Yes| B
I -->|No| J["End Game"]
subgraph "Frame Rate Control"
K["60 FPS = 16.67ms"]
L["30 FPS = 33.33ms"]
M["10 FPS = 100ms"]
end
style B fill:#ffebee
style D fill:#e1f5fe
style E fill:#e8f5e8
style F fill:#e8f5e8
```
```javascript
const gameLoopId = setInterval(() => {
function gameLoop() {
@ -236,6 +364,43 @@ The above will start a HTTP Server on address `http://localhost:5000`. Open up a
- **Provides** a `draw()` method that renders the object on the canvas
- **Sets** default values for all properties that child classes can override
```mermaid
classDiagram
class GameObject {
+x: number
+y: number
+dead: boolean
+type: string
+width: number
+height: number
+img: Image
+draw(ctx)
}
class Hero {
+speed: number
+type: "Hero"
+width: 98
+height: 75
}
class Enemy {
+type: "Enemy"
+width: 98
+height: 50
+setInterval()
}
GameObject <|-- Hero
GameObject <|-- Enemy
class EventEmitter {
+listeners: object
+on(message, listener)
+emit(message, payload)
}
```
Now, extend this `GameObject` to create the `Hero` and `Enemy`:
```javascript
@ -337,6 +502,28 @@ The above will start a HTTP Server on address `http://localhost:5000`. Open up a
- **Makes** it easy to change controls later without affecting game code
- **Allows** multiple systems to respond to the same input
```mermaid
flowchart TD
A["Keyboard Input"] --> B["Window Event Listener"]
B --> C["Event Emitter"]
C --> D["KEY_EVENT_UP"]
C --> E["KEY_EVENT_DOWN"]
C --> F["KEY_EVENT_LEFT"]
C --> G["KEY_EVENT_RIGHT"]
D --> H["Hero Movement"]
D --> I["Sound System"]
D --> J["Visual Effects"]
E --> H
F --> H
G --> H
style A fill:#e1f5fe
style C fill:#e8f5e8
style H fill:#fff3e0
```
2. **Create an EventEmitter class** to publish and subscribe to messages:
```javascript
@ -484,6 +671,26 @@ The above will start a HTTP Server on address `http://localhost:5000`. Open up a
- **Calls** the `draw()` method on each object
- **Passes** the canvas context so objects can render themselves
### 🔄 **Pedagogical Check-in**
**Complete Game System Understanding**: Verify your mastery of the entire architecture:
- ✅ How does inheritance allow Hero and Enemy to share common GameObject properties?
- ✅ Why does the pub/sub pattern make your code more maintainable?
- ✅ What role does the game loop play in creating smooth animation?
- ✅ How do event listeners connect user input to game object behavior?
**System Integration**: Your game now demonstrates:
- **Object-Oriented Design**: Base classes with specialized inheritance
- **Event-Driven Architecture**: Pub/sub pattern for loose coupling
- **Animation Framework**: Game loop with consistent frame updates
- **Input Handling**: Keyboard events with default prevention
- **Asset Management**: Image loading and sprite rendering
**Professional Patterns**: You've implemented:
- **Separation of Concerns**: Input, logic, and rendering separated
- **Polymorphism**: All game objects share common drawing interface
- **Message Passing**: Clean communication between components
- **Resource Management**: Efficient sprite and animation handling
Your enemies should start advancing on your hero spaceship!
}
}
@ -558,6 +765,127 @@ Think of frameworks like having a well-stocked toolbox instead of making every t
- Modern JavaScript features that can make your code cleaner and more maintainable
- Different approaches to managing game objects and their relationships
## 🎯 Your Game Animation Mastery Timeline
```mermaid
timeline
title Game Animation & Interaction Learning Progression
section Movement Fundamentals (20 minutes)
Animation Principles: Frame-based animation
: Position updates
: Coordinate systems
: Smooth movement
section Event Systems (25 minutes)
User Input: Keyboard event handling
: Default behavior prevention
: Event object properties
: Window-level listening
section Game Architecture (30 minutes)
Object Design: Inheritance patterns
: Base class creation
: Specialized behaviors
: Polymorphic interfaces
section Communication Patterns (35 minutes)
Pub/Sub Implementation: Event emitters
: Message constants
: Loose coupling
: System integration
section Game Loop Mastery (40 minutes)
Real-time Systems: Frame rate control
: Update/render cycle
: State management
: Performance optimization
section Advanced Techniques (45 minutes)
Professional Features: Collision detection
: Physics simulation
: State machines
: Component systems
section Game Engine Concepts (1 week)
Framework Understanding: Entity-component systems
: Scene graphs
: Asset pipelines
: Performance profiling
section Production Skills (1 month)
Professional Development: Code organization
: Team collaboration
: Testing strategies
: Deployment optimization
```
### 🛠️ Your Game Development Toolkit Summary
After completing this lesson, you now have mastered:
- **Animation Principles**: Frame-based movement and smooth transitions
- **Event-Driven Programming**: Keyboard input handling with proper event management
- **Object-Oriented Design**: Inheritance hierarchies and polymorphic interfaces
- **Communication Patterns**: Pub/sub architecture for maintainable code
- **Game Loop Architecture**: Real-time update and rendering cycles
- **Input Systems**: User control mapping with default behavior prevention
- **Asset Management**: Sprite loading and efficient rendering techniques
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open the browser console and try `addEventListener('keydown', console.log)` to see keyboard events
- [ ] Create a simple div element and move it around using arrow keys
- [ ] Experiment with `setInterval` to create continuous movement
- [ ] Try preventing default behavior with `event.preventDefault()`
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand event-driven programming
- [ ] Build the moving hero spaceship with full keyboard controls
- [ ] Implement smooth enemy movement patterns
- [ ] Add boundaries to prevent game objects from leaving the screen
- [ ] Create basic collision detection between game objects
### 📅 **Your Week-Long Animation Journey**
- [ ] Complete the full space game with polished movement and interactions
- [ ] Add advanced movement patterns like curves, acceleration, and physics
- [ ] Implement smooth transitions and easing functions
- [ ] Create particle effects and visual feedback systems
- [ ] Optimize game performance for smooth 60fps gameplay
- [ ] Add mobile touch controls and responsive design
### 🌟 **Your Month-Long Interactive Development**
- [ ] Build complex interactive applications with advanced animation systems
- [ ] Learn animation libraries like GSAP or create your own animation engine
- [ ] Contribute to open source game development and animation projects
- [ ] Master performance optimization for graphics-intensive applications
- [ ] Create educational content about game development and animation
- [ ] Build a portfolio showcasing advanced interactive programming skills
**Real-World Applications**: Your game animation skills apply directly to:
- **Interactive Web Applications**: Dynamic dashboards and real-time interfaces
- **Data Visualization**: Animated charts and interactive graphics
- **Educational Software**: Interactive simulations and learning tools
- **Mobile Development**: Touch-based games and gesture handling
- **Desktop Applications**: Electron apps with smooth animations
- **Web Animations**: CSS and JavaScript animation libraries
**Professional Skills Gained**: You can now:
- **Architect** event-driven systems that scale with complexity
- **Implement** smooth animations using mathematical principles
- **Debug** complex interaction systems using browser developer tools
- **Optimize** game performance for different devices and browsers
- **Design** maintainable code structures using proven patterns
**Game Development Concepts Mastered**:
- **Frame Rate Management**: Understanding FPS and timing controls
- **Input Handling**: Cross-platform keyboard and event systems
- **Object Lifecycle**: Creation, update, and destruction patterns
- **State Synchronization**: Keeping game state consistent across frames
- **Event Architecture**: Decoupled communication between game systems
**Next Level**: You're ready to add collision detection, scoring systems, sound effects, or explore modern game frameworks like Phaser or Three.js!
🌟 **Achievement Unlocked**: You've built a complete interactive game system with professional architecture patterns!
## Assignment
[Comment your code](assignment.md)

@ -1,5 +1,22 @@
# Build a Space Game Part 4: Adding A Laser and Detect Collisions
```mermaid
journey
title Your Collision Detection Journey
section Physics Foundation
Understand rectangles: 3: Student
Learn intersection math: 4: Student
Grasp coordinate systems: 4: Student
section Game Mechanics
Implement laser firing: 4: Student
Add object lifecycle: 5: Student
Create collision rules: 5: Student
section System Integration
Build collision detection: 5: Student
Optimize performance: 5: Student
Test interaction systems: 5: Student
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/35)
@ -10,6 +27,36 @@ In this lesson, you'll add laser weapons to your space game and implement collis
By the end, you'll have a functioning combat system where lasers destroy enemies and collisions trigger game events. These same collision principles are used in everything from physics simulations to interactive web interfaces.
```mermaid
mindmap
root((Collision Detection))
Physics Concepts
Rectangle Boundaries
Intersection Testing
Coordinate Systems
Separation Logic
Game Objects
Laser Projectiles
Enemy Ships
Hero Character
Collision Zones
Lifecycle Management
Object Creation
Movement Updates
Destruction Marking
Memory Cleanup
Event Systems
Keyboard Input
Collision Events
Game State Changes
Audio/Visual Effects
Performance
Efficient Algorithms
Frame Rate Optimization
Memory Management
Spatial Partitioning
```
✅ Do a little research on the very first computer game ever written. What was its functionality?
## Collision detection
@ -22,6 +69,29 @@ The approach we'll use treats every game object as a rectangle, similar to how a
Every game object needs coordinate boundaries, similar to how the Mars Pathfinder rover mapped its location on the Martian surface. Here's how we define these boundary coordinates:
```mermaid
flowchart TD
A["🎯 Game Object"] --> B["📍 Position (x, y)"]
A --> C["📏 Dimensions (width, height)"]
B --> D["Top: y"]
B --> E["Left: x"]
C --> F["Bottom: y + height"]
C --> G["Right: x + width"]
D --> H["🔲 Rectangle Bounds"]
E --> H
F --> H
G --> H
H --> I["Collision Detection Ready"]
style A fill:#e3f2fd
style H fill:#e8f5e8
style I fill:#fff3e0
```
```javascript
rectFromGameObject() {
return {
@ -43,6 +113,29 @@ rectFromGameObject() {
Detecting rectangle intersections uses logic similar to how the Hubble Space Telescope determines if celestial objects are overlapping in its field of view. The algorithm checks for separation:
```mermaid
flowchart LR
A["Rectangle 1"] --> B{"Separation Tests"}
C["Rectangle 2"] --> B
B --> D["R2 left > R1 right?"]
B --> E["R2 right < R1 left?"]
B --> F["R2 top > R1 bottom?"]
B --> G["R2 bottom < R1 top?"]
D --> H{"Any True?"}
E --> H
F --> H
G --> H
H -->|Yes| I["❌ No Collision"]
H -->|No| J["✅ Collision Detected"]
style B fill:#e3f2fd
style I fill:#ffebee
style J fill:#e8f5e8
```
```javascript
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
@ -64,6 +157,28 @@ If none of these conditions are true, the rectangles must be overlapping. This a
When a laser hits an enemy, both objects need to be removed from the game. However, deleting objects mid-loop can cause crashes - a lesson learned the hard way in early computer systems like the Apollo Guidance Computer. Instead, we use a "mark for deletion" approach that safely removes objects between frames.
```mermaid
stateDiagram-v2
[*] --> Active: Object Created
Active --> Collided: Collision Detected
Collided --> MarkedDead: Set dead = true
MarkedDead --> Filtered: Next Frame
Filtered --> [*]: Object Removed
Active --> OutOfBounds: Leaves Screen
OutOfBounds --> MarkedDead
note right of MarkedDead
Safe to continue
current frame
end note
note right of Filtered
Objects removed
between frames
end note
```
Here's how we mark something for removal:
```javascript
@ -106,6 +221,31 @@ Unlimited firing rates would overwhelm the game engine and make gameplay too eas
We'll implement a cooldown system that prevents rapid-fire spamming while maintaining responsive controls:
```mermaid
sequenceDiagram
participant Player
participant Weapon
participant Cooldown
participant Game
Player->>Weapon: Press Spacebar
Weapon->>Cooldown: Check if cool
alt Weapon is Ready
Cooldown->>Weapon: cool = true
Weapon->>Game: Create Laser
Weapon->>Cooldown: Start new cooldown
Cooldown->>Cooldown: cool = false
Note over Cooldown: Wait 500ms
Cooldown->>Cooldown: cool = true
else Weapon is Cooling
Cooldown->>Weapon: cool = false
Weapon->>Player: No action
end
```
```javascript
class Cooldown {
constructor(time) {
@ -156,6 +296,22 @@ Starting from your previous lesson's code, you'll add collision detection with s
3. **Enemy and hero collision**: Both objects are destroyed when they intersect
4. **Enemy reaches bottom**: Game over condition when enemies reach the screen bottom
### 🔄 **Pedagogical Check-in**
**Collision Detection Foundation**: Before implementing, ensure you understand:
- ✅ How rectangle boundaries define collision zones
- ✅ Why separation testing is more efficient than intersection calculation
- ✅ The importance of object lifecycle management in game loops
- ✅ How event-driven systems coordinate collision responses
**Quick Self-Test**: What would happen if you deleted objects immediately instead of marking them?
*Answer: Mid-loop deletion could cause crashes or skip objects in iteration*
**Physics Understanding**: You now grasp:
- **Coordinate Systems**: How position and dimensions create boundaries
- **Intersection Logic**: Mathematical principles behind collision detection
- **Performance Optimization**: Why efficient algorithms matter in real-time systems
- **Memory Management**: Safe object lifecycle patterns for stability
## Setting up your development environment
Good news - we've already set up most of the groundwork for you! All your game assets and basic structure are waiting in the `your-work` subfolder, ready for you to add the cool collision features.
@ -198,6 +354,32 @@ Open your browser and navigate to `http://localhost:5000` to see your current ga
Like the systematic approach NASA used to program the Voyager spacecraft, we'll implement collision detection methodically, building each component step by step.
```mermaid
flowchart TD
A["1. Rectangle Bounds"] --> B["2. Intersection Detection"]
B --> C["3. Laser System"]
C --> D["4. Event Handling"]
D --> E["5. Collision Rules"]
E --> F["6. Cooldown System"]
G["Object Boundaries"] --> A
H["Physics Algorithm"] --> B
I["Projectile Creation"] --> C
J["Keyboard Input"] --> D
K["Game Logic"] --> E
L["Rate Limiting"] --> F
F --> M["🎮 Complete Game"]
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#f3e5f5
style E fill:#e0f2f1
style F fill:#fce4ec
style M fill:#e1f5fe
```
#### 1. Add rectangle collision bounds
First, let's teach our game objects how to describe their boundaries. Add this method to your `GameObject` class:
@ -412,6 +594,26 @@ class Hero extends GameObject {
- **Decrements** cooldown timer using interval-based updates
- **Provides** firing status check through `canFire()` method
### 🔄 **Pedagogical Check-in**
**Complete System Understanding**: Verify your mastery of the collision system:
- ✅ How do rectangle boundaries enable efficient collision detection?
- ✅ Why is object lifecycle management critical for game stability?
- ✅ How does the cooldown system prevent performance issues?
- ✅ What role does event-driven architecture play in collision handling?
**System Integration**: Your collision detection demonstrates:
- **Mathematical Precision**: Rectangle intersection algorithms
- **Performance Optimization**: Efficient collision testing patterns
- **Memory Management**: Safe object creation and destruction
- **Event Coordination**: Decoupled system communication
- **Real-time Processing**: Frame-based update cycles
**Professional Patterns**: You've implemented:
- **Separation of Concerns**: Physics, rendering, and input separated
- **Object-Oriented Design**: Inheritance and polymorphism
- **State Management**: Object lifecycle and game state tracking
- **Performance Optimization**: Efficient algorithms for real-time use
### Testing your implementation
Your space game now features complete collision detection and combat mechanics. 🚀 Test these new capabilities:
@ -422,6 +624,121 @@ Your space game now features complete collision detection and combat mechanics.
You've successfully implemented a collision detection system using the same mathematical principles that guide spacecraft navigation and robotics.
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Open browser DevTools and set breakpoints in your collision detection function
- [ ] Try modifying the laser speed or enemy movement to see collision effects
- [ ] Experiment with different cooldown values to test firing rates
- [ ] Add `console.log` statements to track collision events in real-time
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand collision detection algorithms
- [ ] Add visual effects like explosions when collisions occur
- [ ] Implement different types of projectiles with varying properties
- [ ] Create power-ups that enhance player abilities temporarily
- [ ] Add sound effects to make collisions more satisfying
### 📅 **Your Week-Long Physics Programming**
- [ ] Complete the full space game with polished collision systems
- [ ] Implement advanced collision shapes beyond rectangles (circles, polygons)
- [ ] Add particle systems for realistic explosion effects
- [ ] Create complex enemy behavior with collision avoidance
- [ ] Optimize collision detection for better performance with many objects
- [ ] Add physics simulation like momentum and realistic movement
### 🌟 **Your Month-Long Game Physics Mastery**
- [ ] Build games with advanced physics engines and realistic simulations
- [ ] Learn 3D collision detection and spatial partitioning algorithms
- [ ] Contribute to open source physics libraries and game engines
- [ ] Master performance optimization for graphics-intensive applications
- [ ] Create educational content about game physics and collision detection
- [ ] Build a portfolio showcasing advanced physics programming skills
## 🎯 Your Collision Detection Mastery Timeline
```mermaid
timeline
title Collision Detection & Game Physics Learning Progression
section Foundation (10 minutes)
Rectangle Math: Coordinate systems
: Boundary calculations
: Position tracking
: Dimension management
section Algorithm Design (20 minutes)
Intersection Logic: Separation testing
: Overlap detection
: Performance optimization
: Edge case handling
section Game Implementation (30 minutes)
Object Systems: Lifecycle management
: Event coordination
: State tracking
: Memory cleanup
section Interactive Features (40 minutes)
Combat Mechanics: Projectile systems
: Weapon cooldowns
: Damage calculation
: Visual feedback
section Advanced Physics (50 minutes)
Real-time Systems: Frame rate optimization
: Spatial partitioning
: Collision response
: Physics simulation
section Professional Techniques (1 week)
Game Engine Concepts: Component systems
: Physics pipelines
: Performance profiling
: Cross-platform optimization
section Industry Applications (1 month)
Production Skills: Large-scale optimization
: Team collaboration
: Engine development
: Platform deployment
```
### 🛠️ Your Game Physics Toolkit Summary
After completing this lesson, you now have mastered:
- **Collision Mathematics**: Rectangle intersection algorithms and coordinate systems
- **Performance Optimization**: Efficient collision detection for real-time applications
- **Object Lifecycle Management**: Safe creation, updating, and destruction patterns
- **Event-Driven Architecture**: Decoupled systems for collision response
- **Game Loop Integration**: Frame-based physics updates and rendering coordination
- **Input Systems**: Responsive controls with rate limiting and feedback
- **Memory Management**: Efficient object pooling and cleanup strategies
**Real-World Applications**: Your collision detection skills apply directly to:
- **Interactive Simulations**: Scientific modeling and educational tools
- **User Interface Design**: Drag-and-drop interactions and touch detection
- **Data Visualization**: Interactive charts and clickable elements
- **Mobile Development**: Touch gesture recognition and collision handling
- **Robotics Programming**: Path planning and obstacle avoidance
- **Computer Graphics**: Ray tracing and spatial algorithms
**Professional Skills Gained**: You can now:
- **Design** efficient algorithms for real-time collision detection
- **Implement** physics systems that scale with object complexity
- **Debug** complex interaction systems using mathematical principles
- **Optimize** performance for different hardware and browser capabilities
- **Architect** maintainable game systems using proven design patterns
**Game Development Concepts Mastered**:
- **Physics Simulation**: Real-time collision detection and response
- **Performance Engineering**: Optimized algorithms for interactive applications
- **Event Systems**: Decoupled communication between game components
- **Object Management**: Efficient lifecycle patterns for dynamic content
- **Input Handling**: Responsive controls with appropriate feedback
**Next Level**: You're ready to explore advanced physics engines like Matter.js, implement 3D collision detection, or build complex particle systems!
🌟 **Achievement Unlocked**: You've built a complete physics-based interaction system with professional-grade collision detection!
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:

@ -1,15 +1,82 @@
# Build a Space Game Part 5: Scoring and Lives
```mermaid
journey
title Your Game Design Journey
section Player Feedback
Understand scoring psychology: 3: Student
Learn visual communication: 4: Student
Design reward systems: 4: Student
section Technical Implementation
Canvas text rendering: 4: Student
State management: 5: Student
Event-driven updates: 5: Student
section Game Polish
User experience design: 5: Student
Balance challenge and reward: 5: Student
Create engaging gameplay: 5: Student
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/37)
Ready to make your space game feel like a real game? Let's add scoring points and managing lives - the core mechanics that transformed early arcade games like Space Invaders from simple demonstrations into addictive entertainment. This is where your game becomes truly playable.
```mermaid
mindmap
root((Game Feedback Systems))
Visual Communication
Text Rendering
Icon Display
Color Psychology
Layout Design
Scoring Mechanics
Point Values
Reward Timing
Progress Tracking
Achievement Systems
Life Management
Risk vs Reward
Player Agency
Difficulty Balance
Recovery Mechanics
User Experience
Immediate Feedback
Clear Information
Emotional Response
Engagement Loops
Implementation
Canvas API
State Management
Event Systems
Performance
```
## Drawing Text on Screen - Your Game's Voice
To display your score, we need to learn how to render text on the canvas. The `fillText()` method is your primary tool for this - it's the same technique used in classic arcade games to show scores and status information.
```mermaid
flowchart LR
A["📝 Text Content"] --> B["🎨 Styling"]
B --> C["📍 Positioning"]
C --> D["🖼️ Canvas Render"]
E["Font Family"] --> B
F["Font Size"] --> B
G["Color"] --> B
H["Alignment"] --> B
I["X Coordinate"] --> C
J["Y Coordinate"] --> C
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#f3e5f5
```
You have complete control over the text appearance:
```javascript
@ -25,12 +92,64 @@ ctx.fillText("show this on the screen", 0, 0);
In game design, a "life" represents the player's margin for error. This concept dates back to pinball machines, where you'd get multiple balls to play with. In early video games like Asteroids, lives gave players permission to take risks and learn from mistakes.
```mermaid
flowchart TD
A["🎮 Player Action"] --> B{"Risk Assessment"}
B --> C["High Risk, High Reward"]
B --> D["Safe Strategy"]
C --> E{"Outcome"}
D --> F["Steady Progress"]
E -->|Success| G["🏆 Big Points"]
E -->|Failure| H["💔 Lose Life"]
H --> I{"Lives Remaining?"}
I -->|Yes| J["🔄 Try Again"]
I -->|No| K["💀 Game Over"]
J --> B
G --> B
F --> B
style C fill:#ffebee
style D fill:#e8f5e8
style G fill:#e3f2fd
style H fill:#fff3e0
```
Visual representation matters significantly - displaying ship icons instead of just "Lives: 3" creates immediate visual recognition, similar to how early arcade cabinets used iconography to communicate across language barriers.
## Building Your Game's Reward System
Now we'll implement the core feedback systems that keep players engaged:
```mermaid
sequenceDiagram
participant Player
participant GameEngine
participant ScoreSystem
participant LifeSystem
participant Display
Player->>GameEngine: Shoots Enemy
GameEngine->>ScoreSystem: Award Points
ScoreSystem->>ScoreSystem: +100 points
ScoreSystem->>Display: Update Score
Player->>GameEngine: Collides with Enemy
GameEngine->>LifeSystem: Lose Life
LifeSystem->>LifeSystem: -1 life
LifeSystem->>Display: Update Lives
alt Lives > 0
LifeSystem->>Player: Continue Playing
else Lives = 0
LifeSystem->>GameEngine: Game Over
end
```
- **Scoring system**: Each destroyed enemy ship awards 100 points (round numbers are easier for players to calculate mentally). The score displays in the bottom left corner.
- **Life counter**: Your hero starts with three lives - a standard established by early arcade games to balance challenge with playability. Each collision with an enemy costs one life. We'll display remaining lives in the bottom right using ship icons ![life image](solution/assets/life.png).
@ -57,6 +176,32 @@ npm start
This runs a local server at `http://localhost:5000`. Open this address in your browser to see your game. Test the controls with arrow keys and try shooting enemies to verify everything works.
```mermaid
flowchart TD
A["1. Asset Loading"] --> B["2. Game Variables"]
B --> C["3. Collision Detection"]
C --> D["4. Hero Enhancement"]
D --> E["5. Display Functions"]
E --> F["6. Event Handlers"]
G["Life Icon Image"] --> A
H["Score & Lives Tracking"] --> B
I["Hero-Enemy Intersections"] --> C
J["Points & Life Methods"] --> D
K["Text & Icon Rendering"] --> E
L["Reward & Penalty Logic"] --> F
F --> M["🎮 Complete Game"]
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#f3e5f5
style E fill:#e0f2f1
style F fill:#fce4ec
style M fill:#e1f5fe
```
### Time to Code!
1. **Grab the visual assets you'll need**. Copy the `life.png` asset from the `solution/assets/` folder into your `your-work` folder. Then add the lifeImg to your window.onload function:
@ -130,6 +275,22 @@ This runs a local server at `http://localhost:5000`. Open this address in your b
drawLife();
```
### 🔄 **Pedagogical Check-in**
**Game Design Understanding**: Before implementing consequences, ensure you understand:
- ✅ How visual feedback communicates game state to players
- ✅ Why consistent placement of UI elements improves usability
- ✅ The psychology behind point values and life management
- ✅ How canvas text rendering differs from HTML text
**Quick Self-Test**: Why do arcade games typically use round numbers for point values?
*Answer: Round numbers are easier for players to calculate mentally and create satisfying psychological rewards*
**User Experience Principles**: You're now applying:
- **Visual Hierarchy**: Important information positioned prominently
- **Immediate Feedback**: Real-time updates to player actions
- **Cognitive Load**: Simple, clear information presentation
- **Emotional Design**: Icons and colors that create player connection
1. **Implement game consequences and rewards**. Now we'll add the feedback systems that make player actions meaningful:
1. **Collisions cost lives**. Every time your hero crashes into an enemy, you should lose a life.
@ -176,6 +337,141 @@ After implementing these features, test your game to see the complete feedback s
Your game now has the essential mechanics that made early arcade games so compelling - clear goals, immediate feedback, and meaningful consequences for player actions.
### 🔄 **Pedagogical Check-in**
**Complete Game Design System**: Verify your mastery of player feedback systems:
- ✅ How do scoring mechanics create player motivation and engagement?
- ✅ Why is visual consistency important for user interface design?
- ✅ How does the life system balance challenge with player retention?
- ✅ What role does immediate feedback play in creating satisfying gameplay?
**System Integration**: Your feedback system demonstrates:
- **User Experience Design**: Clear visual communication and information hierarchy
- **Event-Driven Architecture**: Responsive updates to player actions
- **State Management**: Tracking and displaying dynamic game data
- **Canvas Mastery**: Text rendering and sprite positioning
- **Game Psychology**: Understanding player motivation and engagement
**Professional Patterns**: You've implemented:
- **MVC Architecture**: Separation of game logic, data, and presentation
- **Observer Pattern**: Event-driven updates for game state changes
- **Component Design**: Reusable functions for rendering and logic
- **Performance Optimization**: Efficient rendering in game loops
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Experiment with different font sizes and colors for the score display
- [ ] Try changing the point values and see how it affects gameplay feel
- [ ] Add console.log statements to track when points and lives change
- [ ] Test edge cases like running out of lives or achieving high scores
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand game design psychology
- [ ] Add sound effects for scoring and losing lives
- [ ] Implement a high score system using localStorage
- [ ] Create different point values for different enemy types
- [ ] Add visual effects like screen shake when losing a life
### 📅 **Your Week-Long Game Design Journey**
- [ ] Complete the full space game with polished feedback systems
- [ ] Implement advanced scoring mechanics like combo multipliers
- [ ] Add achievements and unlockable content
- [ ] Create difficulty progression and balancing systems
- [ ] Design user interfaces for menus and game over screens
- [ ] Study other games to understand engagement mechanisms
### 🌟 **Your Month-Long Game Development Mastery**
- [ ] Build complete games with sophisticated progression systems
- [ ] Learn game analytics and player behavior measurement
- [ ] Contribute to open source game development projects
- [ ] Master advanced game design patterns and monetization
- [ ] Create educational content about game design and user experience
- [ ] Build a portfolio showcasing game design and development skills
## 🎯 Your Game Design Mastery Timeline
```mermaid
timeline
title Game Design & Player Feedback Learning Progression
section Foundation (10 minutes)
Visual Communication: Text rendering
: Icon design
: Layout principles
: Color psychology
section Player Psychology (20 minutes)
Motivation Systems: Point values
: Risk vs reward
: Progress feedback
: Achievement design
section Technical Implementation (30 minutes)
Canvas Mastery: Text positioning
: Sprite rendering
: State management
: Performance optimization
section Game Balance (40 minutes)
Difficulty Design: Life management
: Scoring curves
: Player retention
: Accessibility
section User Experience (50 minutes)
Interface Design: Information hierarchy
: Responsive feedback
: Emotional design
: Usability testing
section Advanced Systems (1 week)
Game Mechanics: Progression systems
: Analytics integration
: Monetization design
: Community features
section Industry Skills (1 month)
Professional Development: Team collaboration
: Design documentation
: Player research
: Platform optimization
```
### 🛠️ Your Game Design Toolkit Summary
After completing this lesson, you now have mastered:
- **Player Psychology**: Understanding motivation, risk/reward, and engagement loops
- **Visual Communication**: Effective UI design using text, icons, and layout
- **Feedback Systems**: Real-time response to player actions and game events
- **State Management**: Tracking and displaying dynamic game data efficiently
- **Canvas Text Rendering**: Professional text display with styling and positioning
- **Event Integration**: Connecting user actions to meaningful game consequences
- **Game Balance**: Designing difficulty curves and player progression systems
**Real-World Applications**: Your game design skills apply directly to:
- **User Interface Design**: Creating engaging and intuitive interfaces
- **Product Development**: Understanding user motivation and feedback loops
- **Educational Technology**: Gamification and learning engagement systems
- **Data Visualization**: Making complex information accessible and engaging
- **Mobile App Development**: Retention mechanics and user experience design
- **Marketing Technology**: Understanding user behavior and conversion optimization
**Professional Skills Gained**: You can now:
- **Design** user experiences that motivate and engage users
- **Implement** feedback systems that guide user behavior effectively
- **Balance** challenge and accessibility in interactive systems
- **Create** visual communication that works across different user groups
- **Analyze** user behavior and iterate on design improvements
**Game Development Concepts Mastered**:
- **Player Motivation**: Understanding what drives engagement and retention
- **Visual Design**: Creating clear, attractive, and functional interfaces
- **System Integration**: Connecting multiple game systems for cohesive experience
- **Performance Optimization**: Efficient rendering and state management
- **Accessibility**: Designing for different skill levels and player needs
**Next Level**: You're ready to explore advanced game design patterns, implement analytics systems, or study game monetization and player retention strategies!
🌟 **Achievement Unlocked**: You've built a complete player feedback system with professional game design principles!
---
## GitHub Copilot Agent Challenge 🚀

@ -1,11 +1,58 @@
# Build a Space Game Part 6: End and Restart
```mermaid
journey
title Your Game Completion Journey
section End Conditions
Define win/lose states: 3: Student
Implement condition checking: 4: Student
Handle state transitions: 4: Student
section Player Experience
Design feedback systems: 4: Student
Create restart mechanics: 5: Student
Polish user interface: 5: Student
section System Integration
Manage game lifecycle: 5: Student
Handle memory cleanup: 5: Student
Create complete experience: 5: Student
```
Every great game needs clear end conditions and a smooth restart mechanism. You've built an impressive space game with movement, combat, and scoring - now it's time to add the final pieces that make it feel complete.
Your game currently runs indefinitely, like the Voyager probes that NASA launched in 1977 - still traveling through space decades later. While that's fine for space exploration, games need defined endpoints to create satisfying experiences.
Today, we'll implement proper win/lose conditions and a restart system. By the end of this lesson, you'll have a polished game that players can complete and replay, just like the classic arcade games that defined the medium.
```mermaid
mindmap
root((Game Completion))
End Conditions
Victory States
Defeat Conditions
Progress Tracking
State Validation
Player Feedback
Visual Messages
Color Psychology
Clear Communication
Emotional Response
State Management
Game Loop Control
Memory Cleanup
Object Lifecycle
Event Handling
Restart Systems
Input Handling
State Reset
Fresh Initialization
User Experience
Polish Elements
Message Display
Smooth Transitions
Error Prevention
Accessibility
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/39)
@ -16,6 +63,38 @@ When should your game end? This fundamental question has shaped game design sinc
As the game creator, you define the victory and defeat conditions. For our space game, here are proven approaches that create engaging gameplay:
```mermaid
flowchart TD
A["🎮 Game Start"] --> B{"Check Conditions"}
B --> C["Enemy Count"]
B --> D["Hero Lives"]
B --> E["Score Threshold"]
B --> F["Level Progress"]
C --> C1{"Enemies = 0?"}
D --> D1{"Lives = 0?"}
E --> E1{"Score ≥ Target?"}
F --> F1{"Objectives Complete?"}
C1 -->|Yes| G["🏆 Victory"]
D1 -->|Yes| H["💀 Defeat"]
E1 -->|Yes| G
F1 -->|Yes| G
C1 -->|No| B
D1 -->|No| B
E1 -->|No| B
F1 -->|No| B
G --> I["🔄 Restart Option"]
H --> I
style G fill:#e8f5e8
style H fill:#ffebee
style I fill:#e3f2fd
```
- **`N` Enemy ships have been destroyed**: It's quite common if you divide up a game into different levels that you need to destroy `N` Enemy ships to complete a level
- **Your ship has been destroyed**: There are definitely games where you lose the game if your ship is destroyed. Another common approach is that you have the concept of lives. Every time a your ship is destroyed it deducts a life. Once all lives have been lost then you lose the game.
- **You've collected `N` points**: Another common end condition is for you to collect points. How you get points is up to you but it's quite common to assign points to various activities like destroying an enemy ship or maybe collect items that items *drop* when they are destroyed.
@ -25,6 +104,35 @@ As the game creator, you define the victory and defeat conditions. For our space
Good games encourage replayability through smooth restart mechanisms. When players complete a game (or meet defeat), they often want to try again immediately - whether to beat their score or improve their performance.
```mermaid
stateDiagram-v2
[*] --> Playing: Game Start
Playing --> Victory: All enemies destroyed
Playing --> Defeat: Lives = 0
Victory --> MessageDisplay: Show win message
Defeat --> MessageDisplay: Show lose message
MessageDisplay --> WaitingRestart: Press Enter prompt
WaitingRestart --> Resetting: Enter key pressed
Resetting --> CleanupMemory: Clear intervals
CleanupMemory --> ClearEvents: Remove listeners
ClearEvents --> InitializeGame: Fresh start
InitializeGame --> Playing: New game begins
note right of MessageDisplay
Color-coded feedback:
Green = Victory
Red = Defeat
end note
note right of Resetting
Complete state reset
prevents memory leaks
end note
```
Tetris exemplifies this perfectly: when your blocks reach the top, you can instantly start a new game without navigating complex menus. We'll build a similar restart system that cleanly resets the game state and gets players back into action quickly.
**Reflection**: Think about the games you've played. Under what conditions do they end, and how are you prompted to restart? What makes a restart experience feel smooth versus frustrating?
@ -73,6 +181,32 @@ Open `http://localhost:5000` in your browser and verify your game is running. Yo
> 💡 **Pro Tip**: To avoid warnings in Visual Studio Code, declare `gameLoopId` at the top of your file as `let gameLoopId;` instead of declaring it inside the `window.onload` function. This follows modern JavaScript variable declaration best practices.
```mermaid
flowchart TD
A["1. Condition Tracking"] --> B["2. Event Handlers"]
B --> C["3. Message Constants"]
C --> D["4. Restart Controls"]
D --> E["5. Message Display"]
E --> F["6. Reset System"]
G["isHeroDead()\nisEnemiesDead()"] --> A
H["Collision Events\nEnd Game Events"] --> B
I["GAME_END_WIN\nGAME_END_LOSS"] --> C
J["Enter Key\nRestart Trigger"] --> D
K["Victory/Defeat\nColor-coded Text"] --> E
L["State Cleanup\nFresh Initialization"] --> F
F --> M["🎮 Complete Game"]
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#f3e5f5
style E fill:#e0f2f1
style F fill:#fce4ec
style M fill:#e1f5fe
```
## Implementation Steps
### Step 1: Create End Condition Tracking Functions
@ -101,6 +235,40 @@ function isEnemiesDead() {
Now we'll connect these condition checks to the game's event system. Every time a collision occurs, the game will evaluate whether it triggers an end condition. This creates immediate feedback for critical game events.
```mermaid
sequenceDiagram
participant Collision
participant GameLogic
participant Conditions
participant EventSystem
participant Display
Collision->>GameLogic: Laser hits enemy
GameLogic->>GameLogic: Destroy objects
GameLogic->>Conditions: Check isEnemiesDead()
alt All enemies defeated
Conditions->>EventSystem: Emit GAME_END_WIN
EventSystem->>Display: Show victory message
else Enemies remain
Conditions->>GameLogic: Continue game
end
Collision->>GameLogic: Enemy hits hero
GameLogic->>GameLogic: Decrease lives
GameLogic->>Conditions: Check isHeroDead()
alt Lives = 0
Conditions->>EventSystem: Emit GAME_END_LOSS
EventSystem->>Display: Show defeat message
else Lives remain
GameLogic->>Conditions: Check isEnemiesDead()
alt All enemies defeated
Conditions->>EventSystem: Emit GAME_END_WIN
end
end
```
```javascript
eventEmitter.on(Messages.COLLISION_ENEMY_LASER, (_, { first, second }) => {
first.dead = true;
@ -232,6 +400,22 @@ function endGame(win) {
- **Color codes** the news - green for good, red for... well, not so good
- **Tells** players exactly how to jump back in
### 🔄 **Pedagogical Check-in**
**Game State Management**: Before implementing reset functionality, ensure you understand:
- ✅ How end conditions create clear gameplay objectives
- ✅ Why visual feedback is essential for player understanding
- ✅ The importance of proper cleanup in preventing memory leaks
- ✅ How event-driven architecture enables clean state transitions
**Quick Self-Test**: What would happen if you didn't clear event listeners during reset?
*Answer: Memory leaks and duplicate event handlers causing unpredictable behavior*
**Game Design Principles**: You're now implementing:
- **Clear Objectives**: Players know exactly what defines success and failure
- **Immediate Feedback**: Game state changes are communicated instantly
- **User Control**: Players can restart when they're ready
- **System Reliability**: Proper cleanup prevents bugs and performance issues
### Step 6: Implement Game Reset Functionality
The reset system needs to completely clean up the current game state and initialize a fresh game session. This ensures players get a clean start without any leftover data from the previous game.
@ -299,6 +483,144 @@ clear() {
- **Managed** complex game state transitions and cleanup
- **Assembled** all components into a cohesive, playable game
### 🔄 **Pedagogical Check-in**
**Complete Game Development System**: Celebrate your mastery of the full game development cycle:
- ✅ How do end conditions create satisfying player experiences?
- ✅ Why is proper state management critical for game stability?
- ✅ How does visual feedback enhance player understanding?
- ✅ What role does the restart system play in player retention?
**System Mastery**: Your complete game demonstrates:
- **Full-Stack Game Development**: From graphics to input to state management
- **Professional Architecture**: Event-driven systems with proper cleanup
- **User Experience Design**: Clear feedback and intuitive controls
- **Performance Optimization**: Efficient rendering and memory management
- **Polish and Completeness**: All the details that make a game feel finished
**Industry-Ready Skills**: You've implemented:
- **Game Loop Architecture**: Real-time systems with consistent performance
- **Event-Driven Programming**: Decoupled systems that scale effectively
- **State Management**: Complex data handling and lifecycle management
- **User Interface Design**: Clear communication and responsive controls
- **Testing and Debugging**: Iterative development and problem-solving
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Play your complete game and test all victory and defeat conditions
- [ ] Experiment with different end condition parameters
- [ ] Try adding console.log statements to track game state changes
- [ ] Share your game with friends and gather feedback
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and reflect on your game development journey
- [ ] Add audio effects for victory and defeat states
- [ ] Implement additional end conditions like time limits or bonus objectives
- [ ] Create different difficulty levels with varying enemy counts
- [ ] Polish the visual presentation with better fonts and colors
### 📅 **Your Week-Long Game Development Mastery**
- [ ] Complete the enhanced space game with multiple levels and progression
- [ ] Add advanced features like power-ups, different enemy types, and special weapons
- [ ] Create a high score system with persistent storage
- [ ] Design user interfaces for menus, settings, and game options
- [ ] Optimize performance for different devices and browsers
- [ ] Deploy your game online and share it with the community
### 🌟 **Your Month-Long Game Development Career**
- [ ] Build multiple complete games exploring different genres and mechanics
- [ ] Learn advanced game development frameworks like Phaser or Three.js
- [ ] Contribute to open source game development projects
- [ ] Study game design principles and player psychology
- [ ] Create a portfolio showcasing your game development skills
- [ ] Connect with the game development community and continue learning
## 🎯 Your Complete Game Development Mastery Timeline
```mermaid
timeline
title Complete Game Development Learning Progression
section Foundation (Lessons 1-2)
Game Architecture: Project structure
: Asset management
: Canvas basics
: Event systems
section Interaction Systems (Lessons 3-4)
Player Control: Input handling
: Movement mechanics
: Collision detection
: Physics simulation
section Game Mechanics (Lesson 5)
Feedback Systems: Scoring mechanisms
: Life management
: Visual communication
: Player motivation
section Game Completion (Lesson 6)
Polish & Flow: End conditions
: State management
: Restart systems
: User experience
section Advanced Features (1 week)
Enhancement Skills: Audio integration
: Visual effects
: Level progression
: Performance optimization
section Professional Development (1 month)
Industry Readiness: Framework mastery
: Team collaboration
: Portfolio development
: Community engagement
section Career Advancement (3 months)
Specialization: Advanced game engines
: Platform deployment
: Monetization strategies
: Industry networking
```
### 🛠️ Your Complete Game Development Toolkit Summary
After completing this entire space game series, you now have mastered:
- **Game Architecture**: Event-driven systems, game loops, and state management
- **Graphics Programming**: Canvas API, sprite rendering, and visual effects
- **Input Systems**: Keyboard handling, collision detection, and responsive controls
- **Game Design**: Player feedback, progression systems, and engagement mechanics
- **Performance Optimization**: Efficient rendering, memory management, and frame rate control
- **User Experience**: Clear communication, intuitive controls, and polish details
- **Professional Patterns**: Clean code, debugging techniques, and project organization
**Real-World Applications**: Your game development skills apply directly to:
- **Interactive Web Applications**: Dynamic interfaces and real-time systems
- **Data Visualization**: Animated charts and interactive graphics
- **Educational Technology**: Gamification and engaging learning experiences
- **Mobile Development**: Touch-based interactions and performance optimization
- **Simulation Software**: Physics engines and real-time modeling
- **Creative Industries**: Interactive art, entertainment, and digital experiences
**Professional Skills Gained**: You can now:
- **Architect** complex interactive systems from scratch
- **Debug** real-time applications using systematic approaches
- **Optimize** performance for smooth user experiences
- **Design** engaging user interfaces and interaction patterns
- **Collaborate** effectively on technical projects with proper code organization
**Game Development Concepts Mastered**:
- **Real-time Systems**: Game loops, frame rate management, and performance
- **Event-Driven Architecture**: Decoupled systems and message passing
- **State Management**: Complex data handling and lifecycle management
- **User Interface Programming**: Canvas graphics and responsive design
- **Game Design Theory**: Player psychology and engagement mechanics
**Next Level**: You're ready to explore advanced game frameworks, 3D graphics, multiplayer systems, or transition into professional game development roles!
🌟 **Achievement Unlocked**: You've completed a full game development journey and built a professional-quality interactive experience from scratch!
**Welcome to the game development community!** 🎮✨
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:

@ -1,5 +1,22 @@
# Build a Banking App Part 1: HTML Templates and Routes in a Web App
```mermaid
journey
title Your Banking App Development Journey
section SPA Fundamentals
Understand single-page apps: 3: Student
Learn template concepts: 4: Student
Master DOM manipulation: 4: Student
section Routing Systems
Implement client-side routing: 4: Student
Handle browser history: 5: Student
Create navigation systems: 5: Student
section Professional Patterns
Build modular architecture: 5: Student
Apply best practices: 5: Student
Create user experiences: 5: Student
```
When Apollo 11's guidance computer navigated to the moon in 1969, it had to switch between different programs without restarting the entire system. Modern web applications work similarly they change what you see without reloading everything from scratch. This creates the smooth, responsive experience users expect today.
Unlike traditional websites that reload entire pages for every interaction, modern web apps update only the parts that need changing. This approach, much like how mission control switches between different displays while maintaining constant communication, creates that fluid experience we've come to expect.
@ -26,6 +43,36 @@ You'll work with HTML templates (reusable blueprints for different screens), Jav
By the end, you'll have a working banking app that demonstrates professional single-page application principles.
```mermaid
mindmap
root((Single-Page Applications))
Architecture
Template System
Client-side Routing
State Management
Event Handling
Templates
Reusable Components
Dynamic Content
DOM Manipulation
Content Switching
Routing
URL Management
History API
Navigation Logic
Browser Integration
User Experience
Fast Navigation
Smooth Transitions
Consistent State
Modern Interactions
Performance
Reduced Server Requests
Faster Page Transitions
Efficient Resource Usage
Better Responsiveness
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/41)
@ -80,6 +127,24 @@ On your computer, create a folder named `bank` with a file named `index.html` in
Templates solve a fundamental problem in web development. When Gutenberg invented movable type printing in the 1440s, he realized that instead of carving entire pages, he could create reusable letter blocks and arrange them as needed. HTML templates work on the same principle instead of creating separate HTML files for each screen, you define reusable structures that can be displayed when needed.
```mermaid
flowchart TD
A["📋 Template Definition"] --> B["💬 Hidden in DOM"]
B --> C["🔍 JavaScript Finds Template"]
C --> D["📋 Clone Template Content"]
D --> E["🔗 Attach to Visible DOM"]
E --> F["👁️ User Sees Content"]
G["Login Template"] --> A
H["Dashboard Template"] --> A
I["Future Templates"] --> A
style A fill:#e3f2fd
style D fill:#e8f5e8
style F fill:#fff3e0
style B fill:#f3e5f5
```
Think of templates as blueprints for different parts of your app. Just as an architect creates one blueprint and uses it multiple times rather than redrawing identical rooms, we create templates once and instantiate them as needed. The browser keeps these templates hidden until JavaScript activates them.
If you want to create multiple screens for a web page, one solution would be to create one HTML file for every screen you want to display. However, this solution comes with some inconvenience:
@ -164,6 +229,22 @@ Then we'll add another HTML template for the dashboard page. This page will cont
> 💡 **Pro Tip**: When creating HTML templates, if you want to see what it will look like, you can comment out the `<template>` and `</template>` lines by enclosing them with `<!-- -->`.
### 🔄 **Pedagogical Check-in**
**Template System Understanding**: Before implementing JavaScript, ensure you understand:
- ✅ How templates differ from regular HTML elements
- ✅ Why templates remain hidden until activated by JavaScript
- ✅ The importance of semantic HTML structure in templates
- ✅ How templates enable reusable UI components
**Quick Self-Test**: What happens if you remove the `<template>` tags from around your HTML?
*Answer: The content becomes visible immediately and loses its template functionality*
**Architecture Benefits**: Templates provide:
- **Reusability**: One definition, multiple instances
- **Performance**: No redundant HTML parsing
- **Maintainability**: Centralized UI structure
- **Flexibility**: Dynamic content switching
✅ Why do you think we use `id` attributes on the templates? Could we use something else like classes?
## Bringing Templates to Life with JavaScript
@ -255,6 +336,23 @@ updateRoute('login');
Routing is essentially about connecting URLs to the right content. Consider how early telephone operators used switchboards to connect calls they would take an incoming request and route it to the correct destination. Web routing works similarly, taking a URL request and determining which content to display.
```mermaid
flowchart LR
A["🌐 URL Path<br/>/dashboard"] --> B["🗺️ Routes Object<br/>Lookup"]
B --> C["🎯 Template ID<br/>'dashboard'"]
C --> D["📌 Find Template<br/>getElementById"]
D --> E["👁️ Display Screen<br/>Clone & Append"]
F["📍 /login"] --> G["🎯 'login'"]
H["📍 /unknown"] --> I["❌ Not Found"]
I --> J["🔄 Redirect to /login"]
style B fill:#e3f2fd
style E fill:#e8f5e8
style I fill:#ffebee
style J fill:#fff3e0
```
Traditionally, web servers handled this by serving different HTML files for different URLs. Since we're building a single-page app, we need to handle this routing ourselves with JavaScript. This approach gives us more control over the user experience and performance.
```mermaid
@ -347,7 +445,57 @@ With routing established, users need a way to navigate through the app. Traditio
We need to coordinate two things: updating the browser's URL so users can bookmark pages and share links, and displaying the appropriate content. When implemented correctly, this creates the seamless navigation users expect from modern applications.
> 🏗️ **Architecture Insight**: Navigation System Components
```mermaid
sequenceDiagram
participant User
participant Browser
participant App
participant Template
User->>Browser: Clicks "Login" link
Browser->>App: onclick event triggered
App->>App: preventDefault() & navigate('/dashboard')
App->>Browser: history.pushState('/dashboard')
Browser->>Browser: URL updates to /dashboard
App->>App: updateRoute() called
App->>Template: Find & clone dashboard template
Template->>App: Return cloned content
App->>Browser: Replace app content with template
Browser->>User: Display dashboard screen
Note over User,Template: User clicks browser back button
User->>Browser: Clicks back button
Browser->>Browser: History moves back to /login
Browser->>App: popstate event fired
App->>App: updateRoute() called automatically
App->>Template: Find & clone login template
Template->>App: Return cloned content
App->>Browser: Replace app content with template
Browser->>User: Display login screen
```
### 🔄 **Pedagogical Check-in**
**Single-Page Application Architecture**: Verify your understanding of the complete system:
- ✅ How does client-side routing differ from traditional server-side routing?
- ✅ Why is the History API essential for proper SPA navigation?
- ✅ How do templates enable dynamic content without page reloads?
- ✅ What role does event handling play in intercepting navigation?
**System Integration**: Your SPA demonstrates:
- **Template Management**: Reusable UI components with dynamic content
- **Client-side Routing**: URL management without server requests
- **Event-driven Architecture**: Responsive navigation and user interactions
- **Browser Integration**: Proper history and back/forward button support
- **Performance Optimization**: Fast transitions and reduced server load
**Professional Patterns**: You've implemented:
- **Model-View Separation**: Templates separate from application logic
- **State Management**: URL state synchronized with displayed content
- **Progressive Enhancement**: JavaScript enhances basic HTML functionality
- **User Experience**: Smooth, app-like navigation without page refreshes
> <20> **Architecture Insight**: Navigation System Components
>
> **What you're building:**
> - **🔄 URL Management**: Updates browser address bar without page reloads
@ -528,6 +676,115 @@ Here's a refresher video on arrow functions:
Now try to use the back and forward buttons of your browsers, and check that the displayed route is correctly updated this time.
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Test your banking app's navigation using browser back/forward buttons
- [ ] Try manually typing different URLs in the address bar to test routing
- [ ] Open browser DevTools and inspect how templates are cloned into the DOM
- [ ] Experiment with adding console.log statements to track the routing flow
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand SPA architecture concepts
- [ ] Add CSS styling to make your banking app templates look professional
- [ ] Implement the 404 error page challenge with proper error handling
- [ ] Create the credits page challenge with additional routing functionality
- [ ] Add loading states and transitions between template switches
### 📅 **Your Week-Long SPA Development Journey**
- [ ] Complete the full banking app with forms, data management, and persistence
- [ ] Add advanced routing features like route parameters and nested routes
- [ ] Implement navigation guards and authentication-based routing
- [ ] Create reusable template components and a component library
- [ ] Add animations and transitions for smoother user experience
- [ ] Deploy your SPA to a hosting platform and configure routing properly
### 🌟 **Your Month-Long Frontend Architecture Mastery**
- [ ] Build complex SPAs using modern frameworks like React, Vue, or Angular
- [ ] Learn advanced state management patterns and libraries
- [ ] Master build tools and development workflows for SPA development
- [ ] Implement Progressive Web App features and offline functionality
- [ ] Study performance optimization techniques for large-scale SPAs
- [ ] Contribute to open source SPA projects and share your knowledge
## 🎯 Your Single-Page Application Mastery Timeline
```mermaid
timeline
title SPA Development & Modern Web Architecture Learning Progression
section Foundation (20 minutes)
Template Systems: HTML template elements
: DOM manipulation
: Content cloning
: Dynamic rendering
section Routing Basics (30 minutes)
Client-side Navigation: URL management
: History API
: Route mapping
: Event handling
section User Experience (40 minutes)
Navigation Polish: Browser integration
: Back button support
: Error handling
: Smooth transitions
section Architecture Patterns (50 minutes)
Professional SPAs: Component systems
: State management
: Performance optimization
: Error boundaries
section Advanced Techniques (1 week)
Framework Integration: React Router
: Vue Router
: Angular Router
: State libraries
section Production Skills (1 month)
Enterprise Development: Build systems
: Testing strategies
: Deployment pipelines
: Performance monitoring
```
### 🛠️ Your SPA Development Toolkit Summary
After completing this lesson, you now have mastered:
- **Template Architecture**: Reusable HTML components with dynamic content rendering
- **Client-side Routing**: URL management and navigation without page reloads
- **Browser Integration**: History API usage and back/forward button support
- **Event-driven Systems**: Navigation handling and user interaction management
- **DOM Manipulation**: Template cloning, content switching, and element management
- **Error Handling**: Graceful fallbacks for invalid routes and missing content
- **Performance Patterns**: Efficient content loading and rendering strategies
**Real-World Applications**: Your SPA development skills apply directly to:
- **Modern Web Applications**: React, Vue, Angular, and other framework development
- **Progressive Web Apps**: Offline-capable applications with app-like experiences
- **Enterprise Dashboards**: Complex business applications with multiple views
- **E-commerce Platforms**: Product catalogs, shopping carts, and checkout flows
- **Content Management**: Dynamic content creation and editing interfaces
- **Mobile Development**: Hybrid apps using web technologies
**Professional Skills Gained**: You can now:
- **Architect** single-page applications with proper separation of concerns
- **Implement** client-side routing systems that scale with application complexity
- **Debug** complex navigation flows using browser developer tools
- **Optimize** application performance through efficient template management
- **Design** user experiences that feel native and responsive
**Frontend Development Concepts Mastered**:
- **Component Architecture**: Reusable UI patterns and template systems
- **State Synchronization**: URL state management and browser history
- **Event-driven Programming**: User interaction handling and navigation
- **Performance Optimization**: Efficient DOM manipulation and content loading
- **User Experience Design**: Smooth transitions and intuitive navigation
**Next Level**: You're ready to explore modern frontend frameworks, advanced state management, or build complex enterprise applications!
🌟 **Achievement Unlocked**: You've built a professional single-page application foundation with modern web architecture patterns!
---
## GitHub Copilot Agent Challenge 🚀

@ -1,5 +1,22 @@
# Build a Banking App Part 2: Build a Login and Registration Form
```mermaid
journey
title Your Form Development Journey
section HTML Foundation
Understand form elements: 3: Student
Learn input types: 4: Student
Master accessibility: 4: Student
section JavaScript Integration
Handle form submission: 4: Student
Implement AJAX communication: 5: Student
Process server responses: 5: Student
section Validation Systems
Create multi-layer validation: 5: Student
Enhance user experience: 5: Student
Ensure data integrity: 5: Student
```
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/43)
@ -12,6 +29,36 @@ In this lesson, we'll transform your static banking app into an interactive appl
By the end, you'll have a complete login and registration system with validation that guides users toward success rather than frustration.
```mermaid
mindmap
root((Form Development))
HTML Foundation
Semantic Elements
Input Types
Accessibility
Label Association
User Experience
Validation Feedback
Error Prevention
Loading States
Success Messaging
JavaScript Integration
Event Handling
AJAX Communication
Data Processing
Error Management
Validation Layers
HTML5 Validation
Client-side Logic
Server-side Security
Progressive Enhancement
Modern Patterns
Fetch API
Async/Await
Form Data API
Promise Handling
```
## Prerequisites
Before we start building forms, let's make sure you've got everything set up correctly. This lesson picks up right where we left off in the previous one, so if you skipped ahead, you might want to go back and get the basics working first.
@ -208,6 +255,22 @@ The registration form requires more detailed information to create a complete us
> 🎯 **Accessibility Challenge**: Try navigating the forms using only your keyboard! Use `Tab` to move between fields, `Space` to check boxes, and `Enter` to submit. This experience helps you understand how screen reader users interact with your forms.
### 🔄 **Pedagogical Check-in**
**Form Foundation Understanding**: Before implementing JavaScript, ensure you understand:
- ✅ How semantic HTML creates accessible form structures
- ✅ Why input types matter for mobile keyboards and validation
- ✅ The relationship between labels and form controls
- ✅ How form attributes affect default browser behavior
**Quick Self-Test**: What happens if you submit a form without JavaScript handling?
*Answer: The browser performs default submission, usually redirecting to the action URL*
**HTML5 Form Benefits**: Modern forms provide:
- **Built-in Validation**: Automatic email and number format checking
- **Mobile Optimization**: Appropriate keyboards for different input types
- **Accessibility**: Screen reader support and keyboard navigation
- **Progressive Enhancement**: Works even when JavaScript is disabled
## Understanding Form Submission Methods
When someone fills out your form and hits submit, that data needs to go somewhere usually to a server that can save it. There are a couple of different ways this can happen, and knowing which one to use can save you from some headaches later.
@ -554,6 +617,26 @@ async function register() {
> 🔒 **Security Consideration**: Currently, data travels over HTTP, which is not secure for production. In real applications, always use HTTPS to encrypt data transmission. Learn more about [HTTPS security](https://en.wikipedia.org/wiki/HTTPS) and why it's essential for protecting user data.
### 🔄 **Pedagogical Check-in**
**Modern JavaScript Integration**: Verify your understanding of asynchronous form handling:
- ✅ How does `event.preventDefault()` change default form behavior?
- ✅ Why is the FormData API more efficient than manual field collection?
- ✅ How do async/await patterns improve code readability?
- ✅ What role does error handling play in user experience?
**System Architecture**: Your form handling demonstrates:
- **Event-Driven Programming**: Forms respond to user actions without page reloads
- **Asynchronous Communication**: Server requests don't block the user interface
- **Error Handling**: Graceful degradation when network requests fail
- **State Management**: UI updates reflect server responses appropriately
- **Progressive Enhancement**: Base functionality works, JavaScript enhances it
**Professional Patterns**: You've implemented:
- **Single Responsibility**: Functions have clear, focused purposes
- **Error Boundaries**: Try/catch blocks prevent application crashes
- **User Feedback**: Loading states and success/error messaging
- **Data Transformation**: FormData to JSON for server communication
## Comprehensive Form Validation
Form validation prevents the frustrating experience of discovering errors only after submission. Like the multiple redundant systems on the International Space Station, effective validation employs multiple layers of safety checks.
@ -731,6 +814,115 @@ graph LR
> 🛡️ **Security Reminder**: Never trust client-side validation alone! Malicious users can bypass client-side checks, so server-side validation is essential for security and data integrity.
### ⚡ **What You Can Do in the Next 5 Minutes**
- [ ] Test your form with invalid data to see validation messages
- [ ] Try submitting the form with JavaScript disabled to see HTML5 validation
- [ ] Open browser DevTools and inspect form data being sent to the server
- [ ] Experiment with different input types to see mobile keyboard changes
### 🎯 **What You Can Accomplish This Hour**
- [ ] Complete the post-lesson quiz and understand form handling concepts
- [ ] Implement the comprehensive validation challenge with real-time feedback
- [ ] Add CSS styling to create professional-looking forms
- [ ] Create error handling for duplicate usernames and server errors
- [ ] Add password confirmation fields with matching validation
### 📅 **Your Week-Long Form Mastery Journey**
- [ ] Complete the full banking app with advanced form features
- [ ] Implement file upload capabilities for profile pictures or documents
- [ ] Add multi-step forms with progress indicators and state management
- [ ] Create dynamic forms that adapt based on user selections
- [ ] Implement form autosave and recovery for better user experience
- [ ] Add advanced validation like email verification and phone number formatting
### 🌟 **Your Month-Long Frontend Development Mastery**
- [ ] Build complex form applications with conditional logic and workflows
- [ ] Learn form libraries and frameworks for rapid development
- [ ] Master accessibility guidelines and inclusive design principles
- [ ] Implement internationalization and localization for global forms
- [ ] Create reusable form component libraries and design systems
- [ ] Contribute to open source form projects and share best practices
## 🎯 Your Form Development Mastery Timeline
```mermaid
timeline
title Form Development & User Experience Learning Progression
section HTML Foundation (15 minutes)
Semantic Forms: Form elements
: Input types
: Labels and accessibility
: Progressive enhancement
section JavaScript Integration (25 minutes)
Event Handling: Form submission
: Data collection
: AJAX communication
: Async/await patterns
section Validation Systems (35 minutes)
Multi-layer Security: HTML5 validation
: Client-side logic
: Server-side verification
: Error handling
section User Experience (45 minutes)
Interface Polish: Loading states
: Success messaging
: Error recovery
: Accessibility features
section Advanced Patterns (1 week)
Professional Forms: Dynamic validation
: Multi-step workflows
: File uploads
: Real-time feedback
section Enterprise Skills (1 month)
Production Applications: Form libraries
: Testing strategies
: Performance optimization
: Security best practices
```
### 🛠️ Your Form Development Toolkit Summary
After completing this lesson, you now have mastered:
- **HTML5 Forms**: Semantic structure, input types, and accessibility features
- **JavaScript Form Handling**: Event management, data collection, and AJAX communication
- **Validation Architecture**: Multi-layer validation for security and user experience
- **Asynchronous Programming**: Modern fetch API and async/await patterns
- **Error Management**: Comprehensive error handling and user feedback systems
- **User Experience Design**: Loading states, success messaging, and error recovery
- **Progressive Enhancement**: Forms that work across all browsers and capabilities
**Real-World Applications**: Your form development skills apply directly to:
- **E-commerce Applications**: Checkout processes, account registration, and payment forms
- **Enterprise Software**: Data entry systems, reporting interfaces, and workflow applications
- **Content Management**: Publishing platforms, user-generated content, and administrative interfaces
- **Financial Applications**: Banking interfaces, investment platforms, and transaction systems
- **Healthcare Systems**: Patient portals, appointment scheduling, and medical record forms
- **Educational Platforms**: Course registration, assessment tools, and learning management
**Professional Skills Gained**: You can now:
- **Design** accessible forms that work for all users including those with disabilities
- **Implement** secure form validation that prevents data corruption and security vulnerabilities
- **Create** responsive user interfaces that provide clear feedback and guidance
- **Debug** complex form interactions using browser developer tools and network analysis
- **Optimize** form performance through efficient data handling and validation strategies
**Frontend Development Concepts Mastered**:
- **Event-Driven Architecture**: User interaction handling and response systems
- **Asynchronous Programming**: Non-blocking server communication and error handling
- **Data Validation**: Client-side and server-side security and integrity checks
- **User Experience Design**: Intuitive interfaces that guide users toward success
- **Accessibility Engineering**: Inclusive design that works for diverse user needs
**Next Level**: You're ready to explore advanced form libraries, implement complex validation rules, or build enterprise-grade data collection systems!
🌟 **Achievement Unlocked**: You've built a complete form handling system with professional validation, error handling, and user experience patterns!
---

@ -6,6 +6,59 @@ Right now, your banking app is like a printed newspaper - informative but static
You'll learn how to communicate with servers asynchronously, handle data that arrives at different times, and transform raw information into something meaningful for your users. This is the difference between a demo and production-ready software.
## ⚡ What You Can Do in the Next 5 Minutes
**Quick Start Pathway for Busy Developers**
```mermaid
flowchart LR
A[⚡ 5 minutes] --> B[Set up API server]
B --> C[Test fetch with curl]
C --> D[Create login function]
D --> E[See data in action]
```
- **Minute 1-2**: Start your API server (`cd api && npm start`) and test the connection
- **Minute 3**: Create a basic `getAccount()` function using fetch
- **Minute 4**: Wire up the login form with `action="javascript:login()"`
- **Minute 5**: Test login and watch account data appear in the console
**Quick Test Commands**:
```bash
# Verify API is running
curl http://localhost:5000/api
# Test account data fetch
curl http://localhost:5000/api/accounts/test
```
**Why This Matters**: In 5 minutes, you'll see the magic of asynchronous data fetching that powers every modern web application. This is the foundation that makes apps feel responsive and alive.
## 🗺️ Your Learning Journey Through Data-Driven Web Applications
```mermaid
journey
title From Static Pages to Dynamic Applications
section Understanding the Evolution
Traditional page reloads: 3: You
Discover AJAX/SPA benefits: 5: You
Master Fetch API patterns: 7: You
section Building Authentication
Create login functions: 4: You
Handle async operations: 6: You
Manage user sessions: 8: You
section Dynamic UI Updates
Learn DOM manipulation: 5: You
Build transaction displays: 7: You
Create responsive dashboards: 9: You
section Professional Patterns
Template-based rendering: 6: You
Error handling strategies: 7: You
Performance optimization: 8: You
```
**Your Journey Destination**: By the end of this lesson, you'll understand how modern web applications fetch, process, and display data dynamically, creating the seamless user experiences we expect from professional applications.
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/45)
@ -28,6 +81,51 @@ This quick test ensures all components are communicating properly:
- Confirms your API server is active and responding
- Validates that your app can reach the server (like checking radio contact before a mission)
## 🧠 Data Management Ecosystem Overview
```mermaid
mindmap
root((Data Management))
Authentication Flow
Login Process
Form Validation
Credential Verification
Session Management
User State
Global Account Object
Navigation Guards
Error Handling
API Communication
Fetch Patterns
GET Requests
POST Requests
Error Responses
Data Formats
JSON Processing
URL Encoding
Response Parsing
Dynamic UI Updates
DOM Manipulation
Safe Text Updates
Element Creation
Template Cloning
User Experience
Real-time Updates
Error Messages
Loading States
Security Considerations
XSS Prevention
textContent Usage
Input Sanitization
Safe HTML Creation
CORS Handling
Cross-Origin Requests
Header Configuration
Development Setup
```
**Core Principle**: Modern web applications are data orchestration systems - they coordinate between user interfaces, server APIs, and browser security models to create seamless, responsive experiences.
---
## Understanding Data Fetching in Modern Web Apps
@ -174,6 +272,24 @@ Think of GET requests like politely asking to borrow a book from the library - y
| **Caching** | Can be cached by browsers | Not typically cached |
| **Security** | Visible in URL/logs | Hidden in request body |
```mermaid
sequenceDiagram
participant B as Browser
participant S as Server
Note over B,S: GET Request (Data Retrieval)
B->>S: GET /api/accounts/test
S-->>B: 200 OK + Account Data
Note over B,S: POST Request (Data Submission)
B->>S: POST /api/accounts + New Account Data
S-->>B: 201 Created + Confirmation
Note over B,S: Error Handling
B->>S: GET /api/accounts/nonexistent
S-->>B: 404 Not Found + Error Message
```
#### Step 3: Bringing It All Together
Now for the satisfying part - let's connect your account fetching function to the login process. This is where everything clicks into place:
@ -417,6 +533,19 @@ Here's something cool about that `role="alert"` we added earlier - it's not just
Small touches like this separate good developers from great ones!
### 🎯 Pedagogical Check-in: Authentication Patterns
**Pause and Reflect**: You've just implemented a complete authentication flow. This is a foundational pattern in web development.
**Quick Self-Assessment**:
- Can you explain why we use async/await for API calls?
- What would happen if we forgot the `encodeURIComponent()` function?
- How does our error handling improve the user experience?
**Real-World Connection**: The patterns you've learned here (async data fetching, error handling, user feedback) are used in every major web application from social media platforms to e-commerce sites. You're building production-level skills!
**Challenge Question**: How might you modify this authentication system to handle multiple user roles (customer, admin, teller)? Think about the data structure and UI changes needed.
#### Step 5: Apply the Same Pattern to Registration
For consistency, implement identical error handling in your registration form:
@ -472,6 +601,22 @@ Before we start building, let's peek at what kind of data your server sends back
Everything you need to build a professional-looking banking dashboard!
```mermaid
flowchart TD
A[User Login] --> B[Fetch Account Data]
B --> C{Data Valid?}
C -->|Yes| D[Store in Global Variable]
C -->|No| E[Show Error Message]
D --> F[Navigate to Dashboard]
F --> G[Update UI Elements]
G --> H[Display Balance]
G --> I[Show Description]
G --> J[Render Transactions]
J --> K[Create Table Rows]
K --> L[Format Currency]
L --> M[User Sees Live Data]
```
> 💡 **Pro Tip**: Want to see your dashboard in action right away? Use the username `test` when you log in - it comes pre-loaded with sample data so you can see everything working without having to create transactions first.
>
**Why the test account is handy:**
@ -577,6 +722,24 @@ Instead of manually creating HTML for each transaction, we'll use templates to g
This technique scales efficiently from a few transactions to thousands, maintaining consistent performance and presentation.
```mermaid
graph LR
A[HTML Template] --> B[JavaScript Clone]
B --> C[Populate with Data]
C --> D[Add to Fragment]
D --> E[Batch Insert to DOM]
subgraph "Performance Benefits"
F[Single DOM Update]
G[Consistent Formatting]
H[Reusable Pattern]
end
E --> F
E --> G
E --> H
```
```mermaid
flowchart LR
A[Transaction Data] --> B[HTML Template]
@ -702,8 +865,73 @@ If everything's working, you should see a fully functional transaction list on y
You've successfully transformed a static webpage into a dynamic web application.
### 🎯 Pedagogical Check-in: Dynamic Content Generation
**Architecture Understanding**: You've implemented a sophisticated data-to-UI pipeline that mirrors patterns used in frameworks like React, Vue, and Angular.
**Key Concepts Mastered**:
- **Template-based rendering**: Creating reusable UI components
- **Document fragments**: Optimizing DOM performance
- **Safe DOM manipulation**: Preventing security vulnerabilities
- **Data transformation**: Converting server data to user interfaces
**Industry Connection**: These techniques form the foundation of modern frontend frameworks. React's virtual DOM, Vue's template system, and Angular's component architecture all build on these core concepts.
**Reflection Question**: How would you extend this system to handle real-time updates (like new transactions appearing automatically)? Consider WebSockets or Server-Sent Events.
---
## 📈 Your Data Management Mastery Timeline
```mermaid
timeline
title Data-Driven Development Journey
section Foundation Building
API Setup & Testing
: Understand client-server communication
: Master HTTP request/response cycle
: Learn debugging techniques
section Authentication Mastery
Async Function Patterns
: Write clean async/await code
: Handle promises effectively
: Implement error boundaries
User Session Management
: Create global state patterns
: Build navigation guards
: Design user feedback systems
section Dynamic UI Development
Safe DOM Manipulation
: Prevent XSS vulnerabilities
: Use textContent over innerHTML
: Create accessibility-friendly interfaces
Template Systems
: Build reusable UI components
: Optimize performance with fragments
: Scale to handle large datasets
section Professional Patterns
Production-Ready Code
: Implement comprehensive error handling
: Follow security best practices
: Create maintainable architectures
Modern Web Standards
: Master Fetch API patterns
: Understand CORS configurations
: Build responsive, accessible UIs
```
**🎓 Graduation Milestone**: You've successfully built a complete data-driven web application using modern JavaScript patterns. These skills translate directly to working with frameworks like React, Vue, or Angular.
**🔄 Next Level Capabilities**:
- Ready to explore frontend frameworks that build on these concepts
- Prepared to implement real-time features with WebSockets
- Equipped to build Progressive Web Apps with offline capabilities
- Foundation set for learning advanced state management patterns
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:

@ -1,5 +1,59 @@
# Build a Banking App Part 4: Concepts of State Management
## ⚡ What You Can Do in the Next 5 Minutes
**Quick Start Pathway for Busy Developers**
```mermaid
flowchart LR
A[⚡ 5 minutes] --> B[Diagnose state issues]
B --> C[Create central state object]
C --> D[Add updateState function]
D --> E[See immediate improvements]
```
- **Minute 1**: Test the current state issue - log in, refresh page, observe logout
- **Minute 2**: Replace `let account = null` with `let state = { account: null }`
- **Minute 3**: Create a simple `updateState()` function for controlled updates
- **Minute 4**: Update one function to use the new pattern
- **Minute 5**: Test the improved predictability and debugging capability
**Quick Diagnostic Test**:
```javascript
// Before: Scattered state
let account = null; // Lost on refresh!
// After: Centralized state
let state = Object.freeze({ account: null }); // Controlled and trackable!
```
**Why This Matters**: In 5 minutes, you'll experience the transformation from chaotic state management to predictable, debuggable patterns. This is the foundation that makes complex applications maintainable.
## 🗺️ Your Learning Journey Through State Management Mastery
```mermaid
journey
title From Scattered State to Professional Architecture
section Diagnosing Problems
Identify state loss issues: 3: You
Understand scattered updates: 4: You
Recognize architecture needs: 6: You
section Centralizing Control
Create unified state object: 5: You
Implement controlled updates: 7: You
Add immutable patterns: 8: You
section Adding Persistence
Implement localStorage: 6: You
Handle serialization: 7: You
Create session continuity: 9: You
section Balancing Freshness
Address data staleness: 5: You
Build refresh systems: 8: You
Achieve optimal balance: 9: You
```
**Your Journey Destination**: By the end of this lesson, you'll have built a professional-grade state management system that handles persistence, data freshness, and predictable updates - the same patterns used in production applications.
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/47)
@ -39,6 +93,54 @@ curl http://localhost:5000/api
- **Tests** the connection and verifies the server is responding
- **Returns** the API version information if everything is working correctly
## 🧠 State Management Architecture Overview
```mermaid
mindmap
root((State Management))
Current Problems
Session Loss
Page Refresh Issues
Browser Close Impact
Variable Reset Problems
Scattered Updates
Multiple Modification Points
Debugging Challenges
Unpredictable Behavior
Incomplete Cleanup
Logout State Issues
Memory Leaks
Security Concerns
Centralized Solutions
Unified State Object
Single Source of Truth
Predictable Structure
Scalable Foundation
Controlled Updates
Immutable Patterns
Object.freeze Usage
Function-Based Changes
State Tracking
History Management
Debug Visibility
Change Auditing
Persistence Strategies
localStorage Integration
Session Continuity
JSON Serialization
Automatic Sync
Data Freshness
Server Refresh
Stale Data Handling
Balance Optimization
Storage Optimization
Minimal Data
Performance Focus
Security Considerations
```
**Core Principle**: Professional state management balances predictability, persistence, and performance to create reliable user experiences that scale from simple interactions to complex application workflows.
---
## Diagnosing the Current State Issues
@ -81,6 +183,32 @@ Instead of chasing our tails, we're going to create a **centralized state manage
![Schema showing the data flows between the HTML, user actions and state](./images/data-flow.png)
```mermaid
flowchart TD
A[User Action] --> B[Event Handler]
B --> C[updateState Function]
C --> D{State Validation}
D -->|Valid| E[Create New State]
D -->|Invalid| F[Error Handling]
E --> G[Object.freeze]
G --> H[Update localStorage]
H --> I[Trigger UI Update]
I --> J[User Sees Changes]
F --> K[User Sees Error]
subgraph "State Management Layer"
C
E
G
end
subgraph "Persistence Layer"
H
L[localStorage]
H -.-> L
end
```
**Understanding this data flow:**
- **Centralizes** all application state in one location
- **Routes** all state changes through controlled functions
@ -144,6 +272,19 @@ const account = state.account;
> 💡 **Note**: This refactoring doesn't immediately solve our problems, but it creates the essential foundation for the powerful improvements coming next!
### 🎯 Pedagogical Check-in: Centralization Principles
**Pause and Reflect**: You've just implemented the foundation of centralized state management. This is a crucial architectural decision.
**Quick Self-Assessment**:
- Can you explain why centralizing state in one object is better than scattered variables?
- What would happen if you forgot to update a function to use `state.account`?
- How does this pattern prepare your code for more advanced features?
**Real-World Connection**: The centralization pattern you've learned is the foundation of modern frameworks like Redux, Vuex, and React Context. You're building the same architectural thinking used in major applications.
**Challenge Question**: If you needed to add user preferences (theme, language) to your app, where would you add them in the state structure? How would this scale?
## Implementing Controlled State Updates
With our state centralized, the next step involves establishing controlled mechanisms for data modifications. This approach ensures predictable state changes and easier debugging.
@ -182,6 +323,26 @@ const immutableState = Object.freeze({ account: userData });
> 💡 **Deep Dive**: Learn about the difference between *shallow* and *deep* immutable objects in the [MDN documentation](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#What_is_shallow_freeze). Understanding this distinction is crucial for complex state structures.
```mermaid
stateDiagram-v2
[*] --> StateV1: Initial State
StateV1 --> StateV2: updateState('account', newData)
StateV2 --> StateV3: updateState('account', anotherUpdate)
StateV3 --> StateV4: updateState('preferences', userSettings)
note right of StateV1
Object.freeze()
Immutable
Debuggable
end note
note right of StateV2
New object created
Previous state preserved
Predictable changes
end note
```
### Task
Let's create a new `updateState()` function:
@ -293,6 +454,24 @@ const savedAccount = JSON.parse(localStorage.getItem('account'));
> 💡 **Advanced Option**: For complex offline applications with large datasets, consider the [`IndexedDB` API](https://developer.mozilla.org/docs/Web/API/IndexedDB_API). It provides a full client-side database but requires more complex implementation.
```mermaid
quadrantChart
title Browser Storage Options
x-axis Low Complexity --> High Complexity
y-axis Short Duration --> Long Duration
quadrant-1 Professional Tools
quadrant-2 Simple Persistence
quadrant-3 Temporary Storage
quadrant-4 Advanced Systems
localStorage: [0.3, 0.8]
sessionStorage: [0.2, 0.2]
HTTP Cookies: [0.6, 0.7]
IndexedDB: [0.9, 0.9]
Memory Variables: [0.1, 0.1]
```
### Task: Implement localStorage Persistence
Let's implement persistent storage so users stay logged in until they explicitly log out. We'll use `localStorage` to store account data across browser sessions.
@ -377,6 +556,20 @@ return navigate('/dashboard');
🎉 **Achievement Unlocked**: You've successfully implemented persistent state management! Your app now behaves like a professional web application.
### 🎯 Pedagogical Check-in: Persistence Architecture
**Architecture Understanding**: You've implemented a sophisticated persistence layer that balances user experience with data management complexity.
**Key Concepts Mastered**:
- **JSON Serialization**: Converting complex objects to storable strings
- **Automatic Synchronization**: State changes trigger persistent storage
- **Session Recovery**: Apps can restore user context after interruptions
- **Centralized Persistence**: One update function handles all storage
**Industry Connection**: This persistence pattern is fundamental to Progressive Web Apps (PWAs), offline-first applications, and modern mobile web experiences. You're building production-level capabilities.
**Reflection Question**: How would you modify this system to handle multiple user accounts on the same device? Consider privacy and security implications.
## Balancing Persistence with Data Freshness
Our persistence system successfully maintains user sessions, but introduces a new challenge: data staleness. When multiple users or applications modify the same server data, local cached information becomes outdated.
@ -415,6 +608,23 @@ curl --request POST \
We'll implement a "refresh on load" pattern that balances the benefits of persistence with the need for fresh data. This approach maintains the smooth user experience while ensuring data accuracy.
```mermaid
sequenceDiagram
participant U as User
participant A as App
participant L as localStorage
participant S as Server
U->>A: Opens app
A->>L: Load saved state
L-->>A: Return cached data
A->>U: Show UI immediately
A->>S: Fetch fresh data
S-->>A: Return current data
A->>L: Update cache
A->>U: Update UI with fresh data
```
### Task: Implement Data Refresh System
We'll create a system that automatically fetches fresh data from the server while maintaining the benefits of our persistent state management.
@ -486,6 +696,60 @@ const routes = {
🎉 **Perfect Balance Achieved**: Your app now combines the smooth experience of persistent state with the accuracy of fresh server data!
## 📈 Your State Management Mastery Timeline
```mermaid
timeline
title Professional State Management Journey
section Problem Recognition
State Issues Diagnosis
: Identify session loss problems
: Understand scattered update issues
: Recognize architectural needs
section Architecture Foundation
Centralized State Design
: Create unified state objects
: Implement controlled update patterns
: Establish immutable principles
Predictable Updates
: Master Object.freeze() usage
: Build debug-friendly systems
: Create scalable patterns
section Persistence Mastery
localStorage Integration
: Handle JSON serialization
: Implement automatic synchronization
: Create session continuity
Data Freshness Balance
: Address staleness challenges
: Build refresh mechanisms
: Optimize performance vs accuracy
section Professional Patterns
Production-Ready Systems
: Implement error handling
: Create maintainable architectures
: Follow industry best practices
Advanced Capabilities
: Ready for framework integration
: Prepared for complex state needs
: Foundation for real-time features
```
**🎓 Graduation Milestone**: You've successfully built a complete state management system using the same principles that power Redux, Vuex, and other professional state libraries. These patterns scale from simple apps to enterprise applications.
**🔄 Next Level Capabilities**:
- Ready to master state management frameworks (Redux, Zustand, Pinia)
- Prepared to implement real-time features with WebSockets
- Equipped to build offline-first Progressive Web Apps
- Foundation set for advanced patterns like state machines and observers
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:

@ -6,6 +6,60 @@ Just like how the printing press made books accessible to everyone, not just scr
By the end of this lesson, you'll understand how to navigate VSCode.dev, open GitHub repositories directly in your browser, and use Git for version control all skills that professional developers rely on daily.
## ⚡ What You Can Do in the Next 5 Minutes
**Quick Start Pathway for Busy Developers**
```mermaid
flowchart LR
A[⚡ 5 minutes] --> B[Visit vscode.dev]
B --> C[Connect GitHub account]
C --> D[Open any repository]
D --> E[Start editing immediately]
```
- **Minute 1**: Navigate to [vscode.dev](https://vscode.dev) - no installation needed
- **Minute 2**: Sign in with GitHub to connect your repositories
- **Minute 3**: Try the URL trick: change `github.com` to `vscode.dev/github` in any repo URL
- **Minute 4**: Create a new file and watch syntax highlighting work automatically
- **Minute 5**: Make a change and commit it through the Source Control panel
**Quick Test URL**:
```
# Transform this:
github.com/microsoft/Web-Dev-For-Beginners
# Into this:
vscode.dev/github/microsoft/Web-Dev-For-Beginners
```
**Why This Matters**: In 5 minutes, you'll experience the freedom of coding anywhere with professional tools. This represents the future of development - accessible, powerful, and immediate.
## 🗺️ Your Learning Journey Through Cloud-Based Development
```mermaid
journey
title From Local Setup to Cloud Development Mastery
section Understanding the Platform
Discover web-based editing: 4: You
Connect to GitHub ecosystem: 6: You
Master interface navigation: 7: You
section File Management Skills
Create and organize files: 5: You
Edit with syntax highlighting: 7: You
Navigate project structures: 8: You
section Version Control Mastery
Understand Git integration: 6: You
Practice commit workflows: 8: You
Master collaboration patterns: 9: You
section Professional Customization
Install powerful extensions: 7: You
Configure development environment: 8: You
Build personal workflows: 9: You
```
**Your Journey Destination**: By the end of this lesson, you'll have mastered a professional cloud development environment that works from any device, enabling you to code with the same tools used by developers at major tech companies.
## What You'll Learn
After we walk through this together, you'll be able to:
@ -26,6 +80,59 @@ The requirements are straightforward:
> 💡 **New to GitHub?** Creating an account is free and takes minutes. Like how a library card gives you access to books worldwide, a GitHub account opens doors to code repositories across the internet.
## 🧠 Cloud Development Ecosystem Overview
```mermaid
mindmap
root((VSCode.dev Mastery))
Platform Benefits
Accessibility
Device Independence
No Installation Required
Instant Updates
Universal Access
Integration
GitHub Connection
Repository Sync
Settings Persistence
Collaboration Ready
Development Workflow
File Management
Project Structure
Syntax Highlighting
Multi-tab Editing
Auto-save Features
Version Control
Git Integration
Commit Workflows
Branch Management
Change Tracking
Customization Power
Extensions Ecosystem
Productivity Tools
Language Support
Theme Options
Custom Shortcuts
Environment Setup
Personal Preferences
Workspace Configuration
Tool Integration
Workflow Optimization
Professional Skills
Industry Standards
Version Control
Code Quality
Collaboration
Documentation
Career Readiness
Remote Work
Cloud Development
Team Projects
Open Source
```
**Core Principle**: Cloud-based development environments represent the future of coding - providing professional-grade tools that are accessible, collaborative, and platform-independent.
## Why Web-Based Code Editors Matter
Before the internet, scientists at different universities couldn't easily share research. Then came ARPANET in the 1960s, connecting computers across distances. Web-based code editors follow this same principle making powerful tools accessible regardless of your physical location or device.
@ -81,6 +188,27 @@ Once everything loads up, you'll see a beautifully clean workspace that's design
- Notice how the sidebar updates to show different information pretty neat, right?
- The Explorer view (📁) is probably where you'll spend most of your time, so get comfortable with it
```mermaid
flowchart TB
subgraph "VSCode.dev Interface Architecture"
A[Activity Bar] --> B[Explorer 📁]
A --> C[Search 🔍]
A --> D[Source Control 🌿]
A --> E[Extensions 🧩]
A --> F[Settings ⚙️]
B --> G[File Tree]
C --> H[Find & Replace]
D --> I[Git Status]
E --> J[Extension Marketplace]
F --> K[Configuration]
L[Sidebar] --> M[Context Panel]
N[Editor Area] --> O[Code Files]
P[Terminal/Output] --> Q[Command Line]
end
```
## Opening GitHub Repositories
Before the internet, researchers had to physically travel to libraries to access documents. GitHub repositories work similarly they're collections of code stored remotely. VSCode.dev eliminates the traditional step of downloading repositories to your local machine before editing.
@ -137,6 +265,19 @@ Like how HTTP and HTTPS use different protocols while maintaining the same domai
- **The interface way**: Great when you're exploring or can't remember exact repository names
- **The URL trick**: Perfect for lightning-fast access when you know exactly where you're going
### 🎯 Pedagogical Check-in: Cloud Development Access
**Pause and Reflect**: You've just learned two methods for accessing code repositories through a web browser. This represents a fundamental shift in how development works.
**Quick Self-Assessment**:
- Can you explain why web-based editing eliminates traditional "development environment setup"?
- What advantages does the URL modification technique provide over local git cloning?
- How does this approach change the way you might contribute to open source projects?
**Real-World Connection**: Major companies like GitHub, GitLab, and Replit have built their development platforms around these cloud-first principles. You're learning the same workflows used by professional development teams worldwide.
**Challenge Question**: How might cloud-based development change the way coding is taught in schools? Consider device requirements, software management, and collaborative possibilities.
## Working with Files and Projects
Now that you've got a repository open, let's start building! VSCode.dev gives you everything you need to create, edit, and organize your code files. Think of it as your digital workshop every tool is right where you need it.
@ -206,6 +347,20 @@ flowchart TD
E --> F[Changes pushed to GitHub]
```
```mermaid
stateDiagram-v2
[*] --> Modified: Edit files
Modified --> Staged: Click + to stage
Staged --> Modified: Click - to unstage
Staged --> Committed: Add message & commit
Committed --> [*]: Sync to GitHub
state Committed {
[*] --> LocalCommit
LocalCommit --> RemotePush: Auto-sync
}
```
**Here's your step-by-step process:**
- Click the "+" icon next to files you want to save (this "stages" them)
- Double-check that you're happy with all your staged changes
@ -227,6 +382,43 @@ Just as a craftsperson's workshop contains specialized tools for different tasks
The extension marketplace hosts thousands of free tools created by developers worldwide. Each extension solves particular workflow challenges, allowing you to build a personalized development environment suited to your specific needs and preferences.
```mermaid
mindmap
root((Extension Ecosystem))
Essential Categories
Productivity
Live Server
Auto Rename Tag
Bracket Pair Colorizer
GitLens
Code Quality
Prettier
ESLint
Spell Checker
Error Lens
Language Support
HTML CSS Support
JavaScript ES6
Python Extension
Markdown Preview
Themes & UI
Dark+ Modern
Material Icon Theme
Peacock
Rainbow Brackets
Discovery Methods
Popular Rankings
Download Counts
User Ratings
Recent Updates
Community Reviews
Recommendations
Workspace Suggestions
Language-based
Workflow-specific
Team Standards
```
### Finding Your Perfect Extensions
The extension marketplace is really well organized, so you won't get lost trying to find what you need. It's designed to help you discover both specific tools and cool stuff you didn't even know existed!
@ -318,6 +510,74 @@ As you discover more cool extensions, you'll want to keep your collection tidy a
> ⚠️ **Performance tip**: Extensions are awesome, but having too many can slow things down. Focus on the ones that genuinely make your life easier and don't be afraid to uninstall ones you never use.
### 🎯 Pedagogical Check-in: Development Environment Customization
**Architecture Understanding**: You've learned to customize a professional development environment using community-created extensions. This mirrors how enterprise development teams build standardized toolchains.
**Key Concepts Mastered**:
- **Extension Discovery**: Finding tools that solve specific development challenges
- **Environment Configuration**: Customizing tools to match personal or team preferences
- **Performance Optimization**: Balancing functionality with system performance
- **Community Collaboration**: Leveraging tools created by the global developer community
**Industry Connection**: Extension ecosystems power major development platforms like VS Code, Chrome DevTools, and modern IDEs. Understanding how to evaluate, install, and configure extensions is essential for professional development workflows.
**Reflection Question**: How would you approach setting up a standardized development environment for a team of 10 developers? Consider consistency, performance, and individual preferences.
## 📈 Your Cloud Development Mastery Timeline
```mermaid
timeline
title Professional Cloud Development Journey
section Platform Foundations
Cloud Development Understanding
: Master web-based editing concepts
: Connect GitHub integration patterns
: Navigate professional interfaces
section Workflow Mastery
File & Project Management
: Create organized project structures
: Master syntax highlighting benefits
: Handle multi-file editing workflows
Version Control Integration
: Understand Git visualization
: Practice commit message standards
: Master change tracking workflows
section Environment Customization
Extension Ecosystem
: Discover productivity extensions
: Configure development preferences
: Optimize performance vs functionality
Professional Setup
: Build consistent workflows
: Create reusable configurations
: Establish team standards
section Industry Readiness
Cloud-First Development
: Master remote development practices
: Understand collaborative workflows
: Build platform-independent skills
Professional Practices
: Follow industry standards
: Create maintainable workflows
: Prepare for team environments
```
**🎓 Graduation Milestone**: You've successfully mastered cloud-based development using the same tools and workflows employed by professional developers at major tech companies. These skills represent the future of software development.
**🔄 Next Level Capabilities**:
- Ready to explore advanced cloud development platforms (Codespaces, GitPod)
- Prepared to work in distributed development teams
- Equipped to contribute to open source projects globally
- Foundation set for modern DevOps and continuous integration practices
## GitHub Copilot Agent Challenge 🚀
Like the structured approach NASA uses for space missions, this challenge involves systematic application of VSCode.dev skills in a complete workflow scenario.

@ -12,10 +12,73 @@ We're essentially building a bridge between natural human communication and mach
By the end of this lesson, AI integration will feel less like a mysterious process and more like another API you can work with. You'll understand the foundational patterns that power applications like ChatGPT and Claude, using the same web development principles you've been learning.
## ⚡ What You Can Do in the Next 5 Minutes
**Quick Start Pathway for Busy Developers**
```mermaid
flowchart LR
A[⚡ 5 minutes] --> B[Get GitHub token]
B --> C[Test AI playground]
C --> D[Copy Python code]
D --> E[See AI responses]
```
- **Minute 1**: Visit [GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground) and create a personal access token
- **Minute 2**: Test AI interactions directly in the playground interface
- **Minute 3**: Click "Code" tab and copy the Python snippet
- **Minute 4**: Run the code locally with your token: `GITHUB_TOKEN=your_token python test.py`
- **Minute 5**: Watch your first AI response generate from your own code
**Quick Test Code**:
```python
import os
from openai import OpenAI
client = OpenAI(
base_url="https://models.github.ai/inference",
api_key="your_token_here"
)
response = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello AI!"}],
model="openai/gpt-4o-mini"
)
print(response.choices[0].message.content)
```
**Why This Matters**: In 5 minutes, you'll experience the magic of programmatic AI interaction. This represents the fundamental building block that powers every AI application you use.
Here's what your finished project will look like:
![Chat app interface showing conversation between user and AI assistant](./assets/screenshot.png)
## 🗺️ Your Learning Journey Through AI Application Development
```mermaid
journey
title From Web Development to AI Integration
section Understanding AI Foundations
Discover generative AI concepts: 4: You
Explore GitHub Models platform: 6: You
Master AI parameters and prompts: 8: You
section Backend Integration
Build Python API server: 5: You
Implement AI function calls: 7: You
Handle async operations: 8: You
section Frontend Development
Create modern chat interface: 6: You
Master real-time interactions: 8: You
Build responsive user experience: 9: You
section Professional Application
Deploy complete AI system: 7: You
Optimize performance patterns: 8: You
Create production-ready app: 9: You
```
**Your Journey Destination**: By the end of this lesson, you'll have built a complete AI-powered application using the same technologies and patterns that power modern AI assistants like ChatGPT, Claude, and Google Bard.
## Understanding AI: From Mystery to Mastery
Before diving into the code, let's understand what we're working with. If you've used APIs before, you know the basic pattern: send a request, receive a response.
@ -69,6 +132,59 @@ graph LR
We'll use GitHub Models for our backend integration, which provides access to professional-grade AI capabilities through a developer-friendly interface. The [GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground) serves as a testing environment where you can experiment with different AI models and understand their capabilities before implementing them in code.
## 🧠 AI Application Development Ecosystem
```mermaid
mindmap
root((AI Development))
Understanding AI
Generative Models
Pattern Recognition
Content Generation
Context Understanding
Response Synthesis
AI Parameters
Temperature Control
Token Limits
Top-p Filtering
System Prompts
Backend Architecture
API Integration
GitHub Models
Authentication
Request Handling
Error Management
Python Infrastructure
FastAPI Framework
Async Operations
Environment Security
CORS Configuration
Frontend Experience
Chat Interface
Real-time Updates
Message History
User Feedback
Loading States
Modern Web Tech
ES6 Classes
Async/Await
DOM Manipulation
Event Handling
Professional Patterns
Security Best Practices
Token Management
Input Validation
XSS Prevention
Error Boundaries
Production Readiness
Performance Optimization
Responsive Design
Accessibility
Testing Strategies
```
**Core Principle**: AI application development combines traditional web development skills with AI service integration, creating intelligent applications that feel natural and responsive to users.
![GitHub Models AI Playground interface with model selection and testing area](./assets/playground.png)
**Here's what makes the playground so useful:**
@ -248,6 +364,24 @@ conversational_params = {
}
```
```mermaid
quadrantChart
title AI Parameter Optimization Matrix
x-axis Low Creativity --> High Creativity
y-axis Short Response --> Long Response
quadrant-1 Creative Content
quadrant-2 Detailed Analysis
quadrant-3 Quick Facts
quadrant-4 Conversational AI
Documentation Bot: [0.2, 0.3]
Customer Service: [0.4, 0.4]
General Assistant: [0.7, 0.5]
Creative Writer: [1.1, 0.9]
Brainstorming Tool: [1.3, 0.8]
```
**Understanding why these parameters matter**: Different applications need different types of responses. A customer service bot should be consistent and factual (low temperature), while a creative writing assistant should be imaginative and varied (high temperature). Understanding these parameters gives you control over your AI's personality and response style.
```
@ -447,6 +581,19 @@ Understanding system prompts gives you incredible power to create specialized AI
**The key insight**: You're not just calling an AI API you're creating a custom AI personality that serves your specific use case. This is what makes modern AI applications feel tailored and useful rather than generic.
### 🎯 Pedagogical Check-in: AI Personality Programming
**Pause and Reflect**: You've just learned to program AI personalities through system prompts. This is a fundamental skill in modern AI application development.
**Quick Self-Assessment**:
- Can you explain how system prompts differ from regular user messages?
- What's the difference between temperature and top_p parameters?
- How would you create a system prompt for a specific use case (like a coding tutor)?
**Real-World Connection**: The system prompt techniques you've learned are used in every major AI application - from GitHub Copilot's coding assistance to ChatGPT's conversational interface. You're mastering the same patterns used by AI product teams at major tech companies.
**Challenge Question**: How might you design different AI personalities for different user types (beginner vs expert)? Consider how the same underlying AI model could serve different audiences through prompt engineering.
## Building the Web API with FastAPI: Your High-Performance AI Communication Hub
Now let's build the backend that connects your frontend to AI services. We'll use FastAPI, a modern Python framework that excels at building APIs for AI applications.
@ -524,6 +671,29 @@ sequenceDiagram
FastAPI->>Frontend: {"response": "Hello! How can I help?"}
```
```mermaid
flowchart TD
A[User Input] --> B[Frontend Validation]
B --> C[HTTP POST Request]
C --> D[FastAPI Router]
D --> E[Pydantic Validation]
E --> F[AI Function Call]
F --> G[GitHub Models API]
G --> H[Response Processing]
H --> I[JSON Response]
I --> J[Frontend Update]
subgraph "Security Layer"
K[CORS Middleware]
L[Environment Variables]
M[Error Handling]
end
D --> K
F --> L
H --> M
```
### Creating the FastAPI Application
Let's build our API step by step. Create a file called `api.py` with the following FastAPI code:
@ -1143,6 +1313,30 @@ graph TD
G --> H[Ready for Next Message]
```
```mermaid
classDiagram
class ChatApp {
+messages: HTMLElement
+form: HTMLElement
+input: HTMLElement
+sendButton: HTMLElement
+BASE_URL: string
+API_ENDPOINT: string
+constructor()
+initializeEventListeners()
+handleSubmit(event)
+callAPI(message)
+appendMessage(text, role)
+escapeHtml(text)
+scrollToBottom()
+setLoading(isLoading)
}
ChatApp --> DOM : manipulates
ChatApp --> FastAPI : sends requests
```
### The Three Pillars of Frontend Development
Every frontend application from simple websites to complex apps like Discord or Slack is built on three core technologies. Think of them as the foundation of everything you see and interact with on the web:
@ -1503,6 +1697,20 @@ try {
This architecture is scalable you could easily add features like message editing, file uploads, or multiple conversation threads without rewriting the core structure.
### 🎯 Pedagogical Check-in: Modern Frontend Architecture
**Architecture Understanding**: You've implemented a complete single-page application using modern JavaScript patterns. This represents professional-level frontend development.
**Key Concepts Mastered**:
- **ES6 Class Architecture**: Organized, maintainable code structure
- **Async/Await Patterns**: Modern asynchronous programming
- **Event-Driven Programming**: Responsive user interface design
- **Security Best Practices**: XSS prevention and input validation
**Industry Connection**: The patterns you've learned (class-based architecture, async operations, DOM manipulation) are the foundation of modern frameworks like React, Vue, and Angular. You're building with the same architectural thinking used in production applications.
**Reflection Question**: How would you extend this chat application to handle multiple conversations or user authentication? Consider the architectural changes needed and how the class structure would evolve.
### Styling Your Chat Interface
Now let's create a modern, visually appealing chat interface with CSS. Good styling makes your application feel professional and improves the overall user experience. We'll use modern CSS features like Flexbox, CSS Grid, and custom properties for a responsive, accessible design.
@ -1852,6 +2060,65 @@ graph TD
- **Reviews** backend terminal output for Python errors or API issues
- **Confirms** environment variables are properly loaded and accessible
## 📈 Your AI Application Development Mastery Timeline
```mermaid
timeline
title Complete AI Application Development Journey
section AI Foundations
Understanding Generative AI
: Grasp pattern recognition concepts
: Master AI parameter control
: Learn prompt engineering techniques
GitHub Models Integration
: Navigate AI service platforms
: Handle authentication securely
: Optimize model parameters
section Backend Development
Python API Architecture
: Build FastAPI applications
: Implement async operations
: Create secure endpoints
AI Service Integration
: Connect to external AI APIs
: Handle rate limiting
: Implement error boundaries
section Frontend Mastery
Modern JavaScript Patterns
: Master ES6 class architecture
: Implement async/await flows
: Build responsive interfaces
Real-time User Experience
: Create dynamic chat interfaces
: Handle loading states
: Optimize user interactions
section Production Readiness
Security & Performance
: Implement secure token management
: Prevent XSS vulnerabilities
: Optimize API performance
Professional Deployment
: Build scalable architectures
: Create maintainable code
: Document development processes
```
**🎓 Graduation Milestone**: You've successfully built a complete AI-powered application using the same technologies and architectural patterns that power modern AI assistants. These skills represent the intersection of traditional web development and cutting-edge AI integration.
**🔄 Next Level Capabilities**:
- Ready to explore advanced AI frameworks (LangChain, LangGraph)
- Prepared to build multi-modal AI applications (text, image, voice)
- Equipped to implement vector databases and retrieval systems
- Foundation set for machine learning and AI model fine-tuning
## GitHub Copilot Agent Challenge 🚀
Use the Agent mode to complete the following challenge:

Loading…
Cancel
Save