Adding and storing a highscore - actionscript-3

I'd like to add a highscore to my android game. I'd like to add it and store for when they return. how do I go about this?
Here's the code for the frame I want it on!
lblScore.text = String(score);
gameOver.addEventListener(TouchEvent.TOUCH_TAP, End);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
function End(event:TouchEvent): void {
gotoAndPlay(1);
}
stage.removeEventListener(TouchEvent.TOUCH_TAP, End);
function refreshScores():void {
lblScore.text = String(score);
score++;
}

You can use SharedObject:
var localstorage:SharedObject = SharedObject.getLocal("anyname");
//Save the data to the SharedObject
localstorage.data.score = 100;
//Commit the save
localstorage.flush();
//Get data in the SharedObject, but check to see if it exists
if (localstorage.data.score != undefined){
//if SharedObject exists so display the data
trace(localstorage.data.score);
}else{
//SharedObject does not exists.
}
//If you want to clear the ShareObject
localstorage.clear();
If you want to save in a database manner then use SQLite

Related

Implicit Coercion of a value of a type of text.flash:TextField to an unrelated Int

Okay, so I'm trying to create a mobile flash game (I'm mostly an animator, a storyteller) and I'm having trouble with the input text for the player name. I've often read helpful tips on this site so I signed up to get some help. The code I use to load and save data is saveDataObject, But as far as I know input text has to be used with package code. I tried to convert it to function var, but then these errors occur. I am unsure how to use the Package class code, and everything I've read on it has been confusing. I am pretty much self taught for everything I know about code though tutorials and forums, so if it isn't explained in a way I can understand I wont be able to do it...
Here's the section of code if I wasn't clear(error lines separate):
var playerName:int;
init(); // this line goes directly beneath the variables
function f_1(init):void
{ // call once to set everything up
saveDataObject = SharedObject.getLocal("DataBattle/character/name"); // give the save data a location
-
playerName = txtPlayer;
-
function addName(e:TouchEvent):void
{
var myTextBox1:TextField = new TextField();
var txtPlayer:TextField = new TextField();
var myText:String = "Cyan";
function CaptureUserInput()
{
captureText();
}
function captureText():void
{
myTextBox1.type = TextFieldType.INPUT;
myTextBox1.background = true;
addChild(myTextBox1);
myTextBox1.text = myText;
myTextBox1.addEventListener(TextEvent.TEXT_INPUT, textInputCapture);
}
function textInputCapture(event:TextEvent):void
{
var str:String = myTextBox1.text;
createOutputBox(str);
}
function createOutputBox(str:String):void
{
txtPlayer.background = false;
txtPlayer.x = 200;
addChild(txtPlayer);
txtPlayer.text = str;
}
-
if(saveDataObject.data.characterName = playerName == null)
-
{ // checks if there is save data
trace("No Player data yet."); // if there isn't any data on the computer...
saveDataObject.data.characterName = playerName; // ...set the savedScore to 0
}
else
{
trace("Player data found."); // if we did find data...
loadData1(); // ...load the data
}
function loadData1():void
{
playerName = saveDataObject.data.characterName; // set the current score to the saved score
trace("Data Loaded!");
}
}
}
function saveData(e:TouchEvent):void
{
saveDataObject.data.characterName = playerName; // 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
}
Would be nice to have some more details about this error. Like which line is actually throwing this error.
However even without it there are few things that looks weird right away.
var playerName:int;
// And few lines below
playerName = txtPlayer;
// Few more lines below
var txtPlayer:TextField = new TextField();
Looks like you're declaring playerName as int so you want to store numeric values, but then txtPlayer is a TextField. So by playerName = txtPlayer; you're trying to store TextField as Int value, which is not gonna work.
I can also see
if(saveDataObject.data.characterName = playerName == null)
and it's like :O
I'm not even sure how this part is being compiled. You want to do playerName == null check (which would return true/false) and then assign it to saveDataObject.data.characterName ?

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

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();

AS3 Object Bin and Reset Button

