Remove Array and its contents with mouse click AS3 Flash CS5.5 - arrays

I have been trying to do this for two nights now and haven't had any joy, please help if you can...
Simple throwing game with darts and other weapons, what I am trying to do is
Remove an array and all of its Children when I change weapon,
I feel sure there is a simple snippet of code that will remove all the children and array with no hassle but I haven't yet figured it out, if you know or could suggest anything, I would really appreciate it.
something like "removeArrayAndAllInstances(balls);" if only...
at the moment I have....(balls is the array in question)
for(var inter:int = balls.length - 1; inter > -1; inter--)
{
balls.splice(1);
balls.splice(1, balls.length);
}
but this docent work for some reason, the array and all of its children are all still on the stage.
I also tried
balls[];
No luck...
Please don't judge my code I am a novice as I am sure was evident and I know its a disgusting mess, sorry (Its the only way it makes sense to me).
I have tried numerous things, hope someone can help
Thanks in advance.....
var mouseTarget:MovieClip;
var balls:Array = new Array();
var ball:MovieClip = new dart();
var hammers:MovieClip = new hammer();
ball.x = 150;
ball.y = 50;
hammer_btn.addEventListener(MouseEvent.MOUSE_DOWN, hammerweapon);
dart_btn.addEventListener(MouseEvent.MOUSE_DOWN, dartweapon);
function removealldartsfromstage(e:MouseEvent):void
{
for(var inter:int = balls.length - 1; inter > -1; inter--)
{
balls.splice(1);
balls.splice(1, balls.length);
}
stage.removeEventListener(MouseEvent.MOUSE_UP, addDart);
}
function dartweapon(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, addHammer);
dart_btn.removeEventListener(MouseEvent.CLICK, dartweapon);
stage.addEventListener(MouseEvent.MOUSE_UP, addDart);
//removeChild(balls);
}
function hammerweapon(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, addDart);
dart_btn.addEventListener(MouseEvent.MOUSE_DOWN, dartweapon);
//stage.addEventListener(MouseEvent.MOUSE_UP, addDart);
stage.addEventListener(MouseEvent.MOUSE_UP, addHammer);
}
function addHammer(e:MouseEvent):void
{
var hammers = new hammer();
addChild(hammers);
removeChild(dart_btn);
addChild(dart_btn);
dart_btn.addEventListener(MouseEvent.CLICK, dartweapon);
balls.splice(10);
}
function addDart(e:MouseEvent):void
{
str.alpha = 0;
var ball = new dart();
addChild(ball);
removeChild(hammer_btn);
addChild(hammer_btn);
ball.x = 150;
ball.y = 50;
balls.push(ball);
trace(balls);
addEventListener(Event.ENTER_FRAME, checkIfHitTest);
hammer_btn.addEventListener(MouseEvent.MOUSE_DOWN, removealldartsfromstage);
function checkIfHitTest(Event)
{
for (var i:int = 0; i<balls.length; i++)
{
if (balls[i].dart_point.hitTestObject(eyeleft))
{
trace("hitleftbullseye");
ball.gotoAndStop("hitlefteyeframe");
Event.currentTarget.removeEventListener(Event.type, checkIfHitTest);
balls.splice(i, 1);
}
}
}
}

The balls array is just a storage for ball references. It bears no relation to the stage or the DisplayObjectContainer which they have been added at all. So you have to remove them individually.
This is what I'd do:
while(balls.length > 0)
{
var ball:MovieClip = balls.pop();
if (ball.parent) // Just to make sure you are referencing the correct container.
{
ball.parent.removeChild(ball);
}
}
I can't follow the logic of your game very well. That said, you'd do well to create conatiners for separate group of clips in order to make managing them easier. For example, in the creation stage:
var ballContainer:Sprite = new Sprite();
addChild(ballContainer);
for (var i:int = 0; i < ballLimit; i++)
{
var ball:Dart = new Dart();
ballContainer.addChild(ball);
}
This way, you can clear them of children all at once:
function removeAllChildren(container:Sprite) // Or just DisplayObjectContainer
{
while(container.numChildren > 0)
{
container.removeChild(container.getChildAt(0));
}
}

Related

Impossible to find the function setBackground on a object

