Problems with adding Score in text field for AS3 - actionscript-3

New here and learning flash AS3. I am having a problem with a game I'm working on. I am a teacher and it is a review game. I would like to display the score as part of a text field. At the very beginning I declare the variable:
var wrongScore:Number = 0;
var correctScore:Number = 0;
Then when an object is dragged and dropped I am trying to display an updated score. It is displaying "Number Correct:" and "Number Wrong:" but not giving the value of correctScore or wrongScore.
function left1Drop (e:MouseEvent): void {
if (left1.hitTestObject(leftTarget))
{
left1.stopDrag();
correct.play();
correctScore += 1;
correctScoreText.text= "Number Correct:" + String(correctScore);
left1.removeEventListener(MouseEvent.MOUSE_DOWN, left1Drag);
}
if (left1.hitTestObject(rightTarget))
{
left1.stopDrag();
left1.x = left1StartX;
left1.y = left1StartY;
wrong.play();
wrongScore += 1;
wrongScoreText.text = "Number Wrong:" + String (wrongScore);
}
else
{
left1.stopDrag();
}
}
I am guessing my problem is somewhere in the code below. But I believe I am typing it exactly as I've seen it elsewhere.
correctScoreText.text= "Number Correct:" + String(correctScore);
Thank you in advance for any help you can offer!!!

Related

How to set dynamic text to a variable?

Im trying out adobe animate for school and until now ive been following a cool rpg game tutorial. but the tutorial ended quicky and now im left on my own browsing the internet. i wanted to add a little star collector feature but the tutorial i found is for flash and i dont know how to use it.
their code is pretty much
money = 0;
onClipEvent (enterFrame) {
if (_root.move_mc.hitTest (this)) {
_root.money++;
this._x = -50;
this._y = -50;
}
}
and i hanged it to
var star:Number = 0;
if(linkMc.hitBoxMc.hitTestObject(overworldMc.starMc1))
{
star += 1;
overworldMc.starMc1.alpha = 0;
}
and it works but now i need to figure out a way to set up a text n the corner telling you how many stars you have.
[link to their image] (https://www.kirupa.com/developer/actionscript/images/textBox_settings.JPG)((((i cant post images yet as i dont have enough points))))
but my version of adobe animate doesnt seem to have the var option! so how do i set up the text?
Try some logic like below. The code is untested, but should be useful to you towards a working solution:
var star :int = 0;
//# create an *enterFrame* function for multiple stars
overworldMc.starMc1.addEventListener( Event.ENTER_FRAME, myClipEvent );
overworldMc.starMc2.addEventListener( Event.ENTER_FRAME, myClipEvent );
overworldMc.starMc3.addEventListener( Event.ENTER_FRAME, myClipEvent );
function myClipEvent( myEvt:Event ) :void
{
//# or... myEvt.currentTarget
if(myEvt.target.hitTestObject(linkMc.hitBoxMc))
{
star += 1; //can be... star++;
myEvt.target.alpha = 0; //# also test replacing *target* with *currentTarget*
//# use String( xxx ) to cast Numeric data type into a Text data type
money_box.text = String(star) + " " + "Stars...";
}
}

Storing top 3 scores

So I have a 3x3 grid of text fields that are meant to show to the 3 best score along with the lap times and carHealths that have been achieved since the game was launched and if a better score then one of the ones in the current leader board is made then the new score, lap time and carHealth replace the old one and move everything below it down by one.
The problem is it only replace the top score even if it is a worse score if just leaves the other 2 spots untouched. Am I just missing something very obvious or am i going about this all wrong?
function leaderBoard(): void
{
if (score < scoreArray[2])
{
return
}
if (score > scoreArray[0])
{
scoreArray.unshift(score);
lapTimerArray.unshift(lapTimer.currentCount);
carHealthArray.unshift(carHealth);
scoreArray.pop()
lapTimerArray.pop()
carHealthArray.pop()
}
else if (score > scoreArray[1])
{
scoreArray.splice(1, 0, score);
lapTimerArray.splice(1, 0, lapTimer.currentCount);
carHealthArray.splice(1, 0, carHealth);
scoreArray.pop();
lapTimerArray.pop();
carHealthArray.pop();
}
else if (score > scoreArray[2])
{
scoreArray.pop();
lapTimerArray.pop();
carHealthArray.pop();
scoreArray.append(score);
lapTimerArray.append(lapTimer.currentCount);
carHealthArray.append(carHealth);
}
}
Oh god :) What do you do if you suddenly want to display top 10 scores ?
How about this approach: You store all information of your cars in ONE object (or class) and then sort your array by score. This way you dan't have to mess with three separate arrays (and maybe you will want to add more properties to your car later):
var car1:Object = {name:"Car 1", score:100, lapTimer:100, carhealth:50};
var car2:Object = {name:"Car 2", score:1050, lapTimer:100, carhealth:50};
var car3:Object = {name:"Car 3", score:700, lapTimer:100, carhealth:50};
var myCars:Array = [car1, car2, car3];
// Then you probably want to pass your car objects to your cars and modify them from there: car3.score = 400 etc. The car objects can be created dynamically based on how many cars you want
// In the end
function displayScores():void
{
myCars.sortOn("score"); // sort cars on score property
// display top 3
for(i:int = 0, i < 3; i++)
{
trace("Place " + (i+1) + " - " + myCars[i].name + ", Score " + myCars[i].score);
}
}

