AS3 Flash how to save score in game and display on different frame - actionscript-3

I'm working on a trivia game that has 3 rounds per level. On the frame while playing the game you can see a box with the current score and when the user has completed the round they are taken to another frame where you can see the score for all three rounds. I can't seem to get the score to display correctly. Here's an image roughly illustrating how I would like the score displayed.
Here's the code I have on round1
import flash.display.MovieClip;
import flash.events.MouseEvent;
//Button
btn_six.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler);
btn_six.buttonMode = true;
btn_six.useHandCursor = true;
function onPressHandler(myEvent:MouseEvent){
trace('Press');
btn_six.gotoAndPlay(5);
}
var saveDataObject:SharedObject;
var currentScore:int;
init();
function init():void{
saveDataObject = SharedObject.getLocal("test");
currentScore = 0;
addEventListener(Event.ENTER_FRAME, saveData);
if(saveDataObject.data.savedScore == null){
trace("No saved data yet.");
saveDataObject.data.savedScore = currentScore;
} else {
trace("Save data found.");
loadData();
}
}
function saveData(e:Event):void{
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function loadData():void{
currentScore = saveDataObject.data.savedScore;
trace("Data Loaded!");
}
var questions:Array=['"I look like a dangling parsnip in this!" she cried. "I will never __________ these jeans!',
"Tell the freckled parrot to put his car in __________.",
"When purchasing a buttercream trowel, always choose one made of __________.",
"Everybody has a cracked snowflake. The question is, __________ one is yours? ",
"Standing at the dock, the loopy basket watched the cruise ship set __________ without him. ",];
var answers:Array=[ ["wear","where"], ["idle","idol"], ["steel","steal"] ,[ "which","witch"] ,[ "sail","sale"] ];
var qno=0;var rnd1; var rnd2;
tick.visible=false;cross.visible=false;incorrect0.visible=false;incorrect1.visible=false;incorrect2.visible=false;incorrect3.visible=false;
var right_answers=0;
var wrong_answers=0;
function change_question(){
if(tick.visible){right_answers++;}
if(cross.visible){wrong_answers++;}
if(qno==questions.length){gotoAndPlay(2);}else{
tick.visible=false;cross.visible=false;
rnd1=Math.ceil(Math.random()*2);
rnd2=Math.ceil(Math.random()*questions.length)-1;
q.text=questions[rnd2];
if(questions[rnd2]=="x"){change_question();}
questions[rnd2]="x";
enable_disable(1);
if(rnd1==1){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==2){opt1.text=answers[rnd2][1];opt2.text=answers[rnd2][0];}
//if(rnd1==3){opt1.text=answers[rnd2][1];opt2.text=answers[rnd2][2];opt3.text=answers[rnd2][0];}
if(wrong_answers==0){incorrect0.visible=true;}
if(wrong_answers==1){incorrect1.visible=true;}
if(wrong_answers==2){incorrect2.visible=true;}
if(wrong_answers==3){incorrect3.visible=true;}
if(wrong_answers==3){gotoAndPlay(3);}
}}
function enable_disable(a){
if(a==0){shade1.mouseEnabled=false;shade2.mouseEnabled=false;}
if(a==1){shade1.mouseEnabled=true;shade2.mouseEnabled=true;}}
change_question();
function ButtonAction1(eventObject:MouseEvent) {qno++;change_question();}
shade1.addEventListener(MouseEvent.CLICK, ButtonAction2);
shade2.addEventListener(MouseEvent.CLICK, ButtonAction3);
function ButtonAction2(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==1) {tick.visible=true;tick.y=shade1.y}else{cross.visible=true;cross.y=shade1.y}
qno++;change_question();
}
function ButtonAction3(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==2){tick.visible=true;tick.y=shade2.y}else{cross.visible=true;cross.y=shade2.y}
qno++;change_question();
}
stop();
On round 1 cleared the code looks like this:
ra.text=right_answers +"/5";
if(wrong_answers==3){gotoAndPlay(3);}
The code is the same on round 2 as round 1
and here's the code on round 2 cleared:
ra2.text=right_answers_r2 +"/10";
if(wrong_answers==3){gotoAndPlay(3);}
addEventListener(Event.ENTER_FRAME,myFunction);
function myFunction(event:Event) {
trace("Do Something");
showScoreText();
}
function showScoreText():void{
MovieClip(root).round1.loadData();
ra.text = MovieClip(root).round1.loadData("");
trace("Score text visible");
}

