AS3 - Check results from an array and add to a counter - actionscript-3

I am trying to make a video quiz and when you click it adds a value of 1 to an array. The array size goes up to [9] and I am trying to read from the array so that if there is a value of 1 in the array between [0] and [9] it will add 1 to the counter.
I have got it working for just the first value in the array so I know it works, but I am not sure about how to make it read from all of the array to check for values of 1.
Heres my code so far:
if (clickTimes[0] == 1)
{
counter2++;
}

Better yet, use a for each...in loop. It's really no different from a regular for loop, but it does provide some synactic sugar.
for each (var i:int in clickTimes)
{
if (i == 1)
{
counter2++;
}
}

For the beauty of it...
counter2 = clickTimes.join('').replace(/0/g, '').length;
It puts all your values in one string, remove the zeros and counts the characters left.

var clickTimes:Array = [1,1,1,0,0,0,1,1,0] // 5 1's and 4 0's
var counter2:int = 0
clickTimes.forEach(function(obj:*){
if (obj == 1){
counter2++;
}
})
trace(counter2) // traces 5

What about using a loop?
for (var i:int = 0; i < clickTimes.length; ++i)
{
if (clickTimes[i] == 1)
counter2++;
}
This would increment counter2, for each element that has a value of 1, in the clickTimes array.

You do not need if. Just the following:
var clickTimes:Array = [1,1,1,0,0,0,1,1,0] // 5 1's and 4 0's
var counter2:int = 0;
for each (var i:int in clickTimes)
{
counter2 += i;
}
trace(counter2); //5

Related

How to add numbers in array via a loop in AS3?

var arr: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
I can add these numbers to an array separately like this but how do I add 1 to 50 at once instead of typing it all the way through?
for (var i:Number=1; i<=50;i++){
var arr:Array(i) = [i];
}
function randomize(a: * , b: * ): int {
return (Math.random() > .5) ? 1 : -1;
}
trace(arr.sort(randomize));
I am trying to implement something like this.
Thank you.
Pretty simple. You can address the Array's elements via square bracket notation. Works both ways:
// Assign 1 to 10-th element of Array A.
A[10] = 1;
// Output the 10-th element of A.
trace(A[10]);
Furthermore, you don't even need to allocate elements in advance, Flash Player will automatically adjust the length of the Array:
// Declare the Array variable.
var A:Array;
// Initialize the Array. You cannot work with Array before you initialize it.
A = new Array;
// Assign some random elements.
A[0] = 1;
A[3] = 2;
// This will create the following A = [1, null, null, 2]
So, your script is about right:
// Initialize the Array.
var arr:Array = new Array;
// Iterate from 1 to 50.
for (var i:int = 1; i <= 50; i++)
{
// Assign i as a value to the i-th element.
arr[i] = i;
}
Just keep in mind that Arrays are 0-based, so if you forget about index 0 it will remain unset (it will be null).

How to walk a game character using mouse event in Adobe Animate CC AS3?