Extra "Space" at end of "If" Requirement AS3

My code works, except it is requiring and extra "Space" at the end to be placed in order for the button to activate? Any ideas? I obviously don't have the space at the end of the user names or passwords in the code. This happens on another frame as well where I have the user type in a web address, I have the conditional set as == "md.website.com" but it is requiring "md.website.com " (extra space at the end) in order for the button to activate.
This code is expecting "AB1234 " and "newuser " instead of "AB1234" "newuser" like I need and I am telling it... I'm sorry, I'm new to AS3 and learning ALL I can, this site rocks for all the help I've already gotten!
username_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
password_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
next_btn.enabled = false;
next_btn.alpha = .5;
function paramChanged3(event:TextEvent):void
{
if (username_txt.text == "AB1234" && password_txt.text == "newuser" )
{
trace("go")
next_btn2.enabled = true;
next_btn2.alpha = 1;
next_btn2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndPlay_20)
}
else
{
next_btn2.enabled = false;
next_btn2.alpha = .5;
}
}
function fl_ClickToGoToAndPlay_20(event:MouseEvent):void
{
gotoAndPlay(20);
}
The problem is that the TextEvent.TEXT_INPUT fires before the text field is actually updated. Try using Event.CHANGE instead (or using two TextEvent.TEXT_INPUT callbacks and appending the input character with event.text within each).
I don't know why AS3 is requiring the extra space, but I removed the exact conditional, and just did a minimum character count. Of course the trainee can then type in anything as long as it matches the minimum requirement, but again, the actual usernames and passwords don't matter, its all simulation anyways, here is the code with the character count....
username_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
password_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
next_btn.enabled = false;
next_btn.alpha = .5;
function paramChanged3(event:TextEvent):void
{
if (username_txt.text != "" && username_txt.length >=5 &&
password_txt.text != "" && password_txt.length >=6)
{
trace("go")
next_btn2.enabled = true;
next_btn2.alpha = 1;
next_btn2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndPlay_20)
}
else
{
next_btn2.enabled = false;
next_btn2.alpha = .5;
}
}
function fl_ClickToGoToAndPlay_20(event:MouseEvent):void
{
gotoAndPlay(20);
}

Save Number with Shared Object and Add to that Saved Number.