Change your loadData function to:
function loadData(){
currentScore = saveDataObject.data.savedScore;
trace("Data Loaded!");
return currentScore;
//^One does not simply expect something returned without returning anything
}
and there's no accepted parameter, so change
ra.text = MovieClip(root).round1.loadData("");
to
ra.text = MovieClip(root).round1.loadData();

try this,
just assume you have completed round 1 and your currentScore is 10 now you are going to round 2 that is on frame 2 and you have a score textfield in the stage now you have to append the text like this score_txt.appendText(String(currentScore)+"\n"); This helps to see both scores round 1 & round 2 keep doing this for all round. Thats it.

you can store the currentScore at the end of the each rounds in associative array and display it.
var scorearray:Array = [{scored:5, outof:10},{scored:10, outof:20},{scored:20, outof:30}];
function displayScore():void
{
for(var i:int=0;i<scorearray.length; i++)
{
var texts:TextField = new TextField();
texts.text = scorearray[i].scored +"/" + scorearray[i].outof;
texts.y = i * 20 + 30;
addChild(texts)
}
}
displayScore();

Related

ERROR in animate (1023: Incompatible override. AND 1021: Duplicate function definition.)

I'm new to Adobe Animate and action script so I really dont know how to fix this.
I'm creating a mcq quiz which goes like this:
if user choose answer a or b or c or d. if a is correct answer, give 1 mark, choose wrong answer 0 mark
The source of the two errors is in the function speed.
Here is the code I made so far...
import flash.events.Event;
import flash.events.EventDispatcher;
stop();
question.text="the question is"
var totalscore=3;
var currentscore=0;
function mark()
{
currentscore = currentscore + 1;
}
/* Click to Go to Scene and Play
Clicking on the specified symbol instance plays the movie from the specified scene and frame.
Instructions:
1. Replace "Scene 3" with the name of the scene you would like play.
2. Replace 1 with the frame number you would like the movie to play from in the specified scene.
*/
ans1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 1;
}
ans2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
ans3.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
ans4.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
stop();
You have 4 functions there all with the same name. That's probably the source of the error.
Also, your script is too complicated. You don't even need 4 different handlers to begin with.
// Subscribe a single handler to all 4 buttons.
ans1.addEventListener(MouseEvent.CLICK, onAnswer);
ans2.addEventListener(MouseEvent.CLICK, onAnswer);
ans3.addEventListener(MouseEvent.CLICK, onAnswer);
ans4.addEventListener(MouseEvent.CLICK, onAnswer);
function onAnswer(e:MouseEvent):void
{
// Event.target contains the reference to the source of the event.
// Figuring if that was a correct answer is easy.
if (e.target == ans1)
{
currentscore += 1;
}
// In any case...
(root as MovieClip).gotoAndPlay(1, "quiz 2");
}

Undefined Property Error 1120 moving functions?

