Week 10: HTML5 Games: Classes
HTML5 Games
Explore the W3Schools HTML5 Games Demo to see how JavaScript can build a game using the Canvas element.
Here is the example refactored for ES6: Dodging Obstacles Game
Understand how objects are generated and then animated with speed and gravity properties. Experiment with values.
Previous Student Canvas Games:
- Escape the Room
- Welcome to Greenhedge
- Game: Inventory
- Knight Runner
- Undead Outpost
- Cowardly Blocks
- Welcome to Kiwi's Garden!
- Dueling Tanks
- Star Adventures
- Color Mixing Game
HTML5 Game Elements:
HTML5 Game Resources:
Game Assets for Knight Runner:
- UI Elements: OwlishMedia
- Background Layers: Edermuniz
- Player/Enemy Sprites:
JS Files for Knight Runner:
In-Class Demos:
Review the HTML5 Game in ES6.
Explore this game with falling balls using keyboard functionality. Experiment with values—what can you change?
Arrow Functions (=>)
An arrow function is just a shorter way to write a function in JavaScript.
Look for the arrow: =>
// Arrow function
objects.forEach(obj => {
obj.update();
});
This does the same thing as:
// Regular function
objects.forEach(function(obj) {
obj.update();
});
If you see =>, it means “this is a function.”
Adding Images and Sound Effects
To add images, first load the image in the Image() object, then draw it with drawImage().
const playerImg = new Image(); playerImg.src = 'player.png'; ctx.drawImage(playerImg, this.x, this.y, this.width, this.height);
To add sound effects, load the audio file in the Audio() object and then use play() when needed.
const shootSound = new Audio('shoot.wav');
shootSound.currentTime = 0; // rewind to start
shootSound.play();
JavaScript Concepts Used in the Canvas Game
- Object Literals — Define single objects with properties and methods (e.g.,
gameArea = { ... }). W3Schools: Objects - Classes — Blueprints for creating objects with shared behavior (
class Player,class Obstacle). W3Schools: Classes - Constructors — Special methods inside classes to initialize object properties. W3Schools: Constructors
- Methods — Functions defined inside objects or classes that describe object actions. W3Schools: Object Methods
thisKeyword — Refers to the current object context. W3Schools: this Keyword- Functions — Reusable blocks of code that perform tasks (
startGame(),updateGame()). W3Schools: Functions - Function Expressions — Assign functions as values, e.g., callbacks in event listeners. W3Schools: Function Definitions
- Arrays — Used to store multiple values in one variable (
obstacles[]). W3Schools: Arrays forEach()Method — Executes a function for each array element. W3Schools: forEach()- Conditionals — Run code only if certain conditions are true (
if/else). W3Schools: If...Else - Comparison Operators — Compare values (
==,===,>,<). W3Schools: Comparisons - Logical Operators — Combine or negate conditions (
&&,||,!). W3Schools: Logical Operators - Arithmetic Operators — Perform math operations (
+,-,*,/,%). W3Schools: Arithmetic - Math Object — Provides random numbers and rounding (
Math.random(),Math.floor()). W3Schools: Math - DOM Access — Selecting elements with
document.getElementById(). W3Schools: getElementById - Events and Listeners — Responding to user actions with
addEventListener(). W3Schools: addEventListener - Timers — Repeating or stopping functions with
setInterval()andclearInterval(). setInterval(), clearInterval() - Canvas Context — Used to draw on the canvas (
getContext('2d')). W3Schools: HTML5 Canvas - Canvas Drawing Methods —
fillRect(),clearRect(),fillText()for shapes and text. fillRect, clearRect, fillText
Popular Games Refactored to HTML5/ES6 with Classes
Pong Logic Steps:
Set up the canvas: Get access to the canvas element and its drawing context so we can draw shapes like paddles and the ball.
Create Paddle class: Each paddle has a position (x, y), size (width, height), and speed. It responds to player input (W/S, arrow keys) and draws itself on the screen each frame.
Create Ball class: The ball has a position, size, and speed in both X and Y directions. It moves, bounces, detects paddle collisions, and resets after a score.
Track game state: Keep score, listen for key presses, and use booleans to store which keys are held down.
Game loop (updateGame): Clear the canvas, update positions, check for collisions, draw everything, and use requestAnimationFrame() for smooth animation.
Asteroids Logic Steps:
Set up the canvas: Same as Pong – get the drawing surface ready.
Create Ship class: The ship has position, direction, and thrust, moves with physics, rotates, shoots, and wraps around the screen.
Create Bullet class: Each bullet starts at the ship’s position, moves in its direction, and disappears after a while.
Create Asteroid class: Asteroids have random positions and velocities, move and wrap around, and detect bullet hits.
Create Game class: Manages ship, asteroids, and input; runs the update/draw loop.
Game Assets + AI Tools for HTML5 Game Development
-
Sprites, Backgrounds, Tiles
- Ludo: AI Sprite and Spritesheet Generator
- OpenGameArt – huge library of free sprites, textures, music, and sound effects (Creative Commons)
- itch.io Game Assets – thousands of free pixel art packs, characters, and UI kits
- CraftPix – free game kits, sprites, backgrounds, GUI elements :contentReference[oaicite:0]{index=0}
- GameArt2D – high-quality sprite sheets, tilesets, and backgrounds
-
Sound Effects & Music
- Freesound – massive library of user-uploaded sound effects (Creative Commons) :contentReference[oaicite:1]{index=1}
- itch.io Audio Packs – free SFX and music for games
- GameMaker Asset Bundles – free packs with music, SFX, and sprites
-
AI Image / Sprite Generators
- DALL·E / ChatGPT Image – generate characters, objects, and backgrounds
- Midjourney – stylized game art and concept visuals
- Leonardo AI – game-focused asset and sprite generation
-
AI Sound + Voice Tools
- ElevenLabs – AI voice generation for characters
- Suno – generate music tracks and loops for games
- PlayHT – text-to-speech for narration or dialogue
-
Helpful Platforms
- Phaser.js – popular JavaScript framework for HTML5 games :contentReference[oaicite:2]{index=2}
- GDevelop – free game engine with built-in asset store :contentReference[oaicite:3]{index=3}
Collaborative HTML5 Canvas Game: 25%
DUE: April 30
In teams of 3-4, create an interactive HTML5 Canvas game that demonstrates your combined skills in design, programming, and creative collaboration. This project is an opportunity to experience a small web development workflow using GitHub for version control and to practice communicating logic, problem-solving, and design ideas as a group.
Each team will work with the Custom GPT created for this class to help plan, refine, and debug their game. Use it to translate your ideas and logic into human-readable steps before writing code. Each student will submit their AI chat transcript as part of the documentation of their contribution and learning process.
Your Steps:
- Team Brainstorm: Develop a shared game concept and visual style. Decide on your core mechanic, objective, and general mood or theme.
- Design and Roles: Identify areas of strength among your team—coding, sound design, animation, art direction, or logic planning—and distribute tasks so that everyone contributes meaningfully.
- Logic Steps: Use the Custom GPT to describe your game’s setup, gameplay loop, and scoring in plain language before coding. Save these chats as documentation.
- Collaborative Coding: Build your game using ES6 JavaScript, committing regularly to GitHub. Use branches and merges to manage contributions.
- Testing and Debugging: Playtest your game as a team and refine responsiveness, balance, and performance.
- Visual and Audio Design: Style the interface with CSS, and integrate sound effects, sprites, or other media to enhance the experience. You may generate assets or ideas with AI tools.
- Integration Statement: In your JavaScript file, include a brief commented section summarizing your game logic, team process, and how you used AI and GitHub.
- Final Submission: Upload your game as
index.htmlin a folder namedgameand ensure all assets and scripts function properly online.
Suggested Game Ideas:
- Platformer with Dynamic Environments: Procedurally generate levels or enemies for replayability.
- Adventure Game with Expressive Characters: Use sprite animation and dialogue for storytelling.
- Physics-Based Puzzle or Destruction Game: Experiment with motion, collisions, and gravity.
- Dodging or Collection Game: Navigate a chaotic field of moving objects to survive or collect items.
- Escape or Maze Game: Design a spatial challenge requiring exploration and problem-solving.
- Educational Game: Make learning interactive through gameplay mechanics.
Grading Criteria:
- Collaboration and Process: Evidence of teamwork, GitHub participation, and AI-assisted planning.
- JavaScript Logic and Implementation: Effective and clear application of ES6 syntax and structure.
- Creative Design and Usability: Quality of interaction, visuals, sound, and overall play experience.
- Documentation and Reflection: Clarity and completeness of your logic statement and AI chat records.
Project Requirements:
- Title screen with game name and team member credits
- Well-commented, functional ES6 code
- Integration statement and AI chat documentation
- GitHub repository link included in submission
- Final build uploaded as
index.htmlin folder namedgame
In-Class Activities:
Canvas Interaction and Animation
Explore this game with falling balls using keyboard functionality. Experiment with values—what can you change? Use HTML5 Game Mentor to develop ideas using this file as a template.
HTML5 Game Groups
Group 1
- Von
- Tiffany
- Jamie
Group 2
- Vincent
- Sonia
- Nakai
Group 3
- Marilyn
- Dalila
- Sophia
Group 4
- Isabelle
- Crystal
- Riley
Group 5
- Gabriel
- Tevin
- Jackson
Settle into groups and discuss ideas. Quickly try out prototypes using HTML5 Game Mentor. At this stage, you are exploring, testing, and researching possibilities. By the end of next week, you should have the basic logic and structure of your game clearly worked out.
AI is not a shortcut to a finished game. If you use it that way, you will skip the most important part of this project: learning how games actually work.
Instead, use AI as a thinking partner:
- to test ideas quickly and see variations
- to help you break down game logic into steps
- to explore different interaction and design possibilities
- to debug and understand code you are already working on
You should always be able to explain: What is happening in your game, why it works, and how the code supports your design. If you can’t explain it, you’re moving too fast.
The goal of this project is not just to make a game—it’s to learn how to think like a designer and developer: working through ideas, iterating, collaborating, and building something meaningful step by step.