I'm trying to do something like: If the column E has the word ok, column D gets formated as red. Seens preety easy, but something is wrong as I'm not entenring the if. Do u guys know what is wrong? I have read some other topics, but seens preety much the same
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
Browser.msgBox(myRangeValues);
for (var i = 0; i < myRangeValues.length; i++){
if(myRangeValues[i][0] == 'ok'){
myRangeValues[i][0].setBackground('red');
}
}
}
Thanks for the attention.
EDIT:
new code not working. I tried to put the logger.log in other lines as well. even without the logger, the error I get is that the function setBackground is impossible to find in the object.
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
for (var i = 0; i < myRangeValues.length; i++)
{
if(myRangeValues[i][1] == 'ok')
{
myRangeValues[i][0].setBackground('red');
//Logger.log("myRangeValues[i][1]: " + myRangeValues[i][1]);
}
}
}
You are mixing up methods.
value arrays don't have setBackground() method, this is a spreadsheet range method
use the code below to do what you want :
function onEdit() {
var ss =SpreadsheetApp.getActiveSheet();
var myRangeValues = ss.getRange('D7:E').getValues();
var myRangeColors = ss.getRange('D7:E').getBackgrounds();// get the colors
for (var i = 0; i < myRangeValues.length; i++)
{
if(myRangeValues[i][1] == 'ok')
{
myRangeColors[i][0]='#F00';
}
}
ss.getRange('D7:E').setBackgrounds(myRangeColors); //set the modified colors
}

Use an array of values for a slider

I want to use an array of id, for my little slider-viewer I'm building. I just want to display multiple things using 2 buttons next and previous.
For now I use something like this, using only 2 url id, but I need at least 20 urlid in my viewer :
var urlid1 = 'd3885ca76ac54e958c2855a4fbd3dbf3';
var urlid2 = '3aa64527d1614998b4812bfefbbc896a';
function Next() {
client.init( urlid2 );
}
function Previous() {
client.init( urlid1 ); }
So I've never use an array before, and the things I tried didn't work. Do you know a proper way to do that ?
This seems straight forward enough
var index = 0;
var array = ["url1", "url2", "url3", ...]
function next() {
index++;
if(index > array.length) {
index = 0;
}
client.init(array[index]);
}
function previous() {
index--;
if(index < 0) {
index = array.length;
}
client.init(array[index]);
}
It may be better practice to actually refactor those changes to the index variable to other functions to enable reuse, but this should give you an idea of how it is done.
If client is something that you have wrote then you might want to look at the naming of your functions, init is normally reserved for instantiating the class as new, from your example you seem to be changing a resource so you may want a function name like client.show(); or client.update();
Thank's Varedis.
Final code is :
var index = 0;
var array = ["0e4b4e0789bf41c7b05129a76de0abb0","3aa64527d1614998b4812bfefbbc896a","d3885ca76ac54e958c2855a4fbd3dbf3","8f927023e10c40b9b22d3c13df7c08aa"];
client.init(array[index]);
function next() {
index++;
if(index >= array.length) {
index = 0;
}
client.init(array[index]);
}
function previous() {
index--;
if(index < 0 ) {
index = array.length-1;
}
client.init(array[index]);
}
I had to use " index = array.length-1; " but I can't explain it. You know why ? How index could be 5 if I only have 4 values ?

AS3 Array items not splicing properly

I'm attempting to make a small game where the user mouses over the circles that fall from the ceiling for points. The circles are added to a container and pushed into an array to hold them, and are removed and spliced when they are mouse-over'd or go off stage.
Everything works fine, until two circles are removed at nearly the same time, whether it be from falling off stage at the same time or mousing over two of them extremely fast. When this happens, the child on stage is removed, but the object is still left in the array, meaning another circle cannot take its place, leaving one less circle spawning every time the issue happens.
Code on main timeline:
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
var ballContainer:Sprite = new Sprite();
addChild(ballContainer);
var maxBalls:uint = 10;
var balls:Array = [];
var ballTypes:Array = [GreenBall];
var ballChances:Array = [800];
var ballVelocities:Array = [1.5];
var ballAccelerations:Array = [1.02];
stage.addEventListener(Event.ENTER_FRAME, onTick);
function onTick(e:Event):void {
while (balls.length < maxBalls){
addBall();
}
}
function addBall():void {
var ballType = ballTypes[0];
var ball = new ballType;
ball.x = Math.ceil(Math.random()*(stage.stageWidth - ball.width));
ball.y = 0 - (ball.height*1.5);
ballContainer.addChild(ball);
balls.push(ball);
}
Code in GreenBall:
import flash.events.Event;
var mainStage = Sprite(root);
var index = mainStage.balls.indexOf(this);
var velocity:Number = mainStage.ballVelocities[0]*randomNumber(0.5, 1.5);
var acceleration:Number = mainStage.ballAccelerations[0];
this.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
function onMouseOver(e:MouseEvent):void {
this.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
removeBall();
}
this.addEventListener(Event.ENTER_FRAME, onTick);
function onTick(e:Event):void {
this.y += velocity;
velocity = velocity*acceleration;
if (this.y > stage.stageHeight + this.height){
this.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
removeBall();
}
}
function removeBall():void {
mainStage.balls.splice(index, 1);//doesn't get spliced if balls are removed too quickly
mainStage.ballContainer.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, onTick);
}
function randomNumber(min:Number, max:Number):Number {
return Math.random()*(max - min) + min;
}
So what's going on? Did I set something up incorrectly? How can I go about fixing this issue?
Any help would be appreciated greatly.
Your logic is flawed - the index should be calculated when the removal occurs. When you remove objects from an array via splice, the index of all the elements after the one you removed is decreased by one.
This means that if you have 10 balls and remove the first, the index value you have for every other ball will be incorrect and you'll be removing the wrong ball from your array on subsequent removals.
Moving the indexOf statement to the removeBall method should solve the issue:
function removeBall():void
{
var index:int = mainStage.balls.indexOf(this);
if(index >= 0)
{
mainStage.balls.splice(index, 1);
mainStage.ballContainer.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, onTick);
}
}
To make it easy on yourself, you could extend Array and make a remove function:
public dynamic class List extends Array
{
public function remove(item:*):void
{
var i:int = indexOf(item);
if(i >= 0) splice(i, 1);
}
}