I'm very, VERY new at flash, and I've tried really hard to figure this out but it's not working. I keep getting the same error: "1120 Access of undefined property goGame" on line 96 and "1136 Incorrect number of arguments expected 1" on line 82.
I know both of these errors has something to do with the ordering of my functions, but I find that when I move the functions to be in front of the listener, more errors pop up demanding the same thing, and the only way I can fix those is moving them in front of each other etc. etc. So I'm kind of stuck. Help would be great appreciated!
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import fl.motion.MotionEvent;
import flash.utils.Timer;
import flash.utils.*;
public class StartGame extends MovieClip
{
var questions: Array=new Array();
var correctAnswers: Array=new Array("blue","Russia","10","stone","true","hydrogen and oxygen","Rapunzel","magician","The Mona Lisa","string","12","mammal","lightning bolt","lacrosse","do");
//Creates am array used for the Quiz Time function
var i = 0;
//used to track player's movements on board
var lives = 3;
//the # of lives given at the beginning of the game
var collide: Boolean;
var myTimer: Timer = new Timer(1000, 60);
//used for timer in Storming the Castle Game
var count = 0;
//used to manage chibiKing movements
//stage.addEventListener(Event.ENTER_FRAME,onFrameLoop);
//loops frames card so animation plays
//function to get to the master instructions page
//function to get the the main board
function randomNumber(){
var number=Math.round(Math.random()*5)+1;
return number;
}//end randomNumber function
function StartGame()
{
instructionsButton.addEventListener(MouseEvent.CLICK, masterInstructions);
//listener on instructions button to open the instructions page
goButton.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}//end StartGame function
function masterInstructions (event:MouseEvent) {
gotoAndPlay(2);
//takes you to the master instructions page
goButton2.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}// end masterInstructions function
function rollDie (event:MouseEvent) {
goRollButton.removeEventListener (MouseEvent.CLICK, rollDie);
//makes player unable to click roll button after pressing once
goRollButton.visible = false;
//removes visiblity of the roll button one clicked
goButtonGame.visible = true;
//makes game button appear so player can proceed to game
var currentRoll=randomNumber();
//randomly rolls a number between 1 and 6
outputNumber.text=String(currentRoll);
//displays the number rolled
var newMoves = i + currentRoll*10;
//moves player forward, i being the number already moved
//roll multipled by ten for frame movements of tween
gameboy.gotoAndStop(newMoves);
//player stops at the new position
i = newMoves;
//i now changed to rolled number
if (i<=300) {
bossGame();
}//if player gets to end of board, automatically start boss game
}//end rollDie function
function playGame (event: MouseEvent) {
gotoAndPlay(3);
//goes to main board game
livesOutput.text=String(lives);
//displays the 3 of lives the player has in the output box
gameBoard.addEventListener(MouseEvent.CLICK, girlJumps);
//event listener for a pop up
goRollButton.addEventListener(MouseEvent.CLICK, rollDie);
//when pressed, button calls die roll function
goButtonGame.addEventListener(MouseEvent.CLICK, goGame);
//when pressed, chooses a random mini game
ball.addEventListener(MouseEvent.MOUSE_DOWN,ballStartDrag);
ball.addEventListener(MouseEvent.MOUSE_UP, ballEndDrag);
bear.addEventListener(MouseEvent.MOUSE_DOWN, bearStartDrag);
bear.addEventListener(MouseEvent.MOUSE_UP, bearEndDrag);
//functions to create drag and drops for objects on stage game board
goButtonGame.visible=false;
//does not display go button so player must roll dice before playing game
}//end playGame function
function ballStartDrag (evt:MouseEvent) {
ball.startDrag();
}//end ballStartDrag function
function bearStartDrag (evt:MouseEvent) {
bear.startDrag();
}//end bearStartDrag function
function ballEndDrag (evt:MouseEvent) {
ball.stopDrag();
}//end ballEndDrag function
function bearEndDrag (evt:MouseEvent) {
bear.stopDrag();
}//end bearEndDrag function
function girlJumps (evt:MouseEvent) {
girlJump.gotoAndPlay(2);
//has character on board to appear by playing tween
}//end girlJumps function
function bossGame (event:KeyboardEvent) {
stage.addEventListener( KeyboardEvent.KEY_DOWN, finalBoss);
//listener to player movement when keyboard is pressed
addEventListener(Event.ENTER_FRAME,movefireball);
//listener to move the fireball
stage.addEventListener(Event.ENTER_FRAME, collision);
//listener to collisions between symbols on stage
livesBoss.text=String(lives);
//displays number of lives in text box
fireball.height = 100;
fireball.width = 100;
fireball.x=40
fireball.y=40
fireball.xVelocity=8;
fireball.yVelocity=8;
//sets fireball parameters
}//end bossGame function
function movefireball (evt: Event) {
fireball.x +=fireball.xVelocity;
fireball.y +=fireball.yVelocity;
//creates speeds of fireball
checkfireballtoWall();
//calls function
var move1:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
var move2:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
//movements randomly created for king's movements
if (count%100 == 0) {
chibiKing.x= move1;
chibiKing.y= move2;
//reassigns chibiKing's movements
}
count++;
//adds to count after so many seconds
}//end movefireball function
function checkfireballtoWall(){
const TOP: Number= 50;
const BOTTOM: Number= stage.stageHeight;
const LEFT: Number= 50;
const RIGHT: Number= stage.stageWidth - 50;
const REVERSE: int = -1;
//limits to fireball's movements
if (fireball.y<TOP) {
fireball.y=TOP;
fireball.yVelocity*=REVERSE;
}
else if (fireball.y>BOTTOM) {
fireball.y=BOTTOM;
fireball.yVelocity*=REVERSE;
}
if (fireball.x<LEFT) {
fireball.x=LEFT;
fireball.xVelocity*=REVERSE;
}
else if (fireball.x>RIGHT) {
fireball.x=RIGHT;
fireball.xVelocity*=REVERSE;
}
//reassignes fireball's direction if fireball hits a certain area
}//end checkfireballtoWall function
function finalBoss (evt: KeyboardEvent) {
if( evt.keyCode == Keyboard.LEFT )
{player.x = player.x - 6;
}
else if( evt.keyCode == Keyboard.UP )
{player.y = player.y - 6;
}
else if( evt.keyCode == Keyboard.RIGHT )
{player.x = player.x + 6;
}
else if( evt.keyCode == Keyboard.DOWN )
{player.y = player.y + 6;
}//allows player to move via keyboard control
}//end finalBoss function
function collision (evt: Event) {
if (player.hitTestObject(chibiKing)) {
gotoAndPlay(14);
//if player hits the king, automatically go to win game screen
if (player.hitTestObject(fireball)) {
lives = lives - 1;
//if player hits fireball, lose a life
if (lives == 0) {
gotoAndPlay(11);}
//if lives equal to zero, go automatically to lose game screen
livesBoss.text=String(lives);
//display the lives remaining the text box
}
}//end collision function
function dragonBattle (event:KeyboardEvent) {
//inset Dragon Battle code
}//end dragonBattle function
function goGame (event:MouseEvent) {
var gameChoose=randomNumber();
//randomly chooses a game to play from the existing mini games
if (gameChoose==1 || gameChoose == 2) {
gotoAndPlay(4);
//game 1 start screen
goButton3.addEventListener (MouseEvent.CLICK, stormingTheCastle);
//listener to go to Storming the Castle Game
}//end goGame function
else if (gameChoose==3 && correctAnswers.length>0) {
gotoAndPlay(7)
//quiz time start screen
quizTimeButton.addEventListener (MouseEvent.CLICK, quizTime);
//quiz time start
}
else {gotoAndPlay(6);
//game 2 start screen
goButton5.addEventListener (MouseEvent.CLICK, dragonBattle);
//listener to start game 2
//wizardess.addEventListener (MouseEvent.CLICK, wizardessMagic);}
}
}//end goGame function
function quizTime (event:MouseEvent) {
questions [0]= "What colour is the sky?";
questions [1]= "What is the world's biggest country in land mass?";
questions [2]= "Do Re Mi Fa So La Ti...";
questions [3]= "How many tentacles does a squid have?";
questions [4]= "In Greek Mythology, looking into Medusa's eyes would turn you to...?";
questions [5]= "True or False: Winnipeg has a hockey team.";
questions [6]= "Water is made out of...?";
questions [7]= "Which princess is the star of Disney's movie 'Tangled'?";
questions [8]= "Harry Houdini was famous for being a(n)...?";
questions [9]= "Leonardo Da Vinci famously painted what?";
questions [10]= "What type of instrument is a sitar?";
questions [11]= "How many are in a dozen?";
questions [12]= "Humans are...?";
questions [13]= "Harry Potter is famous for having a scar shaped as what on his forehead?";
questions [14]= "What is the national sport of Canada?";
//creates questions to go with answers created in startGame function
questionBox.text=questions[questions.length];
//displays the question at the end of the array
answerQuizTime.addEventListener(MouseEvent.CLICK, quiz);
//button to proceed to get quiz marker
}//end quizTime function
function quiz (evt:MouseEvent){
var userAnswer=String(answerInput.text);
//saves the user's answer in userAnswer variable
if (userAnswer==correctAnswers[questions.length]) {
questions.pop();
//removes question from end of array
lives = lives + 1;
//adds life to player's total lives
gotoAndPlay(9);
//goes to minigame win screen
}
else {
questions.pop();
//removes question from end of array
lives = lives - 1;
//removes life from player's total lives
gotoAndPlay(10);
//goes to minigame lose screen
}
}//end quiz function
// handler function for the Arrow Keys to move Player across the stage
function movePlayer(evt: KeyboardEvent) {
// if key is right arrow, move Player to the right
if (evt.keyCode == Keyboard.RIGHT) {
Player.x += 20;
// if key is left arrow, move Player to the left
} else if (evt.keyCode == Keyboard.LEFT) {
Player.x -= 20;
}
}//end movePlayer function
function stormingTheCastle (event:MouseEvent) {
// add a listener for a Frame Event
stage.addEventListener(Event.ENTER_FRAME, onFrameLoop);
// add the listener for Keyboard events to the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, movePlayer);
// create a custom speed property for each knight
//start timer
knight1.velocity = 4;
knight2.velocity = 6;
knight3.velocity = 3;
knight4.velocity = 5;
collide = false;
myTimer.start();
}//end stormingTheCastle function
// each time frame 1 plays, move each knight
//continues if no collision and count less than 60
//return each night to top if it reaches the bottom
function onFrameLoop(evt: Event) {
if (collide == false && myTimer.currentCount < 60) {
if (knight1.y > 292.2)
{knight1.y = 42.45;}
if (knight2.y > 292.2)
{knight2.y = 42.45;}
if (knight3.y > 292.2)
{knight3.y = 42.45;}
if (knight4.y > 292.2)
{knight4.y = 42.45;}
//move knights down by its speed property amount
knight1.y = knight1.y + knight1.velocity;
knight2.y = knight2.y + knight2.velocity;
knight3.y = knight3.y + knight3.velocity;
knight4.y = knight4.y + knight4.velocity;
//trace timer count
trace(myTimer.currentCount);
//if Player is hit by a knight collision is true
if (knight1.hitTestObject(Player) == true) {
collide = true;
trace("test");
}
if (knight2.hitTestObject(Player) == true) {
collide = true;
}
if (knight3.hitTestObject(Player) == true) {
collide = true;
}
if (knight4.hitTestObject(Player) == true) {
collide = true;
}
else {
if (lives == 0) {
gotoAndPlay(11);}
//trace Game Over when collision is true
trace("GAME OVER");
gotoAndPlay(10);
}
} //end onFrameLoop function
}
}//end startGame function
}//end class function
}//end package
In a class file, the order of functions and var definitions is not an issue (aside from anonymous and nested functions which you should probably steer clear of anyway).
Let's start with line 82. You call bossGame(), but when you look at the function, you've defined it so it requires a parameter:
function bossGame (event:KeyboardEvent)
It's expecting you to pass a KeyboardEvent to the function. Though I'm not sure why because looking at that function it seems to have nothing to do with Keyboard input nor does it use that event in any way.
So, take out the parameter:
function bossGame()
Or, make it optional by giving it a default value:
function bossGame(event:KeyboardEvent = null)
For the second error. Your goGame function is actually nested inside another function collision() , so it has no scope except inside the collision function. If you want to be able to access it outside of that function, then you should break it out.
As an aside, you comments beside your closing function brackets are often incorrect making it difficult to read your code.

