as3 event listeners in for loop to pass dynamic variable to function - actionscript-3

I need your help. I have an array with numbers, and I tried to pass a dynamic variable to a function in the mouse event listener. It works but not how I want. Whenever the mouse event listener is activated it passes the last value of that dynamic variable, not the value that was set. I tried to set this["n1"] and this["n2"] when passing to the function, but then the mouse event won't work (respond). How can I fix that? Here is my code:
var niz1:Array = [[1,2],[1,3],[3,4]];
var n,n1,n2;
for(n=0;n<3;n++){
n1=niz1[n][0];
n2=niz1[n][1];
this["hovermc"+n1+"_"+n2].addEventListener(MouseEvent.ROLL_OVER, function(e:MouseEvent) : void {hover_effect_in(null,n1,n2,0,0);});
this["hovermc"+n1+"_"+n2].addEventListener(MouseEvent.ROLL_OUT, function(e:MouseEvent) : void {hover_effect_out(null,n1,n2,0,0);});
}
function hover_effect_in(hovermc:MovieClip,h1:int,h2:int,h3:int,h4:int):void{
if(hovermc != null){
hovermc.hoverbg.alpha=0.7;
}
if(h1 != 0 && h2 != 0 && h3 == 0 && h4 == 0){
this["hovermc"+h1].hoverbg.alpha=0.7;
this["hovermc"+h2].hoverbg.alpha=0.7;
}
}
function hover_effect_out(hovermc:MovieClip,h1:int,h2:int,h3:int,h4:int):void{
if(hovermc != null){
hovermc.hoverbg.alpha=0;
}
if(h1 != 0 && h2 != 0 && h3 == 0 && h4 == 0){
this["hovermc"+h1].hoverbg.alpha=0;
this["hovermc"+h2].hoverbg.alpha=0;
}
}

You are getting those values for n1 and n2 because those are the values of those variable at the time the event function executes even though it might be different at the time the function is defined with the addeventlistener command.
I can't think of a simple way to do what you want to do with your code, but a more practical way would be to have your listener call "hover_effect_in" directly, and then based on the calling mc's name, "e.target.name", apply your array values based on the mc's name. So if name=hovermc_1_2 then n1=1 and n2=2. So, based on a button name, you assign your values in the button handler.
Or, the sophisticated way to do is make a class for "hovermc" which has all your basic code but each class carries one set of your niz1 values and gets assigned to each of your button mcs.

Related

Create a list of Button in Cocos2dx

When I create a list of button and I addTouchEventListener for it, like below code
for (int i = 0; i < btmPlay.size(); i++ )
{
btmPlay.at(i)->addTouchEventListener([&](Ref *sender, ui::Widget::TouchEventType type){
if (type == ui::Widget::TouchEventType::ENDED)
{
CCLOG("%i", i);
}
});
}
when I touch to the first button, the result is 12 ( btmPlay.size() = 13).
What errors?
In your closure, you're capturing the variable i by reference, and that's why clicking any button will print the same value, in this case 12. If, instead, you capture the variable i by value (by replacing [&] with [=]) then each button will print a different value in the range 0-12.
Btw, capturing i by reference in your example is also wrong, because by the time the closure is invoked, the variable is already out of scope, and printing it is UB.

AS3 Null Object Reference After Null Check

