Build a Classic Snake Game in ActionScript 2.0

Well, we’re approaching the end of 2009, and as ever, these final days in December are a time for reflection, memories and nostalgia. At Activetuts+ we endeavor to be forward-thinking, moving with the times and embracing technology. Saying that, it’s also important we appeal to all our readers, so for those of you who haven’t made the jump yet, let’s finish off the year with a bit of ActionScript 2.0!

In this tutorial, you’ll create a simple AS2 snake game.

Step 1: Setting up the File

Start Flash, and click Create New: Flash File (Actionscript 2.0). You can set the stage size to whatever pleases you – I’ve set mine to 500 x 350. I do advise you to set the framerate to 30fps.

Now, you can either decide to follow this step and draw the required movieclips yourself, or you can skip ahead and use the ones I created. If you want to use the ones I created you can find them in the source file. Just add them to the library and drag them onto the stage. If you are going to draw your own: you don’t have to literally draw the same as I did, but do make sure you stick to the sizes.

Step 2: Create the Snake Pit

The first thing we’ll create is the pit for the snake to roam around. Create a rectangle of 400 x 250 and convert it to a movieclip. Make sure you pay attention to the registration point; make it top-left.

Make sure you give the snake pit the instance name snakepit and align it slightly above the center of the stage (so that we can add text below it later, without messing up the aesthetics).

Step 3: Create the Snake’s Head

Draw a square (perhaps with rounded corners) without a border (size 25 x 25) and copy it so you have 2 exactly the same. Convert one of them to a movieclip. Again, pay attention to the top-left registration.

Make sure you give it the instance name bodypart0 and double check that its size is 25 x 25.

Step 4: Snake’s Head ActionScript

Enter the “head” movieclip. Once inside it, add this line of code to the first and only frame:

stop();

Now, draw a little face on the snake’s head, so you can tell it apart from other bodyparts.

Step 5: Additional Face

Add a second frame to the “head” movieclip, and on this frame, draw a sad or dead face.

Step 6: Create the Other Bodyparts

Remember the duplicate square you created in step 3? We’re going to convert it to a movieclip now. Pay attention to the registration point again.

Make sure you give it the instance name bodypart.

Step 7: Create the Score Field

Create a dynamic text field below the right corner of the snake pit. Make sure you set the variable to score. Also, make sure the field is wide enough for several characters, and aligned to the right. The rest of the settings can be set according to your own style – I used Tahoma 24 Bold.

Step 8: Embedding the Font

Since it’s a dynamic text field, we’ll have to embed the font. Click the embed button in the properties panel (where you just defined the variable and text style).

You’ll see the popup shown below. Make sure you select Numerals [0..9].

Step 9: Create the Food

Draw a blue circle without a border, size 25 x 25, and then erase the center using the eraser tool. Now select the circle that remains and convert it to a movieclip. Alternatively, you can design a piece of food for yourself, as long as it remains 25 x 25.

Step 10: Food Instance Name

Give the food a suprising instance name of food. Double check that its size is 25 x 25.

Step 11: Adding Instructions

Left-below the snake pit seemed like a good place to put some pointers. Simply type the static text “Use the arrow keys to move” here. I know, arrow keys don’t function yet, but we’ll get to that shortly. I promise!

Step 12: Creating the Popup

Draw a white square (somewhere outside the stage, for now) and add the text “You died!” to it. This is the popup we’ll display after someone has lost a game.

Convert it to a movieclip, and give it the instance name popup as well. For alignment purposes, I’ve set the registration point to the center.

Step 13: Score

Double click on the popup you just created to enter it. Once inside it, create a dynamic text field (variable = score) and a button reading the text Play Again.

The button should be given the instance name againbutton.

Inside the button, you can create a slightly darker “Over” and even darker “Down” state.

Congratulations, you have created all the visual objects required for the snake game. Now over to the code!

Step 14: newgame Function

Before I throw a chunk of code at you, I’ll tell you what to do with it. All the code in this tutorial goes on the first and only frame of your movie. No need to attach it to buttons or anything. Now, have a look at this piece of ActionScript.

