One lesson per page. Numbers jump, Back and Next step through. Playable boxes need a real browser, not the phone gallery preview.
1 · A game is a loop with rules
A film plays the same frames for everyone. A game asks the player to change what happens next. That needs three things, and only three, before art or menus: something stored in memory, a way to change it, and a way to show it.
state is the memory. Where the hero is, how many coins are left, whether the slime has been touched. input is the change coming from outside. render is the picture of that memory this frame. The game loop repeats: read input, update state, draw.
menu, play, win, lose). If a feature does not change one of those, it is not in the game yet.Design choice, before code: the campfire is the goal, coins are the reason to explore, the slime is the cost of rushing. One verb (move), one risk, one reward. That is enough for a first level.
2 · Draw the cast once
An entity is a thing in the world with data. A sprite is how that thing looks. They are not the same object. The slime can be a green oval today and a painted character tomorrow without changing patrol code.
These symbols live in the page. A game can stamp them with . Feet sit on the bottom of the box, so "standing on the ground" means the ground line and the sprite bottom are the same y.
#3d7dff to another color. Reload. The cast picture and any of that hero follow. The patrol code does not.3 · Coordinates
The page origin is the top-left. X grows right. Y grows down, which is the opposite of a math graph. A hitbox is the rectangle the game uses for touch, often smaller than the drawing so hair and a staff do not count as a hit.
Move the pointer over the board. The numbers are canvas pixels, not CSS pixels.
ctx.fillRect(x, y, w, h); // x,y is the top-left of the box
// feet of a 48px-tall hero standing on groundY:
const top = groundY - 48;
4 · The loop, and delta time
Browsers do not give you a steady clock. requestAnimationFrame calls you when it is ready to paint. A frame is one of those calls. delta time is how many seconds passed since the last call. Move by speed * dt, not by a fixed pixel step, or a fast monitor runs the game faster.
let last = 0;
function frame(now) {
const dt = Math.min(0.033, (now - last) / 1000);
last = now;
coin.x += coin.vx * dt;
draw();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
The cap of 0.033 seconds (about 30 fps worth of time) stops a tab that slept in the background from teleporting the hero across the level on the next frame.
5 · Input is state, not a surprise
Key events fire once. Walking needs "is the key down right now?" Store that in an object. The loop reads the object. Do not move the hero inside the key listener, or a held key and the frame rate fight each other.
const keys = { left:false, right:false, jump:false };
addEventListener('keydown', e => { if (e.key === 'ArrowLeft') keys.left = true; });
addEventListener('keyup', e => { if (e.key === 'ArrowLeft') keys.left = false; });
6 · Position, velocity, gravity
velocity is change in position per second. Gravity is a constant added to vertical velocity. Jumping is not "move up for a while." It is one upward velocity, then gravity. onGround is the permission to jump again. Without it, the player flies.
Click the board to jump the box. It only leaves the ground if it is already on it.
vy += 1400 * dt; // gravity, pixels per second squared
x += vx * dt;
y += vy * dt;
if (y > ground) { y = ground; vy = 0; onGround = true; }
if (jumpPressed && onGround) { vy = -520; onGround = false; }
7 · Collision
Two rectangles overlap when each edge of one has crossed the matching edge of the other. That test is called AABB (axis-aligned bounding box): no rotation, so the edges stay parallel to the screen. Good enough for coins, slimes, and pits.
Drag the gold box. It turns red on overlap.
function hit(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x &&
a.y < b.y + b.h && a.y + a.h > b.y;
}
8 · Rules live in a mode
A state machine is a single word for what the game is doing, plus the transitions it allows. Menu does not simulate the slime. Play does. Win and lose ignore movement until restart. One word beats five booleans that can all be true at once.
Menu
Waiting. The world is not ticking.
if (mode === 'play') { updateWorld(dt); }
if (mode === 'play' && coinsLeft === 0 && hit(player, goal)) mode = 'win';
if (mode === 'play' && hearts <= 0) mode = 'lose';
Trail Camp's win rule: every coin collected, then touch the campfire. Touching the fire early does nothing. That teaches the player the goal without a paragraph of text.
9 · Feedback
The HUD is the numbers the player must see without guessing: hearts, coins, the level name. juice is motion that confirms an event. A coin bobbing is readable. A screen shake on every step is noise. Use juice when the state changes.
coins 2 / 3 hearts ❤❤❤
const bob = Math.sin(time * 4) * 4;
drawCoin(ctx, coin.x, coin.y + bob);
if (justCollected) hudCoins += 1;
10 · Level 1, playable
Same pieces, one world. Arrow keys or A and D to walk. W or space to jump. On a phone, use the buttons. Collect every coin, avoid the slime, stand in the campfire.
Press Play level 1. The world does not tick in the menu.
What the level data is
A level is a list, not a special case in the loop. The loop does not know "level 1." It knows coins, slimes, pits, and a goal x.
const level1 = {
name: 'Day trail',
length: 1800,
spawn: 80,
coins: [420, 760, 1180],
slimes: [{ x: 860, left: 700, right: 1040 }],
pits: [],
goal: 1580
};
11 · Level 2 is data, not a new game
The ridge adds two pits and a second slime. Jump is now required. The coin just past the first pit is the teaching beat: the safe path is slower, the greedy path is the hole. No new code, only a second object in the level list.
const level2 = {
name: 'Ridge',
length: 2500,
spawn: 80,
coins: [360, 980, 1500, 1900, 2300],
slimes: [
{ x: 640, left: 500, right: 820 },
{ x: 1680, left: 1500, right: 1960 }
],
pits: [{ x: 900, w: 130 }, { x: 1760, w: 150 }],
goal: 2360
};
12 · Exercises
All of these are edits in the script at the bottom of this file. Reload after each one.
- Speed. Change
PLAYER.speedfrom 220 to 320. Level 1 should feel rushed. Put it back if the slime becomes unfair. - A new coin. Add
640tolevel1.coins. Win should now require four coins. That proves the win rule reads the list. - Meaner slime. In
updateSlime, change70to140. Notice level 2's second patrol becomes the real threat. - Alternate win. In the win check, delete the
coinsLeft === 0test. The campfire alone ends the level. Decide which rule you prefer, and why. - Third level. Copy
level2, name itNight cut, add a third pit, and point the level 2 button at it. If you did not touch the loop, the data lesson landed.
startLevel(0) and startLevel(1). A third level is levels.push({...}) and a button that calls startLevel(2).13 · Glossary
| Word | Meaning here |
|---|---|
| state | Everything the game remembers. If it is not in state, the next frame cannot know it. |
| game loop | Read input, update state, draw, repeat. |
| frame | One pass of that loop, usually tied to the screen refresh. |
| tick | One update step. Sometimes several ticks run per frame. This course uses one tick per frame. |
| delta time | Seconds since the last frame. Multiply speeds by it. |
| entity | A thing with data: player, coin, slime, goal. |
| sprite | The drawing for an entity. Swap the drawing, keep the data. |
| hitbox | The rectangle used for touch. Often tighter than the art. |
| AABB | Overlap test for upright rectangles. |
| velocity | Position change per second. Separate from position. |
| gravity | A constant added to vertical velocity each second. |
| onGround | Permission to jump. Set when the feet meet ground that is not a pit. |
| input state | Booleans for held keys or buttons. The loop reads them. |
| camera | The offset that keeps the hero on screen while the level is wider than the canvas. |
| scene / level | A data object: length, coins, slimes, pits, goal. |
| state machine | One mode word and the transitions between modes. |
| HUD | Hearts, coins, level name. Information, not decoration. |
| juice | Small motion that confirms a change. Bob, flicker, a flash on hit. |
| spawn | Where an entity starts. The hero spawn is a number in the level. |
| seed | A starting number for random-looking but repeatable layout. This course uses fixed lists instead. |
| parallax | Far hills moving slower than the ground. The playfield hills move at half the camera. |
| win condition | All coins taken and the hero overlapping the campfire. |
| lose condition | Hearts at zero, or a fall through a pit. |
14 · Where to go next
Stay in vanilla canvas until the loop feels boring. A library is a compression of this file, not a replacement for it.