Collision Detection

In this lesson, you will learn how to check for collisions to keep the Tetris pieces inside the game’s boundaries.

We'll cover the following

Tetris would not be a particularly exciting game if all the blocks could pass through each other, or if the walls and floor did not stop them. So, instead of randomly moving the tetromino, we’ll check for potential collisions first, and we only move the tetromino if it’s safe. We have a few different collisions to consider.

We have a collision when the tetromino:

  • Hits the floor
  • Moves left or right into a wall
  • Hits a block on the board
  • Rotates and the new rotation hits a wall or block

There are no helper functions in Canvas for detecting collisions between elements, so we need to implement this feature ourselves.


For the squares of the tetromino to be inside the board, all three of the following statements need to be true:

  • The x position of the square is greater than the x position of the left wall.
  • The x position of the square is less than the x position of the right wall.
  • The y position of the square is greater than the y position of the floor.

We can translate this to code and add it to the method in the board class with which we check that we are inside the boundaries of the board:

Get hands-on with 1200+ tech skills courses.