Editor’s Note: Sorry about this folks, the code syntax highlighter doesn’t want to display this particular chunk of ActionScript in FireFox. Take a look at the code here.

In a nutshell, this bit of code does the following. First, the original bodypart is made invisible – we’ll use duplicates soon. Some default values are (re)set, any duplicates left from the previous game are deleted. In the do { } while() loop, the food and bodypart0 (the head) are given an x and y coordinate. If this matches (so they are at the exact same spot), they are given a new coordinate, until we no longer have a match. Then, the arrays are set up in which we’ll contain the bodyparts’ x and y coordinates.

Step 15: Grabbing the Direction

In this bit of code, we create a keyListener object, which we attach to Key, which represents the keyboard. Whenever a key is pressed, the onKeyDown function is triggered. From the getCode() function, we’ll derive which key was pressed and then define the direction according to this. We’ll store this in the direction variable for later use. Remember: all the code of this tutorial goes on the first and only frame of your movie.

		keyListener = new Object();
		keyListener.onKeyDown = function () {
			keycode = Key.getCode()
			if (keycode == 37) {
				direction = 'left'
			}
			else if (keycode == 38) {
				direction = 'up'
			}
			else if (keycode == 39) {
				direction = 'right'
			}
			else if (keycode == 40) {
				direction = 'down'
			}
		};
		Key.addListener(keyListener);
		

Step 16: onEnterFrame Function

The function down here is a big one. It’s executed on every frame, but only really does something every 5 frames. It checks if the snake isn’t moving outside the box, and then moves all the bodyparts along to their new position. It then checks if the food is there too, and then eats it using the eat() function we’ll discuss later. Then, it checks if the snake is smashing into a wall, and lastly it checks if the snake bites itself in the tail. All these functions will be added soon (insideSnake(), dead(), etcetera). Remember: all the code of this tutorial goes on the first and only frame of your movie.

		this.onEnterFrame = function () {
			if (game) {
				if (framecount/5 == Math.ceil(framecount/5)) {
					if (!(bodypart0._y <= snakepit._y && direction == 'up') && !(bodypart0._y+bodypart0._height >= snakepit._y+snakepit._height-2 && direction=='down') && !(bodypart0._x+bodypart0._width >= snakepit._x+snakepit._width - 2 && direction =='right') && !(bodypart0._x <= snakepit._x && direction == 'left'))
					{
						bodypartsy[0] = bodypart0._y;
						bodypartsx[0] = bodypart0._x;
						for (i=bodypartsy.length-1;i > 0; i--) {
							eval('bodypart'+i)._y = bodypartsy[(i-1)]
							eval('bodypart'+i)._x = bodypartsx[(i-1)]
							bodypartsy[i] = eval('bodypart'+i)._y
							bodypartsx[i] = eval('bodypart'+i)._x
						}
					}
					if (food._x == bodypart0._x && food._y == bodypart0._y) {
						eat()
					}
					if (direction) {
						if (direction == 'up') {
							if (bodypart0._y <= snakepit._y) {
								dead()
							}
							else {
								bodypart0._y-= bodypart0._width
							}
						}
						else if (direction == 'down') {
							if (bodypart0._y+bodypart0._height >= snakepit._y+snakepit._height-2) {
								dead()
							}
							else {
								bodypart0._y+= bodypart0._width
							}
						}
						else if (direction == 'right') {
							if (bodypart0._x+bodypart0._width >= snakepit._x+snakepit._width - 2) {
								dead()
							}
							else {
								bodypart0._x+= bodypart0._width
							}
						}
						else if (direction == 'left') {
							if (bodypart0._x <= snakepit._x) {
								dead()
							}
							else {
								bodypart0._x-= bodypart0._width
							}
						}
					}
					if (game) {
						if (insideSnake(bodypart0._x,bodypart0._y,true)) {
							dead()
						}
					}
				}
				framecount++
			}
		}
		

Step 17: dead() Function