How do i play a song from library when the preloader is a "x"% of total loaded?

I am currently undertaking a final exam based on the presentation of an offline portfolio and I need to make a preloader, where when the process of loading is 25% of total bytes, to play a sound that is imported into the library. I've tried several ways and can’t do it.
I'll leave you the code for my preloader.
//(also this code is a mouse loader in text form)
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS,checkingProgress);
function checkingProgress(event:ProgressEvent):void{
var procentLoaded:Number = event.bytesLoaded/event.bytesTotal*100;
ptxt.text=int(procentLoaded)+"%";
if(procentLoaded == 100){
this.gotoAndPlay(1,"Video-Int");
}
}
stage.addChild(ptxt);
ptxt.mouseEnabled = false;
ptxt.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);
function fl_CustomMouseCursor(event:Event) {
ptxt.x = stage.mouseX;
ptxt.y = stage.mouseY;
}
Mouse.hide();
this.addEventListener(Event.ENTER_FRAME, loading);
function loading(e:Event):void {
var total:Number = this.stage.loaderInfo.bytesTotal;
var loaded:Number = this.stage.loaderInfo.bytesLoaded;
prel.scaleX = loaded/total;
if (total == loaded){
play();
this.removeEventListener(Event.ENTER_FRAME, loading);
}
}
You need to make the sound file in your library available for actionscript.
Give it a Class name ex. MySound
...
var mysound:MySound = new MySound();
var soundPLaying:Boolean = false;
function checkingProgress(event:ProgressEvent):void{
var procentLoaded:Number = event.bytesLoaded/event.bytesTotal*100;
ptxt.text= procentLoaded +"%";
if(procentLoaded > 25 && !soundPlaying){ //check if loaded mor then 25% and sound isn't playing
mysound.play();
soundPlaying = true;
}
if(procentLoaded == 100){
this.gotoAndPlay(1,"Video-Int");
}
}
...
if you need to do some extra stuff like pause, change volume etc you will need a SoundChannel Object

