Move Snake Using Keyboard Input
Learn how to move the snake on the canvas using the keyboard input and event listeners.
We'll cover the following
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:
Add an event listener to the
document
object. The event will listen to thekeydown
event. This event will trigger a callback function each time a key is pressed.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 1400+ tech skills courses.