Hey everyone so basically what I am trying to accomplish is saving a number with the Shared Object which the the coins that the player collects in the game and if they player quits out of the game and comes back to play again the amount of coins he had when he quit will still show and he will be able to add to that amount if the player picks up more coins. I had this working for a bit but then the textfield started displaying "NAN".
Here is how I have it set up.
The Variable private var nCoins:Number;
In the constructor function I have:
sharedObjectCoins = SharedObject.getLocal("CoinsData");
nCoins = 0 + sharedObjectCoins.data.tCoins;
if (sharedObjectCoins.data.tCoins == null)
{
sharedObjectCoins.data.tCoins = nCoins;
}else
{
trace("Save data found."); // if we did find data...
loadDataTimeAttack(); // ...load the data
}
and in the games Enter.Frame Loop I have the function saveDataCoins which is setup like so:
private function saveDataCoins():void
{
if (nCoins > sharedObjectCoins.data.tCoins )
{
sharedObjectCoins.data.tCoins = nCoins;
}
coinsGraphic.coinsText.text = " " + sharedObjectCoins.data.tCoins;
sharedObjectCoins.flush();
}
not sure if you need the function to where the hitTest takes place between the coins and player but here it is:
private function checkPlayerHitCoins():void
{
for (var i:int = 0; i < aCoinsArray.length; i++)
{
//get current point in i loop
var currentCoins:mcCoin = aCoinsArray[i];
//test if player is hitting current point
if(player.hitTestObject(currentCoins))
{
nCoins += 1;
updatecoinsTextScore();
updateCoinsPauseScreen();
//Add points sound effects
var coinsSEffect:Sound = new coinsSound();
coinsSEffect.play();
//remove point on stage
currentCoins.destroyCoins();
//remove points from array
aCoinsArray.splice(i, 1);
trace("Hit: " + aCoinsArray.length);
}
}
}
Please if anyone could help me with this maybe point something out that I am doing wrong. This code worked perfect one time and when I closed the screen and came back to re test it the textfield displayed NAN and thats it when I hitTest the coins sometimes the NAN switches to a number for like a second but then goes back to NAN.
The first time (or rather every time it creates a new shared object) you will be trying to add undefined to 0, which will result in either a runtime error or NaN.
You need to check if the value exists before attempting to do addition with it.
if(sharedObjectCoints.data && sharedObjectCoins.data.tCoins && !isNaN(sharedObjectCoins.data.tCoins)){
nCoins = Number(sharedObjectCoins.data.tCoins); //there's not point in adding 0
trace("Save data found."); // if we did find data...
loadDataTimeAttack(); // ...load the data
}else{
sharedObjectCoins.data.tCoins = nCoins;
}
Also, if you don't manually set a value to a number var, it will start off life as NaN. eg var nCoins:Number will be NaN until you set it to something.
That said, working with the sharedObject directly like this is a very sloppy way to code your program. Really you should just use shared object to load and save the value, and everything in between use a strongly typed variable.
var nCoins:int = 0;
var tCoins:int = 0;
sharedObjectCoins = SharedObject.getLocal("CoinsData");
if(sharedObjectCoins.data && sharedObjectCoins.data.tCoins && !isNaN(sharedObjectCoins.data.tCoins){
tCoins = int(sharedObjectCoins.data.tCoins);
}else{
//no shared object, use default value for tCoins
tCoins = 0; //or whatever it should start off as.
}
Then write a save function
private function saveSharedObject():void {
sharedObjectCoins.data.tCoins = tCoins;
sharedObjectCoins.flush();
}
Then replace all other instances of sharedObjectCoins.data.tCoins with the var tCoins
It's probably best not to flush the shared object every frame for performance purposes.
Also, shared objects may or may not actually save, depending on user preferences, storage space available, etc. They should not be relied upon for critical data retention.
You can listen for problems with the shared object with AsyncErrorEvent.ASYNC_ERROR I believe (It's been a while since I've worked with AS3 Shared Objects)

ActionScript 3: dynamic text help: scoring for game

I am very new to action script 3, and I am trying to make a very basic game right now. However, no matter how many pages I look at I can't find a working way to get my game to keep score :/.
What I am trying to do is make it so that every 10 seconds, 10 points is added to the score (right now I have it replaces with a key, to see if I could get that to work, but it didn't).
This is the code I am trying to use right now:
var playerScore:int = 0
stage.addEventListener(MouseEvent.CLICK,onclick);
function updateTextFields():void{
playerScoreText.text = ("Player Score: " + playerScore);
}
if(Key.isDown(Key.G)){
playerScore++; //increase playerScore by 1
updateTextFields();
}
playerScoreText is the name of the dynamic text
any help will be greatly appreciated :)
This code was all added in Timeline
I am thinking the problem is most likely something with the creation of the dynamic text, but I am not sure.
Make sure the fonts are embedded properly and that the color of the dynamic text field is not same as the background.
also instead of writing
playerScoreText.text = ("Player Score: " + playerScore);
try this
playerScoreText.text = "Player Score: " + String(playerScore);
It sounds like you want to do something like this with the timer class. Your key code isn't written properly.
var playerScore:int = 0;
var score_timer:Timer = new Timer(10000,0);
score_timer.addEventListener(TimerEvent.TIMER,updateTextFields);
score_timer.start();
function updateTextFields(e:TimerEvent):void
{
playerScore+=10
playerScoreText.text = ("Player Score: " + playerScore);
}