I am trying to create a game for kids where they can drag letters on to a stage to make words.
I want to add a 'trash can' where users can drag letters they no longer need to dispose of them. I have created the movie clip but am totally unsure how to make it function using AS3.
I would also like to add a reset button so that the stage reverts to it's original state. Again, I have drawn it up and added the little as3 that I am aware of (to make it a button) but if anyone could assist with how to actually make this happen, I would be grateful.
The files are here: SWF | FLA and the code for the game is as follows:
import flash.display.MovieClip;
for (var i=1; i<27; i++)
{
this["object" + i].addEventListener(MouseEvent.MOUSE_DOWN, onStart);
this["object" + i].addEventListener(MouseEvent.MOUSE_UP, onStop);
}
var sx = 0,sy = 0;
function onStart(e)
{
sx = e.currentTarget.x;
sy = e.currentTarget.y;
e.currentTarget.startDrag();
}
function onStop(e)
{
if ( e.target.dropTarget != null &&
e.target.dropTarget.parent == dest &&
e.currentTarget.name != "copy" )
{
var objectClass:Class =
getDefinitionByName(getQualifiedClassName(e.currentTarget)) as Class;
var copy:MovieClip = new objectClass();
copy.name = "copy";
this.addChild(copy);
copy.x = e.currentTarget.x;
copy.y = e.currentTarget.y;
e.currentTarget.x = sx;
e.currentTarget.y = sy;
copy.addEventListener(MouseEvent.MOUSE_DOWN, onStart);
copy.addEventListener(MouseEvent.MOUSE_UP, onStop);
}
e.currentTarget.stopDrag();
}
resetButton.addEventListener(MouseEvent.CLICK, reset);
resetButton.buttonMode = true;
function reset(event:MouseEvent):void
{
//Not sure what AS3 to add here to reset to original state
}
I have already gave you the solution here Flash AS3 Clone, Drag and Drop
Here, I am providing a detail solution on how to drag objects inside a bin and remove them.
For dropping copied objects inside a bin, after dragging is stopped, check collision with bin object. for more info see,
copiedObject.hitTestObject(binObject)
For e.g.
First create trash-can MovieClip on the stage and give it an instance name 'trashCan' and add following lines to your onStop()(below e.currentTarget.stopDrag();)function like so:
UPDATE:
var copiedObjsArr:Array = [];
function onStop(e)
{
if ( e.target.dropTarget != null &&
e.target.dropTarget.parent == dest &&
e.currentTarget.name != "copy" )
{
//Code here remains same
//.......
//Keep collecting copied letters for further access in `reset()` function
copiedObjsArr.push(copy);
}
else if(e.currentTarget.name == "copy") //this is 'else if' (newly added)
{
var tarObject:MovieClip = e.currentTarget;
// These detects collision of dragged object with the trashCan
if(tarObject.hitTestObject(trashCan)) {
//These removes dragged object from the display list (not from the memory)
removeChild(tarObject);
tarObject = null; //to garbage
}
}
e.currentTarget.stopDrag();
}
And your reset() becomes like so:
function reset(event:MouseEvent):void
{
if(copiedObjsArr.length > 0)
{
//Traverse through all copied letters
for(var i:int = 0; i<copiedObjsArr.length; i++)
{
var objToRemove:MovieClip = copiedObjsArr[i];
removeChild(objToRemove);
objToRemove = null;
}
//Finally empty the array
copiedObjsArr = [];
}
}

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);
}
}
}

use 1 object multiple times in as3?

I'm trying to make something like bookmarks, I have 1 note on the stage and when the user clicks it, it starts to drag and the users drops it where they want. the problem is I want these notes to be dragged multiple times.. here is my code:
import flash.events.MouseEvent;
//notess is the instance name of the movie clip on the stage
notess.inputText.visible = false;
//delet is a delete button inside the movie clip,
notess.delet.visible = false;
//the class of the object i want to drag
var note:notes = new notes ;
notess.addEventListener(MouseEvent.CLICK , newNote);
function newNote(e:MouseEvent):void
{
for (var i:Number = 1; i<10; i++)
{
addChild(note);
//inpuText is a text field in notess movie clip
note.inputText.visible = false;
note.x = mouseX;
note.y = mouseY;
note.addEventListener( MouseEvent.MOUSE_DOWN , drag);
note.addEventListener( MouseEvent.MOUSE_UP , drop);
note.delet.addEventListener( MouseEvent.CLICK , delet);
}
}
function drag(e:MouseEvent):void
{
note.startDrag();
}
function drop(e:MouseEvent):void
{
e.currentTarget.stopDrag();
note.inputText.visible = true;
note.delet.visible = true;
}
function delet(e:MouseEvent):void
{
removeChild(note);
}
any help will be appreciated.
You need to create a new instance of your note class when you drop, copy the location and other variables from the note you were dragging, add your new note to the stage, and return the dragging note to its original position.
Something like:
function drop($e:MouseEvent):void
{
$e.currentTarget.stopDrag();
dropNote($e.currentTarget as Note);
}
var newNote:Note;
function dropNote($note:Note):void
{
newNote = new Note();
// Copy vars:
newNote.x = $note.x;
newNote.y = $note.y;
// etc.
// restore original note.
// You will need to store its original position before you begin dragging:
$note.x = $note.originalX;
$note.y = $note.orgiinalY;
// etc.
// Finally, add your new note to the stage:
addChild(newNote);
}
... this is pseudo-code really, since I don't know if you need to add the new note to a list, or link it to its original note. If you Google ActionScript Drag Drop Duplicate, you will find quite a few more examples.
I think you are not target the drag object in drag function and problem in object instantiation
for (var i:Number = 1; i<numberOfNodes; i++) {
note = new note();
addChild(note);
...
....
}
function drag(e:MouseEvent):void{
(e.target).startDrag();
}
If you are dragging around multiple types of objects (eg. Notes and Images), you could do something like this, rather than hard coding the type of object to be instantiated.
function drop(e:MouseEvent):void{
// Get a reference to the class of the dragged object
var className:String = flash.utils.getQualifiedClassName(e.currentTarget);
var TheClass:Class = flash.utils.getDefinitionByName(className) as Class;
var scope:DisplayObjectContainer = this; // The Drop Target
// Convert the position of the dragged clip to local coordinates
var position:Point = scope.globalToLocal( DisplayObject(e.currentTarget).localToGlobal() );
// Create a new instance of the dragged object
var instance:DisplayObject = new TheClass();
instance.x = position.x;
instance.y = position.y;
scope.addChild(instance);
}