Controlling the snake

The player will be able to control the snake with arrow keys.

The idea: As the player presses one of the arrow keys, snake's head must move in the appropriate direction.

The development: First, we need to import the class to manage keyboard events:

import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;

Then, in Main function, we need to place the listener:

public function Main() {
addChild(bg);
placeSnake();
addEventListener(Event.ENTER_FRAME,onEnterFr);
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyD);
}

Now each time the player presses a key, onKeyD function is called.

We decided snakeDirection's possible values are 0, 1, 2, and 3 respectively for left, up, right, and down directions, ...

Get Flash Game Development by Example now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.