Trail Camp

A short course in how a game is put together. One side-view collector, built in the open: walk, jump, pick up coins, dodge the slime, reach the campfire. Then a second level that uses the same rules. No engine, no asset pack.

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.

read input update state draw repeat
Trail Camp's state is small on purpose: player position, coin list, slime list, hearts, and a mode word (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.

Try this. In the symbol sheet at the bottom of this file, change the hero shirt from #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; });
Try this. Hold a button and watch the flag stay true until release. That flag is what the motion lesson multiplies by speed.

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;
}
A pit is a hole in the ground, not a wall. If the hero's feet are over the pit span, skip the ground collision and let gravity finish the job.

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
};
If level 2 needed a new rule, the first level was not finished. Difficulty here comes from layout: wider gaps, a slime whose patrol covers a coin, a longer walk back after a hit.

12 · Exercises

All of these are edits in the script at the bottom of this file. Reload after each one.

  1. Speed. Change PLAYER.speed from 220 to 320. Level 1 should feel rushed. Put it back if the slime becomes unfair.
  2. A new coin. Add 640 to level1.coins. Win should now require four coins. That proves the win rule reads the list.
  3. Meaner slime. In updateSlime, change 70 to 140. Notice level 2's second patrol becomes the real threat.
  4. Alternate win. In the win check, delete the coinsLeft === 0 test. The campfire alone ends the level. Decide which rule you prefer, and why.
  5. Third level. Copy level2, name it Night cut, add a third pit, and point the level 2 button at it. If you did not touch the loop, the data lesson landed.
Hint for 5. The start buttons call startLevel(0) and startLevel(1). A third level is levels.push({...}) and a button that calls startLevel(2).

13 · Glossary

WordMeaning here
stateEverything the game remembers. If it is not in state, the next frame cannot know it.
game loopRead input, update state, draw, repeat.
frameOne pass of that loop, usually tied to the screen refresh.
tickOne update step. Sometimes several ticks run per frame. This course uses one tick per frame.
delta timeSeconds since the last frame. Multiply speeds by it.
entityA thing with data: player, coin, slime, goal.
spriteThe drawing for an entity. Swap the drawing, keep the data.
hitboxThe rectangle used for touch. Often tighter than the art.
AABBOverlap test for upright rectangles.
velocityPosition change per second. Separate from position.
gravityA constant added to vertical velocity each second.
onGroundPermission to jump. Set when the feet meet ground that is not a pit.
input stateBooleans for held keys or buttons. The loop reads them.
cameraThe offset that keeps the hero on screen while the level is wider than the canvas.
scene / levelA data object: length, coins, slimes, pits, goal.
state machineOne mode word and the transitions between modes.
HUDHearts, coins, level name. Information, not decoration.
juiceSmall motion that confirms a change. Bob, flicker, a flash on hit.
spawnWhere an entity starts. The hero spawn is a number in the level.
seedA starting number for random-looking but repeatable layout. This course uses fixed lists instead.
parallaxFar hills moving slower than the ground. The playfield hills move at half the camera.
win conditionAll coins taken and the hero overlapping the campfire.
lose conditionHearts 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.