Can anyone help me how to access a data from an fla file to another fla file?

Can anyone help me how to access a data from an fla file to another fla file?
I have a starting fla file called "savescore.fla" which is connected to the class called "score.as".I have a "btnAdd" button that if clicked, it will add by one to the variable "scoring" in the class "score.as". I have also a movieclip "btnSave" that would save the score. Lastly, I have a "next_btn" button that would go directly to my another fla file
which is "finalscore.fla". I wanted the "finalscore.fla" to show the current "scoring" variable from the "score.as" class but the problem is that it will only show 0/zero as the score. I think that as "savescore.fla" saves and edits the variable in the "score.as", it will only make changes to itself and not to the "score.as" that's why I still got 0 as the final score because it comes from the "score.as" and not from "savescore.fla". So I was thinking if I could just access the score from the "savescore.fla", it would solve the problem. But I have no idea what codes to put...or can you give me another way?
Here are the codes: (Btw, I am using actionscript 3.0)
savescore.fla:
var lol:score = new score();
var saveDataObject:SharedObject;
//var currentScore:int;
init(); // this line goes directly beneath the variables
function init():void{ // call once to set everything up
saveDataObject = SharedObject.getLocal("test"); // give the save data a location
btnAdd.addEventListener(MouseEvent.CLICK, addScore); // clicking on +1
btnSave.addEventListener(MouseEvent.CLICK, saveData); // clicking on Save
next_btn.addEventListener(MouseEvent.CLICK, sunod); // clicking on +1
if(saveDataObject.data.savedScore == null){ // checks if there is save data
trace("No saved data yet."); // if there isn't any data on the computer...
saveDataObject.data.savedScore = lol.scoring; // ...set the savedScore to 0
} else {
trace("Save data found."); // if we did find data...
loadData(); // ...load the data
}
}
function addScore(e:MouseEvent):void{
lol.scoring+=1; // add 1 to the score
}
function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = lol.scoring; // set the saved score to the current score
trace("Data Saved!");
saveDataObject.flush(); // immediately save to the local drive
trace(saveDataObject.size); // this will show the size of the save file, in bytes
trace(lol.GetFullScore());
}
function loadData():void{
lol.scoring = saveDataObject.data.savedScore; // set the current score to the saved score
trace("Data Loaded!");
}
function sunod(event:MouseEvent):void{
var ldr:Loader=new Loader();
ldr.load(new URLRequest("finalscore.swf"));
addChild(ldr);
}
score.as:
package{
public class score{
public var scoring:int;
function score()
{
}
public function SetScore(val:int):void
{
scoring = val;
}
public function GetFullScore():int
{
return scoring;
trace(scoring);
}
}
}
finalscore.fla:
var lol1:score = new score();
txtScore.text = ("Score: " + lol1.GetFullScore()); // set the text property of the txtScore
trace(lol1.GetFullScore());
Once you have loaded an external swf you can grab a reference to it in an onLoadedHandler. So in savescore:
var myReference:Object;
function loadComplete(event:Event):void {
myReference= event.target.content;
myReference.lol1.GetFullScore();
... or...
var myScore = event.target.lol1.GetFullScore();
etc...
}
you'll want to make sure the reference exists before you use it
EDIT
in your Child SWF create a variable and method to store the parent:
var parentSWF:MovieClip;
function setParent(myParent:MovieClip):void{
parentSWF = myParent;
}
then in the parent send the child a reference :
function loadComplete(event:Event):void {
myReference= event.target.content;
// use the reference to child to call
// any variables or functions in it
myReference.lol1.GetFullScore();
// set the reference in child with the following
// so that the child can call the parent
myReference.setParent(this);
}
then in child you can use lol :
parentSWF.lol;
If you had to go this way you would ideally create measures to check the objects/methods etc exist before they are used
FINAL EDIT
For a start, move
var ldr:Loader=new Loader();
out of the sunod function and put it at the top with the other declaration so that loadcomplete can use it. You need to set up a listener for the loadComplete handler. Put this after your other listeners
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
in your loadcomplete handler in savescore add
myReference.doThisWhenLoaded();
in finalscore put
function doThisWhenLoaded():void{
txtScore.text = ("Score: " + parentSWF.lol);
}
This just seems complete overkill and I'm sure I've overcomplicated your over complications(!). My advice would be to do away with the second swf and just create a finalscore.as object in savescore. This would be so much easier. At the moment I can't see why you want to have another swf floating around. I've never been a fan of multiple swfs though so someone else may well jump in and correct this.
Here's the changes of my code:
savescore.fla:
var lol:score = new score();
var saveDataObject:SharedObject;
init(); // this line goes directly beneath the variables
function init():void{ // call once to set everything up
saveDataObject = SharedObject.getLocal("test"); // give the save data a location
btnAdd.addEventListener(MouseEvent.CLICK, addScore); // clicking on +1
btnSave.addEventListener(MouseEvent.CLICK, saveData); // clicking on Save
next_btn.addEventListener(MouseEvent.CLICK, sunod); // clicking on +1
if(saveDataObject.data.savedScore == null){ // checks if there is save data
trace("No saved data yet."); // if there isn't any data on the computer...
saveDataObject.data.savedScore = lol.scoring; // ...set the savedScore to 0
} else {
trace("Save data found."); // if we did find data...
loadData(); // ...load the data
}
}
function addScore(e:MouseEvent):void{
lol.scoring+=1; // add 1 to the score
}
function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = lol.scoring; // set the saved score to the current score
trace("Data Saved!");
saveDataObject.flush(); // immediately save to the local drive
trace(saveDataObject.size); // this will show the size of the save file, in bytes
trace(lol.GetFullScore());
}
function loadData():void{
lol.scoring = saveDataObject.data.savedScore; // set the current score to the saved score
trace("Data Loaded!");
}
function sunod(event:MouseEvent):void{
var ldr:Loader=new Loader();
ldr.load(new URLRequest("finalscore.swf"));
addChild(ldr);
}
var myReference:Object;
function loadComplete(event:Event):void {
myReference= event.target.content;
myReference.lol1.GetFullScore();
myReference.setParent(this);
}
finalscore.fla:
var lol1:score = new score();
var parentSWF:MovieClip;
txtScore.text = ("Score: " + parentSWF.lol); // this line has the error because of parentSWF.lol
trace(lol1.GetFullScore());
function setParent(myParent:MovieClip):void{
parentSWF = myParent;
}
score.as:
package{
public class score{
public var scoring:int;
function score()
{
}
public function SetScore(val:int):void
{
scoring = val;
}
public function GetFullScore():int
{
return scoring;
trace(scoring);
}
}
}