This one’s nice and easy. It executes the actions that need to be taken when the snake dies: the score needs to be defined in the popup, the popup shown, the snake’s dead-face shown and the game-variable set to false (as the game ended).

		function dead() {
			popup.score = 'score: '+(bodypartsx.length-1)
			popup.swapDepths(this.getNextHighestDepth())
			popup._visible = true
			bodypart0.gotoAndStop(2)
			game = false;
		}
		

Step 18: eat() Function

The function below is triggered in the onEnterFrame function we discussed earlier, when the food is picked up. It first duplicates a part of the snake’s body, then positions it at the spot of the last bodypart (so that it’ll join in the line on the next frame). Its coordinates are added to the coordinate containing arrays, and the food is repositioned (somewhere not inside the snake!). Also, the score is updated.

		function eat() {
			duplicateMovieClip(bodypart,'bodypart'+bodypartsy.length,this.getNextHighestDepth())
			bodypart0.swapDepths(this.getNextHighestDepth())
			eval('bodypart'+bodypartsy.length)._y = eval('bodypart'+(bodypartsy.length-1))._y
			eval('bodypart'+bodypartsx.length)._x = eval('bodypart'+(bodypartsy.length-1))._x
			bodypartsy.push(eval('bodypart'+bodypartsy.length)._y)
			bodypartsx.push(eval('bodypart'+bodypartsx.length)._x)
			do {
				food._x = snakepit._x + Math.floor(((snakepit._width-food._width)/food._width)*Math.random())*food._width
				food._y = snakepit._y + Math.floor(((snakepit._height-food._height)/food._height)*Math.random())*food._height
			} while(insideSnake(food._x,food._y));
			score = bodypartsx.length-1
		}
		

Step 19: insideSnake() Function

This function merely checks if the inputted coordinates match any of the coordinates of the snake’s bodyparts. If skiphead is set to true, it is allowed to match the head’s coordinates (when checking if the head bites its tail, this comes in handy).

				function insideSnake(xneedle, yneedle,skiphead) {
			if (skiphead) { startat = 1; }
			else { startat = 0; }
			for (q=startat; q<bodypartsx.length; q++) {
				if (bodypartsx[q] == xneedle) {
					if (bodypartsy[q] == yneedle) {
						return true;
					}
				}
			}
			return false;
		}
		

Step 20: The Popup Button

As a last bit of code; we still have to add an on-release function to the button inside the popup! It’ll trigger the newgame() function we discussed earlier, when clicked. Remember: all the code of this tutorial goes on the first and only frame of your movie – including this bit about the button!

		popup.againbutton.onRelease = function() {
			newgame()
		}
		

Step 21: Wrapping it All Up

I’m sure you’ve done this before, but now is the time: hit Ctrl+Enter (or Cmd+Enter on a Mac) to compile the swf file and test your game. It should now be fully functional. Enjoy!

Conclusion

If you made it all the way here; congratulations! You created quite an addictive game, in AS2! Of course, a game is never finished. There is always room for creative improvement.

If you have any questions or suggestions, feel free to comment below. Also, I’m quite curious to see files produced as a result of this tutorial – I’d love to see a link in the comments!

Thanks for reading my tutorial. I hope you enjoyed it as much as I did.

Joost Rijneveld is Joost on Activeden
Add Comment

Discussion 90 Comments

