Codesflash
Codesflash
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
stage.addEventListener(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 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
//this function will reset the game
function reset():void {
removeChild(gFood);
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
SnakeDirection = "left";
}else if (event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "right";
}else if (event.keyCode == Keyboard.UP) {
SnakeDirection = "up";
}else if (event.keyCode == Keyboard.DOWN) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.LEFT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.UP ) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.DOWN){
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;