Actionscript While loop & addChild problems - actionscript-3

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.

Related

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.

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 to push instantiated MC into Array dynamically?

Im really stuck. I have 5 MC´s that are being spliced from one array at a certain time. In that same function I want to push another movieclips into another array. The two arrays holds mc's that represent right or wrong answers. So when one question is being given a correct answer that questions visualisation alters.
This function holds a incrementing variable as I do want the mc's to be pushed by the user and one at the time. The thing is I cant seem to refer them properly.
I´ve tried
pQuestSum = this[pQuest + pQuestNumber];
and
pQuestSum = this[pQuest] + pQuestNumber;
and pretty much everything I´ve imagined would work...but the problem is I havent tried
the right thing.
when I trace pQuestSum (which would be the reference) I get an error saying thats its not a number.
this is one of 5 mc's named from 1-5:
var passedquest1:PassedQuest = new PassedQuest();
this is the vars that i try to to build a reference of
var pQuest = "passedquest";
var pQuestNumber = 1;
var pQuestSum;
var questCorrArray:Array = [];
if(event.target.hitTestObject(questArray[ix])){
removeChild(questArray[ix]);
questArray.splice(ix,1);
pQuestNumber ++;
pQuestSum = this[pQuest] + pQuestNumber;
trace("pQuestSum"); // NaN
questCorrArray.push(pQuestSum);
//trace(questArray.length);
pointsIncreased = false;
questPoints = 0;
}
How do I refer an existing movieclip when the reference consists of both a string and a number? Hope I made myself somewhat clear:)
If you had an instance of an object on your timeline called "passedquest1" (as an example), then you could access it this way:
var myObj = this["passedquest" + 1];
Or,
var pQuest = "passedquest";
var pQuestNumber = 1;
var myObj = this[pQuest+ pQuestNumber.toString()];
When you do this: pQuestSum = this[pQuest] + pQuestNumber;, you are trying add the number to an object (this[pQuest]), unless you have number/int var called "passedquest", this will result in NaN.

How to translate multiple labeled movieclip of Actionscript to Starling?

I'm new to starling and this may sound like a noob question but here goes nothing.
Imagine the following scenario (in Flash):
A movieclip named test
Test has 80 frames
Test has 4 labels at 20 frames each
When I script test in my project. I make it loop from label 0-1 (frames 1-19). Then I tell it to loop on label 2 on a certain event.
This way, I do not add or remove a movieclip or instantiate things just one.
Now, if I think about implementing it in starling. I'm thinking make 4 movieclips in flash. Export them as sprite sheets and then make four movieclips in the script. Add whichever moviclip needs to play in the juggler and similarly removechild it at that time.
This way, I'm adding the overhead cost of 'addchild' and 'removechild' everytime I want to switch between those animations. Is that a more cost effective way?
I presume you want to export a single clip, but control multipe(4 animations) rather than a single one. If this is the case, I wrote a few JSFL scripts a couple of years ago (when CS6 wasn't around to export spritesheets) which exported the main timeline of an .fla document as an image sequence, but used the frame labels in the filenames. This made it easy to integrate with TexturePacker. You can see video of it here.
Here's a JSFL snippet which will export a frame sequence with names generated based frame labels which should make it easy to manage in TexturePacker:
var d = (FLfile.getPlatform() == 'macos') ? '/' : '\\'; //delimiter
var doc = fl.getDocumentDOM(); //document
var tl = doc.getTimeline();tl.setSelectedLayers(0,true); //timeline
var cl = tl.layers[0]; //current layer
var numFrames = cl.frameCount;
var className = prompt("Name for your sequence", toClassName(doc.name.substr(0,doc.name.length-4)));
className = className.split('.')[0];//just in case the user adds .as
className = toClassName(className);//remove non alphabet chars
var docPath = doc.pathURI.substr(0,doc.pathURI.length - doc.name.length);
var exportPath = docPath+className+'_export'+d;
if(!FLfile.exists(exportPath)) FLfile.createFolder(exportPath);
fl.outputPanel.clear();
for(i = 0 ; i < numFrames; i++) {
if(cl.frames[i].name != ''){//if frame is labelled
tl.setSelectedFrames(i,i,true);
doc.exportPNG(exportPath+cl.frames[i].name+lpad(''+i,4)+'.png',true,true);
}
}
fl.trace("export complete!");
function lpad(number, length){
var result = '' + number;
while (result.length < length) result = '0' + result;
return result;
}
function toClassName(input){
return input.replace(/[^a-zA-Z]/g, "");
}
Also, I suggest having a look at generator tools like Dynamic-Texture-Atlas-Generator, Fruitfly, etc.

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