This question is related to my previous post, “TypeError: Error #1010: A term is undefined and has no properties” in AS3 because as I mentioned there, I'm creating an Android Game for our thesis. Now, I have a spritesheet of a character in the link: sprite character, I'm using this in the game. I'm researching on how to walk a character, I found one at a website, it actually works but unfortunately, it fails because the character didn't actually walk. I have no idea on what code will be place there. Either I will walk a character by clicking mouse or I will create a button then click on it to walk a character. What would be the code can I use for that? Any help will be appreciated.
P.S. In my previous post, I'm creating a code from timeline but now I transfer it to Actionscript file because of some errors.
EDIT:
Here's my code of the character:
forward.addEventListener(MouseEvent.CLICK, ppap);
function ppap(event:MouseEvent):void{
gril.x += mouseX;
gril.y += mouseY;
gril.gotoAndStop('i');
gameloop();
}
function gameloop(): void {
for (var o = 0; o > 5; o++) {
if (linya.hitTestObject(gril)) {
o++;
gotoAndStop(2);
scorer.visible = true;
timer.visible = true;
}
}
}
And the line: gril.gotoAndStop('a'); where the character is standing.
The gril is the instance name of a character. When it reaches to linya, the question will appear. Thanks!
Let's walk through your broken game loop
function gameloop(): void {
for (var o = 0; o > 5; o++) { //sets o to 0, loops as long as o > 5 (which it isn't, since we just set it to 0;
if (linya.hitTestObject(gril)) {
o++; //this also adds 1 to o
gotoAndStop(2);
scorer.visible = true;
timer.visible = true;
}
// if this part ever executed, it would add 1 to o
}
}
Do you see the problem? This for loop will not execute even once since 0 < 5
Instead it should be
function gameloop(): void {
for (var i = 0; i < 5; i++) {
if (linya.hitTestObject(gril)) {
gotoAndStop(2);
scorer.visible = true;
timer.visible = true;
break;
}
}
}
So here we have a functional (but pointless) for loop. It will work, but the first time through the loop it is going to result in the exact same thing as the second and third and fourth and fifth because changing the variable value by 1 isn't actually changing anything at all. You just telling the program to check the collision state 5 times. Well it does this 5 times before anything else can change. It checks it 5 times every game loop. Well I promise you nothing is moving while that for loop is running so why check it 5 times? I suggest stepping back and getting some help from your teacher or something because this seems way off. Sorry.
Right again #NealDavis and thank You for the comment!!!
I wrote my comment too quickly
Ascending loop from 0->4 (5 items):
for (var i:uint = 0; i < 5; i++){
trace("ascending = " + i);
}
Output:
ascending = 0
ascending = 1
ascending = 2
ascending = 3
ascending = 4
Descending loop from 4->0 (5 items):
for (var j:int = 4; j>=0; j--){
// j must be an int in this case, second mistake!
trace("descending = " + j)
};
Output:
descending = 4
descending = 3
descending = 2
descending = 1
descending = 0
My mistake. SRY
This is well explained in Looping reference
And in ActionScript 3 fundamentals: Loops reference
Shame on me!!! ;)
I'm a noob! :D
So I deleted my comment ;)
WOW, I'm so sorry about this mistake!!!
// You may also create Vectors to store the values.
var ascending:Vector.<uint> = new Vector.<uint>;
var descending:Vector.<uint> = new Vector.<uint>;
for (var k:uint = 0; k < 5; k++){
ascending.push(k+1);
}
trace("ascending Vector.<uint> = " + ascending);
// Output : ascending Vector.<uint> = 1,2,3,4,5
for (var l:int = 4; l >= 0; l--){
descending.push(l+1);
}
trace("descending Vector.<uint> = " + descending);
// Output : descending Vector.<uint> = 5,4,3,2,1
Or in an ascending loop :
trace("\nascending Vector.<uint> loop : ")
for(var m:String in ascending){
trace(m + " = " + ascending[m]);
}
Output :
ascending Vector.<uint> loop :
0 = 1
1 = 2
2 = 3
3 = 4
4 = 5
Or in a descending loop :
trace("descending Vector.<uint> loop : ")
for(var n:String in descending){
trace(n + " = " + descending[n]);
}
Output:
descending Vector.<uint> loop :
0 = 5
1 = 4
2 = 3
3 = 2
4 = 1

ActionScritp 3 removeChild in loop

I have two arrays, fireballs and gombas (enemies).
When I create fireball and gomba, I add them into arrays using push();
I shoot fireballs and move gombas using foor loop
for (var f:int = 0; f < fireballs.length; f++)
{
// move fireballs
}
I also remove fireballs if it goes too far, for example
if (myFireball.x + 1000 < player.x)
{
if (myFireball.parent)
{
myFireball.parent.removeChild(myFireball);
fireballs.splice(myFireball, 1);
}
}
I have no problem removing fireballs, but if fireball hitTestObject gomba, I want to remove both, fireball and gomba, ant thats my problem.
I tried on this way and I get error, a term is undefined and has no properties
for (i = 0; i < fireballs.length; i++)
{
for (var m = 0; m < gombas.length; m++)
{
if (fireballs[i].hitTestObject(gombas[m]))
{
if (fireballs[i].parent)
{
fireballs[i].parent.removeChild(fireballs[i]);
// same for gombas
}
}
}
}
If I use same loop but just check if fireballs and gombas are visible, if fireballs hit gombas I set visible to false and it works ok. Why it wont work with removeChild.
As #itcouldevenbeaboat says, when looping through an array and removing objects, it's better to loop backwards; that way, you won't have index issues.
For example, with the array ["one","two","three"], if you looped through and removed like so:
for( var i:int = 0; i < myArray.length; i++ )
myArray.splice( i, 1 );
What's happening, is this:
i starts at 0, which points to "one"
we remove the object at position 0 from myArray
myArray is now ["two","three"]
at the end of the loop, i is incremented, and becomes 1
we start the next iteraction, and i is 1, which points to "three"
In this example, we've skipped over the "two" String, because the splice has modified the array we're iterating. If we went backwards:
for( var i:int = myArray.length - 1; i >= 0; i-- )
myArray.splice( i, 1 );
Then we get this:
i starts at 2, which points to "three"
we remove the object at position 2 from myArray
myArray is now ["one","two"]
at the end of the loop, i is decremented, and becomes 1
we start the next iteraction, and i is 1, which points to "two"
Thus we remove all the objects from myArray, no problem.
For your particular example, as you're removing objects from the two arrays, you should iterate backwards, which should give you something like:
outer: for ( var i:int = fireballs.length - 1; i >= 0; i-- )
{
for ( var m:int = gombas.length - 1; m >= 0; m-- )
{
if (fireballs[i].hitTestObject(gombas[m]))
{
// remove our fireball and gombas graphics
if( fireballs[i].parent != null )
fireballs[i].parent.removeChild( fireballs[i] );
if( gombas[m].parent != null )
gombas[m].parent.removeChild( gombas[i] );
// remove the fireball and gombas from the array; this is assuming
// that once a fireball hits a gomba, they both disappear
gombas.splice( m, 1 );
fireballs.splice( i, 1 );
// break to the outer loop; the fireballs one, as we don't need
// to go any further in the inner one
break outer;
}
}
}
Note the outer label on the fireballs loop; this lets us jump out once we detect a collision between a fireball and a gomba.
If you want a fireball to hit multiple gombas, then just don't remove the graphics or splice the array.