I have been looking for a solution to this for a while now but cannot find anything.
This problem is very odd so I'll give some background. I am making a tower defense game, and while implementing status effects on enemies (slowed, on fire, etc.) I ran into a weird problem. When the tower kills the enemy with a projectile everything is fine, but for some reason when the enemy is killed by a status effect, I get a null object reference error (both are handled with the method "Enemy.damage(damage:int)"). The weird thing about this is that the status effects are stored in an array that is only referenced in 3 spots. In the ENTER_FRAME event (one ENTER_FRAME event is used to process every aspect in the Game), in the constructor (status = new Array();) and in the destroy method.
One weird part is that if the "status" variable was null, other variables from the destroy method would have given me errors a long time ago. The really weird part is that I have a null check right before I get the error.
Here is where I get the error:
//STATUS EFFECTS
if (status == null) {
trace("test");
}
if (status != null && status.length != 0) {
for (var i:int = 0; i < status.length; i++) {//LINE 101
status[i].applyEffect();
}
}
Here is the error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at game.enemies::Enemy/update()[C:\flash\game\enemies\Enemy.as:101]
"test" never gets printed, and even with the null check I still get the error
EDIT: Here is the Enemy class: http://pastebin.com/LAyMMB1P
The StatusEffect & FireEffect classes: http://pastebin.com/GTGDmjt8 (I can only post 2 links, each is in its own file)
status variable is referenced in StatusEffect.destroy() and here:
override public function onHit(e:Enemy) {
if (upgradeLevel >= 1) {
var onFire = false;
for (var i:int = 0; i < e.status.length; i++) {
if (e.status[i].name_ == "fire") {
onFire = true;
}
}
if (!onFire) {
e.status.push(new FireEffect(e));
}
}
if (upgradeLevel >= 2) {
if (enemiesHit.indexOf(e) == -1) {
enemiesHit.push(e);
e.damage(1);
}
if (upgradeLevel == 2 && enemiesHit.length == 2) {
destroy();
}
} else {
e.damage(super.damage);
destroy();
return;
}
}
This is happening because you can potentially destroy your enemy in the middle of the for loop on line 101.
Destroying the enemy sets the status array to null, so on the next iteration when it checks if i < status.length, status is null, thus the error.
So to illustrate, stepping through the code, let's assume at line 101 there are two items in the status array:
First loop, item at index 0 gets applyEffect() called on it.
inside applyEffect() the specificApplication() method can be called.
inside specificApplication() the super.enemy.damage(1); method is called.
inside the enemy.damage() method, you can potentially call the enemy.destroy method
inside the enemy.destroy method, you set status = null.
NOW the loop from line 101 loops, but status is now null.
Fix this by breaking out of your loop if the enemy is destroyed.
for (var i:int = 0; i < status.length; i++) {//LINE 101
status[i].applyEffect();
if(!status) break;
}
You also have some issue with splicing:
enemy.status.splice(enemy.status.indexOf(this), 1);
While there is nothing wrong with that line on it's own, let's step through the code:
line 101 of Enemy class:
for (var i:int = 0; i < status.length; i++) {
You loop through the status array. For this example, let's say you have two items in the array.
Item A is at position 0. Item B is at position 1 in the array.
First loop, i has a value of 0.
You call status[i].applyEffect(), since i == 0, that is item A.
Inside applyEffect let's say your condition is met so you call destroy (on the StatusEffect class)
Inside the StatusEffect.destroy() method you splice the status array.
Now status has only one item, item B, and item B now has an index of 0 (instead of 1).
Your loop loops, now i == 1.
However, there is no longer any item at index 1 so the loop exits, skipping item B.
To solve it, iterate backwards instead, then your indices won't get out of whack when you splice:
var i:int = status.length
while(i--){
status[i].applyEffect();
}
As an aside, it would be much cleaner if you used var status:Vector.<StatusEffect> instead of an var status:Array. You'd get compile time checking and type safety that way.

which method should i use to create a new keyboard using adobe flash

I'm trying to create a new keyboard somehow, for educational purposes.
I've written this code using actionscript 3.I've created an input text field (named it t1) .when the user presses q button on keyboard(which has an ASCII aquals 81 ) I want the letter b to be printed out on the text field so i've written this code :
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressing);
function pressing(event:KeyboardEvent):void
{
//trace(event.keyCode);
if(event.keyCode==81)
t1.replaceSelectedText("b");
}
the problem was that the method replaceSelectedText prints the tow letters on the screen(q&b) which method can i use instead?
Any help would be appreciated.
When using the replaceSelectedText method, you first need to select the text you want to replace. This can be done with the "setSelection" method. This from the adobe help website:
setSelection(beginIndex:int, endIndex:int):void
"Sets as selected the text designated by the index values of the first and last characters, which are specified with the beginIndex and endIndex parameters."
At the moment, since you don't have any text selected, it appears to just be adding the text "b" as it's replacing nothing. Therefore, you should try first selecting the "q".
Alternatively, you can just use a different method. from the adobe help website:
replaceText(beginIndex:int, endIndex:int, newText:String):void
"Replaces the range of characters that the beginIndex and endIndex parameters specify with the contents of the newText parameter."
This would cut out an extra line of code.
I haven't actually done this myself, so if that doesn't work, here's the link to the adobe help page for Text Fields: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextField.html
I think that to do what you are looking for ( replace a char when it's typed ), a KeyboardEvent.KEY_DOWN is not enough, because when that event is fired, the text is not yet changed, so any change that you did in its handler to your text field will not cancel the insertion of the current typed char. Also, using KeyboardEvent.KEY_UP ( in addition to KeyboardEvent.KEY_DOWN ) will not resolve the problem, because you can fire n times a KeyboardEvent.KEY_DOWN event with the KeyboardEvent.KEY_UP event fired once !
So, I think that the best event that can do the job is the Event.CHANGE event which is fired every time the text of your text field is changed, so you can do like this :
// is there a char to replace ?
var replace_char:Boolean = false;
// the position of the char that we want to replace
var char_position:int = -1;
var text_input:TextField = new TextField();
text_input.type = 'input';
text_input.border = true;
text_input.addEventListener(Event.CHANGE, onTextChange);
function onTextChange(e:Event):void {
if(replace_char && char_position >= 0){
text_input.replaceText(char_position, char_position + 1, 'b');
replace_char = false;
}
}
addChild(text_input);
stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown);
function _onKeyDown(e:KeyboardEvent):void {
if(e.keyCode == 81) {
replace_char = true;
char_position = text_input.selectionBeginIndex;
}
}
EDIT :
To use a list of keys and their equivalents, you can use an object to stock your keys like this :
// list of all keys (chars) and their equivalents
var chars:Object = {
81: 'b', // q => b
83: 'v', // s => v
68: 'c' // d => c
// other chars
}
var char_to_replace:int = -1;
// other instructions
function onTextChange(e:Event):void {
if(replace_char && char_position >= 0 && char_to_replace >= 0){
// get the equivalent of the pressed key from chars object using : chars[key_pressed]
text_input.replaceText(char_position, char_position + 1, chars[char_to_replace]);
replace_char = false;
}
}
// other instructions
function _onKeyDown(e:KeyboardEvent):void {
if(chars[e.keyCode]) {
replace_char = true;
// save the last pressed key to get its equivalent, or save this last one directly, to replace it next
char_to_replace = e.keyCode;
char_position = text_input.selectionBeginIndex;
}
}
Hope that can help.

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)

