ActionScript 3: dynamic text help: scoring for game - actionscript-3

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

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...";
}
}

Word randomization in Actionscript

In Actionscript, I'm trying to find a way to produce strings and string variables which spit out different text each time they're brought up. To purely visualize:
var text:String "Red||Blue"; //Whenever the variable is called, it's either Red or Blue
textoutput("You spot a grey||black cat."); //A function equivalent of the same issue
I can produce a function which does this effect, but it seems a variable cannot be a function, as far as I can tell.
I've considered array variables, but I have no idea how to use an array to spit out a single entry when the variable is called, and I don't know how to make this work for a string that isn't a variable -- assuming I can get away with a single system that works for both situations.
Edit
To expand upon the issue expressed in Batman's answer, using his result on a variable produces a result that 'sticks' to whichever it randomly chooses. Example:
var shoes:String = grabRandomItem("Red shoes||Crimson shoes");
trace("You have " + shoes + ".") //Whichever result is chosen it stays that way.
Moreover, I may want to change this variable to something else that is entirely not-random:
var secondshoes:String = "Blue shoes";
function newshoes():
{
shoes = secondshoes;
}
You want a random value from a list of possible values. Rather than call the variable, you can reference it dynamically...
function random(low:Number=0, high:Number=1):Number {
/* Returns a random number between the low and high values given. */
return Math.floor(Math.random() * (1+high-low)) + low;
}
var options:Array = ["red", "blue", "grey", "black"];
trace("You spot a " + options[random(0, options.length-1)] + " cat.")
//You spot a black cat.
Alternatively, you can use a function in place of a variable to remove the inline logic...
function catColor():String { return options[random(0, options.length-1)]; }
trace("You found a " + catColor() + " key.")
// You found a red key.
Or generalize it to a generic function with arguments.
var options:Object = {
"cat":["grey", "black"],
"key":["gold", "silver"],
"door":["blue", "red", "green"]
}
function get(item:String):String {
return options[item][random(0, options[item].length-1)];
}
trace("You found a " + get("door") + " door.")
// You found a green door.
There are a ton of ways to do this, but to align with the way you'd like to do it, here is the simplest way to accomplish this:
//populate your string: (remove the word private if using timeline code)
private var text_:String = "Red||Blue||Green||Yellow";
//create a getter to use a function like a property
function get text():String {
//create an array by splitting the text on instances of ||
var arr:Array = text_.split("||");
//return a random element of the array you just made
return arr[Math.floor(Math.random() * arr.length)];
}
trace(text);
Even better, create a common function to parse your string:
function grabRandomItem(str:String):String {
var arr:Array = str.split("||");
return arr[Math.floor(Math.random() * arr.length)];
}
//make a getter variable that regenerates everytime it's called.
function get label():String {
return "You spot a " + grabRandomItem("grey||black||blue||red||purple") + " cat";
}
trace(label); //anytime you access the label var, it will re-generate the randomized string
trace(label);
trace(label);
trace(label);
// ^^ should have different results
Of course, this way I think only works best if the text comes from user input. If you are hard coding the text into the app, you might as well just create it in an array directly as show in another answer you have as there's less overhead involved that way.

Actionscript While loop & addChild problems

Hi I'm trying to make a powers calculator that displays every line calculated by the while loop in my actionscript3 code. When I run the program, the flash file only displays the last loop, can anyone help to make it work without using trace? I need it to display in the flash program. Here is my code:
private function evalue(event:MouseEvent = null):void
{
maMiseEnForme.font="Arial";
maMiseEnForme.size=14;
maMiseEnForme.bold=true;
maMiseEnForme.color=0x000000;
monMessage.x=270;
monMessage.y=375;
monMessage.autoSize=TextFieldAutoSiz...
monMessage.border=true;
monMessage.defaultTextFormat=maMiseE...
var base:uint;
var reponse:uint;
var puissanceCount:int=1;
var puissance:uint;
var reponseText:String;
base = uint(boiteBase.text);
puissance = uint(boitePuissance.text);
while (puissanceCount <= puissance)
{
reponse = Math.pow(base,puissanceCount);
reponseText=(base + "^" + puissanceCount + "=" + reponse + "\n");
monMessage.text=reponseText;
addChild(monMessage);
puissanceCount++
}
}
}
}
I have attached a picture of what appears in the .swf window:
P.S: I'm a newbie to flash.
Thanks in advance.
You can use "+=" parameter instead of "=" parameter to update a string variable by "adding string to it" instead of "refreshing it everytime", then you can show text after your while loop finished. You don't need to addChild(nonMessage) in everyloop, just move it after your while{} loop. SO: You just need "monMessage.text+=reponseText;" instead of "monMessage.text=reponseText;" and move your "addChild()" to next to your while loop.