Some errors in flash AS3 game, almost completed with lot of effort and help received

First I really want to thank you for all the help you have given me so far, since I did not know anything about AS3 (basics gotoAnd stuff only) I came to Stackoverflow searching for some code already made but I was encouraged by some members to make the code by myself, now after almost 2 weeks and thanks to a lot of great people my soccer penalty kick game is almost finished, I really love this place.
I know I have to work on some collisions and other stuff since currently the game is not the best (remember I’m just a newbie), but Unfortunately while checking the game functioning by playing it over and over again, I have found the following:
1- When you get 3 fails, then game is over and a play again button appears after some animation, you click on it and everything seems to be fine, but when you continue playing the second time you reach 3 fails, when you click the button a new cursor appears??? Please help
2- I tried millions of times to make the ball move with speed and to animate its trajectory but was unable to make it, any help on this will be highly appreciated. I have speed variables and gravity but I didn’t know how to use them
3- I'm getting a actionscript error related to a removeChild, I tried many times removing some lines but I´m unable to fix it.
4- I'm using too many timers, I don't know if this is recommendable.
Here is the .fla file https://rapidshare.com/files/1702748636/kicks.fla just in case anybody want to try the game (this is really simple since it is my 1st AS project) and want to help me with the code and help me improving the game, and here is the code if somebody does not need to get into the file (I know this place is full of really smart people), once I finish it I know I will be able to do a lot of stuff with AS3.
var score:Number;
var angle:Number;
var speed:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
function initializeGame( ):void
{
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
cursor = new Cursor();
addChild(cursor);
cursor.enabled = true;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function dragCursor(event:MouseEvent):void
{
cursor.x = this.mouseX;
cursor.y = this.mouseY;
}
initializeGame();
var mouse = this.Mouse;
function kick(evt:Event)
{
removeChild(cursor);
pateador_mc.play();
var timer:Timer = new Timer(500,1);
timer.addEventListener(TimerEvent.TIMER, delayedAction);
timer.start();
function delayedAction(e:TimerEvent)
{
moveBall();
}
}
speed=-100000;
var ease:int = 100;
var gravity:Number = 0.5;
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
ball.x = mouseX + Math.cos(angle);
ball.y = mouseY + Math.sin(angle) ;
ballRotation = true;
stage.removeEventListener(MouseEvent.CLICK, kick);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
var timer3:Timer = new Timer(3000,1);
timer3.addEventListener(TimerEvent.TIMER, delayedAction3);
timer3.start();
function delayedAction3(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
addChild(cursor);
keeper.gotoAndStop(1);
}
}
else
{
fails_mc.play();
failed++;
var timer2:Timer = new Timer(3000,1);
timer2.addEventListener(TimerEvent.TIMER, delayedAction2);
timer2.start();
function delayedAction2(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
addChild(cursor);
keeper.gotoAndStop(1);
}
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
}
}
function showScore():void{
goles_txt.text ="" +score;
}
trace (score);
function gameFinished(){
gameOver.play ();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
timer2.stop();
Mouse.show();
this.mouseX=cursor.x ;
this.mouseY=cursor.y;
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain():void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
var timer4:Timer = new Timer(1000,1);
timer4.addEventListener(TimerEvent.TIMER, delayedAction3);
timer4.start();
function delayedAction3(e:TimerEvent)
{
initializeGame();
}
}
}
I’ll really appreciate it guys , I promise I won’t be bothering again for a long time
1/3.
Problem 1 & 3 are the same problem. Looks like your trying to remove the cursor from the stage (removeChild) every click (so it will error after the first click because it's no longer a child of anything). Your adding it back on your delayedAction2 which doesn't run unless your hit test is true and only after 3 seconds. On initialize game you create a whole new cursor and add that to the stage which is why you get a duplicate after the first game.
Rather than removeChild the cursor, it might better to just set it's visibility to false/true and only create it once.
You'll need to use an EnterFrame handler, or timer, or tween for this. I can post an example later.
I can't figure out why you're using timers at all or need to delay your functions, except maybe to allow time for the kick animation?
You're code is very disorganized, naming functions things like 'delayedAction' is bad as it doesn't really tell you anything about the purposed of the function. You also have way too much functions inside of other functions. Here is a quick refactoring of your code I've done to hopefully teach a few things. I've also added the tween for the ball animation.
import flash.events.Event;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
var score:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
var ballTweenX:Tween;
var ballTweenY:Tween;
var targetCursor = new Cursor(); //only want one of these and you want it to exist the whole time so keep out here.
addChild(targetCursor);
initializeGame();
function initializeGame( ):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
targetCursor.visible = true;
Mouse.hide();
}
function dragCursor(event:MouseEvent):void
{
targetCursor.x = this.mouseX;
targetCursor.y = this.mouseY;
}
function kick(evt:Event)
{
//removeChild(targetCursor);
targetCursor.visible = false;
pateador_mc.play();
stage.removeEventListener(MouseEvent.CLICK, kick); //move this here, because you don't the option kick again while already kicking
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor); //added this, you probably don't want the target moving after the click...
setTimeout(moveBall, 500);//cleaner and more efficient than using a timer for a one time delayed call.
}
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
targetX = mouseX + Math.cos(angle);
targetY = mouseY + Math.sin(angle) ;
ballRotation = true;
ballTweenX = new Tween(ball, "x", null, ball.x, targetX, .3, true);
ballTweenY = new Tween(ball, "y", null, ball.y, targetY, .3, true);
ballTweenY.addEventListener(TweenEvent.MOTION_FINISH, ballTweenDone,false,0,true);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
}
function stopBallTween():void {
ballTweenX.stop();
ballTweenY.stop();
}
function ballTweenDone(e:TweenEvent):void {
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
}else
{
fails_mc.play();
failed++;
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
return; //added this because you don't want the rest of this function running if it's a game over
}
}
setTimeout(resetShot, 3000); //you had the code I put in resetShot repeated twice
trace(score);
}
function resetShot():void {
ball.x = 296.35;
ball.y = 353.35;
targetCursor.visible = true;
keeper.gotoAndStop(1);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function showScore():void{
goles_txt.text ="" +score;
}
function gameFinished(){
gameOver.play();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
Mouse.show();
//this.mouseX=cursor.x ;
//this.mouseY=cursor.y; //These are read only properties, your can't set the mouse position...
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain(e:Event = null):void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
setTimeout(initializeGame, 1000);
}