Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 74 ยท Projects

Project: Snake Game on a Canvas

Build a Snake game in Angular with a pure game-logic function, a canvas renderer, keyboard input and a game loop that runs outside Angular's change detection, with runnable stand-ins.

Snake is a good project for learning how Angular fits around code that is not Angular at all. A <canvas> is drawn with imperative commands, a game loop fires many times per second, and keyboard input arrives constantly. If you let Angular check the whole app on every tick, you waste work. So the interesting questions are: where does the game logic live, how do you reach the canvas safely, and how do you keep the loop out of change detection?

You will want Signals: signal, computed and effect, View Queries and Host Bindings and Change Detection first.

Real versus stand-in. The typescript blocks are the real Angular component, to read and copy into a project made with ng new; the site cannot compile Angular. The runnable examples are stand-ins: one runs the pure game logic in TypeScript, and one is a playable canvas game in plain JavaScript that follows the same structure. Click the canvas, then use the arrow keys.

Step 1: the plan

Separate three things:

  1. Game logic: a pure function step(state, direction) that returns the next state. No canvas, no timers, no Angular. Easy to test.
  2. Rendering: a function that draws a state onto a canvas.
  3. The component: owns the canvas, the timer and the keyboard, and shows the score with a signal.
flowchart LR
  K["Keyboard<br/>(host listener)"] --> D["direction"]
  T["Timer, outside Angular<br/>every 120 ms"] --> S["step(state, direction)"]
  D --> S
  S --> R["draw(ctx, state)"]
  S -->|"score changed"| Sig["score signal<br/>(inside Angular)"]

Most ticks never enter Angular; only a changed score does.

Step 2: the pure game logic

The board is a grid. The snake is an array of cells with the head first. Food placement takes a random function as a parameter, so tests can give it a fixed one.

TypeScript
// snake-logic.ts
export interface Cell { x: number; y: number }
export type Direction = 'up' | 'down' | 'left' | 'right';

export interface GameState {
  size: number;
  snake: Cell[]; // head first
  food: Cell;
  score: number;
  alive: boolean;
}

const MOVES: Record<Direction, Cell> = {
  up: { x: 0, y: -1 },
  down: { x: 0, y: 1 },
  left: { x: -1, y: 0 },
  right: { x: 1, y: 0 },
};

export function opposite(a: Direction, b: Direction): boolean {
  return MOVES[a].x + MOVES[b].x === 0 && MOVES[a].y + MOVES[b].y === 0;
}

export function placeFood(size: number, snake: Cell[], random: () => number): Cell {
  const free: Cell[] = [];
  for (let y = 0; y < size; y++) {
    for (let x = 0; x < size; x++) {
      if (!snake.some(c => c.x === x && c.y === y)) free.push({ x, y });
    }
  }
  return free[Math.floor(random() * free.length)];
}

export function step(state: GameState, dir: Direction, random: () => number): GameState {
  if (!state.alive) return state;
  const head = state.snake[0];
  const next = { x: head.x + MOVES[dir].x, y: head.y + MOVES[dir].y };

  const hitsWall = next.x < 0 || next.y < 0 || next.x >= state.size || next.y >= state.size;
  const eats = next.x === state.food.x && next.y === state.food.y;
  // the tail moves away this tick, unless we grow
  const body = eats ? state.snake : state.snake.slice(0, -1);
  const hitsSelf = body.some(c => c.x === next.x && c.y === next.y);
  if (hitsWall || hitsSelf) return { ...state, alive: false };

  const snake = [next, ...body];
  return {
    ...state,
    snake,
    score: state.score + (eats ? 1 : 0),
    food: eats ? placeFood(state.size, snake, random) : state.food,
  };
}

Two details deserve attention. The tail is dropped before the self-collision check, because the cell it leaves is free again on the same tick. And placeFood picks only from free cells, so food can never appear on the snake.

Step 3: the component

The component needs the canvas element, a timer that does not trigger change detection, and keyboard events. The canvas is only available after rendering, so the loop starts in afterNextRender (Component Lifecycle). NgZone.runOutsideAngular runs the timer without Angular noticing each tick; the score signal is set only when the score changes.

TypeScript
// snake-game.ts
import {
  afterNextRender, Component, DestroyRef, ElementRef, inject, NgZone, signal, viewChild,
} from '@angular/core';
import { Direction, GameState, opposite, placeFood, step } from './snake-logic';

const SIZE = 16;
const CELL = 20;

@Component({
  selector: 'app-snake-game',
  host: { '(window:keydown)': 'onKey($event)' },
  template: `
    <p>Score: {{ score() }} @if (!alive()) { <b>Game over</b> }</p>
    <canvas #board width="320" height="320" aria-label="Snake board" role="img"></canvas>
    <button type="button" (click)="restart()">New game</button>
  `,
})
export class SnakeGame {
  private readonly canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('board');
  private readonly zone = inject(NgZone);
  private readonly destroyRef = inject(DestroyRef);

