Back to work

Tetris JS

A Tetris implementation in plain JavaScript with canvas, sound, and touch controls.

Date
Mar 2024
Category
Games
Status
Live

Stack

  • HTML5
  • CSS3
  • JavaScript

Problem

The goal was to build Tetris entirely in JavaScript, without external libraries, and make the game playable on touch screens as well.

Role

I started from MiduDev's code and worked on the game loop, audio management, and touch controls described in the source note.

Decisions

  1. A requestAnimationFrame loop.

    The game draws to a canvas inside a loop synchronized with the screen refresh rate and separates the start screen, gameplay, and game over with a state machine.

  2. Audio with the Web Audio API.

    Sound effects and music load as audio objects, are cloned for playback, and are kept in a registry that can stop them and reset their position.

  3. Touch gestures.

    touchstart, touchmove, and touchend events calculate the displacement to move the piece, and a tap without movement rotates it.

Result

The game includes start, play, and game over screens, sound effects and music, and touch controls in addition to the keyboard.