Using two eventlisteners for one function in Actionscript

I'm making a dots and boxes game in flash using actionscript 3.
Currently I'm completely stuck as I want the player to click two buttons before a line is displayed. I planned to do something like this using the if statement
if button1 and button2 clicked
line1 visible = true
I've also tried adding eventlisteners with one function
function showLine(e:Event):void {
blue0001.visible = true
}
dot00.addEventListener(MouseEvent.CLICK, showLine);
But as far as I know this can only be used when you want to click one button. Is there anyway to have two eventlisteners satisfyed before the function is carried out?
Also how would I (if i can) use the if statements to carry out this?
You would probably do something like this, pseudo-code:
Assume all of the dots are in a dots array.
for (var i: Number = 0; i < dots.length; i++) {
dots.addEventListener(MouseEvent.CLICK, dotClicked, false, 0, true);
}
dotSelected = null;
function dotClicked(evt:MouseEvent):void {
if (dotSelected && isNeighbor(evt.target, dotSelected)) {
showLineConnecting(evt.target, dotSelected)
dotSelected = null;
} else if (!dotSelected) {
highlightDot(evt.target);
dotSelected = evt.target;
} else {
showError("You must click an adjacent dot");
}
}
At the request of the OP, this is what's going on.
for (var i: Number = 0; i < dots.length; i++) {
dots.addEventListener(MouseEvent.CLICK, dotClicked, false, 0, true);
}
Add an event listener to every dot. Here I am assuming you already have an array of dots defined. Each instance in the Array would be a MovieClip (likely), Sprite, or another DisplayObject.
dotSelected = null;
We will use a variable to keep track of any currently selected dot. Since no dot will be selected when the game starts, we set it to null.
function dotClicked(evt:MouseEvent):void {
if (dotSelected && isNeighbor(evt.target, dotSelected)) {
showLineConnecting(evt.target, dotSelected)
dotSelected = null;
} else if (!dotSelected) {
highlightDot(evt.target);
dotSelected = evt.target;
} else {
showError("You must click an adjacent dot");
}
}
This is the function that will get called when any dot is clicked. For explanation's sake, let's take the first click of the game. dotSelected is null, so the first if is false. The second if though is true, because (!dotSelected) is true. So, we run some function I called highlightDot with the dot as the argument. That function could look something like this:
function hightlightDot(dot:Dot):void {
dot.gotoAndStop("selected");
}
Now a second click is made. Now the first part of the first if, dotSelected, is true. The second part is now evaluated. Again I put in a made up function isNeighbor. The isNeighbor function takes two arguments, the dot that was just clicked and the dot that has already been clicked. This function needs to make sure the two dots are adjacent. This could be something like...
function isNeighbor(dot1:Dot, dot2:Dot):void {
return ((dot1.xGrid == dot2.xGrid && Math.abs(dot1.yGrid - dot2.yGrid) == 1) || (Math.abs(dot1.xGrid - dot2.xGrid) == 1) && dot1.yGrid == dot2.yGrid));
}
The above function assumes that the instances of Dot have some properties xGrid and yGrid which defines where in the playing board they sit. If they are in the same row and 1 column apart they are neighbors. If they are in the same column and 1 row apart they are neighbors.
The last thing that happens in a function showLineConnecting is called. That function will again take the two adjacent dots as arguments. It will then draw a line between them in whatever way you choose to do that. Finally, dotSelected is set back to null, allowing another set of dots to be selected.
One thing I just realized, it would probably be helpful to have an additional property that gets triggered on a Dot when it is connected to all of its neighbors so it could no longer be selected.
You will also need logic to handle knowing that a box has been created. For that you would likely just iterate the possibilities given the line that was just drawn. For each line drawn there are only two possible boxes that have been created. So check them both. Watch out for edges.