//code written by FlashGamez007
package{
import [Link];
import [Link];
import [Link];
import [Link]; //used for ENTER_FRAME event
public class Main extends MovieClip{
const speed:int = 20;//speed of the snake
var score:int;
var vx:int;
var vy:int;
var gFood:Food;
var head:SnakePart;
var SnakeDirection:String;
var snake:Array;
public function Main(){
init();
}
function init():void {
//Initialize everything!
vx = 1; vy = 0;
score = 0;
snake = new Array();
SnakeDirection = "";
//add food to the stage
addFood();
//add snakes head to the stage
head = new SnakePart();
head.x = [Link]/2;
head.y = [Link]/2;
[Link](head);
addChild(head);
[Link](KeyboardEvent.KEY_UP , onKeyUp);
[Link](KeyboardEvent.KEY_DOWN , onKeyDown);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
//ENTER_FRAME listener is attached to main class and not to the
stage directly
}
//This function will add food to the stage
function addFood():void {
gFood = new Food();
gFood.x = 50 + [Link]()*([Link]-100);
gFood.y = 50 + [Link]()*([Link]-100);
addChild(gFood);
}
//this function will reset the game
function reset():void {
removeChild(gFood);
addFood();
head.x = [Link]/2;
head.y = [Link]/2;
vx = 1;vy = 0;
for(var i = [Link]-1;i>0;--i){
removeChild(snake[i]);
[Link](i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if([Link] == [Link]){
SnakeDirection = "left";
}else if ([Link] == [Link]) {
SnakeDirection = "right";
}else if ([Link] == [Link]) {
SnakeDirection = "up";
}else if ([Link] == [Link]) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if([Link] == [Link]) {
SnakeDirection = "";
}else if([Link] == [Link]) {
SnakeDirection = "";
}else if([Link] == [Link] ) {
SnakeDirection = "";
}else if([Link] == [Link]){
SnakeDirection = "";
}
}
function onEnterFrame(event:Event):void {
//setting direction of velocity
if(SnakeDirection == "left" && vx != 1) {
vx = -1;
vy = 0;
}else if(SnakeDirection == "right" && vx != -1) {
vx = 1;
vy = 0;
}else if(SnakeDirection == "up" && vy != 1) {
vx = 0;
vy = -1;
}else if(SnakeDirection == "down" && vy != -1) {
vx = 0;
vy = 1;
}
//collison with stage
if(head.x - [Link]/2 <= 0){
score = 0;
reset();
}
if(head.x + [Link]/2 >= [Link]){
score = 0;
reset();
}
if(head.y - [Link]/2 <= 0){
score = 0;
reset();
}
if(head.y + [Link]/2 >= [Link]){
score = 0;
reset();
}
//move body of the snake
for(var i = [Link]-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
//changing the position of snake's head
head.x += vx*speed;
head.y += vy*speed;
//collision with tail
for(var i = [Link]-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
//collision with food
if([Link](gFood)){
score += 1;
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[[Link] - 1].x;
bodyPart.y = snake[[Link] - 1].y;
[Link](bodyPart);
addChild(bodyPart);
}
//display scores
[Link] = String(score);
}
}
}