Move Snake Using Keyboard Input

Learn how to move the snake on the canvas using the keyboard input and event listeners.

Introduction

To recap, in the previous lesson, we could move the snake in the right-hand direction horizontally. Now we will move to the next step and make the game more realistic by adding the functionality to move the snake based on the keyboard input.

Implement: Move the snake with keyboard arrows

To move the snake based on the input provided from the keyboard, we need to follow the steps mentioned below:

  1. Add an event listener to the document object. The event will listen to the keydown event. This event will trigger a callback function each time a key is pressed.

  2. Handle the snake's direction based on the keyboard input.

First let's write a function to handle the keydown event.

Get hands-on with 1200+ tech skills courses.