AS3: Merge multiple 2d Arrays - indexOf not working

I want to merge multiple 2dim Arrays which are of the type [unique number][a fix number]
Since I would like to merge them (and have unique results) I'm searching inside the "retArr" if array[unique number] is present.
Array1: retArr
Array2: arg (multiple 2dim Arrays)
// before here is an additional "for each"-loop which gives me in every iteration a "new" arg-Array.
for (var p:uint = 0; p<arg.length; p++){
if(retArr.length ==0){
var tmp:Array = new Array();
tmp.push(arg[p][0]);
tmp.push(arg[p][1]);
retArr.push(tmp);
}
else{
for(var i:uint = 0; i<retArr.length; i++){
if (retArr[i].indexOf(arg[p][0]) == -1){
var tmp:Array = new Array();
tmp.push(arg[p][0]);
tmp.push(arg[p][1]);
retArr.push(tmp);
break;
}
}
}
}
I think the line
if (retArr[i].indexOf(arg[p][0]) == -1)
is my Problem, since I'm getting double-results in my retArr.
Can anyone help me out please?
To summarize: You have an array of arrays and each array in the parent array has two elements. You want to filter out all the arrays that have duplicated values at index 0. Is this correct?
If so the problem is in your second for loop. Say this is what you have in arg:
var arg:Array = [[0, 1], [2, 3], [2, 3]]
On your first iteration, retArr contains nothing, so [0, 1] is added and the second for loop doesn't run
On your second iteration, the second for loop executes once because the first element of [2, 3] does not appear in [0, 1]
Now here's the problem: On your third iteration, the second for loop executes. It checks to see if [0, 1] contains 2. It doesn't, so it adds it to retArr. It never even checks to see if [2, 3] contains 2.
What you need to do is loop through all elements of retArr, and if there were no matches at all, then you can safely add the array.
var matchFound:Boolean = false;
for(var i:uint = 0; i<retArr.length; i++){
if (retArr[i].indexOf(arg[p][0]) != -1){
matchFound = true;
break;
}
}
if( ! matchFound) {
var tmp:Array = new Array();
tmp.push(arg[p][0]);
tmp.push(arg[p][1]);
retArr.push(tmp);
}
There is another problem: You are filtering out an array even if it's element 0 matches another array's element 1. To only filter out array's that have duplicate element 0's, change this
if (retArr[i].indexOf(arg[p][0]) != -1){
to this
if (retArr[i].indexOf(arg[p][0]) == 0){
It would probably be faster and less complicated if you just did this:
if(retArr[i][0] == arg[p][0]){
It looks like this should be possible by using splice or concat
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#concat%28%29
you can just attach arrays to retArr, without calculating the length and iterating

Loop through array, set property of each element?

Okay, very simple: there is an array containing 3 objects. Each object has a unique property called "ID" with values of either 1, 2, or 3.
One of the objects gets deleted.
The objective now is to update the ID property of each object corresponding to the new array.length value.
So for example, the object with ID of 2 got deleted. The remaining objects in the array would each have ID values of 1 and 3 respectively.
So the objective is to loop through the array and update the ID properties to 1, and 2 (instead of 1 and 3).
So I guess the question is how to write a loop to update a common property of each element in an array. Thanks.
You can use a for-loop to go through the array, as in walkietokyo's answer, or you can use a method closure:
myArray.forEach ( function ( item:*, i:int, arr:Array) : void { item.ID = i; } );
or a while-loop:
var i:int = -1;
while (++i < myArray.length) myArray[i].ID = i;
for (var i:uint = 1; i <= myArray.length; i++) {
myArray[i].ID = i;
}
General info on loops:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcf.html
var i:uint; // for speed keep out of the loop
var arrayLength = myArray.length // for speed keep out of the loop
for (i = 0; i < arrayLength; i++) {
myArray[i].ID = i;
}