resetting an array
Smitch1581 Mar 15, 2011 2:11 PMHi all.
I have created a game with my trusted AS3 CIB series! Its a simple game that when the user collects or drops 10 pieces of fruit the game ends. And displays if you won or lost. (Code is below)
I have created a button (play_btn) that displays when the game finishes. What i am trying to achieve is when you press the button, the game starts again. I have created a listener and a function "startAgain" that resets the fruitLost and fruitCollected variable that i think i should do. But what i am having problems with is resetting the fruitsOnStage array and executing the for loop to create ten items of the fruitsOnStage array. I know the .splice command removes them from the array but what is the easiest way to add them back. Think i'm on the right lines but have no idea how to achieve this!!!
Any help is greatly appreciated
Cheers
import flash.display.MovieClip;
import flash.events.Event;
var fruitArray:Array=new Array(Apple,Banana,Strawberry,Orange,Pear);
var enemy:Array=new Array(blob);
var fruitsOnStage:Array = new Array();
play_btn.visible=false;
var fruitLost:int=0;
var fruitCollected:int=0;
function startAgain(e:Event):void
{
fruitLost=0;
fruitCollected=0;
trace("Hello again");
stage.addEventListener(Event.ENTER_FRAME, startGame);
}
for (var i:int = 0; i <10; i++) {
var pickFruit=fruitArray[int(Math.random()*fruitArray.length)];
var fruit:MovieClip = new pickFruit();
addChild(fruit);
fruit.x=Math.random()*stage.stageWidth;
fruit.y=Math.random()*-500;
fruit.speed=Math.random()*15+5;
fruitsOnStage.push(fruit);
}
stage.addEventListener(Event.ENTER_FRAME, startGame);
function startGame(e:Event):void
{
for (var i:int= 0; i <20; i++) {
var currentFruit:MovieClip=fruitsOnStage[i];
currentFruit.y+=currentFruit.speed;
if (currentFruit.y>stage.stageHeight-currentFruit.height) {
currentFruit.y=0-currentFruit.width;
fruitLost++;
field1_txt.text="You lost "+fruitLost+" pieces of fruit you loser";
}
if (currentFruit.hitTestObject(basket_mc)) {
fruitCollected++;
removeChild(currentFruit);
field2_txt.text="You collected "+fruitCollected+" Bravo";
fruitsOnStage.splice(i,1);
}
if (fruitsOnStage.length<=0) {
field1_txt.text="You won!!!";
play_btn.visible=true;
stage.removeEventListener(Event.ENTER_FRAME, startGame);
play_btn.addEventListener(MouseEvent.CLICK, startAgain);
}
if (fruitLost>=10) {
field1_txt.text="You lost, MUPPET";
play_btn.visible=true;
play_btn.addEventListener(MouseEvent.CLICK, startAgain);
stage.removeEventListener(Event.ENTER_FRAME, startGame);
}
}
}
basket_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragg);
function startDragg(e:Event):void
{
basket_mc.startDrag();
}
basket_mc.addEventListener(MouseEvent.MOUSE_UP, stopDragg);
function stopDragg(e:Event):void
{
basket_mc.stopDrag();
}