Simple Obfuscation Of String Constants in Flash

I am not a F
lash expert.
I have a FLA file of a game coded in ActionScript 3.
The game has a string inside, "www.mywebsite.com".
I want that when someone opens this FLA and searches for ".com" or "mywebsite.com" to find nothing. So I have decided to encode that string somehow. But I never coded in Flash, so I have no idea what to start with and Google isn't helping.
Basically all I want to do is replace this line:
var url1 = 'www.mywebsite.com';
With something like this and be functional.
var url1 = base64_decode('asdahwiyadwaeawr==');
Even a XOR or other simple string manipulation algorithm would be good.
What options do I have without importing any non-standard libraries into Flash?
Anyone looking through your code at something like var url = BlaBla_decode("cvxcvxc"); can simply replace it with var url = "www.HisWebsite.com...
So I guess you're supposing no one will be going through your script line by line but instead search for ".com" (Which would make him a really lazy jerk)!
A simple solution is to come up with a function that would return "www.MyWebsite.com" without writing it;
Something like:
var url:String = youAreStupid();
function youAreStupid():String
{
return String(f(22) + f(22) + f(22) + "extra.extra" + f(12) + f(24) + f(22) + f(4) + f(1) + f(18) + f(8) + f(19) + f(4) + "extra.extra" + f(2) + f(14) + f(12)).replace(/extra/g, "");
}
function f(n:Number):String
{
return String.fromCharCode("a".charCodeAt(0) + n);
}
I can't but say this would be lame way to protect your document, and I suggest you keep a comment at the top of your Script (something clearly visible) : // You won't find it YOU ARE STUPID
Now if he's smart enough to search for youAreStupid, that means he's entitled to change it :p
Of course there's also the simpler:
String("-Ow-Mw-Gw-!.-Ym-Oy-Uw-Ae-Rb-Es-Si-Ot-Se-T.-Uc-Po-Im-D").replace(/-./g, "");
but that's no fun!!!

How Do You Concatenate Arrays In Actionscript 3 When Using Different Image Files?

I've looked everywhere on the web to see if I could find an answer to this and I've looked throughout the Adobe Flash Builder help site too and I can't seem to find a concrete answer for what I'm trying to do.
It is possible to reference an array inside of an image file name, here's the scenario.
I have a list of images that only differ by the number at the end of the name (for example. orangeimg1.jpg, appleimg2.jpg, strawberryim3.jpg, etc. Is it possible when referencing the image that I could somehow reference the array in the file name rather than repeating the same code over and over again?
I have two different arrays set up one for fruit which has (orange, apple, stawberry) and I have another array with the numbers (1, 2, 3). I have jpg images for each of these combinations but how to I reference that in one line when I'm trying to refer to these images. I thought something like source = "[fruit].img.[number].jpg" would work but I'm a newbie so I'm pretty sure that isn't right.
Again I've found some information on the web but it doesn't refer to how it would work if I was coding a source for my images.
I'm really confused and would appreciate any help with this. Thanks.
Strings are concatenated using +.
var fruits:Array = ["banana", "cherry"];
var numbers:Array = [4, 2];
var source = fruits[0] + "img" + numbers[0] + ".jpg"; // bananaimg4.jpg
If you want to create multiple file names, you can use a loop:
for(var i:int = 0; i<fruits.length; i++) {
var source = fruits[i] + "img" + numbers[i] + ".jpg";
// ...
}
You probably don't need that numbers array. If those numbers are in order you could calculate the number in the loop:
for(var i:int = 0; i<fruits.length; i++) {
var source = fruits[i] + "img" + (i+1) + ".jpg";
// ...
}
Above answer is good but i am giving only some changes to make code more effective.
We can use for loop in given below format. it's optimized code:
var len:uint = fruits.length;
for(var i:int = 0; i<len; i++) {
var source = fruits[i] + "img" + (i+1) + ".jpg";
// ...
}