Splice array within array

How can I splice an array within another array?
I'm trying to create a game for kids in my class. Some kind of a trivia history question creator. How to splice the MasterArray so that I would get rid of sub-arrays (Hard-England and Medium-England) within the allEnglandArray. Because the "MasterArray.splice()" seem to be affecting - splicing only the allEngland array, or the allFrance array. But I need to get rid of those sub-arrays...
My code:
var Easy-England:Array = ["item1","item2","item3","item4","item5"];
var Medium-England:Array = ["item6","item7","item8"];
var Hard-England:Array = ["item9","item10"];
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
var Easy-France:Array = ["item11","item12","item13","item14","item15"];
var Medium-France:Array = ["item16","item17","item18"];
var Hard-France:Array = ["item19","item20"];
var allFrance:Array = [Easy-France,Medium-France,Hard-France];
// the list of countries goes on and on and on... (Italy, Hungary, etc.)
var allStuff:Array = [allEngland, allFrance, etc.];
var MasterArray:Array;
// FUNCTIONS
// clear MasterArray - first I clear out completely the MasterArray
function clearMasterArray():void
{
MasterArray.splice(0);
}
// update MasterArray - than I fill the MasterArray with data according to checkBoxes
function updateMasterArray():void
{
for (var i:int = 0; i<checkBoxBlock.myCheckBoxes.length; i++)
{
if (checkBoxBlock.myCheckBoxes[i].selected)
{
MasterArray.push(allStuff[i]);
}
}
}
// splice MasterArray - last thing I do is splice the items according to student's proficiency level, referred to as "studentPL".
function spliceMasterArray():void
{
if (studentPL == 1)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(5,5);
}
}
if (studentPL == 2)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(8,2);
}
}
if (studentPL == 3)
{
for (var i:int = 0; i<allStuff.length; i++)
{
trace("no need to splice");
}
}
}
And after this I call those functions in another function in this order...
function creatorFunction():void
{
clearMasterArray();
updateMasterArray();
spliceMasterArray();
}
Instead of:
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
try this:
var allEngland:Array = Easy-England.concat(Medium-England, Hard-England);
This way you will have a 'flat' array (no sub-arrays), so it will be easier to deal with.

Randomly removing an array

just for the record, i'm using AS3.
I have an issue where I would like to remove a sprite randomly in AS3, I have managed to figure out how to create the sprites so that they fill as a grid, just for the life of me I can't figure out how to remove them!
Here's the code i've used to create them:
function showpixels() : void
{
for (var i:int = 0; i < 40; i++)
{
for (var j:int = 0; j < 40; j++)
{
var s:Sprite = new Sprite();
s.graphics.beginFill(0);
s.graphics.drawRect(i*10, j*10, 10, 10);
s.graphics.endFill();
addChild(s);
pixels.push(s);
}
}
}
Basically I need these to be removed randomly until what's underneath can be seen.
Any help would be good, I'm pretty new to this! Thanks!
function removeRandom():void
{
var rand:uint = Math.random()*pixels.length;
var i:Sprite = Sprite(pixels[rand]);
if(i.parent) i.parent.removeChild(i);
pixels.splice(rand, 1);
}
UPDATE: To remove at random intervals you could try something like this:
var _timer:int = 100;
addEventListener(Event.ENTER_FRAME, _handle);
function _handle(e:Event):void
{
if(pixels.length > 0) _timer --;
if(_timer < 1)
{
_timer = 10 + Math.random()*50;
removeRandom();
}
}
function removeRandom():void
{
var rand:uint = Math.random()*pixels.length;
var i:Sprite = Sprite(pixels[rand]);
if(i.parent) i.parent.removeChild(i);
pixels.splice(rand, 1);
}
Marty's idea works. Another option would be to shuffle the array first and then just pop off elements.
To shuffle an Array use pixels.sort(function (...args):int { return int(2*Math.random()-1) }).
And then you can simple remove them like this:
function remove():void {
if (pixels.length) removeChild(pixels.pop());
else clearInterval(this.id);
}
And add this line at the end of showpixels:
this.id = setInterval(remove, 500);

Resources