Friday, March 2, 2012

Build a Classic Snake Game in AS3

In this tutorial I would like to show you how easy it is to create a classic “Snake” game in Flash. I will try to explain everything easily, step by step, so that you can develop the game further to your needs! The Game will be developed in AS3 and I will use the FlashDevelop IDE.


Introduction

The game won’t be complex. Whenever we hit a wall, it will restart the game. After eating an apple the snake will grow, and a ‘new’ Apple will appear. (Actually, it will be the same apple, but I’ll explain this later.)

One of the most important aspects of the game is the code’s reaction to KEY_DOWN events. The snake will only then change its direction after a tick has passed, not immediately after a keypress. This means that, if the snake is going right, and you press down and left very fast, the snake will go down, not down AND left. Without this ‘feature’ the snake would allow us to go left while we are going right, which would mean it hit itself.


Let’s Look at the Game Already!

Let’s take a look at the final result we will be working towards:


Step 1: Creating the Project

In FlashDevelop, create a new Project, and inside the ‘src’ folder create a ‘com’ folder. In the ‘com’ folder create a new class, and call it ‘Element.as’.

Set the dimensions of the project to 600x600px.

The FlashDevelop project structure

Step 2: Wait… What’s an Element?

The snake is make up of blue squares, which I call elements. We will create an Element Class, which draws the element. The red apple is going to be an element too, so we will extend the code with a few more lines.

Therefore we won’t create a new class for the apple. (But if you really want to, you can.)


Step 3: Writing the Element Class

The Element class creates a square. It doesn’t draw it on the stage, it just creates it. The registration point of the element – the position referred to by its x- and y-coordinates – is in the top-left.

After opening the Element.as you will see something like this:

package com
{
 /**
  * ...
  * @author Fuszenecker Zsombor
  */
 public class Element
 {

  public function Element()
  {

  }

 }
}

First we need this to extend the Shape class, so we can use the graphics object to draw the square. After this, create two variables: one for the direction (if it’s part of the snake), and one for the score value (if it’s an apple), and then change the parameters of the constructor function: [...]

Read more: Build a Classic Snake Game in AS3

No comments:

Post a Comment