Comment Page 2 of 2 1 2
  1. Rikesh says:

    hey guys getting the same error.

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 9: Unexpected ‘gt’ encountered
    for (i=bodypartsy.length-1;i > 0; i–) {

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 11: Unexpected ‘}’ encountered
    }

    does any pro has time to resolve this issue.. would be very thankful to ya all.

    • Staff

      Hi Rikesh,

      The “Unexpected ‘gt’ encountered” error sounds like you have code like this:

      for (i=bodypartsy.length-1;i &gt; 0; i–) {

      I’m not sure how that would happen, but is that what your code looks like?

  2. Rikesh says:

    hi michael thanks for the quick reply i had &gt but i replaced it with > now code is like this

    bodypart._visible = false
    newgame()
    function newgame() {
    bodypart0.gotoAndStop(1);
    direction = ”; //the direction in which we’re moving
    framecount = 0;
    score = 0;
    game = true; // is there currently a game being played?
    for (i=bodypartsy.length-1; i>0; i–) {
    removeMovieClip(eval(‘bodypart’+i));
    }

    but now i dont get a error but i get a message ” a script in this movie is causing flash player to run slowly…. do u want to abort?

  3. Rikesh says:

    hi tried like u said it gave me an error

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 9: ‘)’ expected
    for (i=bodypartsy.length-1; i>0; i = i – 1) {

  4. Rikesh says:

    i copy pasted ur code. and now even if i kept “-” instead of – it again didnt work it says
    ” a script in this movie is causing flash player to run slowly…. do u want to abort?

  5. Kris says:

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 18: Unexpected ‘lt’ encountered
    if (!(bodypart0._y <= snakepit._y && direction == ‘up’) && !(bodypart0._y+bodypart0._height >= snakepit._y+snakepit._height-2 && direction==’down’) && !(bodypart0._x+bodypart0._width >= snakepit._x+snakepit._width – 2 && direction ==’right’) && !(bodypart0._x <= snakepit._x && direction == ‘left’))

    Total ActionScript Errors: 1 Reported Errors: 1

    ??? I need i little help.. :)

  6. Alex says:

    does this work on flash mx. i tried to open the .fla file but it doesnt open in flash mx

  7. Dimitris says:

    Hi Everyone… What programm I have to use to make this game?
    And if you can give me a download Link!

    Thanks in Advance for your help!

  8. ashraf says:

    Why i cant open the source code?its says “unexpected file format” …anyway i’m using macromedia flash 8 pro…. please help me…

  9. Trimex says:

    Hi, i made this and its rly awesome ^^
    but got a few questions :)

    i can’t find the code for the following things:

    i want that if the snake hits the wall, it apears back on the other side, so it doesnt die.

    and also code for:

    when my snake is moving to a left, its impossible to go right (right arrow doesnt work), when it goes up its impossible to go down(down arrow doesnt work) and vice verca.

    would be absolutly great if u can note down the code for this, cuz im stuck :s

  10. Quiettime1 says:

    What would you guys say I should do to make my first ever game? I have never scripted a single line before, never coded anything and I don’t understand any codespeak at all.
    Help?

    • Archaeologistt says:

      Any of the games in these tutes are pretty good to start with. Also, look for resources and info on AS3 ActionScript 3) and Flash on the Adobe websites. Good luck, it’s great fun writing code.

  11. saif says:

    i got high score 35 :) lol

  12. shahan says:

    hey i was just wondering if theres a way to make the snake move faster everytime it gets the food?????????
    also everytime i change the size of the objects the snake seems to die once it is outside the wall not when it hits the wall….. any help would be great thanks!!!!

  13. koccak says:

    oya om, skrip apabila ular numbur dinding mati yg mn ???

  14. Maija says:

    This game seems to be okay :)
    but one error in the coding is that you can actually go back into yourself and kill yourself (going to left and pressing to right kills you), wich is a small but annoying error. could you fix that?
    thanx

  15. Ruffryder says:

    So ive created this game and it works perfectly but how would i go abouts adding a function that speeds the snake up as it go collects the food, so it gets faster and faster as it eats each piece of food?
    Could you please help!!

    • Jacob says:

      Try setting up a number variable that holds sort of a multiplier for the speed which is increased everytime it eats the food and then change the code for each direction from

      bodypart0._y-= bodypart0._width

      to

      bodypart0._y-= bodypart0._width * VAR NAME HERE

      that is just changing the up though. You’d have to add * VAR NAME HERE to the end of all the movements.

      EDIT: It speeds it up but causes a weird bug. Maybe you’ll know how to fix it

  16. Sean says:

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 17: Statement must appear within on/onClipEvent handler
    keyListener.onKeyDown = function () {

    Total ActionScript Errors: 4 Reported Errors: 4

    What do I do???

  17. Flet says:

    Great tutorial, but what´s the code for as3

  18. leftyoo says:

    where do I put the code for your ‘key’ thing? :[

  19. will says:

    This isn’t a good tutorial, there are many bugs. I can barely get it working from your instructions and even with the source code.

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.