  protected readonly score = signal(0);
  protected readonly alive = signal(true);

  private state: GameState = this.freshState();
  private direction: Direction = 'right';
  private queued: Direction = 'right';

  constructor() {
    afterNextRender(() => {
      this.zone.runOutsideAngular(() => {
        const timer = setInterval(() => this.tick(), 120);
        this.destroyRef.onDestroy(() => clearInterval(timer));
      });
    });
  }

  protected onKey(event: KeyboardEvent): void {
    const map: Record<string, Direction> = {
      ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right',
    };
    const wanted = map[event.key];
    if (!wanted) return;
    event.preventDefault();
    if (!opposite(wanted, this.direction)) this.queued = wanted;
  }

  protected restart(): void {
    this.state = this.freshState();
    this.direction = this.queued = 'right';
    this.score.set(0);
    this.alive.set(true);
  }

  private tick(): void {
    this.direction = this.queued;
    const before = this.state;
    this.state = step(this.state, this.direction, Math.random);
    this.draw();
    if (this.state.score !== before.score) this.zone.run(() => this.score.set(this.state.score));
    if (before.alive && !this.state.alive) this.zone.run(() => this.alive.set(false));
  }

  private draw(): void {
    const ctx = this.canvas().nativeElement.getContext('2d')!;
    ctx.clearRect(0, 0, SIZE * CELL, SIZE * CELL);
    ctx.fillStyle = '#dc2626';
    ctx.fillRect(this.state.food.x * CELL, this.state.food.y * CELL, CELL, CELL);
    ctx.fillStyle = '#16a34a';
    for (const c of this.state.snake) ctx.fillRect(c.x * CELL + 1, c.y * CELL + 1, CELL - 2, CELL - 2);
  }

  private freshState(): GameState {
    const snake = [{ x: 4, y: 8 }, { x: 3, y: 8 }, { x: 2, y: 8 }];
    return { size: SIZE, snake, food: placeFood(SIZE, snake, Math.random), score: 0, alive: true };
  }
}

Why the queued direction? Two key presses within one tick could otherwise turn the snake back into itself: press Up then Left quickly while heading right, and the second press would be checked against the old direction. Queueing one direction per tick, and comparing it with the direction used by the last tick, avoids that.

The score and alive state are signals because the template shows them. The board is not: it is drawn by hand, so Angular has nothing to track there. Running the loop outside the zone matters most in zone-based apps; in a zoneless app (Change Detection) setting a signal is what schedules an update, and the loop does not trigger anything on its own. zone.run is harmless there, and keeps the code correct in both setups.

In the real template, set the width and height attributes of the canvas to the same size as the drawing area (here 320 by 320). CSS sizing would stretch the pixels instead.

Step 4: run the game logic

The first stand-in plays the pure logic with a fixed random function, so every run prints the same result.

TypeScript Snake logic: moving, eating, crashing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Because step is pure, you can test every rule (growth, wall, self-collision, no steps after death) with plain assertions and no canvas.

Step 5: play it

This stand-in is the full game in plain JavaScript: the same step rules, a canvas renderer and a setInterval loop. Click the board to focus the page, then use the arrow keys.

A playable snake on a canvas

Ideas to extend it

  • Speed up the game every five points by restarting the timer.
  • Keep a high score in a signal and, in a real app, in localStorage (Todo project shows safe persistence).
  • Add touch controls with swipe detection.
  • Pause when the tab is hidden with the visibilitychange event.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the game rule logic written as a pure step(state, direction) function?

    A pure function takes a state and returns the next one. You can check every rule with plain assertions.
  2. 2. What does runOutsideAngular achieve for the game loop?

    Zone.js normally triggers a change detection check after each timer callback. Running the loop outside the zone avoids dozens of needless checks per second.
  3. 3. Why is the canvas used only after afterNextRender?

    The view query has no element until the component is rendered, and afterNextRender runs only in the browser.
  4. 4. Why is the snake's tail removed before the self-collision check?

    Moving into the cell the tail is leaving is legal. Only when the snake eats does the tail stay.

Summary

  • Keep game rules in a pure function that returns the next state, and pass randomness in as a parameter.
  • Reach the canvas with viewChild.required and start drawing in afterNextRender.
  • Run the high-frequency loop with NgZone.runOutsideAngular and enter Angular only when a displayed value changes.
  • Handle keyboard input with a host listener and queue one direction per tick.
  • Signals hold what the template shows (score, alive); the canvas is drawn imperatively.

Next: Project: Event Calendar.